Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

The Final Earth 2: build a city on floating islands in space

Mason Chencbfb713ec7ed
diff --git a/Makefile b/Makefile
index 7a40a499..6cbae376 100644
--- a/Makefile
+++ b/Makefile
@@ -24,7 +24,7 @@ RAM_LIMIT = 148928
# custom builds of Epsilon 25.2's source give apps less: 133652 bytes; every game fits there too, in NumPlay and on
# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)
CUSTOM_RAM = 133652
-BIG_APPS = Celeste HollowKnight ChampionIsland NumBlocks NumDrive
+BIG_APPS = Celeste HollowKnight ChampionIsland FinalEarth2 NumBlocks NumDrive
# the calculator's space for installed apps (0x90200000 to 0x903F0000 in its flash)
APP_SPACE = 2031616
# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has
@@ -205,6 +205,7 @@ APP_numvisuals = games/numvisuals/output/numvisuals.nwa:NumVisuals.nwa
APP_celeste = games/celeste/output/celeste.nwa:Celeste.nwa
APP_championisland = games/championisland/output/championisland.nwa:ChampionIsland.nwa
APP_hollowknight = games/hollowknight/output/hollowknight.nwa:HollowKnight.nwa
+APP_finalearth2 = games/finalearth2/output/finalearth2.nwa:FinalEarth2.nwa
apps: | $(B)
$(MAKE) -C games/numdash build NWLINK="node node_modules/nwlink/bin/nwlink"
@@ -218,6 +219,7 @@ apps: | $(B)
$(MAKE) -C games/celeste build NWLINK="$(NWLINK)"
$(MAKE) -C games/championisland build NWLINK="$(NWLINK)"
$(MAKE) -C games/hollowknight build NWLINK="$(NWLINK)"
+ $(MAKE) -C games/finalearth2 build NWLINK="$(NWLINK)"
cd games/tetris/tetris && NWLINK="$(NWLINK)" $(CARGO) build --release --quiet
cp $(word 1,$(subst :, ,$(APP_numdash))) $(B)/apps/$(word 2,$(subst :, ,$(APP_numdash)))
cp $(word 1,$(subst :, ,$(APP_crossyroad))) $(B)/apps/$(word 2,$(subst :, ,$(APP_crossyroad)))
@@ -231,6 +233,7 @@ apps: | $(B)
cp $(word 1,$(subst :, ,$(APP_celeste))) $(B)/apps/$(word 2,$(subst :, ,$(APP_celeste)))
cp $(word 1,$(subst :, ,$(APP_championisland))) $(B)/apps/$(word 2,$(subst :, ,$(APP_championisland)))
cp $(word 1,$(subst :, ,$(APP_hollowknight))) $(B)/apps/$(word 2,$(subst :, ,$(APP_hollowknight)))
+ cp $(word 1,$(subst :, ,$(APP_finalearth2))) $(B)/apps/$(word 2,$(subst :, ,$(APP_finalearth2)))
arm-none-eabi-strip --strip-unneeded $(B)/apps/Tetris.nwa
STD_APPS = $(foreach g,$(STD_GAMES),$(B)/apps/$(NWA_$(g)))
@@ -285,5 +288,6 @@ clean:
-$(MAKE) -C games/numvisuals clean
-$(MAKE) -C games/championisland clean
-$(MAKE) -C games/hollowknight clean
+ -$(MAKE) -C games/finalearth2 clean
-cd games/tetris/tetris && $(CARGO) clean
-$(foreach g,$(STD_GAMES),$(MAKE) -C games/$(g) clean;)
diff --git a/README.md b/README.md
index cb5976ff..f57c34d8 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
<p align="center">
<b>17 free games for your NumWorks calculator, in one app.</b><br>
- Plus <b>Hollow Knight</b>, <b>Celeste</b> and <b>Champion Island</b>, three big games that come as apps of their own.<br>
+ Plus <b>The Final Earth 2</b>, <b>Hollow Knight</b>, <b>Celeste</b> and <b>Champion Island</b>, four big games that come as apps of their own.<br>
For the N0110, N0115 and N0120, in English, <a href="#in-french-and-chinese">French and Chinese</a>, and for <a href="#on-upsilon">Upsilon</a>.
</p>
@@ -29,7 +29,7 @@
</p>
<p align="center">
- <b>New: <a href="#new-hollow-knight">Hollow Knight</a></b>, from King's Pass to Hornet in Greenpath. &nbsp;<b>And <a href="#new-numblocks">NumBlocks</a></b>, a world like Minecraft 1.8.
+ <b>New: <a href="#new-the-final-earth-2">The Final Earth 2</a></b>, a city on floating islands in space. &nbsp;<b>And <a href="#new-hollow-knight">Hollow Knight</a></b>, from King's Pass to Hornet in Greenpath.
</p>
<p align="center">
@@ -42,6 +42,29 @@ NumPlay is open source and completely free, and it took a lot of work to make. I
Want a game that isn't here? I'm open to requests: email me at [[email protected]](mailto:[email protected]).
+## New: The Final Earth 2
+
+<p align="center">
+ <img src="docs/media/finalearth2.gif" width="640" alt="The Final Earth 2: building a house on a city in free play, then its window and the happiness window">
+</p>
+
+Build a city on floating islands in space, right on your calculator.
+
+- **Every scenario and free play map** of the free version, with their goals and stories.
+- **87 buildings:** houses, farms, labs, factories, teleporters, parks and the alien buildings, with their upgrades.
+- **Citizens live their lives:** they work, go to school, look for fun, have children and grow old.
+- **The game's look:** its own pictures, fonts, sky and islands, day and night.
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/FinalEarth2.nwa"><img src="https://img.shields.io/badge/Download-FinalEarth2.nwa-3E6FB5?style=for-the-badge" alt="Download FinalEarth2.nwa"></a>
+</p>
+
+<p align="center">
+ It's too big to fit next to NumPlay, so it comes on its own. &nbsp;<a href="games/finalearth2/README.md"><b>More about The Final Earth 2</b></a> &nbsp;·&nbsp; <a href="docs/play.md#the-final-earth-2"><b>How to play</b></a>
+</p>
+
+
+
## New: NumBlocks
<p align="center">
@@ -191,6 +214,10 @@ Click a file to download it. Not sure which one? Take the first.
<td width="120" align="center"><img src="docs/media/thumb_hollowknight.png" width="112" alt="Hollow Knight"></td>
<td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/HollowKnight.nwa">HollowKnight.nwa</a><br>Hollow Knight: from King's Pass to Hornet in Greenpath. It fills the calculator's app space, so it comes on its own, not inside NumPlay (<a href="games/hollowknight/README.md">more</a>)</td>
</tr>
+ <tr>
+ <td width="120" align="center"><img src="docs/media/thumb_finalearth2.png" width="112" alt="The Final Earth 2"></td>
+ <td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/FinalEarth2.nwa">FinalEarth2.nwa</a><br>The Final Earth 2: build a city on floating islands in space. It's too big to fit next to NumPlay, so it comes on its own (<a href="games/finalearth2/README.md">more</a>)</td>
+ </tr>
<tr>
<td width="120" align="center"><img src="docs/media/thumb_numdrive.png" width="112" alt="NumDrive"></td>
<td><a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumDrive.nwa">NumDrive.nwa</a><br>Only NumDrive: drive, flip, finish</td>
@@ -282,9 +309,9 @@ You need your calculator, its USB cable, and a computer with **Google Chrome** o
| Calculator | Software | What runs |
| --- | --- | --- |
| N0120 | Epsilon 23.2 or newer (the calculator's own software) | Everything |
-| N0110, N0115 | Epsilon 23.2 or newer | Everything. These models are about 2.5 times slower, so the big games (Hollow Knight, Celeste, NumDrive, NumBlocks, Champion Island) show fewer frames per second, but they keep their speed. |
+| N0110, N0115 | Epsilon 23.2 or newer | Everything. These models are about 2.5 times slower, so the big games (The Final Earth 2, Hollow Knight, Celeste, NumDrive, NumBlocks, Champion Island) show fewer frames per second, but they keep their speed. |
| N0110, N0115 | Upsilon | NumPlay-Upsilon.nwa: 13 games. See [On Upsilon](#on-upsilon). |
-| Any | Custom software built from Epsilon 25.2's source | Everything, Celeste, Hollow Knight and Champion Island too. These builds can give apps less memory (133 KB): on one that gives even less, a game that needs more than there is says how much on its card. |
+| Any | Custom software built from Epsilon 25.2's source | Everything, The Final Earth 2, Celeste, Hollow Knight and Champion Island too. These builds can give apps less memory (133 KB): on one that gives even less, a game that needs more than there is says how much on its card. |
To see your calculator's model and software, open **Settings**, then **About**. To update the software, go to [my.numworks.com](https://my.numworks.com) with the calculator plugged in.
@@ -292,7 +319,7 @@ To see your calculator's model and software, open **Settings**, then **About**.
**NumPlay-French.nwa** and **NumPlay-Chinese.nwa** are NumPlay with every game in French or in Chinese (simplified). Install them like NumPlay.nwa, instead of it. Your progress is the same in every language.
-A few things stay in English: logos and words drawn into pictures, level names, the calculator's key names, NumBlocks' commands, and Portal Returns' chamber stories. Celeste, Hollow Knight and Champion Island come in English only.
+A few things stay in English: logos and words drawn into pictures, level names, the calculator's key names, NumBlocks' commands, and Portal Returns' chamber stories. The Final Earth 2, Celeste, Hollow Knight and Champion Island come in English only.
### On Upsilon
@@ -317,6 +344,7 @@ Upsilon support is new. If it doesn't work on your calculator, please [email me]
- **The calculator restarts once after installing**: it shows the NumWorks logo, then asks for your language. That's normal. Your apps are at the end of the home screen after that.
- **Celeste, Hollow Knight and Champion Island each fill the whole space for apps.** Install one of them alone, without NumPlay and without each other: if you pick more than fits, they don't install.
+- **The Final Earth 2 doesn't fit next to NumPlay.** Install it without NumPlay.
- **Installing replaces the apps you installed before.** To keep one, add it again with the new one.
- Check your calculator's software is **Epsilon 23.2 or newer** (Settings, then About), and update it at [my.numworks.com](https://my.numworks.com) if not.
@@ -339,6 +367,10 @@ Upsilon support is new. If it doesn't work on your calculator, please [email me]
<td><img src="docs/media/hollowknight.gif" alt="Hollow Knight: the Knight in King's Pass, against the False Knight and Hornet"></td>
<td><img src="games/hollowknight/docs/greenpath.png" width="100%" alt="Hollow Knight: Greenpath"></td>
</tr>
+ <tr>
+ <td><img src="docs/media/finalearth2.gif" alt="The Final Earth 2: building a house on a city in free play, then its window and the happiness window"></td>
+ <td><img src="games/finalearth2/docs/night.png" width="100%" alt="The Final Earth 2: a city at night"></td>
+ </tr>
<tr>
<td><img src="docs/media/numdrive.gif" alt="NumDrive gameplay"></td>
<td><img src="docs/media/balatro.gif" alt="Balatro: a Four of a Kind scoring with five Jokers"></td>
@@ -387,6 +419,7 @@ Upsilon support is new. If it doesn't work on your calculator, please [email me]
- **Minecraft** by Mojang inspired NumBlocks, which uses Minecraft 1.8.8's textures, font and screens and makes its worlds the way Minecraft 1.8.8 does.
- **Celeste** inspired NumPlay's Celeste, which uses the game's own pictures, maps, texts and fonts. Not affiliated with Maddy Makes Games.
- **Hollow Knight** inspired NumPlay's Hollow Knight, which uses the game's own pictures, animations, maps, texts and fonts. Not affiliated with Team Cherry.
+- **[The Final Earth 2](https://store.steampowered.com/app/1180130/The_Final_Earth_2/)** by [Florian van Strien](https://florianvanstrien.nl) inspired NumPlay's The Final Earth 2, which uses the game's own pictures, fonts and texts, with additional sprites by LukXD99. Not affiliated with him.
- **Buckshot Roulette** by Mike Klubnika inspired NumPlay's Buckshot Roulette, whose scenes are rendered from the game through the Open Buckshot Roulette project (1503Dev). Fonts: Fake Receipt by Ray Larabie and Dot Matrix by Dionaea.
- The **Doodle Champion Island Games** (2021) inspired Champion Island, which uses the doodle's own pictures, maps and texts from the [Google-Doodle-Champion-Island](https://github.com/potherca-blog/Google-Doodle-Champion-Island) archive by potherca-blog, and the **PixelMplus** font by Itou Hiroki ([license](LICENSES/PixelMplus.txt)).
- **[Portal Returns](https://www.cemetech.net/downloads/files/1313/x1313)** by MateoConLechuga for the TI-84 Plus CE, with sprites by CKH4 and Portal Prelude chambers ported by Unicorn from BuilderBoy's original.
@@ -403,4 +436,4 @@ NumPlay is licensed under the [GNU General Public License v3.0](LICENSE). Copyri
Code and fonts from others keep their own licenses: the `UNLICENSE` files in the games' folders and the [LICENSES](LICENSES) folder. The names, artwork and music of the games NumPlay is inspired by belong to their makers and are not covered by it.
-<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper). Tetris is a trademark of The Tetris Company, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco and Connect Four of Hasbro.</sub>
+<sub>Unofficial fan games, not affiliated with NumWorks, RobTop Games (Geometry Dash), Hipster Whale (Crossy Road), the makers of Drive Mad, LocalThunk or Playstack (Balatro), Mike Klubnika or Critical Reflex (Buckshot Roulette), Mojang or Microsoft (Minecraft), Maddy Makes Games (Celeste), Team Cherry (Hollow Knight), Florian van Strien (The Final Earth 2), MateoConLechuga (Portal Returns), Valve (Portal), .GEARS (Flappy Bird), Bandai Namco (Pac-Man), Hasbro (Connect Four), Google (Snake, Solitaire, Block Breaker, Doodle Champion Island Games), STUDIO4°C or Microsoft (Minesweeper). Tetris is a trademark of The Tetris Company, Minecraft of Mojang Synergies AB, Pac-Man of Bandai Namco and Connect Four of Hasbro.</sub>
diff --git a/docs/media/finalearth2.gif b/docs/media/finalearth2.gif
new file mode 100644
index 00000000..2869258a
Binary files /dev/null and b/docs/media/finalearth2.gif differ
diff --git a/docs/media/thumb_finalearth2.png b/docs/media/thumb_finalearth2.png
new file mode 100644
index 00000000..6502cf33
Binary files /dev/null and b/docs/media/thumb_finalearth2.png differ
diff --git a/docs/play.md b/docs/play.md
index 8418be0b..38acf3cc 100644
--- a/docs/play.md
+++ b/docs/play.md
@@ -116,6 +116,29 @@ Choose Climb, then a chapter, then Start. Madeline can dash once in the air (twi
<br clear="right">
+## The Final Earth 2
+
+<img src="media/finalearth2.gif" width="320" align="right" alt="The Final Earth 2: building a house on a city in free play">
+
+The Final Earth 2 comes as its own app, `FinalEarth2.nwa`: it is too big to share the calculator with NumPlay.
+
+| Key | What it does |
+| --- | --- |
+| **Arrows** | Move the cursor, or the focus in menus and windows |
+| **shift** + **arrows** | Move the view faster |
+| **OK** | Open what is under the cursor, choose, build here |
+| **Back** | Close, stop building, open the game menu |
+| **toolbox** | Open or close the build menu |
+| **var** | Go to the buttons and materials at the bottom right, and back |
+| **alpha** | Pause |
+| **+** and **-** | Zoom in and out |
+| **⌫** | Destroy the building under the cursor |
+| **Home** | Save and quit |
+
+Choose a scenario or a free play map. Build woodcutters and stone mines for materials, farms for food and houses for your citizens; buildings stack on top of each other. In the build menu, left and right go through the buildings, up and down change the category, and **OK** picks one; then **OK** builds where the cursor is, and **Back** goes back to the menu. Each goal of a scenario tells you what to do next, and **?** shows it again. On the speed button, **OK** switches between normal and double speed, and **shift** with **OK** goes through all five speeds. Home saves and quits, and the title then offers Continue. Your city is also copied into `finalearth2_saves.py`, so installing the app again doesn't erase it.
+
+<br clear="right">
+
## NumDrive
<img src="media/numdrive.gif" width="320" align="right" alt="NumDrive gameplay">
diff --git a/games/finalearth2/.gitignore b/games/finalearth2/.gitignore
new file mode 100644
index 00000000..342d9dda
--- /dev/null
+++ b/games/finalearth2/.gitignore
@@ -0,0 +1,2 @@
+output/
+build/
diff --git a/games/finalearth2/Makefile b/games/finalearth2/Makefile
new file mode 100644
index 00000000..42023ce1
--- /dev/null
+++ b/games/finalearth2/Makefile
@@ -0,0 +1,96 @@
+# The Final Earth 2 on the NumWorks calculator.
+# make output/finalearth2.nwa
+# make check link it like the calculator does (output/finalearth2.bin)
+# make host build/play: the game on a computer, for tests and screenshots
+# make test the simulation, stories, saves and buildings, checked on a computer (with the sanitizers)
+# make render build/render: drawing tests, run; images in build/shots
+# make data src/data.bin and src/data.h from the original's web files (REF=their folder, Python + Pillow)
+Q ?= @
+# the ARM toolchain on the PATH, or in TOOLCHAIN=<its bin folder>
+TOOLCHAIN ?=
+BIN = $(if $(TOOLCHAIN),$(TOOLCHAIN)/)
+CC = $(BIN)arm-none-eabi-gcc
+NWLINK ?= npx --yes -- [email protected]
+STRIP ?= $(BIN)arm-none-eabi-strip --strip-unneeded
+SIZE = $(BIN)arm-none-eabi-size
+BUILD_DIR = output
+REF ?=
+
+# the drawing runs every frame at -O2; the rest is small at -Os
+HOT = src/gfx.c src/bg.c
+COLD = $(filter-out $(HOT) src/plat_host.c src/plat_eadk.c,$(wildcard src/*.c))
+COLD_OBJ = $(patsubst src/%.c,$(BUILD_DIR)/cold/%.o,$(COLD))
+HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
+
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DDATA_BIN='"src/data.bin"'
+CFLAGS += -O2 -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
+CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
+CFLAGS += -ffunction-sections -fdata-sections $(EXTRA)
+LDFLAGS = -Wl,--relocatable -nostartfiles --specs=nano.specs
+LDFLAGS += -Wl,-e,main -Wl,-u,eadk_app_name -Wl,-u,eadk_app_icon -Wl,-u,eadk_api_level
+LDFLAGS += -Wl,--gc-sections -flinker-output=nolto-rel
+
+.PHONY: build check clean host test render data
+build: $(BUILD_DIR)/finalearth2.nwa
+
+# apps get 133652 bytes of RAM on custom builds of Epsilon 25.2 (148928 or more on official ones)
+check: $(BUILD_DIR)/finalearth2.nwa
+ $(Q) $(NWLINK) nwa-bin --ram-length 133652 $< $(BUILD_DIR)/finalearth2.bin
+ @echo "BIN $(BUILD_DIR)/finalearth2.bin: $$(wc -c < $(BUILD_DIR)/finalearth2.bin) bytes"
+
+$(BUILD_DIR)/data.o: src/data.S src/data.bin | $(BUILD_DIR)
+ $(Q) $(CC) -c -DDATA_BIN='"src/data.bin"' $< -o $@
+
+$(BUILD_DIR)/cold/%.o: src/%.c $(HEADERS)
+ @mkdir -p $(@D)
+ $(Q) $(CC) $(CFLAGS) -Os -c $< -o $@
+
+$(BUILD_DIR)/finalearth2.nwa: $(HOT) src/plat_eadk.c $(COLD_OBJ) $(HEADERS) $(BUILD_DIR)/icon.o $(BUILD_DIR)/data.o
+ @echo "LD $@"
+ $(Q) $(CC) $(CFLAGS) $(LDFLAGS) $(HOT) src/plat_eadk.c $(COLD_OBJ) $(BUILD_DIR)/data.o $(BUILD_DIR)/icon.o -lm -o $@
+ $(Q) $(STRIP) $@
+ $(Q) $(SIZE) $@
+
+$(BUILD_DIR)/icon.o: src/icon.png | $(BUILD_DIR)
+ @echo "ICON $<"
+ $(Q) $(NWLINK) png-icon-o $< $@
+
+$(BUILD_DIR):
+ $(Q) mkdir -p $@
+
+HOST_FLAGS = -std=gnu11 -O1 -g -Wall -Wextra -Wno-unused-parameter -Isrc -DHOST -DDATA_BIN='"src/data.bin"'
+HOST_SAN = -fsanitize=address,undefined -fno-sanitize-recover=undefined
+HOST_SRC = $(filter-out src/plat_eadk.c,$(wildcard src/*.c))
+host: build/play
+build/play: $(HOST_SRC) tests/play.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(HOST_SRC) tests/play.c src/data.S -lm -o $@
+ @echo "HOST $@"
+
+# drawing tests (tests/render.c): only the renderer and the backdrop
+RENDER_SRC = src/gfx.c src/bg.c src/plat_host.c
+render: build/render
+ $(Q) ./build/render build/shots
+build/render: $(RENDER_SRC) tests/render.c src/data.S src/data.bin src/gfx.h src/bg.h src/data.h src/plat.h
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(RENDER_SRC) tests/render.c src/data.S -lm -o $@
+ @echo "HOST $@"
+
+# the tests without the interface (tests/noui.c stands in for it); bldtest has its own stand-ins
+TEST_SRC = $(filter-out src/plat_eadk.c src/game.c $(wildcard src/ui*.c),$(wildcard src/*.c))
+test: build/storytest build/savetest build/simtest build/bldtest
+ $(Q) ./build/storytest > /dev/null && ./build/simtest > /dev/null && ./build/savetest build/savetest_out \
+ && ./build/bldtest | tail -1
+build/storytest build/savetest build/simtest: build/%: $(TEST_SRC) tests/%.c tests/noui.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(TEST_SRC) tests/$*.c tests/noui.c src/data.S -lm -o $@
+build/bldtest: $(TEST_SRC) tests/bldtest.c src/data.S src/data.bin $(HEADERS)
+ $(Q) mkdir -p $(dir $@)
+ $(Q) cc $(HOST_FLAGS) $(HOST_SAN) $(TEST_SRC) tests/bldtest.c src/data.S -lm -o $@
+
+data:
+ @test -n "$(REF)" || { echo "make data REF=<the folder of the original's web files>"; exit 1; }
+ python3 -I tools/pack.py $(REF)
+
+clean:
+ $(Q) rm -rf $(BUILD_DIR) build
diff --git a/games/finalearth2/README.md b/games/finalearth2/README.md
new file mode 100644
index 00000000..b3378851
--- /dev/null
+++ b/games/finalearth2/README.md
@@ -0,0 +1,93 @@
+> **The Final Earth 2 is a [NumPlay](../../README.md) game that comes on its own.** It is too big to fit next to NumPlay on the calculator. Get `FinalEarth2.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+<p align="center">
+ <img src="src/icon.png" width="84" alt="The Final Earth 2 icon">
+</p>
+
+<h1 align="center">The Final Earth 2</h1>
+
+<p align="center">
+ <b>Build a city on floating islands in space, on the NumWorks calculator.</b><br>
+ All four scenarios and the six free play maps of the free version.
+</p>
+
+<p align="center">
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/FinalEarth2.nwa"><b>Download FinalEarth2.nwa</b></a>
+ &nbsp;·&nbsp; <a href="#controls">Controls</a>
+</p>
+
+<p align="center">
+ <img src="../../docs/media/finalearth2.gif" width="640" alt="The Final Earth 2: building a city on a floating island">
+</p>
+
+## Highlights
+
+* **Every scenario:** A New Beginning, An Interworld City, Hacking Alien Tech and City of the Key, with their goals, stories and tutorials.
+* **Free play:** Mega World, Random Archipelago, Empty Canvas, Divided, Random Mini Worlds and Many Worlds, with the starting resources and citizens you choose.
+* **Every building:** 87 of them, from houses, farms and woodcutters to labs, factories, teleporters, parks, restaurants and the alien buildings, each with its upgrades.
+* **Citizens live their lives:** they walk to work and to school, eat, look for fun after work, have children, grow old, and pick up hobbies.
+* **Research, upgrades and policies:** the same costs and effects as the original, down to the numbers.
+* **The game's look:** its own pictures, fonts, sky, planets, clouds and floating islands, day and night.
+* **Saved as you go:** Home saves and quits, the game saves every other day, and Continue picks up where you left off. Your city is also copied into `finalearth2_saves.py`, so installing the app again doesn't erase it.
+
+<table>
+ <tr>
+ <td align="center"><img src="docs/lostship.png" width="390" alt="A New Beginning: the ship's tiny world"><br><sub>A New Beginning: the first scenario</sub></td>
+ <td align="center"><img src="docs/city.png" width="390" alt="A city on Mega World"><br><sub>A city on Mega World, in free play</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/build.png" width="390" alt="Building a house"><br><sub>Building: the places a house can go are outlined</sub></td>
+ <td align="center"><img src="docs/house.png" width="390" alt="A house's window"><br><sub>A house's window, with its upgrade</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/happiness.png" width="390" alt="The happiness window"><br><sub>What makes your citizens happy</sub></td>
+ <td align="center"><img src="docs/night.png" width="390" alt="The city at night"><br><sub>The same city at night</sub></td>
+ </tr>
+ <tr>
+ <td align="center"><img src="docs/key.png" width="390" alt="City of the Key"><br><sub>City of the Key</sub></td>
+ <td align="center"><img src="docs/title.png" width="390" alt="The title screen"><br><sub>The title screen</sub></td>
+ </tr>
+</table>
+
+## How to play
+
+Choose a scenario, or a free play map. Your citizens need homes, food and work: build woodcutters and stone mines for materials, farms for food, and houses to live in. Buildings stack on top of each other, so your city grows up as well as out. In a scenario, each goal tells you what to do next, and **?** at the bottom right shows the current one again.
+
+Move the cursor with the arrows. Press **toolbox** to open the build menu: left and right go through the buildings, up and down change the category, and **OK** picks one. Then move to where you want it and press **OK** to build; **Back** goes back to the menu to pick another. Press **OK** on a building to see what it does, upgrade it, or see who lives and works there. Press **var** to reach the buttons and materials at the bottom right: population, happiness, speed, pause and the menu.
+
+## Controls
+
+| Key | What it does |
+| --- | --- |
+| Arrows | Move the cursor, or the focus in menus and windows |
+| shift + arrows | Move the view faster |
+| OK | Open what is under the cursor, choose, build here |
+| Back | Close, stop building, open the game menu |
+| toolbox | Open or close the build menu |
+| var | Go to the buttons and materials at the bottom right, and back |
+| alpha | Pause |
+| + and - | Zoom in and out |
+| ⌫ | Destroy the building under the cursor |
+| Home | Save and quit |
+
+On the speed button, **OK** switches between normal and double speed, and **shift** with **OK** goes through all five speeds. While building, hold **OK** and move to build on every cell you pass, in the building modes that allow it. When the game asks for a name, type it with **alpha** (twice to keep letters on), or pick letters from the grid on screen.
+
+## Good to know
+
+* **On its own:** The Final Earth 2 is too big to fit next to NumPlay. Installing it from the NumWorks website swaps out NumPlay and the other apps, and installing NumPlay again swaps it back out. Your city in each one is kept.
+* **The free version's content:** the premium and holiday buildings and scenarios are not here, and there is no music or sound (the calculator has no speaker).
+* **A few limits:** a city holds up to 800 citizens and 700 buildings, and Random Mini Worlds makes 63 worlds instead of 400, so they fit in the calculator's memory.
+* **No ads:** the original's production boost from watching an ad is left out.
+
+## Credits
+
+Inspired by [The Final Earth 2](https://store.steampowered.com/app/1180130/The_Final_Earth_2/) by [Florian van Strien](https://florianvanstrien.nl), not affiliated with him. Go play the original: it's on Steam, Android, iOS and the web, with music, the premium scenarios and more.
+
+* The pictures, fonts, texts and citizens' names come from the game's own files, and its rules, numbers and the way citizens find their way follow the game's own code.
+* Additional sprites by LukXD99, as in the original's credits.
+
+Made by Mason Chen as part of NumPlay.
+
+## License
+
+The game's code is licensed under the GNU General Public License v3.0: see the `LICENSE` file at the root of the repository. The game's pictures, fonts and texts keep their own terms (see Credits).
diff --git a/games/finalearth2/docs/build.png b/games/finalearth2/docs/build.png
new file mode 100644
index 00000000..838a612c
Binary files /dev/null and b/games/finalearth2/docs/build.png differ
diff --git a/games/finalearth2/docs/city.png b/games/finalearth2/docs/city.png
new file mode 100644
index 00000000..d807d3a4
Binary files /dev/null and b/games/finalearth2/docs/city.png differ
diff --git a/games/finalearth2/docs/happiness.png b/games/finalearth2/docs/happiness.png
new file mode 100644
index 00000000..5a02a1a9
Binary files /dev/null and b/games/finalearth2/docs/happiness.png differ
diff --git a/games/finalearth2/docs/house.png b/games/finalearth2/docs/house.png
new file mode 100644
index 00000000..82af2fcd
Binary files /dev/null and b/games/finalearth2/docs/house.png differ
diff --git a/games/finalearth2/docs/key.png b/games/finalearth2/docs/key.png
new file mode 100644
index 00000000..89ed827e
Binary files /dev/null and b/games/finalearth2/docs/key.png differ
diff --git a/games/finalearth2/docs/lostship.png b/games/finalearth2/docs/lostship.png
new file mode 100644
index 00000000..6ac311dd
Binary files /dev/null and b/games/finalearth2/docs/lostship.png differ
diff --git a/games/finalearth2/docs/night.png b/games/finalearth2/docs/night.png
new file mode 100644
index 00000000..013974da
Binary files /dev/null and b/games/finalearth2/docs/night.png differ
diff --git a/games/finalearth2/docs/title.png b/games/finalearth2/docs/title.png
new file mode 100644
index 00000000..5254ff87
Binary files /dev/null and b/games/finalearth2/docs/title.png differ
diff --git a/games/finalearth2/src/assign.c b/games/finalearth2/src/assign.c
new file mode 100644
index 00000000..0e1404c8
--- /dev/null
+++ b/games/finalearth2/src/assign.c
@@ -0,0 +1,453 @@
+/* The Final Earth 2: who works, lives and studies where
+ * (simulation.JobAssigner, HouseAssigner, SchoolAssigner) and the search for
+ * the best place near a building (pathfinder.PermanentFinder). */
+#include "sim.h"
+#include "bld.h"
+#include "scratch.h"
+#define prio (scratch->prio)
+#define seen (scratch->seen)
+
+/* ---------------------------------------------------------------- PermanentFinder.query
+ * a search over the buildings' neighbours, teleporters, landing sites,
+ * elevators and worlds' surfaces from a permanent (or a world's x), for the
+ * goal with the highest niceness (the first goal reached when there is no
+ * niceness), stopping at one as nice as best_expected */
+typedef bool (*IsGoal)(const Perm *p, const void *ctx);
+typedef float (*Niceness)(const Perm *p);
+#define no_elevators (scratch->no_elevators) /* dontCheckElevators */
+static int finder_queries; /* this tick (canPerformQuery) */
+static int finder_limit_for;
+
+static void finder_relax(uint16_t to, float np, float max_distance) {
+ if (seen[to] == 1) {
+ if (np < prio[to]) {
+ prio[to] = np;
+ heap_up(heap_index(to));
+ }
+ } else if (seen[to] != 2 && (max_distance < 0 || np <= max_distance)) {
+ seen[to] = 1;
+ prio[to] = np;
+ heap_push(to);
+ }
+}
+
+uint16_t finder_query(uint16_t from, int from_world, float from_x, IsGoal is_goal, const void *ctx, Niceness niceness,
+ float max_distance, const Cit *citizen, float best_expected) {
+ memset(seen, 0, sizeof seen);
+ memset(no_elevators, 0, sizeof no_elevators);
+ heap_n = 0;
+ finder_queries++;
+ if (from) {
+ prio[from] = 0;
+ seen[from] = 1;
+ heap_push(from);
+ } else {
+ World *w = &worlds[from_world];
+ for (int x = 0; x < w->ncols; x++) {
+ uint16_t b = perm_at(from_world, x, 0);
+ if (!b) continue;
+ float pr = fabsf(perm_city_x(P(b)) - from_x);
+ if (max_distance >= 0 && pr > max_distance) continue;
+ prio[b] = pr;
+ seen[b] = 1;
+ heap_push(b);
+ }
+ }
+ float max_nice = -10000;
+ uint16_t best = NONE;
+ bool tp_done = !operating_cost.teleportersEnabled;
+ static uint8_t ls_done[64];
+ memset(ls_done, 0, sizeof ls_done);
+ uint16_t private_tp = (citizen && citizen->home && bld_has_private_teleporter(P(citizen->home))) ? citizen->home : NONE;
+ while (heap_n) {
+ uint16_t cur = heap_pop();
+ Perm *p = &perms[cur];
+ seen[cur] = 2;
+ if (is_goal(p, ctx)) {
+ if (niceness) {
+ float n = niceness(p);
+ if (n >= best_expected) return cur;
+ if (n > max_nice) best = cur, max_nice = n;
+ } else {
+ return cur;
+ }
+ }
+ if (is_building(p)) {
+ if (p->left) finder_relax(p->left, prio[cur] + 20, max_distance);
+ if (p->right) finder_relax(p->right, prio[cur] + 20, max_distance);
+ if (p->top) finder_relax(p->top, prio[cur] + 20, max_distance);
+ if (p->bottom) finder_relax(p->bottom, prio[cur] + 20, max_distance);
+ }
+ bool is_private = cur == private_tp;
+ if ((is_a(p, B_TELEPORTER) || is_private) && !tp_done) {
+ float r = rnd_range(0, 2);
+ int len = 0;
+ for (int j = 1; j < MAX_PERMS; j++)
+ if ((perms[j].flags & PF_USED) && is_a(&perms[j], B_TELEPORTER)) len++;
+ float inv = len ? 2.0f / len : 0;
+ int t = 0;
+ for (int j = 1; j < MAX_PERMS; j++)
+ if ((perms[j].flags & PF_USED) && is_a(&perms[j], B_TELEPORTER))
+ finder_relax((uint16_t)j, prio[cur] + 9 + fmodf(r + t++ * inv, 2.0f), max_distance);
+ if (!is_private && private_tp) finder_relax(private_tp, prio[cur] + 10, max_distance);
+ tp_done = true;
+ } else if (is_a(p, B_LANDINGSITE) && landing_group_of[cur] && landing_group_of[cur] <= 64 && !ls_done[landing_group_of[cur] - 1]) {
+ for (int j = 1; j < MAX_PERMS; j++)
+ if (landing_group_of[j] == landing_group_of[cur])
+ finder_relax((uint16_t)j, prio[cur] + bld_flying_distance(P((uint16_t)j), p), max_distance);
+ ls_done[landing_group_of[cur] - 1] = 1;
+ } else if (is_a(p, B_ELEVATOR) && !no_elevators[cur]) {
+ int h = col_stack_height(p->world, p->col);
+ for (int y = 0; y < h; y++) {
+ Perm *e = P(perm_at(p->world, p->col, y));
+ if (!e || !is_a(e, B_ELEVATOR)) continue;
+ finder_relax(pid(e), prio[cur] + abs((int)e->row - (int)p->row), max_distance);
+ no_elevators[pid(e)] = 1;
+ }
+ }
+ if (p->row == 0) {
+ World *w = &worlds[p->world];
+ for (int x = 0; x < w->ncols; x++) {
+ uint16_t b = perm_at(p->world, x, 0);
+ if (b) finder_relax(b, prio[cur] + fabsf(20.0f * (x - p->col)), max_distance);
+ }
+ }
+ }
+ return best;
+}
+static uint16_t finder_query_for_citizen(const Cit *c, IsGoal is_goal, const void *ctx, Niceness niceness, float max_distance, bool quick) {
+ if (c->inPermanent) return finder_query(c->inPermanent, 0, 0, is_goal, ctx, niceness, max_distance, quick ? NULL : c, 1e8f);
+ return finder_query(NONE, c->onWorld, c->relativeX, is_goal, ctx, niceness, max_distance, quick ? NULL : c, 1e8f);
+}
+
+/* quickQueryForCitizen: the result is kept for expiry_hours for queries from about the same place */
+#define QCACHE 48
+static struct { uint8_t world, x, y, key; uint16_t perm; float expiry; } qcache[QCACHE];
+static int qcache_next;
+uint16_t finder_quick_query(const Cit *c, IsGoal is_goal, const void *ctx, uint8_t key, float expiry_hours, Niceness niceness,
+ float max_distance) {
+ int xi, yi;
+ if (c->inPermanent) xi = P(c->inPermanent)->col, yi = P(c->inPermanent)->row / 5;
+ else xi = (int)c->relativeX / 20, yi = 0;
+ float now = (float)city.timeSinceStart;
+ for (int i = 0; i < QCACHE; i++) {
+ if (qcache[i].key != key || qcache[i].world != c->onWorld || qcache[i].x != xi || qcache[i].y != yi) continue;
+ if (now < qcache[i].expiry) return qcache[i].perm;
+ if (qcache[i].perm && (perms[qcache[i].perm].flags & PF_USED) && is_goal(P(qcache[i].perm), ctx)) {
+ qcache[i].expiry += expiry_hours * 60;
+ return qcache[i].perm;
+ }
+ uint16_t f = finder_query_for_citizen(c, is_goal, ctx, niceness, max_distance, true);
+ qcache[i].perm = f;
+ qcache[i].expiry = now + expiry_hours * 60;
+ return f;
+ }
+ uint16_t f = finder_query_for_citizen(c, is_goal, ctx, niceness, max_distance, true);
+ int i = qcache_next++ % QCACHE;
+ qcache[i].key = key, qcache[i].world = c->onWorld, qcache[i].x = (uint8_t)xi, qcache[i].y = (uint8_t)yi;
+ qcache[i].perm = f;
+ qcache[i].expiry = now + expiry_hours * 60;
+ return f;
+}
+void finder_invalidate(void) { memset(qcache, 0, sizeof qcache); }
+void finder_pre_update(void) {
+ finder_queries = 0;
+ if (finder_limit_for > 0) finder_limit_for--;
+}
+bool finder_can_query(void) { return finder_limit_for > 0 ? finder_queries < 10 : true; }
+void finder_request_limiting(bool strict_first) {
+ finder_limit_for = 120;
+ if (strict_first) finder_queries = 10;
+}
+
+/* ---------------------------------------------------------------- homes */
+static uint16_t cit_shard(const Cit *c) { return c->inPermanent ? P(c->inPermanent)->shard : worlds[c->onWorld].surfaceShard; }
+static int remaining_home(const Perm *p) { return bld_residents(p) - p->nresidents; }
+static bool home_with_room(const Perm *p) {
+ if (!is_a(p, B_HOUSE) || remaining_home(p) <= 0) return false;
+ int fixed = bld_fixed_capacity_for_workers(p);
+ return fixed == 0 || p->nworkers >= fixed;
+}
+static bool goal_home_shard(const Perm *p, const void *ctx) { return home_with_room(p) && p->shard == *(const uint16_t *)ctx; }
+static bool goal_home_shard_or_tp(const Perm *p, const void *ctx) {
+ return goal_home_shard(p, ctx) || (is_a(p, B_TELEPORTER) && operating_cost.teleportersEnabled);
+}
+static float home_niceness(const Perm *p) { return bld_attractiveness(p); }
+static float home_niceness_tp(const Perm *p) { return is_a(p, B_TELEPORTER) ? 100 : bld_attractiveness(p); }
+
+#define private_tp_left (scratch->u.assign.tp_left) /* per shard */
+
+/* the best home among all permanents (whereMaxWithMax) */
+static uint16_t best_home_anywhere(IsGoal goal, const void *ctx, Niceness nice, float stop_at) {
+ uint16_t best = NONE;
+ float bn = -1e30f;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || !goal(p, ctx)) continue;
+ float n = nice(p);
+ if (n >= stop_at) return (uint16_t)i;
+ if (n > bn) bn = n, best = (uint16_t)i;
+ }
+ return best;
+}
+
+/* HouseAssigner's search for a home for one citizen */
+static void find_home(Cit *c) {
+ if (c->home) return;
+ uint16_t shard = cit_shard(c), newhome = NONE;
+ if (shard < MAX_SHARDS && private_tp_left[shard] > 0) {
+ if (c->job) {
+ uint16_t js = P(c->job)->shard;
+ newhome = finder_query(c->job, 0, 0, goal_home_shard_or_tp, &js, home_niceness_tp, -1, NULL, 99.999999f);
+ } else {
+ newhome = best_home_anywhere(goal_home_shard_or_tp, &shard, home_niceness_tp, 99.999999f);
+ }
+ if (newhome && is_a(P(newhome), B_TELEPORTER)) {
+ newhome = NONE;
+ for (int i = 1; i < MAX_PERMS && !newhome; i++) {
+ Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && is_a(p, B_HOUSE) && p->shard == shard && bld_has_private_teleporter(p) && home_with_room(p))
+ newhome = (uint16_t)i;
+ }
+ }
+ } else if (c->job) {
+ uint16_t js = P(c->job)->shard;
+ newhome = finder_query(c->job, 0, 0, goal_home_shard, &js, home_niceness, -1, NULL, 99.999999f);
+ } else {
+ newhome = best_home_anywhere(goal_home_shard, &shard, home_niceness, 99.999999f);
+ }
+ if (newhome) {
+ c->home = newhome;
+ P(newhome)->nresidents++;
+ if (bld_has_private_teleporter(P(newhome)) && shard < MAX_SHARDS) private_tp_left[shard]--;
+ }
+}
+
+void assign_houses(void) {
+ if (!(sim_flags & SIM_HOUSES_CHANGED)) return;
+ static uint16_t people[101], places[101], transfer[101];
+ memset(scratch->u.assign.tp_left, 0, sizeof scratch->u.assign.tp_left);
+ uint16_t nshards = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].shard + 1 > nshards) nshards = (uint16_t)(perms[i].shard + 1);
+ for (int w = 0; w < nworlds; w++)
+ if (worlds[w].surfaceShard + 1 > nshards) nshards = (uint16_t)(worlds[w].surfaceShard + 1);
+ /* each home's residents who may move (not forced to live there) */
+ uint8_t *movable = scratch->u.assign.movable;
+ memset(movable, 0, MAX_PERMS);
+ for (int j = 1; j < MAX_CITS; j++)
+ if ((cits[j].flags & CF_ALIVE) && cits[j].home && !(cits[j].flags & CF_FORCED_HOME)) movable[cits[j].home]++;
+ for (uint16_t sh = 0; sh < nshards; sh++) {
+ /* people in worse homes move to better ones with room */
+ memset(people, 0, sizeof people);
+ memset(places, 0, sizeof places);
+ memset(transfer, 0, sizeof transfer);
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->shard != sh || !is_a(p, B_HOUSE)) continue;
+ float a = bld_attractiveness(p);
+ int q = (int)(a < 0 ? 0 : a > 100 ? 100 : a);
+ if (is_a(p, B_WORK)) continue; /* WorkWithHome */
+ if (bld_has_private_teleporter(p) && remaining_home(p) > 0 && a > 99.9f && sh < MAX_SHARDS) private_tp_left[sh]++;
+ people[q] = (uint16_t)(people[q] + movable[i]);
+ places[q] = (uint16_t)(places[q] + remaining_home(p));
+ }
+ int cp = 0, cpl = 100;
+ while (cp < cpl) {
+ while (cp < cpl && people[cp] > 0) {
+ int t = people[cp] < places[cpl] ? people[cp] : places[cpl];
+ transfer[cp] = (uint16_t)(transfer[cp] + t);
+ places[cpl] = (uint16_t)(places[cpl] - t);
+ people[cp] = (uint16_t)(people[cp] - t);
+ cpl--;
+ }
+ cp++;
+ }
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->shard != sh || !is_a(p, B_HOUSE)) continue;
+ float a = bld_attractiveness(p);
+ int q = (int)(a < 0 ? 0 : a > 100 ? 100 : a);
+ if (!transfer[q]) continue;
+ for (int j = MAX_CITS - 1; j >= 1; j--) {
+ Cit *c = &cits[j];
+ if ((c->flags & CF_ALIVE) && c->home == i && transfer[q] > 0 && !(c->flags & CF_FORCED_HOME)) {
+ cit_evict_from_home(c);
+ transfer[q]--;
+ }
+ }
+ }
+ }
+ uint8_t *impossible = scratch->u.assign.impossible;
+ memset(impossible, 0, MAX_SHARDS);
+ for (int j = 1; j < MAX_CITS; j++) {
+ Cit *c = &cits[j];
+ if (!(c->flags & CF_ALIVE)) continue;
+ uint16_t sh = cit_shard(c);
+ if (sh < MAX_SHARDS && impossible[sh]) continue;
+ find_home(c);
+ if (!c->home && sh < MAX_SHARDS) impossible[sh] = 1;
+ }
+ sim_flags &= (uint8_t)~SIM_HOUSES_CHANGED;
+}
+
+/* ---------------------------------------------------------------- jobs */
+int priority_jobs[64]; /* per class: workers wanted first (1000000: all of them); set by the worker distribution window */
+static bool max_prio(int cls) { return cls < 64 && priority_jobs[cls] == 1000000; }
+
+void assign_jobs(void) {
+ if (story_is("cityofthekey")) {
+ int c = pcls_find("SecretSocietyHouse");
+ if (c >= 0 && c < 64) priority_jobs[c] = 8;
+ }
+ if (!(sim_flags & SIM_JOBS_CHANGED)) return;
+ int16_t *short_by = scratch->u.assign.short_by;
+ memset(short_by, 0, sizeof scratch->u.assign.short_by);
+ for (int k = 0; k < 64 && k < npcls; k++) short_by[k] = max_prio(k) ? 0 : priority_jobs[k];
+ uint16_t *with_job = scratch->u.assign.list;
+ int nwj = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || !is_a(p, B_WORK)) continue;
+ if (p->nworkers < bld_jobs(p)) with_job[nwj++] = (uint16_t)i;
+ if (max_prio(p->cls)) short_by[p->cls] += bld_jobs(p);
+ short_by[p->cls] -= p->nworkers;
+ }
+ bool prio_mode = false;
+ for (int k = 0; k < npcls && k < 256; k++)
+ if (short_by[k] > 0) prio_mode = true;
+ bool anyone_without = false;
+ for (int j = 1; j < MAX_CITS; j++)
+ if ((cits[j].flags & CF_ALIVE) && (cits[j].flags & CF_WITHOUT_JOB)) { anyone_without = true; break; }
+ if (!prio_mode && !anyone_without) {
+ sim_flags &= (uint8_t)~SIM_JOBS_CHANGED;
+ return;
+ }
+ bool cotk = story_is("cityofthekey");
+ int secret = cotk ? pcls_find("SecretSocietyHouse") : -1;
+ uint8_t *shard_no_options = scratch->u.assign.shard_no_options;
+ memset(shard_no_options, 0, MAX_SHARDS);
+ bool need_sort = true, any = true;
+ while (any) {
+ any = false;
+ if (need_sort) {
+ /* fewest workers first (a stable insertion sort, as the original's merge sort) */
+ for (int i = 1; i < nwj; i++) {
+ uint16_t k = with_job[i];
+ int j = i - 1;
+ while (j >= 0) {
+ Perm *a = P(with_job[j]), *b = P(k);
+ bool b_first = cotk && (int)b->cls == secret && (int)a->cls != secret;
+ bool a_first = cotk && (int)a->cls == secret;
+ if (!b_first && (a_first || a->nworkers <= b->nworkers)) break;
+ with_job[j + 1] = with_job[j];
+ j--;
+ }
+ with_job[j + 1] = k;
+ }
+ need_sort = false;
+ }
+ for (int bi = 0; bi < nwj; bi++) {
+ Perm *b = P(with_job[bi]);
+ if (b->nworkers >= bld_jobs(b)) continue;
+ if (prio_mode && short_by[b->cls] <= 0) continue;
+ Cit *best = NULL;
+ for (int j = 1; j < MAX_CITS; j++) {
+ Cit *c = &cits[j];
+ if ((c->flags & CF_ALIVE) && (c->flags & CF_WITHOUT_JOB) && cit_shard(c) == b->shard) { best = c; break; }
+ }
+ if (prio_mode && !best) {
+ if (b->shard < MAX_SHARDS && !shard_no_options[b->shard]) {
+ Perm *fire = NULL;
+ int fw = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *w = &perms[i];
+ if (!(w->flags & PF_USED) || !is_a(w, B_WORK)) continue;
+ if (w->shard == b->shard && w->nworkers > fw && short_by[w->cls] < 0) fire = w, fw = w->nworkers;
+ }
+ if (fire && fire->nworkers > 0) {
+ /* the last of its workers */
+ for (int j = MAX_CITS - 1; j >= 1 && !best; j--)
+ if ((cits[j].flags & CF_ALIVE) && cits[j].job == pid(fire)) best = &cits[j];
+ cit_lose_job(best, true);
+ short_by[fire->cls]++;
+ } else if (b->shard < MAX_SHARDS) {
+ shard_no_options[b->shard] = 1;
+ }
+ }
+ }
+ if (best) {
+ any = true;
+ short_by[b->cls]--;
+ best->flags &= (uint16_t)~CF_WITHOUT_JOB;
+ best->job = pid(b);
+ b->nworkers++;
+ bld_after_give_job(b, best);
+ if (cit_shard(best) == b->shard && (!best->home || !bld_keeps_residents(P(best->home)))) {
+ cit_evict_from_home(best);
+ bool assigned = false;
+ if (is_a(b, B_HOUSE) && remaining_home(b) > 0) {
+ best->home = pid(b);
+ b->nresidents++;
+ assigned = true;
+ }
+ if (!best->home || (!assigned && bld_has_private_teleporter(P(best->home)))) find_home(best);
+ }
+ }
+ }
+ if (!any && prio_mode) {
+ any = true;
+ prio_mode = false;
+ need_sort = true;
+ }
+ }
+ sim_flags &= (uint8_t)~SIM_JOBS_CHANGED;
+}
+
+/* ---------------------------------------------------------------- schools */
+void assign_schools(void) {
+ if (!(sim_flags & SIM_SCHOOLS_CHANGED)) return;
+ uint16_t *schools = scratch->u.assign.list;
+ int ns = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && is_a(p, B_SCHOOL) && p->nstudents < bld_student_capacity(p) && p->nworkers > 0)
+ schools[ns++] = (uint16_t)i;
+ }
+ /* fewest students first */
+ for (int i = 1; i < ns; i++) {
+ uint16_t k = schools[i];
+ int j = i - 1;
+ while (j >= 0 && P(schools[j])->nstudents > P(k)->nstudents) schools[j + 1] = schools[j], j--;
+ schools[j + 1] = k;
+ }
+ bool any = true;
+ int left = 0;
+ for (int j = 1; j < MAX_CITS; j++)
+ if ((cits[j].flags & CF_ALIVE) && cit_age(&cits[j]) < 16 && !cits[j].school) left++;
+ while (left > 0 && any) {
+ any = false;
+ for (int i = ns - 1; i >= 0; i--) {
+ Perm *s = P(schools[i]);
+ Cit *st = NULL;
+ for (int j = 1; j < MAX_CITS && !st; j++) {
+ Cit *c = &cits[j];
+ if (!(c->flags & CF_ALIVE) || cit_age(c) >= 16 || c->school) continue;
+ if (cit_shard(c) == s->shard || (c->home && bld_has_private_teleporter(P(c->home)) && (worlds[s->world].flags & WF_HAS_TELEPORTER_ON_GROUP)))
+ st = c;
+ }
+ if (st) {
+ any = true;
+ left--;
+ st->school = pid(s);
+ s->nstudents++;
+ if (s->nstudents >= bld_student_capacity(s)) {
+ for (int k = i; k + 1 < ns; k++) schools[k] = schools[k + 1];
+ ns--;
+ }
+ }
+ if (left == 0) break;
+ }
+ }
+ sim_flags &= (uint8_t)~SIM_SCHOOLS_CHANGED;
+}
diff --git a/games/finalearth2/src/bg.c b/games/finalearth2/src/bg.c
new file mode 100644
index 00000000..d9f43cbd
--- /dev/null
+++ b/games/finalearth2/src/bg.c
@@ -0,0 +1,876 @@
+/* The backdrop and the worlds' islands (bg.h), ported from the original's
+ * CityTime, graphics.Stars, graphics.BackgroundImages, graphics.Cloud,
+ * graphics.WorldImage, graphics.GroundDecoration and World. */
+#include "bg.h"
+#include <math.h>
+#include <stdlib.h>
+#include <string.h>
+#include "data.h"
+
+#define W2 (SCREEN_W / 2)
+#define H2 (SCREEN_H / 2)
+
+static int floordiv(int a, int b) { return a >= 0 ? a / b : -((-a + b - 1) / b); }
+static int jsround(double v) { return (int)floor(v + 0.5); } /* Math.round */
+/* n / d as a double: the calculator's build reads constants such as 0.2 as floats
+ * (-fsingle-precision-constant), so the island's numbers are written as exact ratios */
+#define DBL(n, d) ((double)(n) / (double)(d))
+
+/* ---------------------------------------------------------------- random numbers */
+/* random.SeedeableRandom: xorshift128+ on Haxe's Int64 (its right shifts keep the sign) */
+typedef struct { uint64_t s0, s1; } SRand;
+
+static void srand_init(SRand *r, int32_t seed) {
+ r->s0 = (uint64_t)(int64_t)seed;
+ r->s1 = 89432;
+}
+
+static uint64_t srand_next(SRand *r) {
+ uint64_t s0 = r->s0, s1 = r->s1;
+ r->s0 = s1;
+ s1 ^= s1 << 23;
+ s1 ^= (uint64_t)((int64_t)s1 >> 18);
+ s1 ^= s0;
+ s1 ^= (uint64_t)((int64_t)s0 >> 5);
+ r->s1 = s1;
+ return r->s0 + r->s1;
+}
+
+/* getInt(min, max): min to max - 1 */
+static int srand_int(SRand *r, int min, int max) {
+ uint64_t v = srand_next(r) >> 1;
+ int64_t n = (int64_t)max - min;
+ if (n < 0) n = -n;
+ if (!n) return min; /* (the original throws) */
+ return min + (int)(v % (uint64_t)n);
+}
+
+/* getFloat(min, max) */
+static double srand_float(SRand *r, double min, double max) {
+ int32_t low = (int32_t)(uint32_t)srand_next(r);
+ return fabs(low / (double)2147483647) * (max - min) + min;
+}
+
+/* where the original uses Math.random (random.Random): the stars, the clouds, decorations */
+static SRand rng;
+static double rnd_float(double min, double max) { return srand_float(&rng, min, max); }
+static int rnd_int(int n) { return srand_int(&rng, 0, n); }
+
+/* ---------------------------------------------------------------- the sky's colour */
+/* CityTime.skyColors */
+static const struct { uint32_t color; float time; } sky_colors[] = {
+ {2626656, 0}, {2626656, 4}, {12541833, 6}, {12541833, 6.5f}, {11389183, 8.5f}, {11389183, 11},
+ {12247804, 13}, {12247804, 17}, {8872356, 20.5f}, {8872356, 21}, {2626656, 23}, {2626656, 24}};
+
+uint32_t bg_sky_color(float hour) {
+ int n = (int)(sizeof sky_colors / sizeof sky_colors[0]);
+ for (int i = 0; i + 1 < n; i++) {
+ if (hour < sky_colors[i + 1].time) {
+ uint32_t a = sky_colors[i].color, b = sky_colors[i + 1].color;
+ float t = (hour - sky_colors[i].time) / (sky_colors[i + 1].time - sky_colors[i].time);
+ uint32_t c = 0;
+ for (int sh = 16; sh >= 0; sh -= 8) {
+ float va = (float)(a >> sh & 255), vb = (float)(b >> sh & 255);
+ c |= (uint32_t)(int)(va + t * (vb - va)) << sh;
+ }
+ return c;
+ }
+ }
+ return sky_colors[0].color;
+}
+
+float bg_stars_alpha(float t) {
+ if (t >= 23 || t < 4) return 1;
+ if (t >= 4 && t < 6) return 1 - (t - 4) / 2;
+ if (t >= 21 && t < 23) return 1 - (23 - t) / 2;
+ return 0;
+}
+
+float bg_clouds_alpha(float t) {
+ float a;
+ if (t >= 21 || t < 4) a = 1;
+ else if (t >= 4 && t < 6) a = 1 - (t - 4) / 2;
+ else if (t >= 19.5f && t < 21.5f) a = 1 - (23 - t - 1.5f) / 2;
+ else a = 0;
+ a = (0.76923076923076916f - a) * 1.3f;
+ return a < 0 ? 0 : a > 1 ? 1 : a;
+}
+
+/* ---------------------------------------------------------------- stars */
+/* graphics.Stars: maxStarX * maxStarY / 1000 stars over an 800 x 800 field centred on the
+ * screen, which doesn't move with the view. Kept: the ones the screen can show at zoom 1
+ * (field x 240..559, y 280..519; zoom 2 shows a part of that). */
+#define STAR_FIELD 800
+#define STAR_X0 ((STAR_FIELD - SCREEN_W) / 2)
+#define STAR_Y0 ((STAR_FIELD - SCREEN_H) / 2)
+#define MAX_STARS 128
+typedef struct { uint16_t x; uint8_t y, alpha; uint16_t color; } Star;
+static Star stars[MAX_STARS];
+static int nstars;
+
+/* thx.color.Hsl._c */
+static double hsl_c(double d, double s, double l) {
+ double m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s, m1 = 2 * l - m2;
+ d = fmod(d, 360);
+ if (d < 0) d += 360;
+ if (d < 60) return m1 + (m2 - m1) * d / 60;
+ if (d < 180) return m2;
+ if (d < 240) return m1 + (m2 - m1) * (240 - d) / 60;
+ return m1;
+}
+
+static void make_stars(void) {
+ nstars = 0;
+ for (int i = 0; i < STAR_FIELD * STAR_FIELD / 1000; i++) {
+ rnd_int(STAR_FIELD); /* posX, posY: drawn, then not used */
+ rnd_int(STAR_FIELD);
+ double h = rnd_float(0, 360), s = rnd_float(0, 1), l = rnd_float(DBL(9, 10), 1);
+ uint32_t r = (uint32_t)jsround(hsl_c(h + 120, s, l) * 255) & 255, g = (uint32_t)jsround(hsl_c(h, s, l) * 255) & 255,
+ b = (uint32_t)jsround(hsl_c(h - 120, s, l) * 255) & 255;
+ int x = rnd_int(STAR_FIELD), y = rnd_int(STAR_FIELD);
+ double a = rnd_float(DBL(2, 10), DBL(6, 10));
+ x -= STAR_X0;
+ y -= STAR_Y0;
+ if (x < 0 || x >= SCREEN_W || y < 0 || y >= SCREEN_H || nstars >= MAX_STARS) continue;
+ stars[nstars++] = (Star){(uint16_t)x, (uint8_t)y, (uint8_t)jsround(a * 255), rgb565_near(r << 16 | g << 8 | b)};
+ }
+}
+
+static float stars_now; /* the stars' stage alpha this frame */
+
+static void draw_stars(const GfxBand *b, void *ctx) {
+ (void)ctx;
+ int z = b->zoom, ox = (SCREEN_W - STAR_FIELD * z) / 2 + STAR_X0 * z, oy = (SCREEN_H - STAR_FIELD * z) / 2 + STAR_Y0 * z;
+ for (int i = 0; i < nstars; i++) {
+ const Star *s = &stars[i];
+ int x = ox + s->x * z, y = oy + s->y * z;
+ if (y + z <= b->cy0 || y >= b->cy1 || x + z <= b->cx0 || x >= b->cx1) continue;
+ uint32_t a5 = gfx_alpha32((uint32_t)(s->alpha * stars_now + 0.5f));
+ if (!a5) continue;
+ for (int yy = y; yy < y + z; yy++) {
+ if (yy < b->cy0 || yy >= b->cy1) continue;
+ uint16_t *row = b->px + (yy - b->y0) * SCREEN_W;
+ for (int xx = x; xx < x + z; xx++)
+ if (xx >= b->cx0 && xx < b->cx1) row[xx] = gfx_blend(s->color, row[xx], a5);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- planets */
+static BgPlanet planets[BG_MAX_PLANETS];
+static int nplanets;
+
+void bg_set_planets(const BgPlanet *p, int n) {
+ if (n > BG_MAX_PLANETS) n = BG_MAX_PLANETS;
+ nplanets = n < 0 ? 0 : n;
+ if (nplanets) memcpy(planets, p, sizeof *p * (size_t)nplanets);
+}
+
+/* ---------------------------------------------------------------- clouds */
+/* graphics.Cloud: a cloud is a few 60 x 60 tiles of spr_clouds (16 x 2 of them, 2 pixels
+ * apart) chosen to fit each other by their meta (Cloud.texturesMeta). The tiles are made
+ * again from the cloud's own seed whenever needed instead of being kept. */
+static const uint8_t cloud_meta[31] = {0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 4, 3, 1, 4, 5, 6, 3, 7, 7, 8, 8, 9, 10, 11, 11, 12, 13, 14, 14, 5, 6};
+enum { TL_CORNER, TL_SECOND, TL_SECOND_NOUP, TR_CORNER, TR_CORNER_NOUP, BL_CORNER, BL_SECOND, BR_CORNER,
+ TL_SIMPLE, C_LEFT, C_RIGHT, C_TOP, C_LEFTRIGHT, C_LEFTRIGHT_NOTOP, CLOUD_LISTS };
+static uint8_t cloud_list[CLOUD_LISTS][8], cloud_list_n[CLOUD_LISTS];
+
+static void make_cloud_lists(void) {
+ memset(cloud_list_n, 0, sizeof cloud_list_n);
+ for (int i = 0; i < 31; i++) {
+ int m = cloud_meta[i];
+#define TO(l) cloud_list[l][cloud_list_n[l]++] = (uint8_t)i
+ if (m == 7 || m == 9 || m == 10) TO(TL_CORNER);
+ if (m == 9 || m == 10) TO(TL_SECOND);
+ if (m == 10) TO(TL_SECOND_NOUP);
+ if (m == 5 || m == 12 || m == 13) TO(TR_CORNER);
+ if (m == 5 || m == 13) TO(TR_CORNER_NOUP);
+ if (m == 8 || m == 11) TO(BL_CORNER);
+ if (m == 11) TO(BL_SECOND);
+ if (m == 6 || m == 14) TO(BR_CORNER);
+ if (m == 7) TO(TL_SIMPLE);
+ if (m == 1) TO(C_LEFT);
+ if (m == 3) TO(C_RIGHT);
+ if (m == 0) TO(C_TOP);
+ if (m == 2 || m == 4) TO(C_LEFTRIGHT);
+ if (m == 4) TO(C_LEFTRIGHT_NOTOP);
+#undef TO
+ }
+}
+
+typedef struct {
+ float x, y; /* position */
+ uint32_t seed; /* of its tiles */
+ uint8_t layer; /* 0 (far) to 2 */
+ uint8_t alpha; /* alph, 0..255 */
+ int8_t x0, y0, x1, y1; /* its rect, in tiles */
+} Cloud;
+static Cloud clouds[BG_MAX_CLOUDS];
+static int nclouds;
+
+#define CLOUD_TILES 32
+typedef struct {
+ struct { int8_t x, y; uint8_t t; } t[CLOUD_TILES];
+ int n, x0, y0, x1, y1;
+ uint32_t r; /* the tiles' random numbers (xorshift32) */
+} CloudShape;
+
+static float cs_float(CloudShape *c) {
+ c->r ^= c->r << 13;
+ c->r ^= c->r >> 17;
+ c->r ^= c->r << 5;
+ return (float)(c->r >> 8) * (1.0f / 16777216.0f);
+}
+static int cs_pick(CloudShape *c, int list) { return cloud_list[list][(int)(cs_float(c) * cloud_list_n[list])]; }
+
+static void cs_add(CloudShape *c, int x, int y, int t) {
+ if (c->n >= CLOUD_TILES) return;
+ c->t[c->n].x = (int8_t)x;
+ c->t[c->n].y = (int8_t)y;
+ c->t[c->n].t = (uint8_t)t;
+ c->n++;
+ if (x < c->x0) c->x0 = x;
+ if (y < c->y0) c->y0 = y;
+ if (x + 1 > c->x1) c->x1 = x + 1;
+ if (y + 1 > c->y1) c->y1 = y + 1;
+}
+
+/* Cloud.makeANiceCloudForMe; layer 0 to 2 (its parallaxLayer is layer + 1) */
+static void make_cloud(CloudShape *c, uint32_t seed, int layer) {
+ c->n = c->x0 = c->y0 = c->x1 = c->y1 = 0;
+ c->r = seed ? seed : 1;
+ int pl = 4 - (layer + 1);
+ struct { int8_t x, y; } left[16], right[16];
+ int nl = 0, nr = 0, second = -1;
+ const uint8_t *meta = cloud_meta;
+ if (pl == 3 && cs_float(c) < 0.8f) {
+ cs_add(c, 0, 0, cs_pick(c, C_LEFT));
+ right[nr].x = 1, right[nr++].y = 0;
+ } else {
+ int tl = cs_pick(c, TL_CORNER), tr = cs_pick(c, TR_CORNER), bl = cs_pick(c, BL_CORNER), br = cs_pick(c, BR_CORNER);
+ cs_add(c, 0, 0, tl);
+ cs_add(c, 1, 0, tr);
+ cs_add(c, 0, 1, bl);
+ cs_add(c, 1, 1, br);
+ if (meta[tl] == 9 || meta[tl] == 10) left[nl].x = -1, left[nl++].y = 0;
+ if (meta[bl] == 11) left[nl].x = -1, left[nl++].y = 1;
+ if (cs_float(c) < (pl == 2 ? 0.1f : 0.8f) && pl < 3) {
+ int desire = (int)(cs_float(c) * 4);
+ bool trs = meta[tr] == 12 || meta[tr] == 13;
+ if (desire < 2 && trs && meta[br] == 14) second = 0;
+ if (desire == 2 && trs) second = 1;
+ if (desire == 3 && meta[br] == 14) second = 2;
+ }
+ if ((second == -1 || second == 2) && (meta[tr] == 12 || meta[tr] == 13)) right[nr].x = 2, right[nr++].y = 0;
+ if ((second == -1 || second == 1) && meta[br] == 14) right[nr].x = 2, right[nr++].y = 1;
+ if (meta[tl] == 9) cs_add(c, 0, -1, cs_pick(c, C_TOP));
+ if (meta[tr] == 12) cs_add(c, 1, -1, cs_pick(c, C_TOP));
+ if (second != -1) {
+ int sx = 2, sy = second == 0 ? 0 : second == 1 ? -1 : 1;
+ int tl2 = cs_pick(c, second == 1 ? TL_SIMPLE : second == 2 ? TL_SECOND_NOUP : TL_SECOND);
+ int tr2 = cs_pick(c, second == 2 ? TR_CORNER_NOUP : TR_CORNER);
+ int bl2 = cs_pick(c, second == 2 ? BL_CORNER : BL_SECOND);
+ int br2 = cs_pick(c, BR_CORNER);
+ cs_add(c, sx, sy, tl2);
+ cs_add(c, sx + 1, sy, tr2);
+ cs_add(c, sx, sy + 1, bl2);
+ cs_add(c, sx + 1, sy + 1, br2);
+ if (second == 2 && meta[bl2] == 11) left[nl].x = (int8_t)(sx - 1), left[nl++].y = (int8_t)(sy + 1);
+ if (meta[tr2] == 12 || meta[tr2] == 13) right[nr].x = (int8_t)(sx + 2), right[nr++].y = (int8_t)sy;
+ if (meta[br2] == 14) right[nr].x = (int8_t)(sx + 2), right[nr++].y = (int8_t)(sy + 1);
+ if (meta[tl2] == 9) cs_add(c, sx, sy - 1, cs_pick(c, C_TOP));
+ if (meta[tr2] == 12) cs_add(c, sx + 1, sy - 1, cs_pick(c, C_TOP));
+ }
+ }
+ while (nl > 0) {
+ int x = left[nl - 1].x, y = left[--nl].y;
+ if (x > -1 && cs_float(c) < 0.6f - 0.1f * pl) {
+ int t = cs_pick(c, y <= 0 ? C_LEFTRIGHT : C_LEFTRIGHT_NOTOP);
+ cs_add(c, x, y, t);
+ if (meta[t] == 2) cs_add(c, x, y - 1, cs_pick(c, C_TOP));
+ if (nl < 16) left[nl].x = (int8_t)(x - 1), left[nl++].y = (int8_t)y;
+ } else {
+ cs_add(c, x, y, cs_pick(c, C_LEFT));
+ }
+ }
+ while (nr > 0) {
+ int x = right[nr - 1].x, y = right[--nr].y;
+ if (x < 3 && cs_float(c) < 0.6f - 0.1f * pl) {
+ int t = cs_pick(c, y <= 0 && (second != 1 || y <= -1) ? C_LEFTRIGHT : C_LEFTRIGHT_NOTOP);
+ cs_add(c, x, y, t);
+ if (meta[t] == 2) cs_add(c, x, y - 1, cs_pick(c, C_TOP));
+ if (nr < 16) right[nr].x = (int8_t)(x + 1), right[nr++].y = (int8_t)y;
+ } else {
+ cs_add(c, x, y, cs_pick(c, C_RIGHT));
+ }
+ }
+}
+
+/* common.Rectangle.intersects */
+static bool intersects(int ax, int ay, int aw, int ah, int bx, int by, int bw, int bh) {
+ bool x = (ax >= bx && ax < bx + bw) || (bx >= ax && bx < ax + aw);
+ return x && ((by >= ay && by < ay + ah) || (ay >= by && ay < by + bh));
+}
+
+#define CLOUD_BASE 0.12500000125f /* BackgroundImages.cloudSpeedBase, cloudSpeedParallaxMult */
+#define PARALLAX 0.2f
+
+/* BackgroundImages.doCloudsStep for one layer */
+static void clouds_step(float timeMod, const BgEdges *e, int layer) {
+ float p = PARALLAX * (float)(layer + 1);
+ float left = (float)e->minX * p - 300 - 300 - W2, right = (float)e->maxX * p + 120 + 300 + W2;
+ float miny = (float)e->minY * p - 300 - H2, maxy = (float)e->maxY * p + 300 + H2;
+ float chance = (7 - layer * 1.8f) * (maxy - miny) * 0.0000009f;
+ if (chance > 0.15f) chance = 0.15f;
+ if (rnd_float(0, 1) < timeMod * chance && nclouds < BG_MAX_CLOUDS) {
+ Cloud n;
+ n.y = (float)rnd_float(miny, maxy);
+ n.x = left - 300;
+ n.layer = (uint8_t)layer;
+ n.alpha = (uint8_t)jsround((DBL(1, 10) + (layer + 1) * DBL(15, 100) + rnd_float(0, DBL(1, 10))) * 255);
+ n.seed = (uint32_t)srand_next(&rng);
+ CloudShape s;
+ make_cloud(&s, n.seed, layer);
+ n.x0 = (int8_t)s.x0, n.y0 = (int8_t)s.y0, n.x1 = (int8_t)s.x1, n.y1 = (int8_t)s.y1;
+ bool hit = false;
+ for (int i = 0; i < nclouds && !hit; i++) {
+ const Cloud *c = &clouds[i];
+ if (c->layer != layer) continue;
+ int dx = jsround(n.x - c->x), dy = jsround(n.y - c->y);
+ hit = intersects(c->x0 * 60, c->y0 * 60, (c->x1 - c->x0) * 60, (c->y1 - c->y0) * 60, n.x0 * 60 + dx,
+ n.y0 * 60 + dy, (n.x1 - n.x0) * 60, (n.y1 - n.y0) * 60);
+ }
+ if (!hit) clouds[nclouds++] = n;
+ }
+ float speed = CLOUD_BASE * timeMod + CLOUD_BASE * timeMod * (float)(layer + 1);
+ int k = 0;
+ for (int i = 0; i < nclouds; i++) {
+ Cloud c = clouds[i];
+ if (c.layer == layer) {
+ c.x += speed;
+ if (c.x > right) continue;
+ }
+ clouds[k++] = c;
+ }
+ nclouds = k;
+}
+
+void bg_clouds_start(const BgEdges *e) {
+ nclouds = 0;
+ for (int layer = 0; layer < 3; layer++)
+ for (int i = 0; i < 500 + (e->maxX - e->minX) / 40; i++) clouds_step(40, e, layer);
+}
+
+void bg_clouds_update(float timeMod, const BgEdges *e) {
+ for (int layer = 0; layer < 3; layer++) clouds_step(timeMod, e, layer);
+}
+
+int bg_cloud_count(void) { return nclouds; }
+
+void bg_init(uint32_t seed) {
+ srand_init(&rng, (int32_t)seed);
+ make_cloud_lists();
+ make_stars();
+ nclouds = 0;
+}
+
+/* ---------------------------------------------------------------- drawing the sky */
+static uint32_t frame_no = 1; /* bg's frames (bg_draw_sky starts one), for the shape cache */
+static uint16_t sky565;
+
+void bg_draw_sky(const BgCamera *cam, double time) {
+ frame_no++;
+ int z = cam->zoom == 2 ? 2 : 1;
+ double hour = fmod(time / 60, 24);
+ sky565 = rgb565_near(bg_sky_color((float)hour));
+ gfx_zoom(z);
+ gfx_fill(sky565);
+ /* stars */
+ stars_now = bg_stars_alpha((float)hour);
+ if (stars_now > 0) gfx_call(draw_stars, NULL, 0, SCREEN_H);
+ /* the original's viewPos: the screen's centre */
+ double vx = cam->x + (double)W2 / z, vy = cam->y + (double)H2 / z;
+ /* planets and moons (BackgroundImages.update), their stage moving at 0.15 of the view */
+ double ppar = DBL(15000000015LL, 100000000000LL);
+ int px = (int)floor(-vx * ppar * z + W2), py = (int)floor(-vy * ppar * z + H2);
+ for (int i = 0; i < nplanets; i++) {
+ const BgPlanet *p = &planets[i];
+ int sw = spr_w(p->spr), sh = spr_h(p->spr);
+ int n = (sw + 2) / (p->width + 2);
+ if (n < 3) continue;
+ int fw = (sw + 2) / n - 2;
+ double len = sqrt((double)p->x * p->x + (double)p->y * p->y);
+ double dir = atan2(p->y, p->x) + time * DBL(175, 10000000) * p->velocity;
+ int x = jsround(px + z * (len * cos(dir) - fw * 0.5)), y = jsround(py + z * (len * sin(dir) - sh * 0.5));
+ gfx_sprite_ex(p->spr, (fw + 2) * (n - 2), 0, fw, sh, x, y, 0, 255, sky565);
+ gfx_sprite_ex(p->spr, (fw + 2) * p->image, 0, fw, sh, x, y, 0, 102, GFX_NO_TINT);
+ gfx_sprite_ex(p->spr, (fw + 2) * (n - 1), 0, fw, sh, x, y, 0, 10, GFX_NO_TINT);
+ }
+ /* clouds, far layer first */
+ float ca = bg_clouds_alpha((float)hour);
+ if (ca <= 0) return;
+ for (int layer = 0; layer < 3; layer++) {
+ float par = PARALLAX + PARALLAX * layer;
+ int ox = (int)floor(-vx * par * z + W2), oy = (int)floor(-vy * par * z + H2);
+ for (int i = 0; i < nclouds; i++) {
+ const Cloud *c = &clouds[i];
+ if (c->layer != layer) continue;
+ /* the cloud's rect on screen */
+ float sx = (float)ox + z * c->x, sy = (float)oy + z * c->y;
+ if (sx + z * 60 * c->x1 < 0 || sx + z * 60 * c->x0 >= SCREEN_W || sy + z * 60 * c->y1 < 0 ||
+ sy + z * 60 * c->y0 >= SCREEN_H)
+ continue;
+ int a = (int)(c->alpha * ca + 0.5f);
+ if (a <= 0) continue;
+ CloudShape s;
+ make_cloud(&s, c->seed, layer);
+ for (int k = 0; k < s.n; k++) {
+ int t = s.t[k].t;
+ int x = bg_floor(sx + z * 60.0f * s.t[k].x + 0.5f), y = bg_floor(sy + z * 60.0f * s.t[k].y + 0.5f);
+ gfx_sprite_ex(SPR_CLOUDS, 62 * (t % 16), 62 * (t / 16), 60, 60, x, y, 0, (uint8_t)a, GFX_NO_TINT);
+ }
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- islands */
+/* graphics.WorldImage.makeWorldSprite, kept down each column: its core (a byte: if not 0, row 0
+ * is outline and rows 1 to core - 1 fill), then runs from the core down, a byte each
+ * kind << 6 | (length - 1), kind 0 clear, 1 fill, 2 outline, 3 outline that ends the column;
+ * 0xFF: no runs. Before the columns, for every 32 columns: the offset of the first (u16), and
+ * the smallest core of those that aren't the island's two edges (u8, then u8 0). */
+#define MAXH 256
+#define HW (MAXH / 32)
+#define RING 64
+
+typedef struct {
+ const BgWorld *owner;
+ int32_t seed;
+ int16_t w, h;
+ uint8_t look;
+ uint16_t off, size; /* in the pool */
+ uint32_t used; /* the frame it was last needed */
+} Slot;
+_Static_assert(BG_SHAPE_POOL <= 65536, "shape offsets are 16-bit");
+static uint8_t pool[BG_SHAPE_POOL];
+static Slot slots[BG_SHAPE_SLOTS];
+static uint32_t pool_top;
+
+void bg_forget_shapes(void) {
+ memset(slots, 0, sizeof slots);
+ pool_top = 0;
+}
+
+typedef struct {
+ uint8_t *p;
+ uint32_t n, cap;
+} Out;
+static void out_byte(Out *o, uint32_t b) {
+ if (o->n < o->cap) o->p[o->n] = (uint8_t)b;
+ o->n++;
+}
+
+/* one column (F its pixels, L and R its neighbours'): its core byte, then its runs from the core
+ * down; returns the core */
+static int put_column(Out *o, const uint32_t *F, const uint32_t *L, const uint32_t *R, int h, bool edge) {
+ uint32_t O[HW];
+ int last = -1;
+ for (int k = 0; k < HW; k++) {
+ uint32_t up = F[k] << 1 | (k ? F[k - 1] >> 31 : 0), down = F[k] >> 1 | (k + 1 < HW ? F[k + 1] << 31 : 0);
+ O[k] = edge ? F[k] : F[k] & ~(L[k] & R[k] & up & down);
+ if (F[k]) last = k * 32 + 31 - __builtin_clz(F[k]);
+ }
+ if (last >= h) last = h - 1;
+ /* the core: row 0 (outline, as the top always is) and the fill under it */
+ int core = 0;
+ if (F[0] & 1) {
+ core = 1;
+ while (core <= last && (F[core >> 5] >> (core & 31) & 1) && !(O[core >> 5] >> (core & 31) & 1)) core++;
+ }
+ out_byte(o, (uint32_t)core);
+ int y = core;
+ if (y > last) {
+ out_byte(o, 0xFF);
+ return core;
+ }
+ while (y <= last) {
+ int kind = (F[y >> 5] >> (y & 31) & 1) ? ((O[y >> 5] >> (y & 31) & 1) ? 2 : 1) : 0;
+ int n = 1;
+ while (y + n <= last) {
+ int yy = y + n;
+ int k2 = (F[yy >> 5] >> (yy & 31) & 1) ? ((O[yy >> 5] >> (yy & 31) & 1) ? 2 : 1) : 0;
+ if (k2 != kind) break;
+ n++;
+ }
+ y += n;
+ if (y > last) { /* the column's last run (outline, as its lowest pixel always is) ends it */
+ while (n > 63) {
+ int m = n - 63 < 64 ? n - 63 : 64;
+ out_byte(o, (uint32_t)(kind << 6 | (m - 1)));
+ n -= m;
+ }
+ out_byte(o, (uint32_t)(3 << 6 | (n - 1)));
+ } else {
+ while (n > 0) {
+ int m = n < 64 ? n : 64;
+ out_byte(o, (uint32_t)(kind << 6 | (m - 1)));
+ n -= m;
+ }
+ }
+ }
+ return core;
+}
+
+/* makes the world's island into o (o->n: the bytes it needs, even past o->cap) */
+static void make_island(const BgWorld *w, Out *o) {
+ int width = w->w, height = w->h > MAXH ? MAXH : w->h;
+ SRand r;
+ srand_init(&r, w->seed);
+ int below = height - 10 < 0 ? 0 : height - 10 > 12 ? 12 : height - 10, wh = height - below;
+ double minYMax = floor(wh - wh / 4.0), maxYMin = floor(wh - wh / 3.0), minYMin = floor(wh - wh / 2.0);
+ if (w->look == BG_LOOK_ROCK_LESS_JAGGED) {
+ minYMax = floor(wh - wh / 8.0);
+ maxYMin = floor(wh - wh / 6.0);
+ minYMin = floor(wh - wh / 4.0);
+ }
+ /* the outline's points: (0, 0), then deep and shallow in turn, then (width - 1, 0) */
+ enum { MAXP = 100 };
+ int ptx[MAXP], pty[MAXP], np = 0;
+ ptx[np] = 0, pty[np++] = 0;
+ double a = wh / 4.0 + srand_int(&r, -5, 6), b = width / 3.0;
+ int side = (int)(a < b ? a : b);
+ double d = floor((width - side * 2) / (srand_int(&r, 25, 35) + width / 40.0));
+ int n = (int)(d > 1 ? d : 1);
+ if (n > (MAXP - 2) / 2) n = (MAXP - 2) / 2;
+ double xchange = floor((width - side * 2) / (double)n);
+ int xx = side + (int)((width - side * 2 - xchange * (n - 0.5)) / 2);
+ for (int i = 0; i < n; i++) {
+ int x = xx + srand_int(&r, -6, 7);
+ ptx[np] = x, pty[np++] = srand_int(&r, (int)minYMax, wh);
+ if (i != n - 1) {
+ x = xx + (int)(xchange / 2) + srand_int(&r, -6, 7);
+ ptx[np] = x, pty[np++] = srand_int(&r, (int)minYMin, (int)maxYMin);
+ }
+ xx += (int)xchange;
+ }
+ ptx[np] = width - 1, pty[np++] = 0;
+
+ double pf1 = DBL(16, 10), pf2 = DBL(12, 10), pchange = 8;
+ if (w->look == BG_LOOK_KEY) pf1 = 1, pf2 = DBL(8, 10), pchange = 3;
+
+ /* the columns' pixels, in a ring: a column is done 20 columns later, when no earth part
+ * (which reaches 18 columns back) can touch it or its neighbours any more */
+ uint32_t ring[RING][HW];
+ memset(ring, 0, sizeof ring);
+ static const uint32_t none[HW];
+#define PIX(x, y) (ring[(x) & (RING - 1)][(y) >> 5] |= 1u << ((y) & 31))
+ /* every 32nd column: u16 offset of its runs, u8 its chunk's core (the fill rows 1 to core - 1
+ * that all its columns but the island's two edges have), u8 0 */
+ int nchk = (width + 31) / 32, done = 0, core = 255;
+ uint32_t base = (uint32_t)nchk * 4;
+ for (uint32_t i = 0; i < base; i++) out_byte(o, 0);
+#define FINISH(c) \
+ do { \
+ int c_ = (c), k_ = 4 * (c_ >> 5); \
+ if (!(c_ & 31)) { \
+ uint32_t at = o->n - base; \
+ if ((uint32_t)k_ + 1 < o->cap) o->p[k_] = (uint8_t)at, o->p[k_ + 1] = (uint8_t)(at >> 8); \
+ core = 255; \
+ } \
+ int cc_ = put_column(o, ring[c_ & (RING - 1)], c_ > 0 ? ring[(c_ - 1) & (RING - 1)] : none, \
+ c_ + 1 < width ? ring[(c_ + 1) & (RING - 1)] : none, height, c_ == 0 || c_ == width - 1); \
+ if (c_ > 0 && c_ < width - 1 && cc_ < core) core = cc_; \
+ if (((c_ & 31) == 31 || c_ == width - 1) && (uint32_t)k_ + 2 < o->cap) o->p[k_ + 2] = (uint8_t)(core > 255 ? 255 : core); \
+ if (c_ > 0) memset(ring[(c_ - 1) & (RING - 1)], 0, sizeof ring[0]); \
+ } while (0)
+
+ int cur = 0;
+ double add = 0;
+ for (int i = 0; i < width; i++) {
+ double maxAdd = pchange / (abs(pty[cur + 1] - pty[cur]) + 5);
+ double v = add + srand_float(&r, -maxAdd, maxAdd);
+ add = v < -DBL(2, 10) ? -DBL(2, 10) : v > DBL(2, 10) ? DBL(2, 10) : v;
+ if (i > ptx[cur + 1]) {
+ if (pty[cur + 1] > pty[cur]) {
+ /* bits of earth floating under the point */
+ int parts = srand_int(&r, 1, 3), dist = srand_int(&r, 5, 8);
+ for (int op = 0; op < parts; op++) {
+ int bx = srand_int(&r, -2, 3) + i - (parts - 1) * dist + dist * 2 * op;
+ int by = pty[cur + 1] + srand_int(&r, 0, 3);
+ int fromX = bx - 1, toX = bx;
+ for (int y = by + 2; y < by + 11; y++) {
+ if (y <= by + 5) {
+ fromX -= srand_int(&r, 0, y < by + 5 ? 3 : 2);
+ toX += srand_int(&r, 0, y < by + 5 ? 3 : 2);
+ } else {
+ int v1 = fromX + srand_int(&r, 0, y > by + 6 ? 3 : 2);
+ fromX = toX < v1 ? toX : v1;
+ int v2 = toX - srand_int(&r, 0, y > by + 6 ? 3 : 2);
+ toX = fromX > v2 ? fromX : v2;
+ }
+ if (y == by + 2 && toX - fromX == 1) ++toX;
+ if (y == by + 3 && toX - fromX == 2) --fromX;
+ for (int x = fromX; x < toX; x++)
+ if (x >= 0 && x < width && y + 2 < height && x >= i - 40 && x < i + 20) PIX(x, y);
+ }
+ }
+ }
+ ++cur;
+ }
+ int x0 = ptx[cur], y0 = pty[cur], x1 = ptx[cur + 1], y1 = pty[cur + 1];
+ double t = x1 != x0 ? (double)(i - x0) / (x1 - x0) : i > x0 ? INFINITY : i < x0 ? -INFINITY : NAN;
+ if (y1 < y0) t = pow(t, pf1 - t * pf2 + add);
+ else t = 1 - pow(1 - t, pf1 - (1 - t) * pf2 - add);
+ double v12 = floor(t * (y1 - y0) + y0), v2 = wh - 1;
+ double bottom = v2 < v12 ? v2 : v12;
+ if (bottom >= 0) {
+ int bt = (int)bottom;
+ for (int j = 0; j <= bt && j < height; j++) PIX(i, j);
+ }
+ if (i - 20 >= 0) FINISH(i - 20);
+ done = i - 19;
+ }
+ for (int c = done < 0 ? 0 : done; c < width; c++) FINISH(c);
+#undef PIX
+#undef FINISH
+}
+
+static void compact(void) {
+ /* slots by offset, slid down */
+ uint32_t at = 0;
+ for (;;) {
+ int best = -1;
+ for (int i = 0; i < BG_SHAPE_SLOTS; i++)
+ if (slots[i].owner && slots[i].off >= at && (best < 0 || slots[i].off < slots[best].off)) best = i;
+ if (best < 0) break;
+ if (slots[best].off != at) memmove(pool + at, pool + slots[best].off, slots[best].size);
+ slots[best].off = (uint16_t)at;
+ at += (slots[best].size + 1) & ~1u;
+ }
+ pool_top = at;
+}
+
+/* the island's slot, made if needed (-1: it can't be) */
+static int shape_of(BgWorld *w) {
+ if (w->h <= 0 || w->w <= 0) return -1;
+ if (w->shape) {
+ Slot *s = &slots[w->shape - 1];
+ if (s->owner == w && s->seed == w->seed && s->w == w->w && s->h == w->h && s->look == w->look) {
+ s->used = frame_no;
+ return w->shape - 1;
+ }
+ }
+ w->shape = 0;
+ int slot = -1;
+ for (int i = 0; i < BG_SHAPE_SLOTS && slot < 0; i++)
+ if (!slots[i].owner) slot = i;
+ Out o = {pool + pool_top, 0, BG_SHAPE_POOL - pool_top};
+ make_island(w, &o);
+ if (o.n > o.cap || slot < 0) {
+ /* room: let go of the islands seen longest ago (not this frame's) */
+ uint32_t need = o.n;
+ for (;;) {
+ uint32_t live = 0;
+ for (int i = 0; i < BG_SHAPE_SLOTS; i++)
+ if (slots[i].owner) live += (slots[i].size + 1) & ~1u;
+ if (BG_SHAPE_POOL - live >= need && slot >= 0) break;
+ int old = -1;
+ for (int i = 0; i < BG_SHAPE_SLOTS; i++)
+ if (slots[i].owner && slots[i].used != frame_no && (old < 0 || slots[i].used < slots[old].used)) old = i;
+ if (old < 0) return -1;
+ slots[old].owner = NULL;
+ if (slot < 0) slot = old;
+ }
+ compact();
+ o = (Out){pool + pool_top, 0, BG_SHAPE_POOL - pool_top};
+ make_island(w, &o);
+ if (o.n > o.cap) return -1;
+ }
+ slots[slot] = (Slot){w, w->seed, w->w, w->h, w->look, (uint16_t)pool_top, (uint16_t)o.n, frame_no};
+ pool_top += (o.n + 1) & ~1u;
+ w->shape = (uint8_t)(slot + 1);
+ return slot;
+}
+
+/* the runs of column c of a shape */
+static const uint8_t *column(const Slot *s, int c) {
+ const uint8_t *base = pool + s->off, *p = base + ((s->w + 31) / 32) * 4;
+ p += base[4 * (c >> 5)] | base[4 * (c >> 5) + 1] << 8;
+ for (int k = c & ~31; k < c; k++) {
+ p++; /* the core */
+ while (*p++ < 0xC0) {}
+ }
+ return p;
+}
+
+typedef struct {
+ uint8_t slot, z;
+ int16_t x, y; /* screen position of the rect's top-left */
+ uint16_t fill, outline;
+} IslandDraw;
+#define MAX_ISLAND_DRAWS 48
+static IslandDraw island_draws[MAX_ISLAND_DRAWS]; /* a ring: a frame draws fewer than this */
+static unsigned nisland_draws;
+
+/* rows y0..y1 - 1 of an island column at screen x0..x1 - 1, in one colour */
+static inline void island_rows(const GfxBand *b, const IslandDraw *d, int x0, int x1, int y0, int y1, uint16_t col) {
+ int sy0 = d->y + y0 * d->z, sy1 = d->y + y1 * d->z;
+ if (sy0 < b->cy0) sy0 = b->cy0;
+ if (sy1 > b->cy1) sy1 = b->cy1;
+ uint16_t *q = b->px + (sy0 - b->y0) * SCREEN_W + x0;
+ if (x1 - x0 == 1)
+ for (int sy = sy0; sy < sy1; sy++, q += SCREEN_W) q[0] = col;
+ else if (x1 - x0 == 2)
+ for (int sy = sy0; sy < sy1; sy++, q += SCREEN_W) q[0] = q[1] = col;
+}
+
+static void draw_island(const GfxBand *b, void *ctx) {
+ const IslandDraw *d = ctx;
+ const Slot *s = &slots[d->slot];
+ if (!s->owner) return;
+ int z = d->z, w = s->w;
+ int c0 = floordiv(b->cx0 - d->x, z), c1 = floordiv(b->cx1 - d->x + z - 1, z);
+ int r0 = floordiv(b->cy0 - d->y, z), r1 = floordiv(b->cy1 - d->y + z - 1, z);
+ if (c0 < 0) c0 = 0;
+ if (c1 > w) c1 = w;
+ if (r0 < 0) r0 = 0;
+ if (c0 >= c1 || r1 <= 0) return;
+ const uint8_t *base = pool + s->off, *cols = base + 4 * ((w + 31) / 32);
+ for (int k = c0 >> 5; k <= (c1 - 1) >> 5; k++) {
+ const uint8_t *chk = base + 4 * k;
+ int ka = k * 32 > c0 ? k * 32 : c0, kb = k * 32 + 32 < c1 ? k * 32 + 32 : c1, core = chk[2];
+ /* the chunk's core (but for the island's edges), as rows: the outline on top, the fill under it */
+ int fa = ka > 0 ? ka : 1, fb = kb < w - 1 ? kb : w - 1;
+ if (core && fa < fb) {
+ int sx0 = d->x + fa * z, sx1 = d->x + fb * z;
+ for (int ry = r0; ry < r1 && ry < core; ry++) {
+ int sy0 = d->y + ry * z, sy1 = sy0 + z;
+ if (sy0 < b->cy0) sy0 = b->cy0;
+ if (sy1 > b->cy1) sy1 = b->cy1;
+ for (int sy = sy0; sy < sy1; sy++) gfx_band_span(b, sy, sx0, sx1, ry ? d->fill : d->outline, 255);
+ }
+ }
+ bool inside = r1 <= core; /* the band shows only the core here */
+ const uint8_t *p = cols + (chk[0] | chk[1] << 8);
+ for (int c = k * 32; c < kb; c++) {
+ bool edge = c == 0 || c == w - 1;
+ int cc = *p++; /* the column's core */
+ if (c < ka || (inside && !edge)) {
+ while (*p++ < 0xC0) {}
+ continue;
+ }
+ int x0 = d->x + c * z, x1 = x0 + z;
+ if (x0 < b->cx0) x0 = b->cx0;
+ if (x1 > b->cx1) x1 = b->cx1;
+ if (cc) { /* the part of its core the chunk's doesn't draw */
+ int from = edge || !core ? 0 : core;
+ if (from == 0 && r0 == 0) island_rows(b, d, x0, x1, 0, 1, d->outline);
+ if (from < 1) from = 1;
+ if (from < r0) from = r0;
+ if (from < cc && from < r1) island_rows(b, d, x0, x1, from, cc < r1 ? cc : r1, d->fill);
+ }
+ int y = cc;
+ for (;;) {
+ uint8_t v = *p++;
+ if (v == 0xFF) break;
+ if (y >= r1) { /* the rest is below the band */
+ if (v < 0xC0)
+ while (*p++ < 0xC0) {}
+ break;
+ }
+ int kind = v >> 6, n = (v & 63) + 1;
+ if (kind && y + n > r0) island_rows(b, d, x0, x1, y > r0 ? y : r0, y + n < r1 ? y + n : r1,
+ kind == 1 ? d->fill : d->outline);
+ y += n;
+ if (kind == 3) break;
+ }
+ }
+ }
+}
+
+/* decorations */
+static const struct { const char *name; uint16_t spr; } decos[DECO_KINDS] = {
+ {"", 0}, {"spr_grass", SPR_GRASS}, {"spr_flowers", SPR_FLOWERS}, {"spr_flowers_blue", SPR_FLOWERS_BLUE},
+ {"spr_decoration_rocks", SPR_DECORATION_ROCKS}, {"spr_decoration_keycity", SPR_DECORATION_KEYCITY},
+ {"spr_flowers_keycity", SPR_FLOWERS_KEYCITY}, {"spr_purplegrass", SPR_PURPLEGRASS}, {"spr_redgrass", SPR_REDGRASS}};
+
+int bg_deco_kind(const char *name) {
+ for (int k = 1; k < DECO_KINDS; k++)
+ if (name && !strcmp(name, decos[k].name)) return k;
+ return 0;
+}
+uint16_t bg_deco_sprite(int kind) { return kind > 0 && kind < DECO_KINDS ? decos[kind].spr : 0; }
+int bg_deco_frames(int kind) { return kind > 0 && kind < DECO_KINDS ? (spr_w(decos[kind].spr) + 2) / 22 : 0; }
+
+void bg_set_decoration(uint8_t *d, int col, int kind, int frame, bool has_ground_permanent) {
+ d[col] = 0;
+ if (has_ground_permanent || kind <= 0 || kind >= DECO_KINDS) return;
+ int n = bg_deco_frames(kind);
+ if (frame < 0) frame = rnd_int(n);
+ if (frame >= n || frame > 15) frame = 0;
+ d[col] = (uint8_t)(kind << 4 | frame);
+}
+
+void bg_world_decorate(const BgWorld *w, uint8_t *d) {
+ if (w->h == 0 || w->look == BG_LOOK_SNOW) return;
+ for (int c = 0; c < (w->w + 19) / 20; c++) bg_set_decoration(d, c, DECO_GRASS, -1, false);
+}
+
+int bg_look(const char *a) {
+ if (!a) return BG_LOOK_NORMAL;
+ if (!strcmp(a, "key")) return BG_LOOK_KEY;
+ if (!strcmp(a, "key2")) return BG_LOOK_KEY2;
+ if (!strcmp(a, "rock")) return BG_LOOK_ROCK;
+ if (!strcmp(a, "rock:lessJagged")) return BG_LOOK_ROCK_LESS_JAGGED;
+ if (!strcmp(a, "snow")) return BG_LOOK_SNOW;
+ return BG_LOOK_NORMAL;
+}
+
+void bg_draw_world(BgWorld *w, const uint8_t *d, const BgCamera *cam) {
+ int z = cam->zoom == 2 ? 2 : 1;
+ gfx_zoom(z);
+ int ox = bg_floor(-cam->x * z), oy = bg_floor(-cam->y * z);
+ int x = ox + w->x * z, y = oy + w->y * z;
+ if (w->h > 0 && x < SCREEN_W && x + w->w * z > 0 && y < SCREEN_H && y + w->h * z > 0) {
+ int slot = shape_of(w);
+ if (slot >= 0) {
+ uint32_t fill = 5259312, outline = 2103312;
+ if (w->look == BG_LOOK_KEY || w->look == BG_LOOK_KEY2) fill = 5195330, outline = 1973275;
+ if (w->look == BG_LOOK_ROCK || w->look == BG_LOOK_ROCK_LESS_JAGGED) fill = 5197647, outline = 1973790;
+ IslandDraw *id = &island_draws[nisland_draws++ % MAX_ISLAND_DRAWS];
+ *id = (IslandDraw){(uint8_t)slot, (uint8_t)z, (int16_t)x, (int16_t)y, rgb565_near(fill), rgb565_near(outline)};
+ gfx_call(draw_island, id, y, w->h * z);
+ }
+ }
+ /* the decorations, 20 pixels above the ground */
+ if (!d) return;
+ for (int c = 0; c < (w->w + 19) / 20; c++) {
+ if (!d[c]) continue;
+ int kind = d[c] >> 4, f = d[c] & 15;
+ if (kind >= DECO_KINDS) continue;
+ gfx_sprite_ex(decos[kind].spr, 22 * f, 0, 20, 20, x + 20 * c * z, y - 20 * z, 0, 255, GFX_NO_TINT);
+ }
+}
+
+bool bg_world_mask(BgWorld *w, int cx, int cy) {
+ if (cx < 0 || cy < 0 || cx * 20 >= w->w || cy * 20 >= w->h) return false;
+ int slot = shape_of(w);
+ if (slot < 0) return false;
+ const Slot *s = &slots[slot];
+ const uint8_t *p = column(s, cx * 20);
+ int r0 = cy * 20, r1 = r0 + 20;
+ bool hit = false;
+ for (int c = cx * 20; c < cx * 20 + 20 && c < s->w && !hit; c++) {
+ int y = *p++;
+ if (y && r0 < y) hit = true; /* its core: rows 0 to core - 1 */
+ for (;;) {
+ uint8_t v = *p++;
+ if (v == 0xFF) break;
+ int kind = v >> 6, n = (v & 63) + 1;
+ if (kind && y < r1 && y + n > r0) hit = true;
+ y += n;
+ if (kind == 3) break;
+ }
+ }
+ return hit;
+}
diff --git a/games/finalearth2/src/bg.h b/games/finalearth2/src/bg.h
new file mode 100644
index 00000000..f50874fc
--- /dev/null
+++ b/games/finalearth2/src/bg.h
@@ -0,0 +1,106 @@
+/* The Final Earth 2: the backdrop and the worlds' islands.
+ *
+ * Ported from the original: the sky's colour over the day (CityTime), the
+ * stars (graphics.Stars), the planets and moons (graphics.BackgroundImages),
+ * the clouds (graphics.Cloud), each world's island (graphics.WorldImage, made
+ * from its seed with the original's random.SeedeableRandom, so a seed gives
+ * the same island) and the grass and other decorations on the ground
+ * (graphics.GroundDecoration, World.setDecoration).
+ *
+ * Layers, back to front, as the original's City stacks them: bg_draw_sky
+ * (sky, stars, planets, the three cloud layers), then the city: buildings'
+ * backs, citizens inside, buildings, then bg_draw_world for each world (its
+ * island and decorations, in the same stage as the buildings' fronts; they
+ * don't overlap), then citizens outside. */
+#ifndef FE_BG_H
+#define FE_BG_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "gfx.h"
+
+/* the camera: the city position of the screen's top-left, and the zoom (1 or 2).
+ * The original's viewPos (the screen's centre) is (x + SCREEN_W / 2 / zoom, y + SCREEN_H / 2 / zoom). */
+typedef struct {
+ float x, y;
+ int zoom;
+} BgCamera;
+/* screen position of a city position (the original's moving view: its offset floored, then the
+ * nearest pixel); for buildings, citizens and everything else in the city */
+static inline int bg_floor(float v) { int i = (int)v; return i - (v < (float)i); }
+static inline int bg_screen_x(const BgCamera *c, float x) { return bg_floor(x * c->zoom + 0.5f) + bg_floor(-c->x * c->zoom); }
+static inline int bg_screen_y(const BgCamera *c, float y) { return bg_floor(y * c->zoom + 0.5f) + bg_floor(-c->y * c->zoom); }
+
+/* City.getCityEdges() (the worlds and what is built on them), which the clouds spread over */
+typedef struct { int minX, maxX, minY, maxY; } BgEdges;
+
+/* ---------------------------------------------------------------- the sky */
+void bg_init(uint32_t seed); /* seeds the stars and clouds (the original uses Math.random) */
+uint32_t bg_sky_color(float hour); /* CityTime.getCurrentColor: 0xRRGGBB at this hour (0 to 24) */
+float bg_stars_alpha(float hour); /* Stars.update: the stars' stage alpha */
+float bg_clouds_alpha(float hour); /* Stars.update: cloudsAlpha */
+
+/* a story's planets and moons (its backgroundSprites) */
+typedef struct {
+ uint16_t spr; /* SPR_PLANETS_SMALL... */
+ uint16_t width; /* its "width" (frames are cut as getTexturesByWidth does) */
+ uint8_t image; /* the frame shown */
+ int16_t x, y; /* place at time 0 */
+ float velocity;
+} BgPlanet;
+#define BG_MAX_PLANETS 8
+void bg_set_planets(const BgPlanet *p, int n);
+
+/* the clouds: bg_clouds_start once the worlds are made (BackgroundImages.postCreate: the sky
+ * filled with clouds as if they had always been there), bg_clouds_update each tick with the
+ * original's timeMod times the game speed (BackgroundImages.update: they drift right, new ones
+ * come from the left) */
+#define BG_MAX_CLOUDS 128
+void bg_clouds_start(const BgEdges *e);
+void bg_clouds_update(float timeMod, const BgEdges *e);
+int bg_cloud_count(void);
+
+/* sky, stars, planets and clouds; time: CityTime.timeSinceStart (minutes) */
+void bg_draw_sky(const BgCamera *cam, double timeSinceStart);
+
+/* ---------------------------------------------------------------- the worlds */
+enum { BG_LOOK_NORMAL, BG_LOOK_KEY, BG_LOOK_KEY2, BG_LOOK_ROCK, BG_LOOK_ROCK_LESS_JAGGED, BG_LOOK_SNOW };
+int bg_look(const char *appearance); /* the original's appearance string ("", "key", "rock:lessJagged"...) */
+
+/* A world's look. Its island is made from the rect, the seed and the look when it
+ * is first drawn (or its mask asked for), and kept in a cache of BG_SHAPE_POOL
+ * bytes: about 3 bytes for each pixel column of island (theLostShip's 440 take
+ * 1314 bytes, FreePlayManyWorlds' 21 worlds 12.5 KB in all). Worlds not drawn for
+ * a while give their room to others and are made again when seen (some ms for a
+ * wide one); the islands one frame draws must fit together, or the last ones
+ * aren't drawn. A world must stay at the same address while its island is cached
+ * (bg_forget_shapes() after moving or reloading worlds). */
+typedef struct {
+ int16_t x, y, w, h; /* rect in city pixels; h 0: an invisible world (no island, no mask) */
+ int32_t seed;
+ uint8_t look; /* BG_LOOK_* */
+ uint8_t shape; /* bg.c's: the cache slot of its island + 1, 0 if none */
+} BgWorld;
+#define BG_SHAPE_POOL 6144
+#define BG_SHAPE_SLOTS 32
+void bg_forget_shapes(void);
+
+/* ground decorations: a byte per 20-pixel column, 0 for none, else kind << 4 | frame */
+enum { DECO_GRASS = 1, DECO_FLOWERS, DECO_FLOWERS_BLUE, DECO_ROCKS, DECO_KEYCITY, DECO_FLOWERS_KEYCITY,
+ DECO_PURPLEGRASS, DECO_REDGRASS, DECO_KINDS };
+int bg_deco_kind(const char *textureName); /* "spr_grass"... (0 if none) */
+uint16_t bg_deco_sprite(int kind);
+int bg_deco_frames(int kind);
+/* World.setDecoration: a decoration at column col (frame < 0: a random one); does nothing if
+ * the column has a permanent at the bottom (has_ground_permanent), as the original */
+void bg_set_decoration(uint8_t *decos, int col, int kind, int frame, bool has_ground_permanent);
+/* the new World's grass on every column (none for the snow look) */
+void bg_world_decorate(const BgWorld *w, uint8_t *decos);
+
+/* the island and the decorations (decos: one byte per column, or NULL) */
+void bg_draw_world(BgWorld *w, const uint8_t *decos, const BgCamera *cam);
+
+/* WorldImage's collision mask: whether the 20x20 cell (cx, cy) of the world's rect holds any of
+ * its island (Builder.canBuildBuilding); false for invisible worlds. Makes the island if it isn't
+ * cached. */
+bool bg_world_mask(BgWorld *w, int cx, int cy);
+#endif
diff --git a/games/finalearth2/src/bld.c b/games/finalearth2/src/bld.c
new file mode 100644
index 00000000..3e7c4bcb
--- /dev/null
+++ b/games/finalearth2/src/bld.c
@@ -0,0 +1,436 @@
+/* The Final Earth 2: the base classes' behaviour (Permanent, Building,
+ * House, Work, School and the entertainment and medical buildings'
+ * interfaces), dispatched to a class's own functions where it has them; the
+ * city-wide hooks the simulation calls (city changes, jobs), and the
+ * buildings' part of starting, saving and loading a city. */
+#include "bldi.h"
+#include "save.h"
+
+HappinessState happiness = {.happiness = -1, .actionSpeedModifier = 1, .actionSpeedModifierWithoutPenalties = 1,
+ .lastOvertimeDay = -1, .lastRestoreTime = -1, .veryUnhappyFromDay = -1, .lastShownVeryUnhappyWarning = -1};
+PoliciesVars policies = {.schoolMaxEdu = 1, .schoolClassSizeMod = 1};
+UpgradesVars upgrades = {.stoneMiningSpeed = 1, .computerChipFactorySpeed = 1};
+OperatingCostState operating_cost = {true};
+float bld_anim;
+bool bld_secret_orchid, bld_secret_dance, bld_secret_hangar;
+
+static inline const PermOps *OPS(const Perm *p) { return PC(p)->ops; }
+#define HAS(p, f) (OPS(p) && OPS(p)->f)
+
+/* ---------------------------------------------------------------- work */
+float bld_start_time(const Perm *p) { return HAS(p, start_time) ? OPS(p)->start_time(p) : PC(p)->startTime; }
+float bld_end_time(const Perm *p) { return HAS(p, end_time) ? OPS(p)->end_time(p) : PC(p)->endTime; }
+int bld_jobs(const Perm *p) { return HAS(p, jobs) ? OPS(p)->jobs(p) : PC(p)->jobs; }
+int bld_workers(const Perm *p) { return p->nworkers; }
+uint16_t bld_first_building_to_go_to(Perm *p) {
+ return HAS(p, first_building_to_go_to) ? OPS(p)->first_building_to_go_to(p) : pid(p);
+}
+/* Work.work: stop when it's time */
+void bld_work(Perm *p, Cit *c, float timeMod, bool shouldStopWorking) {
+ if (HAS(p, work)) {
+ OPS(p)->work(p, c, timeMod, shouldStopWorking);
+ return;
+ }
+ if (shouldStopWorking) c->currentAction = 2;
+}
+/* the job given (JobAssigner, after the building counts the new worker): its place in the workers' list */
+void bld_after_give_job(Perm *p, Cit *c) {
+ c->jobIndex = (uint8_t)(p->nworkers - 1);
+ if (HAS(p, after_give_job)) OPS(p)->after_give_job(p, c);
+ if (is_a(p, B_SCHOOL)) sim_flags |= SIM_SCHOOLS_CHANGED;
+}
+/* c leaves job's workers: those after it move up a place (HxOverrides.remove) */
+void bld_on_lose_job(Perm *job, Cit *c) {
+ if (!job) return;
+ uint16_t j = pid(job);
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *o = &cits[i];
+ if (o != c && (o->flags & CF_ALIVE) && o->job == j && o->jobIndex > c->jobIndex) o->jobIndex--;
+ }
+}
+
+/* ---------------------------------------------------------------- homes */
+int bld_residents(const Perm *p) {
+ int n = HAS(p, residents) ? OPS(p)->residents(p) : PC(p)->residents;
+ return n ? n + upgrades_residents_bonus(p->cls) : 0;
+}
+/* get_attractiveness: base (a home's info.quality, which city upgrades raise) and bonus (its upgrades and
+ * neighbours) */
+float bld_attractiveness(const Perm *p) {
+ float base;
+ if (HAS(p, attractiveness)) base = OPS(p)->attractiveness(p);
+ else if (is_a(p, B_HOUSE)) base = (float)PC(p)->quality + upgrades_quality_bonus(p->cls);
+ else base = 50;
+ return base + p->bonusAttractiveness;
+}
+float bld_years_to_live_longer(const Perm *p) { return HAS(p, years_to_live_longer) ? OPS(p)->years_to_live_longer(p) : 0; }
+bool bld_has_private_teleporter(const Perm *p) { return HAS(p, has_private_teleporter) && OPS(p)->has_private_teleporter(p); }
+/* WorkWithHome: its home is for its workers */
+int bld_fixed_capacity_for_workers(const Perm *p) {
+ if (HAS(p, fixed_capacity_for_workers)) return OPS(p)->fixed_capacity_for_workers(p);
+ return is_a(p, B_HOUSE) && is_a(p, B_WORK) ? bld_residents(p) : 0;
+}
+bool bld_keeps_residents(const Perm *p) { return p->cls == CLS_HouseOfTheKeyFriends; }
+
+/* House.walkAround */
+void bld_walk_around(Perm *p, Cit *c, float steps) {
+ if (HAS(p, walk_around)) {
+ OPS(p)->walk_around(p, c, steps);
+ return;
+ }
+ int r = rnd_int(4);
+ if (r == 0 && steps > 120) {
+ cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ } else if (r == 1) {
+ int x = rnd_between(3, 7);
+ cit_move_and_wait(c, x, rnd_between(30, 60), THEN_NONE, 0, false, false);
+ } else if (r == 2) {
+ int x = rnd_between(12, 16);
+ cit_move_and_wait(c, x, rnd_between(30, 60), THEN_NONE, 0, false, false);
+ } else {
+ wait_ticks(c, 90, 120);
+ }
+}
+
+/* ---------------------------------------------------------------- schools */
+float bld_school_start(const Perm *p) { (void)p; return 7; }
+float bld_school_end(const Perm *p) { (void)p; return 16; }
+int bld_student_capacity(const Perm *p) { return HAS(p, student_capacity) ? OPS(p)->student_capacity(p) : 0; }
+void bld_be_at_school(Perm *p, Cit *c, float timeMod) {
+ if (HAS(p, be_at_school)) OPS(p)->be_at_school(p, c, timeMod);
+}
+int student_index(const Perm *school, const Cit *c) {
+ int n = 0;
+ uint16_t s = pid(school);
+ for (int i = 1; i < cid(c); i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].school == s) n++;
+ return n;
+}
+
+/* ---------------------------------------------------------------- entertainment */
+bool ent_is_open(const Perm *p) { return HAS(p, is_open) ? OPS(p)->is_open(p) : true; }
+bool ent_is_open_for_existing_visitors(const Perm *p) {
+ return HAS(p, is_open_for_existing_visitors) ? OPS(p)->is_open_for_existing_visitors(p) : ent_is_open(p);
+}
+int ent_type(const Perm *p) { return HAS(p, entertainment_type) ? OPS(p)->entertainment_type(p) : PC(p)->entType; }
+float ent_min_time(const Perm *p) { return PC(p)->entMinTime; }
+float ent_max_time(const Perm *p) { return PC(p)->entMaxTime; }
+float ent_min_satisfy(const Perm *p) { return PC(p)->entMinSatisfy; }
+float ent_max_satisfy(const Perm *p) { return PC(p)->entMaxSatisfy; }
+bool ent_finish(Perm *p, Cit *c, float timeMod) {
+ return HAS(p, finish_entertainment) ? OPS(p)->finish_entertainment(p, c, timeMod) : true;
+}
+void ent_be_entertained(Perm *p, Cit *c, float timeMod) {
+ if (HAS(p, be_entertained)) OPS(p)->be_entertained(p, c, timeMod);
+}
+
+bool bld_is_lab(const Perm *p) { return p->cls == CLS_Laboratory || p->cls == CLS_ExperimentationLab; }
+float bld_herb_capacity(const Perm *p) { return HAS(p, herb_capacity) ? OPS(p)->herb_capacity(p) : 0; }
+float bld_entertainment_capacity(const Perm *p) {
+ return (HAS(p, entertainment_capacity) ? OPS(p)->entertainment_capacity(p) : 0) + p->bonusEntertainmentCapacity;
+}
+int bld_secondary_entertainment_types(const Perm *p) { return HAS(p, secondary_entertainment_types) ? OPS(p)->secondary_entertainment_types(p) : 0; }
+float bld_entertainment_quality(const Perm *p) { return HAS(p, entertainment_quality) ? OPS(p)->entertainment_quality(p) : PC(p)->entQuality; }
+float bld_medical_quality(const Perm *p) { return HAS(p, medical_quality) ? OPS(p)->medical_quality(p) : 0; }
+float bld_medical_capacity(const Perm *p) { return HAS(p, medical_capacity) ? OPS(p)->medical_capacity(p) : 0; }
+
+/* ---------------------------------------------------------------- adjacent effects */
+float bld_effect(const Perm *p, int effect) {
+ if (!is_building(p)) return 0;
+ switch (effect) {
+ case EF_FARM:
+ if (p->cls == CLS_IndoorFarm || p->cls == CLS_EcoFarm || p->cls == CLS_ExperimentalFarm) return 1;
+ if (p->cls == CLS_FarmHouse) return farmhouse_farm_effects(p);
+ return 0;
+ case EF_ALIEN_HOUSE: return p->cls == CLS_AlienHouse ? 1 : 0;
+ case EF_COMMUNITY:
+ return p->cls == CLS_ModernRusticHome || p->cls == CLS_ParkPod || class_is(p->cls, CLS_Park) ||
+ class_is(p->cls, CLS_BotanicalGardens) || p->cls == CLS_RooftopPark
+ ? 1
+ : 0;
+ case EF_CROPS: return p->cls == CLS_Laboratory && has_upgrade_bit(p, UB_Laboratory_FarmingResearch) ? 7.5f : 0;
+ case EF_TREE_GROWTH: return p->cls == CLS_Laboratory && has_upgrade_bit(p, UB_Laboratory_TreePlantationResearch) ? 0.2f : 0;
+ case EF_RESTAURANT_CAP: return p->cls == CLS_HerbGarden && p->mode == MODE_HerbGarden_CulinaryHerbs ? 10 : 0;
+ }
+ return 0;
+}
+float adj_effect_lr(const Perm *p, int effect) { return bld_effect(P(p->left), effect) + bld_effect(P(p->right), effect); }
+float adj_effect(const Perm *p, int effect) {
+ return bld_effect(P(p->left), effect) + bld_effect(P(p->right), effect) + bld_effect(P(p->top), effect) +
+ bld_effect(P(p->bottom), effect);
+}
+
+/* ---------------------------------------------------------------- citizens' small moves */
+/* the original's steps inline in work(): toward x at the walking speed, no path */
+void step_to_x(Cit *c, float x, float timeMod) {
+ float spd = c->pathWalkSpeed / 100.0f * timeMod;
+ if (fabsf(x - c->relativeX) < spd) c->relativeX = x;
+ else c->relativeX += (x > c->relativeX ? 1 : -1) * spd;
+}
+void set_rel(Cit *c, float x, float y) { c->relativeX = x, c->relativeY = y; }
+void wait_ticks(Cit *c, int tmin, int tmax) { cit_wait(c, rnd_between(tmin, tmax), THEN_NONE, 0); }
+void move_x(Cit *c, int x) { cit_move(c, x, THEN_NONE, 0, false); }
+void move_x_slow(Cit *c, int x) { cit_move(c, x, THEN_NONE, 0, true); }
+/* educationLevel = max(min(edu + amount, cap), edu), once per visit */
+bool educate(Cit *c, float amount, float cap) {
+ if (c->flags & CF_BUILDING_INITED) return false;
+ float e = c->educationLevel + amount;
+ if (e > cap) e = cap;
+ if (e > c->educationLevel) c->educationLevel = e;
+ c->flags |= CF_BUILDING_INITED;
+ return true;
+}
+/* out of its permanent, at the door (a building) or where it stands (a world resource) */
+void leave_to_surface(Cit *c) { cit_instant_leave_permanent(c); }
+
+/* ---------------------------------------------------------------- transport (bld_transport.c) */
+float bld_teleport_x(const Perm *p) { return transport_teleport_x(p); }
+void bld_teleport_used(Perm *p) { transport_teleport_used(p); }
+void bld_teleport_arrived(Perm *p) { transport_teleport_arrived(p); }
+bool bld_elevator_open_door(Perm *p) { return transport_elevator_open_door(p); }
+void bld_elevator_used(Perm *p) { transport_elevator_used(p); }
+void bld_elevator_arrived(Perm *p) { transport_elevator_arrived(p); }
+float bld_flying_distance(const Perm *a, const Perm *b) {
+ return (fabsf((float)(perm_city_x(a) - perm_city_x(b))) + fabsf((float)(perm_city_y(a) - perm_city_y(b)))) / 3;
+}
+
+/* ---------------------------------------------------------------- the city changes (CitySimulation.updatePathfinder) */
+static void invalidate_pathfinding_info(Perm *p) {
+ if (p->cls == CLS_WoodcuttingCentre || p->cls == CLS_StoneMine) ST(BlueCollarState, p)->nearest = NONE;
+ else if (p->cls == CLS_ExplorationCentre) ST(ExplorationState, p)->nearestRuins = NONE;
+}
+void finder_request_limiting(bool strict_first);
+void bld_city_changed(bool invalidate) {
+ if (invalidate) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (perms[i].flags & PF_USED) invalidate_pathfinding_info(&perms[i]);
+ finder_request_limiting(true);
+ }
+ memset(world_unavailable, 0, sizeof world_unavailable); /* World.onCityChange */
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && HAS(p, on_city_change)) OPS(p)->on_city_change(p);
+ }
+ operating_cost_recalculate();
+}
+
+/* Building.onBuild (after World.build put it in its stack) */
+void bld_on_build(Perm *p) {
+ if (HAS(p, on_build)) OPS(p)->on_build(p);
+}
+/* postCreate (after City.onBuildBuilding linked it): the classes that have one */
+void garden_post_create(Perm *p);
+void redwood_post_create(Perm *p);
+void hall_post_create(Perm *p);
+void stone_center_post_create(Perm *p);
+void bld_post_create(Perm *p) {
+ if (!p) return;
+ if (class_is(p->cls, CLS_BotanicalGardens)) garden_post_create(p);
+ else if (class_is(p->cls, CLS_RedwoodTree)) redwood_post_create(p);
+ else if (p->cls == CLS_HoloGameHall) hall_post_create(p);
+ else if (p->cls == CLS_StoneResearchCenter) stone_center_post_create(p);
+ else if (p->cls == CLS_CityHall) {
+ if (p->mode >= 4) upgrade_first_mode(p); /* (its first mode, if missing) */
+ } else {
+ decoration_post_create(p); /* (the rooftop decorations only) */
+ }
+}
+
+/* tryDestroy of the classes that refuse: the cityofthekey's first landing sites, redwoods holding a tree house up */
+int bld_destroy_check(const Perm *p, const char **why) {
+ *why = NULL;
+ if (p->cls == CLS_LandingSite && story_is("cityofthekey") && (perm_city_x(p) == 100 || perm_city_x(p) == -100)) {
+ *why = "The Key wouldn't want that.";
+ return DR_PROTECTED;
+ }
+ if (class_is(p->cls, CLS_RedwoodTree)) {
+ redwood_destroy_refusal(p, why);
+ if (*why) return DR_REFUSED;
+ }
+ return DR_OK;
+}
+
+/* doorX: mirrored buildings move it */
+float house_door_x(const Perm *p);
+float bld_door_x(const Perm *p) {
+ switch (p->cls) {
+ case CLS_RooftopDecoration: case CLS_RooftopDecoration2: case CLS_RooftopDecoration3: case CLS_RooftopDecoration4:
+ return decoration_door_x(p);
+ default: return house_door_x(p);
+ }
+}
+
+/* workers[index]: the worker at that place of the list (jobIndex), NULL if none */
+Cit *worker_at(const Perm *p, int index) {
+ uint16_t id = pid(p);
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job == id && cits[i].jobIndex == index) return &cits[i];
+ return NULL;
+}
+/* workers[0].currentAction == 0 (is_open tests): the buildings whose first worker works, found once a step */
+static uint8_t first_working[(MAX_PERMS + 7) / 8];
+static uint32_t first_working_step = 0xFFFFFFFFu, bld_step;
+bool first_worker_working(const Perm *p) {
+ if (first_working_step != bld_step) {
+ memset(first_working, 0, sizeof first_working);
+ for (int i = 1; i < MAX_CITS; i++) {
+ const Cit *c = &cits[i];
+ if ((c->flags & CF_ALIVE) && c->job && c->jobIndex == 0 && c->currentAction == 0)
+ first_working[c->job >> 3] |= (uint8_t)(1 << (c->job & 7));
+ }
+ first_working_step = bld_step;
+ }
+ uint16_t id = pid(p);
+ return p->nworkers > 0 && (first_working[id >> 3] >> (id & 7) & 1);
+}
+
+/* World.build and City.onBuildBuilding for a building the code makes itself (a redwood growing, a tree house):
+ * no cost; replace: the permanent at (col, row) goes first */
+uint16_t bld_build_at(int w, int col, int row, int cls, bool replace) {
+ if (replace) {
+ uint16_t old = perm_at(w, col, row);
+ if (old) perm_destroy(old, true);
+ }
+ uint16_t id = perm_new(cls, w, col, row);
+ if (!id) return NONE;
+ bld_on_build(P(id));
+ city_update_connections();
+ sim_update_pathfinder(replace, id);
+ unlocks_research(cls);
+ bld_post_create(P(id));
+ unlocks_check_build_related();
+ return id;
+}
+
+/* ---------------------------------------------------------------- drawing */
+void bld_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ if (HAS(p, draw)) {
+ OPS(p)->draw(b, p, layer, x, y);
+ return;
+ }
+ if (PC(p)->kind == KIND_BUILDING) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ draw_upgrades(b, p, layer, x, y, true);
+ }
+}
+void bld_draw_free(const GfxBand *b, int layer) {
+ flying_draw_free(b, layer);
+ research_bot_draw_free(b, layer);
+ hobby_draw_free(b, layer);
+}
+
+/* ---------------------------------------------------------------- the story's questions */
+static Perm *first_of(int cls) {
+ /* world by world, column by column (the original's permanents order for scenario worlds) */
+ for (int w = 0; w < nworlds; w++)
+ for (int x = 0; x < worlds[w].ncols; x++)
+ for (int y = 0; y < col_stack_height(w, x); y++) {
+ Perm *p = P(perm_at(w, x, y));
+ if (p && p->cls == cls) return p;
+ }
+ return NULL;
+}
+float bld_alien_ruins_explored(void) {
+ Perm *p = first_of(CLS_ComputerAlienRuins);
+ return p ? ruins_explored(p) : 0;
+}
+float research_bot_time_working(const Perm *p);
+float bld_research_bot_time(void) {
+ Perm *p = first_of(CLS_ResearchBot);
+ return p ? research_bot_time_working(p) : 0;
+}
+int hacker_mission(const Perm *p);
+float bld_hacker_mission(void) {
+ Perm *p = first_of(CLS_HackerHQ);
+ return p ? (float)hacker_mission(p) : -1;
+}
+float decryptor_time_working(const Perm *p);
+float bld_decryptor_time(void) {
+ Perm *p = first_of(CLS_AlienDecryptor);
+ return p ? decryptor_time_working(p) : 0;
+}
+
+/* ---------------------------------------------------------------- start, save and load */
+uint8_t TH_CHANGE_FLOOR, TH_CHANGE_FLOOR_WAIT_30_60;
+static void th_change_floor(Cit *c, uint16_t arg) { (void)arg; cit_change_floor(c, THEN_NONE, 0); }
+static void th_change_floor_wait(Cit *c, uint16_t arg) { (void)arg; cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0); }
+
+void bld_init(void) {
+ static bool done;
+ if (done) return;
+ done = true;
+ TH_CHANGE_FLOOR = then_register(th_change_floor);
+ TH_CHANGE_FLOOR_WAIT_30_60 = then_register(th_change_floor_wait);
+ bld_houses_init();
+ bld_production_init();
+ bld_services_init();
+ bld_entertainment_init();
+ bld_transport_init();
+ bld_unique_init();
+ bld_world_init();
+ bld_hobbies_init();
+}
+
+/* a new city: the city-wide state of the buildings as the original's constructors make it */
+void bld_new_city(void) {
+ bld_init();
+ memset(&upgrades, 0, sizeof upgrades);
+ upgrades.stoneMiningSpeed = upgrades.computerChipFactorySpeed = 1;
+ memset(&policies, 0, sizeof policies);
+ policies.schoolMaxEdu = policies.schoolClassSizeMod = 1;
+ bonuses.extraFoodFromFarms = 0;
+ bonuses.machinePartsFactorySpeed = bonuses.labSpeed = bonuses.indoorFarmSpeed = bonuses.ecoFarmSpeed = 1;
+ recycling_amount = 0;
+ bld_anim = 0;
+ eating.foodRationing = false;
+ upgrades_new_city();
+ saucers_new_city();
+ ruins_new_city();
+ hobbies_new_city();
+ unique_new_city();
+}
+
+void bld_after_load(void) {
+ ruins_after_load();
+ hobbies_after_load();
+ upgrades_after_load();
+}
+
+void saucers_save(SaveIO *io);
+bool saucers_load(SaveIO *io);
+void hobbies_save(SaveIO *io);
+bool hobbies_load(SaveIO *io);
+void unique_save(SaveIO *io);
+bool unique_load(SaveIO *io);
+/* what is not in the permanents (save.c calls these after the citizens) */
+void bld_save(SaveIO *io) {
+ save_u32(io, 0x424C4431u); /* "BLD1" */
+ save_bytes(io, &city_upgrades, sizeof city_upgrades);
+ save_f32(io, recycling_amount);
+ save_u8(io, (uint8_t)(bld_secret_orchid | bld_secret_dance << 1 | bld_secret_hangar << 2));
+ /* the workers' places in their jobs' lists, citizen by citizen */
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job) save_u8(io, cits[i].jobIndex);
+ saucers_save(io);
+ hobbies_save(io);
+ unique_save(io);
+}
+bool bld_load(SaveIO *io) {
+ if (load_u32(io) != 0x424C4431u) return false;
+ load_bytes(io, &city_upgrades, sizeof city_upgrades);
+ recycling_amount = load_f32(io);
+ uint8_t secrets = load_u8(io);
+ bld_secret_orchid = secrets & 1, bld_secret_dance = secrets >> 1 & 1, bld_secret_hangar = secrets >> 2 & 1;
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job) cits[i].jobIndex = load_u8(io);
+ if (!saucers_load(io) || !hobbies_load(io) || !unique_load(io)) return false;
+ bld_after_load();
+ return true;
+}
+
+/* once a simulation step, after the permanents (CitySimulation: buildingUpgradesToUpdate) */
+void building_upgrades_update(float timeMod) {
+ bld_anim += timeMod;
+ bld_step++;
+}
diff --git a/games/finalearth2/src/bld.h b/games/finalearth2/src/bld.h
new file mode 100644
index 00000000..46da4b75
--- /dev/null
+++ b/games/finalearth2/src/bld.h
@@ -0,0 +1,208 @@
+/* The Final Earth 2: what buildings do for citizens, and the city-wide
+ * systems they touch (happiness, policies, research, operating costs). */
+#ifndef FE_BLD_H
+#define FE_BLD_H
+#include <math.h>
+#include <stdlib.h>
+#include "sim.h"
+
+/* the citizens' sprites (spr_children and spr_humans, 51 each, then Dracula and Waldo) and names */
+#define NCITIZEN_SPRITES 53
+#define NCITIZEN_NAMES 8913
+#define NAME_WALDO 3730
+#define NAME_DRACULA 8913
+
+/* ---------------------------------------------------------------- city-wide state */
+typedef struct {
+ float happiness; /* -1 until first computed */
+ float actualHappiness;
+ float actionSpeedModifier, actionSpeedModifierWithoutPenalties;
+ float homeHappiness, schoolHappiness, purposeHappiness, entertainmentHappiness;
+ float medicalHappiness, specializedMedicalHappiness;
+ float perEntertainmentType[5];
+ float healthCapacityByType[10];
+ int numberOfGroupsWithCitizens;
+ float foodShortageUnhappiness, foodRationingUnhappiness;
+ float overtimeUnhappinessActual, overtimeUnhappinessShown, lastOvertime, lastOvertimeDay, lastRestoreTime;
+ float enthusiasmHappiness, happinessEnthusiasmLevel;
+ float fullHappinessTime, fullHappinessTimeout;
+ int veryUnhappyFromDay, lastShownVeryUnhappyWarning;
+ bool ignoreUnhappyCitizens;
+ bool gloryOfTheKey;
+} HappinessState;
+extern HappinessState happiness;
+/* a HappinessBoost's text: HB_* (the user interface says it in the original's words) */
+enum { HB_MUSIC_FESTIVAL, HB_CITIZEN_GRATEFULNESS, HB_HAUNTED_LABS };
+void happiness_add_boost(double until, float boost, bool over_max, uint8_t text);
+int happiness_boosts(void); /* the boosts running */
+float happiness_boost(int i, uint8_t *text); /* boost i: its amount and its text (HB_*) */
+/* simulation.GloryOfTheKey (cityofthekey): its happiness and the three parts it is the mean of */
+typedef struct {
+ float gloryOfTheKeyHappiness, highEndHomeHappiness, expensiveRestaurantHappiness, sculpturesHappiness;
+} GloryOfTheKey;
+float glory_of_the_key_happiness(void);
+const GloryOfTheKey *glory_of_the_key(void);
+
+#define STATS_DAYS 7
+typedef struct {
+ int people, jobs, houseCapacity, peopleWithHome, peopleWithAJob, children, laborForce, peopleWorkingAtLabs;
+ double materialProduction[M_COUNT][STATS_DAYS], materialUsed[M_COUNT][STATS_DAYS]; /* today first */
+ float lastMorningCommute;
+} Stats;
+extern Stats stats;
+void stats_add_production(int m, double amount);
+void stats_add_used(int m, double amount);
+/* the city's materials, recording the stats (Materials setters) */
+void mat_add(int m, double amount); /* produced */
+bool mat_take(int m, double amount); /* used, if there is enough */
+bool mat_can_afford(const float cost[M_COUNT]);
+void mat_pay(const float cost[M_COUNT]); /* (no stats, like building costs) */
+
+typedef struct {
+ bool foodRationing;
+ float currentFoodSaveByHerbsPct, herbsCap, foodShortage, totalConsumedFoodPerDay;
+} EatingState;
+extern EatingState eating;
+
+typedef struct {
+ int softPopLimit, mode, targetPopAmount;
+ float updateStatsIn;
+} BabyMakerState;
+extern BabyMakerState babies;
+int spawners_pending(void);
+void unlocks_check_stat_related(void);
+void ui_pause_for_window(void);
+void operating_cost_recalculate(void);
+void operating_cost_set_teleporters(bool on, bool by_user);
+
+typedef struct {
+ float workTimeChange; /* policies.vars.workTimeChange (MandatoryOvertime) */
+ float schoolMaxEdu, schoolClassSizeMod; /* SmallerClasses (1 and 1 until bld_new_city) */
+} PoliciesVars;
+extern PoliciesVars policies;
+
+typedef struct {
+ float extendAgeBy; /* upgrades.vars.extendAgeBy */
+ float rocketTeleporterReward;
+ /* cityUpgrades.UpgradeVars, set by bld_new_city and the city upgrades (upgrades.c) */
+ float stoneMiningSpeed, computerChipFactorySpeed, recyclingAmount, stoneTeleporterChanceForRefinedMetals;
+ float extraEcoFarmFoodToPlot1, extraEcoFarmFoodToPlot2, superComputerUpgrade, fasterRocketFuelFactory;
+ float nightClubEntertainmentQualityBonus;
+ uint16_t stoneResearchCenterWithFossils; /* the building, 0 none */
+ bool hasBirthControl, starDatabaseIsMoreEffective, stoneTeleporterHasBigStones, advancedBuildingAllowed;
+ bool hasGalacticLibrary, hasConnectedMachines, hasGeneEditing;
+} UpgradesVars;
+extern UpgradesVars upgrades;
+
+typedef struct {
+ bool teleportersEnabled;
+} OperatingCostState;
+extern OperatingCostState operating_cost;
+
+void stats_on_commute(float minutes);
+void baby_on_citizen_death(void);
+bool story_is(const char *name);
+
+/* ---------------------------------------------------------------- what a building is and does */
+float bld_start_time(const Perm *p);
+float bld_end_time(const Perm *p);
+float bld_school_start(const Perm *p);
+float bld_school_end(const Perm *p);
+int bld_jobs(const Perm *p);
+int bld_residents(const Perm *p);
+int bld_workers(const Perm *p);
+int bld_student_capacity(const Perm *p);
+int bld_fixed_capacity_for_workers(const Perm *p);
+float bld_attractiveness(const Perm *p); /* get_attractiveness (base + bonus) */
+float bld_years_to_live_longer(const Perm *p);
+bool bld_has_private_teleporter(const Perm *p);
+bool bld_keeps_residents(const Perm *p); /* HouseOfTheKeyFriends */
+uint16_t bld_first_building_to_go_to(Perm *p);
+float bld_door_x(const Perm *p); /* doorX (mirrored buildings move it) */
+void bld_work(Perm *p, Cit *c, float timeMod, bool shouldStopWorking);
+void bld_walk_around(Perm *p, Cit *c, float stepsInBuilding);
+void bld_be_at_school(Perm *p, Cit *c, float timeMod);
+void bld_after_give_job(Perm *p, Cit *c);
+/* transport */
+float bld_teleport_x(const Perm *p);
+void bld_teleport_used(Perm *p);
+void bld_teleport_arrived(Perm *p);
+bool bld_elevator_open_door(Perm *p);
+void bld_elevator_used(Perm *p);
+void bld_elevator_arrived(Perm *p);
+float bld_flying_distance(const Perm *a, const Perm *b); /* estimatedFlyingDistanceTo */
+bool flying_board(Cit *c, Perm *in, Perm *dest); /* a landing site's step: false if the path was dropped */
+uint16_t bld_misdirector(void);
+bool bld_is_misdirector(const Perm *p);
+float bld_misdirect_chance(void);
+void bld_misdirector_reward(Perm *p);
+
+bool bld_is_lab(const Perm *p); /* Laboratory, ExperimentationLab, GrapheneLab (stats) */
+float bld_herb_capacity(const Perm *p);
+float bld_entertainment_capacity(const Perm *p); /* base + bonus (any permanent) */
+int bld_secondary_entertainment_types(const Perm *p);
+float bld_entertainment_quality(const Perm *p);
+float bld_medical_quality(const Perm *p);
+float bld_medical_capacity(const Perm *p);
+
+/* entertainment buildings */
+bool ent_is_open(const Perm *p);
+bool ent_is_open_for_existing_visitors(const Perm *p);
+int ent_type(const Perm *p);
+float ent_min_time(const Perm *p), ent_max_time(const Perm *p); /* hours */
+float ent_min_satisfy(const Perm *p), ent_max_satisfy(const Perm *p); /* days */
+bool ent_finish(Perm *p, Cit *c, float timeMod);
+void ent_be_entertained(Perm *p, Cit *c, float timeMod);
+
+/* hobbies (simulation.citizenSpecialActions) */
+bool hobby_is_active(const Cit *c);
+void hobby_update(Cit *c, float timeMod);
+void hobby_on_die(Cit *c);
+
+/* the buildings' part of the city (bld*.c): bld_init once at start (it registers the closures);
+ * bld_new_city when a city is made (before its worlds); bld_after_load after a save is read */
+void bld_init(void);
+void bld_new_city(void);
+void bld_after_load(void);
+void bld_city_changed(bool invalidate); /* updatePathfinder: onCityChange and friends (sim.c) */
+void bld_on_lose_job(Perm *job, Cit *c); /* before c leaves job's workers (citizen.c) */
+void bld_customize(Perm *p, int decor, bool mirrored); /* a story stack's look: decoration (-1 none), mirrored */
+void saucer_spawn(int world, int amount, int ageMin, int ageMax, int toCol); /* SpawnFlyingSaucer */
+/* window buttons the user interface answers itself (a class's window passes them to win_button; pressing one
+ * calls window_action with it, which ignores it): */
+enum {
+ WA_UI_BIRTH_CONTROL = 100, /* MedicalClinic: "Manage Birth Control" window */
+ WA_UI_CITY_NAME, /* CityHall: "Change City Name" */
+ WA_UI_REPLACE_HOUSES, /* LivingResearchCenter: "Upgrade Basic Houses" (the house upgrade window) */
+ WA_UI_MOVE_RUINS, /* explored alien ruins: pick an empty column, then bld_move_resource */
+ WA_UI_COLOR_PICKER, /* a tinted decoration: pick a colour, then bld_customize_color */
+ WA_UI_DUPLICATE /* a tinted decoration: build another like it (bld_customize, bld_customize_color) */
+};
+/* a class's own tryDestroy: DR_OK, or DR_PROTECTED or DR_REFUSED (build.h) with the window's words in why */
+int bld_destroy_check(const Perm *p, const char **why);
+void bld_customize_color(Perm *p, int32_t rgb); /* customizeColor: 0xRRGGBB, -1 none */
+int32_t bld_decoration_color(const Perm *p); /* currentRecolor, -1 none */
+int bld_decoration_look(const Perm *p, bool *mirrored); /* currentTexture and mirrored (Duplicate) */
+uint16_t bld_move_resource(uint16_t id, int world, int col); /* a world resource to an empty column (its new id) */
+void resource_planted(Perm *p, float materials_left, float regrow); /* a forest or rock from the build menu */
+/* GUI.showSimpleWindow(text, null, true): the open windows give way to a text (the user interface's) */
+void ui_show_simple(const char *text);
+/* a building's mission as a goal (getGlobalGoal: hackers, Secret Society, hippies): false if none */
+bool bld_global_goal(const Perm *p, const char **category, const char **text);
+/* the music festival (simulation.festival): while it runs, sim.c updates citizens with festival_citizen */
+bool festival_running(void);
+void festival_citizen(Cit *c, float timeMod);
+/* drawing what belongs to no permanent on screen (flying saucers and craft, hobbies' props): at the end of
+ * each layer's band function, after the permanents (view.c) */
+void bld_draw_free(const GfxBand *b, int layer);
+/* how far a permanent may draw outside its 20x20 cell (pipes, flowers on roofs), in city pixels */
+#define BLD_DRAW_ABOVE 12
+#define BLD_DRAW_BELOW 12
+
+/* assign.c */
+void assign_jobs(void);
+void assign_houses(void);
+void assign_schools(void);
+void finder_pre_update(void);
+void finder_invalidate(void);
+#endif
diff --git a/games/finalearth2/src/bld_decoration.c b/games/finalearth2/src/bld_decoration.c
new file mode 100644
index 00000000..ee825fe9
--- /dev/null
+++ b/games/finalearth2/src/bld_decoration.c
@@ -0,0 +1,138 @@
+/* The Final Earth 2: decoration (buildings.md 12): painted blocks,
+ * decorative windows and the rooftop decorations, their looks, colours and
+ * mirroring; and the story's customised buildings (bld_customize). */
+#include "bldi.h"
+#include "lang_data.h"
+
+static uint16_t decor_sprite(const Perm *p) {
+ switch (p->cls) {
+ case CLS_ColoredBlock: return SPR_COLOREDBLOCK;
+ case CLS_RooftopDecoration: return SPR_SLANTEDROOF;
+ case CLS_RooftopDecoration2: return SPR_SLANTEDROOFTOP;
+ case CLS_RooftopDecoration3: return SPR_DOMEROOF;
+ default: return SPR_ROOFBOTTOM;
+ }
+}
+/* getSubImageNumber: (width + 2) / 22 */
+static int sub_images(const Perm *p) { return (spr_w(decor_sprite(p)) + 2) / 22; }
+
+static void decor_init(Perm *p) { memset(p->s, 0, sizeof(DecorState)); }
+static uint16_t decor_tint(const DecorState *s) {
+ return s->bits & DS_TINTED ? tint565((uint32_t)s->rgb[0] << 16 | (uint32_t)s->rgb[1] << 8 | s->rgb[2]) : GFX_NO_TINT;
+}
+static void decor_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ const DecorState *s = STC(DecorState, p);
+ draw_decoration(b, p, layer, x, y, decor_sprite(p), s->look, s->bits & DS_FLIPPED, decor_tint(s));
+}
+/* mirror(): the field and the drawer turn, and the door moves */
+static void decor_mirror(Perm *p) {
+ DecorState *s = ST(DecorState, p);
+ s->bits ^= DS_MIRRORED | DS_FLIPPED;
+ s->bits = (uint8_t)((s->bits & ~DS_DOOR14) | DS_DOOR_SET | (s->bits & DS_MIRRORED ? DS_DOOR14 : 0));
+}
+float decoration_door_x(const Perm *p) {
+ const DecorState *s = STC(DecorState, p);
+ return s->bits & DS_DOOR_SET ? (s->bits & DS_DOOR14 ? 14 : 4) : PC(p)->doorX;
+}
+/* postCreate: a mirrored one is drawn mirrored; mirror() turns the field back (it is set again after) and so
+ * puts the door at 4 (as written). Done as its outcome, so that doing it twice changes nothing. */
+void decoration_post_create(Perm *p) {
+ if (p->cls != CLS_RooftopDecoration && p->cls != CLS_RooftopDecoration2 && p->cls != CLS_RooftopDecoration3 &&
+ p->cls != CLS_RooftopDecoration4)
+ return;
+ DecorState *s = ST(DecorState, p);
+ if (s->bits & DS_MIRRORED) s->bits = (uint8_t)((s->bits & ~DS_DOOR14) | DS_FLIPPED | DS_DOOR_SET);
+}
+static void decor_window(Perm *p, WinOut *w) {
+ const DecorState *s = STC(DecorState, p);
+ if (!(s->bits & DS_TINTED)) {
+ win_button(w, 0, L_change_building_color, WA_CYCLE_0, true);
+ } else {
+ /* the user interface's colour picker sets it with bld_customize_color */
+ win_button(w, 0, L_change_building_color, WA_UI_COLOR_PICKER, true);
+ win_space(w, 4);
+ win_button(w, 0, L_duplicate_building, WA_UI_DUPLICATE, true);
+ }
+ if (p->cls == CLS_RooftopDecoration) win_button(w, 0, L_mirror, WA_MIRROR, true); /* (only the slanted roof) */
+}
+static void decor_action(Perm *p, int a) {
+ DecorState *s = ST(DecorState, p);
+ if (a == WA_CYCLE_0) {
+ /* CycleValueButton over getSubImageNumber() - 1 looks (the last one is for any colour) */
+ int n = sub_images(p) - 1;
+ s->look = (uint8_t)(n > 0 ? (s->look + 1) % n : 0);
+ } else if (a == WA_MIRROR) {
+ decor_mirror(p);
+ }
+}
+#define DECOR_OPS {.init = decor_init, .draw = decor_draw, .window = decor_window, .window_action = decor_action}
+const PermOps ops_ColoredBlock = DECOR_OPS;
+const PermOps ops_RooftopDecoration = DECOR_OPS;
+const PermOps ops_RooftopDecoration2 = DECOR_OPS;
+const PermOps ops_RooftopDecoration3 = DECOR_OPS;
+const PermOps ops_RooftopDecoration4 = DECOR_OPS;
+
+/* GlassPiece: an empty indoor farm (0) or tree plantation (1) */
+static void glass_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, STC(DecorState, p)->look ? SPR_TREEPLANTATION : SPR_INDOORFARM, false);
+}
+static void glass_window(Perm *p, WinOut *w) { (void)p, win_button(w, 0, "Change Building Color", WA_CYCLE_0, true); }
+static void glass_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0) ST(DecorState, p)->look = (uint8_t)((ST(DecorState, p)->look + 1) % 2);
+}
+const PermOps ops_GlassPiece = {.init = decor_init, .draw = glass_draw, .window = glass_window, .window_action = glass_action};
+
+static bool is_decoration(const Perm *p) {
+ return p->cls == CLS_ColoredBlock || p->cls == CLS_GlassPiece || p->cls == CLS_RooftopDecoration ||
+ p->cls == CLS_RooftopDecoration2 || p->cls == CLS_RooftopDecoration3 || p->cls == CLS_RooftopDecoration4;
+}
+void house_mirror(Perm *p); /* (bld_houses.c: Loft, LandedExplorationShip) */
+/* the story's "Class*mirrored.decor" and "Class_mirrored" buildings (Story: customize, or mirror) */
+void bld_customize(Perm *p, int decor, bool mirrored) {
+ if (!p) return;
+ if (is_decoration(p)) {
+ DecorState *s = ST(DecorState, p);
+ s->look = (uint8_t)(decor < 0 ? 0 : decor);
+ /* (ColoredBlock and GlassPiece take no mirroring) */
+ if (mirrored && p->cls != CLS_ColoredBlock && p->cls != CLS_GlassPiece) s->bits |= DS_MIRRORED;
+ else s->bits &= (uint8_t)~DS_MIRRORED;
+ decoration_post_create(p);
+ return;
+ }
+ if (mirrored) house_mirror(p);
+}
+/* customizeColor: the "any colour" look, tinted (rgb < 0: none) */
+void bld_customize_color(Perm *p, int32_t rgb) {
+ if (!p || !is_decoration(p) || p->cls == CLS_GlassPiece) return;
+ DecorState *s = ST(DecorState, p);
+ if (rgb < 0) {
+ s->bits &= (uint8_t)~DS_TINTED;
+ return;
+ }
+ s->bits |= DS_TINTED;
+ s->rgb[0] = (uint8_t)(rgb >> 16), s->rgb[1] = (uint8_t)(rgb >> 8), s->rgb[2] = (uint8_t)rgb;
+}
+/* ICustomizableOnBuild.areSameCustomizations: the look (and colour; a slanted roof's mirroring too) the builder
+ * would give; true for classes not customised on building */
+bool bld_same_customizations(const Perm *p, int decor, bool mirrored, int32_t color) {
+ if (!is_decoration(p)) return true;
+ const DecorState *s = STC(DecorState, p);
+ if (s->look != decor) return false;
+ if (p->cls == CLS_GlassPiece) return true;
+ if (bld_decoration_color(p) != color) return false;
+ return p->cls != CLS_RooftopDecoration || ((s->bits & DS_MIRRORED) != 0) == mirrored;
+}
+/* the look the Duplicate button builds again (createOrRemoveBuilderForThis): look, mirroring (the roof pieces) */
+int bld_decoration_look(const Perm *p, bool *mirrored) {
+ *mirrored = false;
+ if (!p || !is_decoration(p)) return 0;
+ const DecorState *s = STC(DecorState, p);
+ *mirrored = p->cls != CLS_ColoredBlock && p->cls != CLS_GlassPiece && (s->bits & DS_MIRRORED);
+ return s->look;
+}
+/* currentRecolor, for the colour picker (-1 none) */
+int32_t bld_decoration_color(const Perm *p) {
+ if (!p || !is_decoration(p)) return -1;
+ const DecorState *s = STC(DecorState, p);
+ return s->bits & DS_TINTED ? (int32_t)((uint32_t)s->rgb[0] << 16 | (uint32_t)s->rgb[1] << 8 | s->rgb[2]) : -1;
+}
diff --git a/games/finalearth2/src/bld_draw.c b/games/finalearth2/src/bld_draw.c
new file mode 100644
index 00000000..6bdab79e
--- /dev/null
+++ b/games/finalearth2/src/bld_draw.c
@@ -0,0 +1,299 @@
+/* The Final Earth 2: the buildings' drawers (buildings.buildingDrawers.*):
+ * a building's back on LAYER_BG and front on LAYER_MAIN, merged with its
+ * neighbours' where the drawer does that, its upgrades' sprites, and colour
+ * helpers for the light shows. Everything is drawn into the band with
+ * gfx_band_sprite, positions scaled by the band's zoom. */
+#include "bldi.h"
+
+/* ---------------------------------------------------------------- basics */
+#ifdef HOST
+#include <stdio.h>
+#include <stdlib.h>
+int bld_bad_draws; /* (tests: parts asked for outside their sprite) */
+#endif
+void dr_part(const GfxBand *b, uint16_t spr, int sx, int sy, int w, int h, int x, int y, int dx, int dy, uint8_t flags,
+ uint8_t alpha, uint16_t tint) {
+ if (!spr || !alpha) return;
+#ifdef HOST
+ if (sx < 0 || sy < 0 || w <= 0 || h <= 0 || sx + w > spr_w(spr) || sy + h > spr_h(spr)) {
+ bld_bad_draws++;
+ if (getenv("BLD_DEBUG")) printf("bad part: spr %d (%dx%d) %d,%d %dx%d\n", spr, spr_w(spr), spr_h(spr), sx, sy, w, h);
+ }
+#endif
+ gfx_band_sprite(b, spr, sx, sy, w, h, x + dx * b->zoom, y + dy * b->zoom, flags, alpha, tint);
+}
+/* frame i of a strip of frames fw wide, 2 pixels apart (Resources.getTexturesByWidth) */
+void dr_frame(const GfxBand *b, uint16_t spr, int fw, int i, int x, int y, int dx, int dy, uint8_t flags, uint8_t alpha,
+ uint16_t tint) {
+ dr_part(b, spr, (fw + 2) * i, 0, fw, spr_h(spr), x, y, dx, dy, flags, alpha, tint);
+}
+void dr_sprite(const GfxBand *b, uint16_t spr, int x, int y, int dx, int dy, uint8_t flags, uint8_t alpha) {
+ dr_part(b, spr, 0, 0, spr_w(spr), spr_h(spr), x, y, dx, dy, flags, alpha, GFX_NO_TINT);
+}
+int frames_of(uint16_t spr, int fw) { return spr ? (spr_w(spr) + 2) / (fw + 2) : 0; }
+
+/* thx.color: HSV and HSL to RGB (hue in degrees) */
+static uint32_t rgbf(float r, float g, float b) {
+ int ri = (int)(r * 255 + 0.5f), gi = (int)(g * 255 + 0.5f), bi = (int)(b * 255 + 0.5f);
+ ri = ri < 0 ? 0 : ri > 255 ? 255 : ri, gi = gi < 0 ? 0 : gi > 255 ? 255 : gi, bi = bi < 0 ? 0 : bi > 255 ? 255 : bi;
+ return (uint32_t)(ri << 16 | gi << 8 | bi);
+}
+uint32_t hsv_to_rgb(float h, float s, float v) {
+ h = fmodf(h, 360);
+ if (h < 0) h += 360;
+ float c = v * s, hp = h / 60, x = c * (1 - fabsf(fmodf(hp, 2) - 1)), m = v - c;
+ float r = 0, g = 0, b = 0;
+ if (hp < 1) r = c, g = x;
+ else if (hp < 2) r = x, g = c;
+ else if (hp < 3) g = c, b = x;
+ else if (hp < 4) g = x, b = c;
+ else if (hp < 5) r = x, b = c;
+ else r = c, b = x;
+ return rgbf(r + m, g + m, b + m);
+}
+uint32_t hsl_to_rgb(float h, float s, float l) {
+ float c = (1 - fabsf(2 * l - 1)) * s;
+ float v = l + c / 2;
+ return hsv_to_rgb(h, v > 0 ? 2 * (1 - l / v) : 0, v);
+}
+
+/* ---------------------------------------------------------------- what each building's drawer shows */
+static const uint16_t main_textures[3] = {SPR_BOTANICALGARDENS, SPR_INDOORPARK, SPR_INDOORPARK_ALT1};
+static const uint16_t dome_textures[2][3] = {
+ {SPR_DOME_BOTANICALGARDEN, SPR_DOME_BOTANICALGARDEN_ALT1, SPR_DOME_BOTANICALGARDEN_ALT2},
+ {SPR_DOME_BOTANICALGARDEN_B, SPR_DOME_BOTANICALGARDEN_ALT1B, SPR_DOME_BOTANICALGARDEN_ALT2B}};
+
+void bld_drawer(const Perm *p, Drawer *d) {
+ const PermClass *pc = PC(p);
+ d->kind = DRW_NORMAL;
+ d->name = d->group = pc->sprite;
+ if (pc->kind != KIND_BUILDING) {
+ d->kind = DRW_NONE;
+ return;
+ }
+ switch (p->cls) {
+ case CLS_Park: case CLS_StatueGarden: case CLS_StatueOfHappiness: case CLS_StatueOfTheKey:
+ d->kind = DRW_AUTOMERGE;
+ d->name = d->group = main_textures[STC(ParkState, p)->mainTexture % 3];
+ break;
+ case CLS_ParkPod:
+ d->kind = DRW_AUTOMERGE;
+ d->name = d->group = main_textures[STC(ParkPodState, p)->mainTexture % 3];
+ break;
+ case CLS_Library: case CLS_Restaurant: case CLS_NightClub: case CLS_ScrapyardNightClub: case CLS_FactoryPub:
+ case CLS_HoloGameHall: case CLS_TreeHuggerBase:
+ d->kind = DRW_AUTOMERGE;
+ break;
+ case CLS_BotanicalGardens:
+ d->kind = DRW_ALLDIR;
+ d->name = d->group = main_textures[STC(GardenState, p)->mainTexture % 3];
+ break;
+ case CLS_BotanicalGardensDome: {
+ const GardenState *g = STC(GardenState, p);
+ d->kind = DRW_ROOFDOWN;
+ d->name = dome_textures[g->domeVersion & 1][g->mainTexture % 3];
+ d->group = main_textures[g->mainTexture % 3];
+ break;
+ }
+ case CLS_BlossomRestaurant: case CLS_BlossomHut:
+ d->kind = DRW_ALLDIR;
+ break;
+ case CLS_HerbGarden:
+ d->kind = DRW_DIFFTYPE;
+ if (p->mode == MODE_HerbGarden_MedicalHerbs) d->name = SPR_HERBGARDEN_MEDIC, d->group = SPR_BOTANICALGARDENS;
+ else d->name = SPR_HERBGARDEN, d->group = SPR_RESTAURANT;
+ break;
+ case CLS_RooftopPark:
+ d->kind = DRW_ROOFTOP_AM;
+ break;
+ case CLS_ColoredBlock: case CLS_RooftopDecoration: case CLS_RooftopDecoration2: case CLS_RooftopDecoration3:
+ case CLS_RooftopDecoration4: case CLS_RedwoodTree:
+ d->kind = DRW_DECORATION;
+ break;
+ case CLS_MechanicalHouse: d->name = d->group = mechanical_house_texture(p); break;
+ case CLS_Mansion: d->name = d->group = mansion_texture(p); break;
+ case CLS_GlassPiece: d->name = d->group = STC(DecorState, p)->look ? SPR_TREEPLANTATION : SPR_INDOORFARM; break;
+ default: break;
+ }
+}
+
+static bool merges_h(int kind) {
+ return kind == DRW_AUTOMERGE || kind == DRW_ALLDIR || kind == DRW_DIFFTYPE || kind == DRW_ROOFTOP_AM || kind == DRW_ROOFDOWN;
+}
+static bool merges_v(int kind) { return kind == DRW_ALLDIR || kind == DRW_ROOFDOWN; }
+/* isConnectedBuilding: the other merges (both ways if both is set) and shows the same texture or group */
+static bool connected(const Drawer *me, const Perm *o, bool both) {
+ if (!is_building(o)) return false;
+ Drawer od;
+ bld_drawer(o, &od);
+ if (!merges_h(od.kind) || (both && !merges_v(od.kind))) return false;
+ return od.name == me->name || od.group == me->group;
+}
+static bool same_texture(const Drawer *me, const Perm *o) {
+ if (!is_building(o)) return false;
+ Drawer od;
+ bld_drawer(o, &od);
+ return merges_h(od.kind) && od.name == me->name;
+}
+
+/* NormalBuildingDrawer: the 64x20 sheet's front (0), front with door (22) and back (44) */
+void draw_normal(const GfxBand *b, const Perm *p, int layer, int x, int y, uint16_t spr, bool mirrored) {
+ uint8_t f = mirrored ? GFX_FLIPX : 0;
+ if (layer == LAYER_BG) dr_part(b, spr, 44, 0, 20, 20, x, y, 0, 0, f, 255, GFX_NO_TINT);
+ else if (layer == LAYER_MAIN) dr_part(b, spr, p->row == 0 ? 22 : 0, 0, 20, 20, x, y, 0, 0, f, 255, GFX_NO_TINT);
+}
+/* CustomizableBuildingDrawer: a front without a door and a back of their own (0: the standard frames) */
+void draw_custom(const GfxBand *b, const Perm *p, int layer, int x, int y, uint16_t spr, bool mirrored,
+ uint16_t front_spr, int front_frame, uint16_t back_spr, int back_frame) {
+ uint8_t f = mirrored ? GFX_FLIPX : 0;
+ if (layer == LAYER_BG) {
+ if (back_spr) dr_frame(b, back_spr, 20, back_frame, x, y, 0, 0, f, 255, GFX_NO_TINT);
+ else dr_part(b, spr, 44, 0, 20, 20, x, y, 0, 0, f, 255, GFX_NO_TINT);
+ } else if (layer == LAYER_MAIN) {
+ if (p->row != 0 && front_spr) dr_frame(b, front_spr, 20, front_frame, x, y, 0, 0, f, 255, GFX_NO_TINT);
+ else dr_part(b, spr, p->row == 0 ? 22 : 0, 0, 20, 20, x, y, 0, 0, f, 255, GFX_NO_TINT);
+ }
+}
+/* DecorationBuildingDrawer: sub-image n at x 22n, on the main stage */
+void draw_decoration(const GfxBand *b, const Perm *p, int layer, int x, int y, uint16_t spr, int sub, bool mirrored,
+ uint16_t tint) {
+ (void)p;
+ if (layer == LAYER_MAIN) dr_part(b, spr, sub * 22, 0, 20, 20, x, y, 0, 0, mirrored ? GFX_FLIPX : 0, 255, tint);
+}
+
+/* the half frames of a striped sheet (getTexturesByWidth(name, 10, true)) */
+static inline int half_x(int i) { return 11 * i - (i & 1); }
+static void half(const GfxBand *b, uint16_t spr, int i, int row, int h, int x, int y, int dx, int dy) {
+ dr_part(b, spr, half_x(i), row * h, 10, h, x, y, dx, dy, 0, 255, GFX_NO_TINT);
+}
+
+/* the secondary background's row: alone, a garden below only, both, a garden above only */
+void draw_garden_plants(const GfxBand *b, const Perm *p, int x, int y, uint16_t spr, int texture, bool top, bool bottom) {
+ (void)p;
+ int row = (bottom ? 1 : 0) + (top ? 3 : 0) - (top && bottom ? 2 : 0);
+ dr_part(b, spr, 20 * texture, 20 * row, 20, 20, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+
+/* AutoMerging (and its rooftop and different-type kinds), AllDir and RooftopDown drawers */
+void draw_merging(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ if (layer != LAYER_BG && layer != LAYER_MAIN) return;
+ Drawer d;
+ bld_drawer(p, &d);
+ bool door = p->row == 0;
+ bool bg = layer == LAYER_BG;
+ if (d.kind == DRW_AUTOMERGE || d.kind == DRW_ROOFTOP_AM || d.kind == DRW_DIFFTYPE) {
+ const Perm *l = P(p->left), *r = P(p->right);
+ if (d.kind == DRW_ROOFTOP_AM) {
+ /* AutoMergingBuildingDrawerRooftop: on the ground, the buildings 20 pixels aside; else beside the one below */
+ const Perm *bot = P(p->bottom);
+ if (!bot) {
+ l = P(permanent_at_pos(perm_city_x(p) - 20, perm_city_y(p)));
+ r = P(permanent_at_pos(perm_city_x(p) + 20, perm_city_y(p)));
+ if (!is_building(l)) l = NULL;
+ if (!is_building(r)) r = NULL;
+ } else {
+ l = P(bot->left) ? P(P(bot->left)->top) : NULL;
+ r = P(bot->right) ? P(P(bot->right)->top) : NULL;
+ }
+ }
+ bool hl = connected(&d, l, false), hr = connected(&d, r, false);
+ int el = 0, er = 0;
+ if (d.kind == DRW_DIFFTYPE) {
+ el = hl && !same_texture(&d, l) ? 6 : 0;
+ er = hr && !same_texture(&d, r) ? 6 : 0;
+ }
+ if (bg) {
+ half(b, d.name, 4 + (hl ? 6 : 0) + el, 0, 20, x, y, 0, 0);
+ half(b, d.name, 5 + (hr ? 6 : 0) + er, 0, 20, x, y, 10, 0);
+ } else {
+ half(b, d.name, (door ? 2 : 0) + (hl ? 6 : 0) + el, 0, 20, x, y, 0, 0);
+ half(b, d.name, 1 + (door ? 2 : 0) + (hr ? 6 : 0) + er, 0, 20, x, y, 10, 0);
+ }
+ return;
+ }
+ if (d.kind == DRW_ROOFDOWN) {
+ /* RooftopDownMergingDrawer: one 20x20 frame of six */
+ bool hb = connected(&d, P(p->bottom), true);
+ if (bg) dr_frame(b, d.name, 20, hb ? 5 : 2, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ else dr_frame(b, d.name, 20, (hb ? 3 : 0) + (door ? 1 : 0), x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ return;
+ }
+ if (d.kind != DRW_ALLDIR) return;
+ const Perm *l = P(p->left), *r = P(p->right), *t = P(p->top), *bo = P(p->bottom);
+ bool hl = connected(&d, l, true), hr = connected(&d, r, true), ht = connected(&d, t, true), hb = connected(&d, bo, true);
+ bool htl = hl && ht && connected(&d, P(t->left), true);
+ bool htr = hr && ht && connected(&d, P(t->right), true);
+ bool hbl = hl && hb && connected(&d, P(l->bottom), true);
+ bool hbr = hr && hb && connected(&d, P(r->bottom), true);
+ hl = hl || connected(&d, l, false);
+ hr = hr || connected(&d, r, false);
+ int ktl = (hl ? 1 : 0) + (ht ? 2 : 0) + (htl ? 1 : 0), ktr = (hr ? 1 : 0) + (ht ? 2 : 0) + (htr ? 1 : 0);
+ int kbl = (hl ? 1 : 0) + (hb ? 2 : 0) + (hbl ? 1 : 0), kbr = (hr ? 1 : 0) + (hb ? 2 : 0) + (hbr ? 1 : 0);
+ uint16_t set = 0; /* setForegroundTextures / setBackgroundTextures (grids of 10 half columns) */
+ if (bg) {
+ if (p->cls == CLS_BlossomHut) set = SPR_BLOOMHOUSE;
+ if (set) {
+ half(b, set, 2 * ktl, 0, 10, x, y, 0, 0);
+ half(b, set, 1 + 2 * ktr, 0, 10, x, y, 10, 0);
+ half(b, set, 2 * kbl, 1, 10, x, y, 0, 10);
+ half(b, set, 1 + 2 * kbr, 1, 10, x, y, 10, 10);
+ } else {
+ half(b, d.name, 6 * ktl + 4, 0, 10, x, y, 0, 0);
+ half(b, d.name, 1 + 6 * ktr + 4, 0, 10, x, y, 10, 0);
+ half(b, d.name, 6 * kbl + 4, 1, 10, x, y, 0, 10);
+ half(b, d.name, 1 + 6 * kbr + 4, 1, 10, x, y, 10, 10);
+ }
+ if (p->cls == CLS_BotanicalGardens)
+ draw_garden_plants(b, p, x, y, SPR_BOTANICALGARDENS_PLANTS, STC(GardenState, p)->texture, ht, hb);
+ } else {
+ if (p->cls == CLS_BlossomRestaurant && !door) set = SPR_BLOOMRESTAURANT_FOREGROUND;
+ if (set) {
+ half(b, set, 2 * ktl, 0, 10, x, y, 0, 0);
+ half(b, set, 1 + 2 * ktr, 0, 10, x, y, 10, 0);
+ half(b, set, 2 * kbl, 1, 10, x, y, 0, 10);
+ half(b, set, 1 + 2 * kbr, 1, 10, x, y, 10, 10);
+ } else {
+ int dd = door ? 2 : 0;
+ half(b, d.name, 6 * ktl + dd, 0, 10, x, y, 0, 0);
+ half(b, d.name, 1 + 6 * ktr + dd, 0, 10, x, y, 10, 0);
+ half(b, d.name, 6 * kbl + dd, 1, 10, x, y, 0, 10);
+ half(b, d.name, 1 + 6 * kbr + dd, 1, 10, x, y, 10, 10);
+ }
+ }
+}
+
+/* SmartLights: CityTime.getCurrentColor over its keys (linear in RGB) */
+static uint16_t smart_light_tint(void) {
+ static const float t[7] = {0, 4, 6, 19, 21, 23, 24};
+ static const uint32_t c[7] = {0xE00000, 0xE00000, 0xFFFFFF, 0xFFFFFF, 0xFFD547, 0xFFD547, 0xE00000};
+ float h = hour_now();
+ int i = 0;
+ while (i < 5 && h >= t[i + 1]) i++;
+ float f = (h - t[i]) / (t[i + 1] - t[i]);
+ uint32_t a = c[i], bb = c[i + 1], out = 0;
+ for (int s = 16; s >= 0; s -= 8) {
+ float v = (float)(a >> s & 255) + ((float)(bb >> s & 255) - (float)(a >> s & 255)) * f;
+ out |= (uint32_t)(int)(v + 0.5f) << s;
+ }
+ return rgb565(out);
+}
+
+/* the building's upgrades' sprites (and its mode's) on this layer: cached ones, or the others after them */
+void draw_upgrades(const GfxBand *b, const Perm *p, int layer, int x, int y, bool no_cache) {
+ if (p->cls >= CLS_COUNT) return;
+ const ClassUpgrades *cu = &class_upgrades[p->cls];
+ for (int k = 0; k < 4; k++) {
+ int u;
+ if (k < 3) {
+ if (!cu->up[k] || !(p->upgrades >> k & 1)) continue;
+ u = cu->up[k] - 1;
+ } else {
+ if (!cu->mode[0] || p->mode >= 4 || !cu->mode[p->mode]) continue;
+ u = cu->mode[p->mode] - 1;
+ }
+ const UpgradeInfo *ui = &upgrade_info[u];
+ if (!ui->sprite || ui->layer != layer || (ui->noCache != 0) != no_cache) continue;
+ uint16_t tint = u == U_SmartLights ? smart_light_tint() : GFX_NO_TINT;
+ dr_frame(b, ui->sprite, 20, upgrade_look(p, u), x, y, 0, 0, 0, 255, tint);
+ }
+}
diff --git a/games/finalearth2/src/bld_entertainment.c b/games/finalearth2/src/bld_entertainment.c
new file mode 100644
index 00000000..456d28f5
--- /dev/null
+++ b/games/finalearth2/src/bld_entertainment.c
@@ -0,0 +1,1161 @@
+/* The Final Earth 2: entertainment (buildings.md 9): bars and restaurants,
+ * parks and gardens (ParkWalk), redwood trees, night clubs and their light
+ * shows, the art museum, the arcade and the holo game hall. */
+#include "bldi.h"
+
+static void walk_wait(Cit *c, int xmin, int xmax, int tmin, int tmax, bool slow) {
+ int x = rnd_between(xmin, xmax);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), THEN_NONE, 0, false, slow);
+}
+static void night_visit(Cit *c) {
+ /* bars and clubs: the night's entertainment satisfied for a few days (first call per visit) */
+ if (!(c->flags & CF_BUILDING_INITED)) {
+ c->wantsNightEntertainmentIn = (uint8_t)rnd_between(1, 5);
+ c->flags |= CF_BUILDING_INITED;
+ }
+}
+static bool open_between(const Perm *p, float start, float close) {
+ return first_worker_working(p) && hours_in(hour_now(), start, close);
+}
+static float workers_times(const Perm *p, float per) { return p->nworkers * per; }
+static void plain_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ draw_upgrades(b, p, layer, x, y, true);
+}
+
+/* ---------------------------------------------------------------- Pub and CarrotJuiceBar */
+static uint8_t TH_PUB_MOVE, TH_FACTORYPUB_MOVE, TH_TABLE, TH_LUX_TABLE, TH_ARCADE_MOVE, TH_MUSEUM_MOVE;
+static void th_pub_move(Cit *c, uint16_t arg) { (void)arg; move_x(c, rnd_between(7, 16)); }
+static void pub_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (c->relativeY < 5) cit_change_floor(c, TH_PUB_MOVE, 0);
+ else cit_wait_random(c, 120, 180, TH_PUB_MOVE, 0);
+ night_visit(c);
+}
+static float pub_capacity(const Perm *p) { return workers_times(p, 50); }
+static bool pub_open(const Perm *p) {
+ return p->nworkers == 1 && open_between(p, 20 - 0.5f, 4.5f) && !STC(PubState, p)->marked;
+}
+static void pub_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop && hour_now() > 4.5f) c->currentAction = 2;
+ else if (c->relativeY < 5) cit_change_floor(c, THEN_NONE, 0);
+ else step_to_x(c, 3, timeMod);
+}
+void pub_set_marking(Perm *p, bool on) {
+ if (p && p->cls == CLS_Pub) ST(PubState, p)->marked = on;
+}
+static void pub_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ plain_draw(b, p, layer, x, y);
+ if (layer == LAYER_MAIN && STC(PubState, p)->marked) dr_sprite(b, SPR_PUB_MARKING_KEY, x, y, 2, 10, 0, 255);
+}
+const PermOps ops_Pub = {.work = pub_work, .is_open = pub_open, .entertainment_capacity = pub_capacity,
+ .be_entertained = pub_be_entertained, .draw = pub_draw};
+
+/* (as written: with two or three workers it is never open) */
+static bool juice_open(const Perm *p) { return p->nworkers == 1 && open_between(p, 20 - 0.5f, 4.5f); }
+static void juice_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop && hour_now() > 4.5f) {
+ c->currentAction = 2;
+ return;
+ }
+ switch (worker_index(c)) {
+ case 0:
+ if (c->relativeY < 5) cit_change_floor(c, THEN_NONE, 0);
+ else step_to_x(c, 3, timeMod);
+ break;
+ case 1:
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 12, 16, 30, 60, false);
+ break;
+ case 2:
+ if (c->relativeY < 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 7, 16, 90, 120, false);
+ break;
+ }
+}
+const PermOps ops_CarrotJuiceBar = {.work = juice_work, .is_open = juice_open, .entertainment_capacity = pub_capacity,
+ .be_entertained = pub_be_entertained, .draw = plain_draw};
+
+/* ---------------------------------------------------------------- restaurants */
+static bool is_restaurant(const Perm *q) { return q && class_is(q->cls, CLS_Restaurant); }
+static bool restaurant_open(const Perm *p) { return p->nworkers >= 1 && open_between(p, 16 - 0.5f, 0.5f); }
+static float restaurant_capacity(const Perm *p) { return (float)(int)(p->nworkers * (45 + adj_effect_lr(p, EF_RESTAURANT_CAP))); }
+/* getTopTable: arg bit 0 says a restaurant is on the right */
+static void th_table(Cit *c, uint16_t arg) {
+ static const int8_t x[4] = {4, 7, 14, 17};
+ move_x(c, x[rnd_int(3 + (arg & 1))]);
+}
+static void restaurant_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ if (c->flags & CF_BUILDING_INITED) {
+ cit_wait_random(c, 30, 60, THEN_NONE, 0);
+ return;
+ }
+ bool left = is_restaurant(P(p->left)), right = is_restaurant(P(p->right));
+ c->wantsNightEntertainmentIn = (uint8_t)rnd_between(1, 5);
+ c->flags |= CF_BUILDING_INITED;
+ if (c->relativeY <= 5) {
+ if (rnd_int(3) <= 1) cit_change_floor(c, TH_TABLE, right);
+ else if (left) move_x(c, rnd_int(2) == 0 ? 1 : 6);
+ else move_x(c, rnd_int(2) == 0 ? 3 : 6);
+ } else {
+ th_table(c, right);
+ }
+}
+static void restaurant_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop && hour_now() > 0.5f) {
+ c->currentAction = 2;
+ return;
+ }
+ switch (worker_index(c)) {
+ case 0:
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else step_to_x(c, 12, timeMod);
+ break;
+ case 1:
+ if (c->relativeY < 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, is_restaurant(P(p->left)) ? 0 : 3, is_restaurant(P(p->right)) ? 19 : 16, 60, 90, false);
+ break;
+ }
+}
+const PermOps ops_Restaurant = {.work = restaurant_work, .is_open = restaurant_open, .entertainment_capacity = restaurant_capacity,
+ .be_entertained = restaurant_be_entertained, .draw = draw_merging};
+
+static float lux_capacity(const Perm *p) { return (float)(int)(p->nworkers * (25 + adj_effect_lr(p, EF_RESTAURANT_CAP))); }
+static void th_lux_table(Cit *c, uint16_t arg) { (void)arg; move_x(c, rnd_int(2) == 0 ? 4 : 14); }
+static void lux_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (c->flags & CF_BUILDING_INITED) {
+ cit_wait_random(c, 30, 60, THEN_NONE, 0);
+ return;
+ }
+ c->wantsNightEntertainmentIn = (uint8_t)rnd_between(1, 5);
+ c->flags |= CF_BUILDING_INITED;
+ if (c->relativeY <= 5) {
+ if (rnd_int(3) == 0) move_x(c, rnd_between(4, 6));
+ else cit_change_floor(c, TH_LUX_TABLE, 0);
+ } else {
+ th_lux_table(c, 0);
+ }
+}
+static void lux_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop && hour_now() > 0.5f) {
+ c->currentAction = 2;
+ return;
+ }
+ switch (worker_index(c)) {
+ case 0:
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else step_to_x(c, 12, timeMod);
+ break;
+ case 1:
+ if (c->relativeY < 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 3, 16, 60, 90, false);
+ break;
+ }
+}
+const PermOps ops_LuxuryRestaurant = {.work = lux_work, .is_open = restaurant_open, .entertainment_capacity = lux_capacity,
+ .be_entertained = lux_be_entertained, .draw = plain_draw};
+
+/* FactoryPub: a refined metals factory (bld_production.c) that is also a pub */
+static bool factory_pub_open(const Perm *p) { return p->nworkers >= 1 && open_between(p, 16.5f - 0.5f, 4.5f); }
+static float factory_pub_capacity(const Perm *p) { return workers_times(p, 25); }
+static void th_factory_pub_move(Cit *c, uint16_t arg) { (void)arg; move_x(c, rnd_between(8, 16)); }
+static void factory_pub_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ if (c->relativeY < 5) {
+ cit_change_floor(c, TH_FACTORYPUB_MOVE, 0);
+ } else {
+ int x = rnd_between(8, P(p->right) && P(p->right)->cls == CLS_FactoryPub ? 19 : 16);
+ int16_t s[] = {4, (int16_t)x, 8, (int16_t)rnd_between(60, 120)};
+ cit_set_path(c, s, 2);
+ }
+ night_visit(c);
+}
+void factory_work(Perm *p, Cit *c, float timeMod, bool stop);
+static void factory_pub_init(Perm *p) { upgrade_first_mode(p); }
+const PermOps ops_FactoryPub = {.init = factory_pub_init, .work = factory_work, .update = factory_update_any,
+ .is_open = factory_pub_open, .entertainment_capacity = factory_pub_capacity,
+ .be_entertained = factory_pub_be_entertained, .draw = factory_draw_any,
+ .window = factory_window_lines};
+
+/* BlossomRestaurant */
+static float blossom_capacity(const Perm *p) { return (float)(int)(p->nworkers * (50 + adj_effect_lr(p, EF_RESTAURANT_CAP))); }
+static void blossom_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ if (c->flags & CF_BUILDING_INITED) {
+ cit_wait_random(c, 30, 60, THEN_NONE, 0);
+ return;
+ }
+ static const int8_t low[6] = {1, 2, 5, 13, 14, 17}, up[4] = {1, 4, 12, 17};
+ const Perm *bo = P(p->bottom);
+ if (!bo || bo->cls != CLS_BlossomRestaurant) move_x(c, low[rnd_int(6)]);
+ else move_x(c, up[rnd_int(4)]);
+ c->flags |= CF_BUILDING_INITED;
+}
+static void blossom_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop && hour_now() > 0.5f) c->currentAction = 2;
+ else walk_wait(c, 3, 18, 60, 120, true);
+}
+const PermOps ops_BlossomRestaurant = {.work = blossom_work, .is_open = restaurant_open, .entertainment_capacity = blossom_capacity,
+ .be_entertained = blossom_be_entertained, .draw = draw_merging};
+
+/* ---------------------------------------------------------------- ParkWalk */
+bool park_open(void) {
+ float h = hour_now();
+ return h >= 6.0f && h < 22;
+}
+static bool is_park(const Perm *q) { return q && class_is(q->cls, CLS_Park); }
+static bool is_garden(const Perm *q) { return q && class_is(q->cls, CLS_BotanicalGardens); }
+bool park_like(const Perm *p) { return is_park(p) || is_garden(p); }
+/* beEntertainedPark (as written: through a park pod, the path's last wait is cut off) */
+void park_walk(const Perm *left, const Perm *right, Cit *c) {
+ bool lskip = false, rskip = false;
+ if (left && left->cls == CLS_ParkPod) left = P(left->left), lskip = true;
+ if (right && right->cls == CLS_ParkPod) right = P(right->right), rskip = true;
+ bool lg = is_garden(left), rg = is_garden(right);
+ bool lwalk = lg && (!left->bottom || !is_garden(P(left->bottom)));
+ bool rwalk = rg && (!right->bottom || !is_garden(P(right->bottom)));
+ if (!lg && is_park(left)) lg = lwalk = true;
+ if (!rg && is_park(right)) rg = rwalk = true;
+ bool doing = false;
+ int go = rnd_int(1 + lg + rg);
+ if (lg && go == 0) {
+ if (lskip) {
+ if (lwalk) {
+ int16_t s[] = {12, 50, 2, 0, 2, 0, 4, (int16_t)rnd_between(0, 18), 8, (int16_t)rnd_between(100, 180)};
+ cit_set_path(c, s, 4);
+ doing = true;
+ }
+ } else if (lwalk) {
+ int16_t s[] = {12, 50, 2, 0, 4, (int16_t)rnd_between(0, 18), 8, (int16_t)rnd_between(100, 180)};
+ cit_set_path(c, s, 4);
+ doing = true;
+ } else if (rnd_int(2) == 0) {
+ walk_wait(c, -3, -3, 70, 90, true);
+ doing = true;
+ }
+ } else if (rg && go == 1) {
+ if (rskip) {
+ if (rwalk) {
+ int16_t s[] = {12, 50, 3, 0, 3, 0, 4, (int16_t)rnd_between(0, 18), 8, (int16_t)rnd_between(100, 180)};
+ cit_set_path(c, s, 4);
+ doing = true;
+ }
+ } else if (rwalk) {
+ int16_t s[] = {12, 50, 3, 0, 4, (int16_t)rnd_between(0, 18), 8, (int16_t)rnd_between(100, 180)};
+ cit_set_path(c, s, 4);
+ doing = true;
+ } else if (rnd_int(2) == 0) {
+ walk_wait(c, 21, 21, 70, 90, true);
+ doing = true;
+ }
+ }
+ if (!doing) walk_wait(c, lg ? 0 : 3, rg ? 18 : 15, 100, 180, true);
+}
+
+/* ---------------------------------------------------------------- Park and its kinds (statues) */
+static uint16_t park_plants(const Perm *p) {
+ switch (p->cls) {
+ case CLS_StatueGarden: return SPR_STATUEGARDEN_STATUES;
+ case CLS_StatueOfHappiness: return SPR_STATUEOFHAPPINESS;
+ case CLS_StatueOfTheKey: return SPR_STATUEOFTHEKEY;
+ default: return SPR_PARK_PLANTS;
+ }
+}
+static int park_choices(const Perm *p) {
+ int n = frames_of(park_plants(p), 20);
+ return p->cls == CLS_Park && !bld_secret_orchid ? n - 3 : n; /* numberOfLockedParkTextures */
+}
+static void park_init(Perm *p) {
+ ParkState *s = ST(ParkState, p);
+ s->texture = (uint8_t)rnd_int(park_choices(p));
+ if (p->cls == CLS_StatueOfHappiness || p->cls == CLS_StatueOfTheKey) s->texture = 0;
+}
+static float park_capacity(const Perm *p) {
+ return p->cls == CLS_StatueGarden ? 40 : p->cls == CLS_StatueOfHappiness || p->cls == CLS_StatueOfTheKey ? 80 : 30;
+}
+static int park_type(const Perm *p) { return p->cls == CLS_Park ? 3 : 2; }
+static bool park_is_open(const Perm *p) { (void)p; return park_open(); }
+static void park_be_entertained(Perm *p, Cit *c, float timeMod) { (void)timeMod; park_walk(P(p->left), P(p->right), c); }
+static void park_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ const ParkState *s = STC(ParkState, p);
+ draw_merging(b, p, layer, x, y);
+ if (layer == LAYER_BG) {
+ uint16_t spr = park_plants(p);
+ dr_frame(b, spr, 20, s->texture % frames_of(spr, 20), x, y, 0, 0, s->mirrored ? GFX_FLIPX : 0, 255, GFX_NO_TINT);
+ if (s->podium) dr_sprite(b, SPR_FESTIVAL_PODIUM_SMALL, x, y, s->podium == 2 ? -3 : 3, 20 - spr_h(SPR_FESTIVAL_PODIUM_SMALL) - 1, 0, 255);
+ }
+}
+static void park_window(Perm *p, WinOut *w) {
+ if (p->cls == CLS_StatueGarden) {
+ win_button(w, 0, "Mirror", WA_MIRROR, true);
+ /* (the developer's message beside the elephant sculptures) */
+ if (STC(ParkState, p)->texture == 0) {
+ win_text(w, "A Message from the Developer");
+ win_text(w, "Let's ensure elephants are not just pixely statues on tiny worlds in 2142. The climate crisis is the most "
+ "important threat facing wildlife - and humans.");
+ }
+ }
+ win_button(w, 0, "Change Building Color", WA_CYCLE_0, true);
+ const char *t = p->cls == CLS_Park ? "Change Plants" : p->cls == CLS_StatueGarden ? "Change Sculptures" : "Change Statue";
+ win_button(w, 0, t, WA_CYCLE_1, true);
+}
+static void park_action(Perm *p, int a) {
+ ParkState *s = ST(ParkState, p);
+ if (a == WA_MIRROR) s->mirrored ^= 1;
+ else if (a == WA_CYCLE_0) s->mainTexture = (uint8_t)((s->mainTexture + 1) % 3);
+ else if (a == WA_CYCLE_1) s->texture = (uint8_t)((s->texture + 1) % park_choices(p));
+}
+const PermOps ops_Park = {.init = park_init, .is_open = park_is_open, .entertainment_capacity = park_capacity,
+ .entertainment_type = park_type, .be_entertained = park_be_entertained, .draw = park_draw,
+ .window = park_window, .window_action = park_action};
+
+/* ParkFestivalEntertainment: festival staff on a podium, visitors in front of it */
+static uint8_t *podium_of(Perm *p) { return is_park(p) ? &ST(ParkState, p)->podium : &ST(GardenState, p)->podium; }
+void park_festival_work(Perm *p, Cit *c, float timeMod, int id) {
+ bool show = true;
+ int px = 3;
+ const Perm *l = P(p->left);
+ int main_texture = is_park(p) ? STC(ParkState, p)->mainTexture : 0;
+ if (l) {
+ if (show && is_park(l)) show = false;
+ if (show && is_garden(l)) {
+ show = false;
+ if (l->bottom && is_garden(P(l->bottom))) {
+ if (main_texture == 0) px = -3;
+ show = true;
+ }
+ }
+ }
+ uint8_t *podium = podium_of(p);
+ if (show) {
+ *podium = px == 3 ? 1 : 2;
+ int my = id == 0 ? px + 3 : px;
+ step_to_x(c, (float)my, timeMod);
+ if (c->relativeX >= my && c->relativeX <= my + 1) set_rel(c, (float)my, 4);
+ } else {
+ *podium = 0;
+ walk_wait(c, 0, 17, 60, 90, false);
+ }
+}
+void park_festival_entertained(Perm *p, Cit *c) {
+ uint8_t podium = *podium_of(p);
+ if (!podium) {
+ park_walk(P(p->left), P(p->right), c);
+ return;
+ }
+ int xmin = (podium == 2 ? -3 : 3) + spr_w(SPR_FESTIVAL_PODIUM_SMALL);
+ const Perm *r = P(p->right);
+ walk_wait(c, xmin, r && park_like(r) ? 19 : 16, 100, 180, true);
+}
+void park_festival_stop(Perm *p) { *podium_of(p) = 0; }
+
+/* ---------------------------------------------------------------- BotanicalGardens and the dome */
+static const uint8_t garden_sets[6] = {2, 3, 2, 4, 2, 2};
+static int garden_group(int texture) {
+ int g = -1, i = 0;
+ while (i <= texture && g < 5) i += garden_sets[++g];
+ return g;
+}
+static int garden_first(int group) {
+ int t = 0;
+ for (int i = 0; i < group; i++) t += garden_sets[i];
+ return t;
+}
+static void garden_set_group(Perm *p, int group) {
+ GardenState *s = ST(GardenState, p);
+ s->texture = (uint8_t)(garden_first(group) + rnd_int(garden_sets[group]));
+}
+bool garden_is_tree(const Perm *p) { return STC(GardenState, p)->texture >= 7 && STC(GardenState, p)->texture <= 10; }
+static void garden_on_build(Perm *p) { ST(GardenState, p)->justBuilt = 1; }
+/* postCreate: a new garden takes the plants' group of the garden below (or above), else any plants */
+void garden_post_create(Perm *p) {
+ GardenState *s = ST(GardenState, p);
+ if (!s->justBuilt) return;
+ const Perm *from = NULL;
+ if (is_garden(P(p->bottom))) from = P(p->bottom);
+ if (is_garden(P(p->top))) from = P(p->top);
+ if (from) garden_set_group(p, garden_group(STC(GardenState, from)->texture));
+ else s->texture = (uint8_t)rnd_int(15);
+ s->justBuilt = 0;
+}
+/* positionSpritesMerging: an upper garden follows the plants' group of its stack's bottom garden */
+static void garden_city_change(Perm *p) {
+ const Perm *leader = p;
+ while (leader->bottom && is_garden(P(leader->bottom))) leader = P(leader->bottom);
+ if (leader == p) return;
+ int g = garden_group(STC(GardenState, leader)->texture);
+ if (g != garden_group(STC(GardenState, p)->texture)) garden_set_group(p, g);
+}
+static float garden_capacity(const Perm *p) { (void)p; return 40; }
+static bool garden_open(const Perm *p) { return (!p->bottom || !is_garden(P(p->bottom))) && park_open(); }
+static void garden_be_entertained(Perm *p, Cit *c, float timeMod) { (void)timeMod; park_walk(P(p->left), P(p->right), c); }
+static void garden_window(Perm *p, WinOut *w) {
+ if (p->cls == CLS_BotanicalGardensDome) win_button(w, 0, "Change Dome Variant", WA_CYCLE_3, true);
+ win_button(w, 0, "Change Building Color", WA_CYCLE_0, true);
+ win_button(w, 0, "Change Plants", WA_CYCLE_1, true);
+ win_button(w, 0, "Change Plants Variant", WA_CYCLE_2, true);
+}
+/* setGroupOfSecondaryTexture: the whole connected stack of gardens gets the next group */
+static void garden_action(Perm *p, int a) {
+ GardenState *s = ST(GardenState, p);
+ if (a == WA_CYCLE_0) {
+ s->mainTexture = (uint8_t)((s->mainTexture + 1) % 3);
+ } else if (a == WA_CYCLE_3) {
+ s->domeVersion ^= 1;
+ } else if (a == WA_CYCLE_1) {
+ int g = (garden_group(s->texture) + 1) % 6;
+ Drawer d, od;
+ bld_drawer(p, &d);
+ Perm *b = p;
+ int cls = p->cls == CLS_BotanicalGardensDome ? CLS_BotanicalGardens : p->cls;
+ for (;;) {
+ Perm *below = P(b->bottom);
+ if (!below || !class_is(below->cls, cls)) break;
+ bld_drawer(below, &od);
+ if (od.name != d.name && od.group != d.group) break;
+ b = below;
+ }
+ for (;;) {
+ garden_set_group(b, g);
+ Perm *above = P(b->top);
+ if (!above || !class_is(above->cls, cls)) break;
+ bld_drawer(above, &od);
+ if (od.name != d.name && od.group != d.group) break;
+ b = above;
+ }
+ } else if (a == WA_CYCLE_2) {
+ int g = garden_group(s->texture), first = garden_first(g);
+ s->texture = (uint8_t)(first + (s->texture - first + 1) % garden_sets[g]);
+ }
+}
+static void dome_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer == LAYER_BG) {
+ Drawer d;
+ bld_drawer(p, &d);
+ const Perm *bo = P(p->bottom);
+ bool hb = false;
+ if (is_building(bo)) {
+ Drawer od;
+ bld_drawer(bo, &od);
+ hb = (od.kind == DRW_ALLDIR || od.kind == DRW_ROOFDOWN) && (od.name == d.name || od.group == d.group);
+ }
+ draw_garden_plants(b, p, x, y, SPR_DOME_BOTANICALGARDEN_PLANTS, STC(GardenState, p)->texture, false, hb);
+ }
+}
+const PermOps ops_BotanicalGardens = {.on_build = garden_on_build, .on_city_change = garden_city_change,
+ .is_open = garden_open, .entertainment_capacity = garden_capacity,
+ .be_entertained = garden_be_entertained, .draw = draw_merging, .window = garden_window,
+ .window_action = garden_action};
+const PermOps ops_BotanicalGardensDome = {.on_build = garden_on_build, .on_city_change = garden_city_change,
+ .is_open = garden_open, .entertainment_capacity = garden_capacity,
+ .be_entertained = garden_be_entertained, .draw = dome_draw,
+ .window = garden_window, .window_action = garden_action};
+
+/* ---------------------------------------------------------------- RooftopPark */
+static void rooftop_neighbours(const Perm *p, const Perm **l, const Perm **r) {
+ const Perm *bo = P(p->bottom);
+ if (!bo) {
+ *l = P(permanent_at_pos(perm_city_x(p) - 20, perm_city_y(p)));
+ *r = P(permanent_at_pos(perm_city_x(p) + 20, perm_city_y(p)));
+ if (!is_building(*l)) *l = NULL;
+ if (!is_building(*r)) *r = NULL;
+ } else {
+ *l = P(bo->left) ? P(P(bo->left)->top) : NULL;
+ *r = P(bo->right) ? P(P(bo->right)->top) : NULL;
+ }
+}
+static void rooftop_park_init(Perm *p) { ST(RooftopParkState, p)->texture = (uint8_t)rnd_int(frames_of(SPR_ROOFTOPPARK_PLANTS, 20)); }
+static float rooftop_capacity(const Perm *p) { (void)p; return 35; }
+/* beEntertainedRooftopPark */
+static void rooftop_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ const Perm *l, *r;
+ rooftop_neighbours(p, &l, &r);
+ bool lg = l && l->cls == CLS_RooftopPark, rg = r && r->cls == CLS_RooftopPark;
+ if (lg && c->relativeX < 1) {
+ cit_go_to_permanent(c, pid(l));
+ c->relativeX += 20;
+ walk_wait(c, 3, 15, 100, 180, true);
+ return;
+ }
+ if (rg && c->relativeX > 19) {
+ cit_go_to_permanent(c, pid(r));
+ c->relativeX -= 20;
+ walk_wait(c, 3, 15, 100, 180, true);
+ return;
+ }
+ int go = rnd_int(1 + lg + rg);
+ if (lg && go == 0) move_x_slow(c, 0);
+ else if (rg && go == 1) move_x_slow(c, 20);
+ else walk_wait(c, 0, 19, 100, 180, true);
+}
+static void rooftop_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer == LAYER_BG) dr_frame(b, SPR_ROOFTOPPARK_PLANTS, 20, STC(RooftopParkState, p)->texture, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+static void rooftop_window(Perm *p, WinOut *w) { (void)p; win_button(w, 0, "Change Plants", WA_CYCLE_0, true); }
+static void rooftop_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0) {
+ RooftopParkState *s = ST(RooftopParkState, p);
+ s->texture = (uint8_t)((s->texture + 1) % frames_of(SPR_ROOFTOPPARK_PLANTS, 20));
+ }
+}
+const PermOps ops_RooftopPark = {.init = rooftop_park_init, .is_open = park_is_open, .entertainment_capacity = rooftop_capacity,
+ .be_entertained = rooftop_be_entertained, .draw = rooftop_draw, .window = rooftop_window,
+ .window_action = rooftop_action};
+
+/* ---------------------------------------------------------------- RedwoodTree and RedwoodTreeHouse */
+static bool is_redwood(const Perm *q) { return q && class_is(q->cls, CLS_RedwoodTree); }
+static Perm *redwood_primary(Perm *p) {
+ while (p->top && is_redwood(P(p->top))) p = P(p->top);
+ return p;
+}
+static void set_primary(Perm *p, bool on) {
+ ST(RedwoodState, p)->isPrimary = on;
+ if (on) p->flags |= PF_ROOFTOP;
+ else p->flags &= (uint8_t)~PF_ROOFTOP;
+}
+static void redwood_init(Perm *p) {
+ RedwoodState *s = ST(RedwoodState, p);
+ s->lastExpanded = (float)city.timeSinceStart;
+ s->subImage = (uint8_t)rnd_between(4, 7);
+ set_primary(p, true);
+}
+void redwood_post_create(Perm *p) {
+ /* (postCreate: rooftop only at the top of its trunk; the tree house keeps what its maker set) */
+ if (p->cls == CLS_RedwoodTree) {
+ bool top = redwood_primary(p) == p;
+ if (top) p->flags |= PF_ROOFTOP;
+ else p->flags &= (uint8_t)~PF_ROOFTOP;
+ }
+}
+static void redwood_destroy(Perm *p) {
+ /* the primary's status goes to the segment below */
+ if (redwood_primary(p) == p && is_redwood(P(p->bottom))) set_primary(P(p->bottom), true);
+}
+static float redwood_capacity(const Perm *p) { (void)p; return 30; }
+static void redwood_be_entertained(Perm *p, Cit *c, float timeMod) { (void)p, (void)c, (void)timeMod; }
+/* updateSprite: the sub-image from the trunk's shape */
+static int redwood_sub_image(const Perm *p) {
+ const RedwoodState *s = STC(RedwoodState, p);
+ const Perm *t = P(p->top), *b = P(p->bottom);
+ if (!t && !b) return s->hasGrass ? 9 : 0;
+ if (t && !t->top && !b) return s->hasGrass ? 10 : 1;
+ if (!t && b && !b->bottom) return 2;
+ if (!b) return s->hasGrass ? 11 : 3;
+ if (!t) return 8;
+ if (!t->top) return 7;
+ return s->subImage;
+}
+static void redwood_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ if (p->cls == CLS_RedwoodTreeHouse) draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ else draw_decoration(b, p, layer, x, y, SPR_REDWOOD, redwood_sub_image(p), false, GFX_NO_TINT);
+}
+static bool redwood_can_build_house(const Perm *p) { return p->top && P(p->top)->top && p->bottom; }
+static bool redwood_can_build_above(Perm *p) {
+ Perm *pr = redwood_primary(p);
+ return !perm_at(pr->world, pr->col, pr->row + 1) && pr->row + 1 < 255;
+}
+static void house_price(float m[M_COUNT]) {
+ memset(m, 0, sizeof(float) * M_COUNT);
+ m[M_WOOD] = 50, m[M_MACHINEPARTS] = 20, m[M_REFINEDMETAL] = 10;
+ if (unlock_state(CLS_RedwoodTreeHouse) != UNLOCK_RESEARCHED) m[M_KNOWLEDGE] = 2500;
+}
+static void redwood_window(Perm *p, WinOut *w) {
+ RedwoodState *s = ST(RedwoodState, p);
+ bool house = p->cls == CLS_RedwoodTreeHouse;
+ if (!house) {
+ if (p->top && p->bottom && P(p->top)->top) win_button(w, 0, "Change Variant", WA_CYCLE_0, true);
+ if (!p->bottom) win_button(w, 0, s->hasGrass ? "Remove Grass" : "Add Grass", WA_TOGGLE, true);
+ }
+ Perm *pr = redwood_primary(p);
+ if (city.timeSinceStart > STC(RedwoodState, pr)->lastExpanded + 1440) {
+ static const float grow[M_COUNT] = {[M_WOOD] = 100, [M_FOOD] = 50};
+ win_button(w, 0, "Make Redwood Grow", WA_BUILD, mat_can_afford(grow));
+ win_text(w, "Make this redwood grow taller. You can do this once every 24 hours.");
+ win_cost(w, grow);
+ } else {
+ int hrs = (int)ceil(24 - (city.timeSinceStart - STC(RedwoodState, pr)->lastExpanded) / 60);
+ if (hrs <= 1) win_line(w, "You can make this redwood grow in one hour.");
+ else win_line1(w, "You can make this redwood grow in [0] hours.", hrs);
+ }
+ if (!house && redwood_can_build_house(p)) {
+ float m[M_COUNT];
+ house_price(m);
+ win_button(w, 0, "Build Tree House", WA_BUILD_2, mat_can_afford(m));
+ win_text(w, "Build a tree house here. It can house two people.");
+ win_cost(w, m);
+ } else if (house) {
+ win_button(w, 0, "Remove Tree House", WA_BUILD_2, true);
+ win_text(w, ""); /* (createActivatableButton without a description) */
+ }
+ win_text(w, "Texture and concept by Luk XD 99");
+}
+/* the segment replaced by a tree house (or back): destroyForReplacement and World.build, not primary */
+static uint16_t redwood_replace(Perm *p, int cls) {
+ int w = p->world, col = p->col, row = p->row;
+ perm_destroy(pid(p), true);
+ uint16_t id = perm_new(cls, w, col, row);
+ if (!id) return NONE;
+ bld_on_build(P(id));
+ set_primary(P(id), false);
+ city_update_connections();
+ sim_update_pathfinder(true, id);
+ unlocks_research(cls);
+ bld_post_create(P(id));
+ unlocks_check_build_related();
+ return id;
+}
+static void redwood_action(Perm *p, int a) {
+ RedwoodState *s = ST(RedwoodState, p);
+ if (a == WA_CYCLE_0) {
+ s->subImage = (uint8_t)(4 + (s->subImage - 4 + 1) % 3);
+ } else if (a == WA_TOGGLE) {
+ s->hasGrass ^= 1;
+ } else if (a == WA_BUILD) {
+ static const float grow[M_COUNT] = {[M_WOOD] = 100, [M_FOOD] = 50};
+ Perm *pr = redwood_primary(p);
+ if (city.timeSinceStart <= STC(RedwoodState, pr)->lastExpanded + 1440) return;
+ if (!mat_can_afford(grow) || !redwood_can_build_above(p)) return;
+ mat_pay(grow);
+ set_primary(pr, false);
+ int w = pr->world, col = pr->col, row = pr->row + 1;
+ uint16_t id = perm_new(CLS_RedwoodTree, w, col, row);
+ if (!id) return;
+ bld_on_build(P(id));
+ set_primary(P(id), true);
+ city_update_connections();
+ sim_update_pathfinder(false, id);
+ unlocks_research(CLS_RedwoodTree);
+ bld_post_create(P(id));
+ unlocks_check_build_related();
+ } else if (a == WA_BUILD_2) {
+ float m[M_COUNT];
+ house_price(m);
+ if (p->cls == CLS_RedwoodTreeHouse) {
+ for (int i = 0; i < M_COUNT; i++) city.materials.m[i] += m[i] * upgrades.recyclingAmount;
+ redwood_replace(p, CLS_RedwoodTree);
+ } else if (mat_can_afford(m) && redwood_can_build_house(p)) {
+ mat_pay(m);
+ redwood_replace(p, CLS_RedwoodTreeHouse);
+ }
+ }
+}
+/* tryDestroy: not where a tree house would be left in a wrong place */
+void redwood_destroy_refusal(const Perm *p, const char **why) {
+ const Perm *t = P(p->top), *b = P(p->bottom);
+ bool house_t = t && t->cls == CLS_RedwoodTreeHouse, house_b = b && b->cls == CLS_RedwoodTreeHouse;
+ const Perm *bb = b ? P(b->bottom) : NULL;
+ if ((!t && b && bb && bb->cls == CLS_RedwoodTreeHouse) || (t && !t->top && house_b) || (!b && house_t))
+ *why = "You cannot destroy this redwood tree, as that would result a tree house to be placed in an incorrect location.";
+}
+static bool never_open_any(const Perm *p) { (void)p; return false; } /* get_isOpen: false */
+static void redwood_house_walk(Perm *p, Cit *c, float steps) {
+ (void)p, (void)steps;
+ c->relativeY = 5;
+ int x = rnd_between(2, 17);
+ cit_move_and_wait(c, x, rnd_between(60, 90), THEN_NONE, 0, false, false);
+}
+const PermOps ops_RedwoodTree = {.init = redwood_init, .destroy = redwood_destroy, .entertainment_capacity = redwood_capacity,
+ .is_open = never_open_any, .be_entertained = redwood_be_entertained, .draw = redwood_draw,
+ .window = redwood_window, .window_action = redwood_action};
+const PermOps ops_RedwoodTreeHouse = {.init = redwood_init, .destroy = redwood_destroy, .entertainment_capacity = redwood_capacity,
+ .is_open = never_open_any, .be_entertained = redwood_be_entertained,
+ .walk_around = redwood_house_walk, .draw = redwood_draw, .window = redwood_window,
+ .window_action = redwood_action};
+
+/* ---------------------------------------------------------------- NightClub */
+static bool is_club(const Perm *q) { return q && q->cls == CLS_NightClub; }
+static float club_capacity(const Perm *p) {
+ float q = has_upgrade_bit(p, UB_NightClub_BetterLightShow) ? 40 : 0; /* nightClubEntertainmentQuantity */
+ return p->nworkers * (40 + q) + upgrades.nightClubEntertainmentQualityBonus;
+}
+static bool club_open(const Perm *p) { return p->nworkers == 1 && open_between(p, 20 - 0.5f, 6); }
+static void club_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ NightClubState *s = ST(NightClubState, p);
+ if (stop && hour_now() > 6) {
+ c->currentAction = 2;
+ } else if (is_club(P(p->left))) {
+ walk_wait(c, 0, is_club(P(p->right)) ? 19 : 17, 20, 50, false);
+ s->lightsAreOn = 60 * 4;
+ } else {
+ step_to_x(c, 1, timeMod);
+ s->lightsAreOn = 3 * 4;
+ }
+}
+static void club_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ NightClubState *s = ST(NightClubState, p);
+ if (!s->knownCitizen) s->knownCitizen = cid(c), s->knownSet = 60;
+ else if (s->knownCitizen == cid(c)) s->knownSet = 60;
+ int wait_mod = s->color == 1 ? -3 : s->color == 2 || s->color == 4 ? 3 : 0;
+ const Perm *l = P(p->left), *r = P(p->right);
+ bool hl = is_club(l), hr = is_club(r);
+ int go = rnd_int(2 + hl + hr);
+ bool lr = s->color != 4 || s->knownCitizen != cid(c);
+ if (hl && lr && go == 0 && club_open(l)) {
+ int16_t st[] = {2, 0, 4, (int16_t)rnd_between(5, 19), 8, (int16_t)rnd_between(5, 6)};
+ cit_set_path(c, st, 3);
+ } else if (hr && lr && go == 1 && club_open(r)) {
+ int16_t st[] = {3, 0, 4, (int16_t)rnd_between(0, 17), 8, (int16_t)rnd_between(5, 6)};
+ cit_set_path(c, st, 3);
+ } else {
+ walk_wait(c, hl ? 0 : 5, hr ? 19 : 17, 5 + wait_mod, 6 + wait_mod, s->color == 2 || s->color == 4);
+ }
+ night_visit(c);
+}
+static bool dj_working_here(const Perm *p) {
+ Cit *dj = worker_at(p, 0);
+ return dj && dj->inPermanent == pid(p) && dj->currentAction == 0;
+}
+static void club_update(Perm *p, float timeMod) {
+ NightClubState *s = ST(NightClubState, p);
+ int dec = round_random(fminf(1, timeMod) * 4);
+ s->lightsAreOn = (uint8_t)(s->lightsAreOn > dec ? s->lightsAreOn - dec : 0);
+ if (s->knownCitizen) {
+ if (s->knownSet < timeMod) s->knownCitizen = 0, s->knownSet = 0;
+ else s->knownSet = tick_down(s->knownSet, timeMod);
+ }
+}
+/* the light show, from the clock: lasers sweeping between their ends, lights fading in and out */
+static float triangle(float t, float lo, float hi) {
+ float span = hi - lo;
+ if (span <= 0) return lo;
+ float m = fmodf(t, 2 * span);
+ if (m < 0) m += 2 * span;
+ return m < span ? lo + m : hi - (m - span);
+}
+static uint16_t club_laser_tint(const Perm *p, int k, float t) {
+ int color = STC(NightClubState, p)->color;
+ static const float start_hue[4] = {180, 0, 90, 270};
+ float hue;
+ switch (color) {
+ case 1: hue = 0; break;
+ case 2: hue = 170 + 75 * (0.5f + 0.5f * sinf(t * 0.004f + k * 1.7f)); break;
+ case 3: hue = fmodf(t * 0.6f + k * 97, 360); break;
+ case 4: hue = 270 + 60 * (0.5f + 0.5f * sinf(t * 0.004f + k * 1.3f)); break;
+ default: hue = fmodf(start_hue[k] + t, 360); break;
+ }
+ return tint565(hsv_to_rgb(hue, 0.7f, 1));
+}
+static void club_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer != LAYER_BG) return;
+ const NightClubState *s = STC(NightClubState, p);
+ if (s->lightsAreOn == 0 && !dj_working_here(p)) return;
+ float t = bld_anim + (hash32(pid(p)) & 1023);
+ /* the two lights at (5, 4) and (10, 4) */
+ for (int k = 0; k < 2; k++) {
+ float period = s->color == 1 || s->color == 3 ? 35 : s->color == 4 ? 110 : 50;
+ float ph = t + k * 17;
+ int cycle = (int)(ph / period);
+ float in = fmodf(ph, period);
+ float rise = s->color == 4 ? 40 : 10;
+ float a = in < rise ? in / rise : in < 2 * rise ? 2 - in / rise : 0;
+ if (a <= 0) continue;
+ uint32_t h = hash32((uint32_t)pid(p) * 7919u + (uint32_t)k * 104729u + (uint32_t)cycle);
+ uint32_t rgb;
+ switch (s->color) {
+ case 1: rgb = hsl_to_rgb((float)(h % 60), 0.8f, 0.6f); break;
+ case 2: rgb = hsl_to_rgb((float)(170 + h % 75), 0.8f, 0.7f); break;
+ case 3: rgb = 0xFFFFFF; break;
+ case 4: rgb = hsl_to_rgb((float)(270 + h % 60), 0.8f, 0.7f); break;
+ default: rgb = hsl_to_rgb((float)(h % 360), 0.8f, 0.5f); break;
+ }
+ dr_part(b, s->color == 3 ? SPR_NIGHTCLUB_LIGHT_RAINBOW : SPR_NIGHTCLUB_LIGHT, 0, 0, 5, 15, x, y, 5 + 5 * k, 4, 0,
+ (uint8_t)(a * 255), tint565(rgb));
+ }
+ /* lasers: from (2, 3) and (17, 3), and (7, 4) and (12, 4) with the better light show */
+ static const int8_t sx[4] = {2, 17, 7, 12}, sy[4] = {3, 3, 4, 4};
+ int n = has_upgrade_bit(p, UB_NightClub_BetterLightShow) ? 4 : 2;
+ float lo = is_club(P(p->left)) ? 1 : 6;
+ for (int k = 0; k < n; k++) {
+ float speed = s->color == 2 || s->color == 4 ? 0.65f : s->color == 1 ? 1.5f : 1.0f;
+ float ex = triangle(t * speed + k * 23, lo, 18);
+ int f = (int)floorf(fabsf(ex - sx[k]));
+ f = f < 0 ? 0 : f > 17 ? 17 : f;
+ bool flip = ex < sx[k];
+ dr_part(b, SPR_NIGHTCLUB_LASER, f * 20, 0, 18, spr_h(SPR_NIGHTCLUB_LASER), x, y, flip ? sx[k] + 1 - 18 : sx[k], sy[k],
+ flip ? GFX_FLIPX : 0, 255, club_laser_tint(p, k, t));
+ }
+}
+static void club_window(Perm *p, WinOut *w) {
+ if (!bld_secret_dance) return;
+ static const char *const names[5] = {"Colorful", "Fast & Red", "Slow & Blue", "Rainbow Light", "Romantic & Pink"};
+ char b[96];
+ int k = 0;
+ for (const char *s = "Change Light Show ("; *s; s++) b[k++] = *s;
+ for (const char *s = names[STC(NightClubState, p)->color % 5]; *s; s++) b[k++] = *s;
+ b[k++] = ')';
+ b[k] = 0;
+ win_button(w, 0, b, WA_CYCLE_0, true);
+}
+static void club_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0 && bld_secret_dance) {
+ NightClubState *s = ST(NightClubState, p);
+ s->color = (uint8_t)((s->color + 1) % 5);
+ }
+}
+const PermOps ops_NightClub = {.work = club_work, .update = club_update, .is_open = club_open,
+ .entertainment_capacity = club_capacity, .be_entertained = club_be_entertained,
+ .draw = club_draw, .window = club_window, .window_action = club_action};
+
+/* ---------------------------------------------------------------- ScrapyardNightClub */
+static bool is_scrapyard(const Perm *q) { return q && q->cls == CLS_ScrapyardNightClub; }
+static void scrapyard_init(Perm *p) {
+ ScrapyardState *s = ST(ScrapyardState, p);
+ s->texLeft = (uint8_t)rnd_int(frames_of(SPR_SYNIGHTCLUB_LEFTTEXTURES, 20));
+ s->texOther = (uint8_t)rnd_int(frames_of(SPR_SYNIGHTCLUB_MAINTEXTURES, 20));
+ s->shownLeft = 0; /* (as written: the other machines show until the left neighbour changes) */
+}
+static float scrapyard_capacity(const Perm *p) { return p->nworkers * 120 + upgrades.nightClubEntertainmentQualityBonus; }
+static bool scrapyard_open(const Perm *p) { return p->nworkers == 1 && open_between(p, 20 - 0.5f, 6); }
+static void scrapyard_city_change(Perm *p) {
+ ScrapyardState *s = ST(ScrapyardState, p);
+ bool hl = is_scrapyard(P(p->left));
+ if (s->hadLeft != hl) {
+ s->shownLeft = !hl;
+ s->hadLeft = hl;
+ }
+}
+static void scrapyard_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ ScrapyardState *s = ST(ScrapyardState, p);
+ if (stop && hour_now() > 6) {
+ c->currentAction = 2;
+ } else if (is_scrapyard(P(p->left))) {
+ walk_wait(c, 0, is_scrapyard(P(p->right)) ? 19 : 17, 20, 50, false);
+ s->lightsAreOn = 60 * 4;
+ } else {
+ step_to_x(c, 1, timeMod);
+ s->lightsAreOn = 3 * 4;
+ }
+}
+static void scrapyard_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ const Perm *l = P(p->left), *r = P(p->right);
+ bool hl = is_scrapyard(l), hr = is_scrapyard(r);
+ int go = rnd_int(2 + hl + hr);
+ if (hl && go == 0 && scrapyard_open(l)) {
+ int16_t st[] = {2, 0, 4, (int16_t)rnd_between(5, 19), 8, (int16_t)rnd_between(5, 6)};
+ cit_set_path(c, st, 3);
+ } else if (hr && go == 1 && scrapyard_open(r)) {
+ int16_t st[] = {3, 0, 4, (int16_t)rnd_between(0, 17), 8, (int16_t)rnd_between(5, 6)};
+ cit_set_path(c, st, 3);
+ } else {
+ walk_wait(c, hl ? 0 : 5, hr ? 19 : 17, 8, 9, false);
+ }
+ night_visit(c);
+}
+static void scrapyard_update(Perm *p, float timeMod) {
+ ScrapyardState *s = ST(ScrapyardState, p);
+ int dec = round_random(fminf(1, timeMod) * 4);
+ s->lightsAreOn = (uint8_t)(s->lightsAreOn > dec ? s->lightsAreOn - dec : 0);
+ s->active = s->lightsAreOn > 0 || dj_working_here(p);
+}
+/* the machines' lights, each pair of textures its own (secondaryBackgroundSprites), from the clock */
+static void sy_light(const GfxBand *b, uint16_t spr, int x, int y, int dx, int dy, float sxs, float sys, float hue, float sat,
+ float alpha) {
+ int w = spr_w(spr), h = spr_h(spr);
+ int dw = (int)(w * sxs + 0.5f), dh = (int)(h * sys + 0.5f);
+ if (dw < 1) dw = 1;
+ if (dh < 1) dh = 1;
+ uint16_t t = tint565(hsv_to_rgb(hue, sat, 1));
+ uint8_t a = (uint8_t)(alpha < 0 ? 0 : alpha > 1 ? 255 : alpha * 255);
+ /* (scaled lights are drawn at their scaled size, a pixel column or row of the sprite repeated) */
+ for (int i = 0; i < dh; i += h)
+ for (int j = 0; j < dw; j += w) dr_part(b, spr, 0, 0, dw - j < w ? dw - j : w, dh - i < h ? dh - i : h, x, y, dx + j, dy + i, 0, a, t);
+}
+static void scrapyard_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer != LAYER_BG) return;
+ const ScrapyardState *s = STC(ScrapyardState, p);
+ bool left = s->shownLeft;
+ int tex = left ? s->texLeft : s->texOther;
+ dr_frame(b, left ? SPR_SYNIGHTCLUB_LEFTTEXTURES : SPR_SYNIGHTCLUB_MAINTEXTURES, 20, tex, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ if (!s->active) return;
+ float t = bld_anim;
+ if (left) {
+ if (tex == 0) {
+ static const int8_t pos[4][2] = {{3, 2}, {7, 4}, {12, 3}, {16, 4}};
+ static const float ys[4] = {0.8f, 0.4f, 0.8f, 0.5f};
+ for (int k = 0; k < 4; k++) sy_light(b, SPR_SYNIGHTCLUB_LIGHTS, x, y, pos[k][0], pos[k][1], 1, ys[k], fmodf(72 * k + t, 360), 0.65f, 1);
+ } else if (tex == 1) {
+ float base = fmodf((float)(p->col * 60 + p->row * 75) + 0.5f * t, 360);
+ static const int8_t pos[3][2] = {{2, 1}, {6, 5}, {10, 9}};
+ for (int k = 0; k < 3; k++) sy_light(b, SPR_SYNIGHTCLUB_WATERFALLLIGHT, x, y, pos[k][0], pos[k][1], 1, 1, base + 25 * k, 0.7f, 1);
+ sy_light(b, SPR_SYNIGHTCLUB_WATERFALLLIGHT_LAST, x, y, 15, 13, 1, 1, base + 75, 0.7f, 1);
+ } else {
+ static const int8_t pos[3][2] = {{4, 3}, {3, 7}, {6, 11}};
+ static const float xs[3] = {1.4f, 1.5f, 1.2f};
+ for (int k = 0; k < 3; k++) {
+ float hue = 120 * k + 180 * (0.5f + 0.5f * sinf(t * 0.01f + k * 2.1f + p->col));
+ sy_light(b, SPR_SYNIGHTCLUB_LIGHTS_H, x, y, pos[k][0], pos[k][1], xs[k], 1, hue, 0.65f, 1);
+ }
+ }
+ } else if (tex == 0) {
+ static const int8_t pos[5][2] = {{2, 3}, {6, 2}, {10, 3}, {14, 4}, {17, 2}};
+ static const float ys[5] = {1.1f, 1, 1.1f, 1.3f, 1};
+ for (int k = 0; k < 5; k++) sy_light(b, SPR_SYNIGHTCLUB_LIGHTS, x, y, pos[k][0], pos[k][1], 1, ys[k], fmodf(60 * k + t, 360), 0.65f, 1);
+ } else if (tex == 1) {
+ static const int8_t pos[9][2] = {{2, 2}, {1, 7}, {2, 13}, {8, 3}, {6, 8}, {8, 13}, {13, 3}, {13, 8}, {12, 13}};
+ for (int k = 0; k < 9; k++) {
+ /* each mini light: a wait, a colour, fade in, hold, fade out */
+ float ph = t + k * 37 + (hash32(pid(p) * 31u + (uint32_t)k) & 127);
+ int cycle = (int)(ph / 100);
+ float in = fmodf(ph, 100);
+ uint32_t h = hash32((uint32_t)pid(p) * 977u + (uint32_t)k * 131u + (uint32_t)cycle);
+ float a = in < 10 ? in / 10 : in < 65 ? 1 : in < 75 ? (75 - in) / 10 : 0;
+ if (a > 0) sy_light(b, SPR_SYNIGHTCLUB_MINILIGHT, x, y, pos[k][0], pos[k][1], 1, 1, (float)(h % 360), 0.6f + (h >> 9) % 30 / 100.0f, a);
+ }
+ } else {
+ static const int8_t pos[6][2] = {{3, 3}, {4, 3}, {9, 8}, {10, 8}, {15, 5}, {16, 5}};
+ static const float ys[6] = {1.2f, 1.2f, 0.7f, 0.7f, 1, 1};
+ for (int k = 0; k < 6; k++) {
+ float hue = fmodf(120 * k + (k & 1 ? -1.5f : 1.5f) * t, 360);
+ if (hue < 0) hue += 360;
+ sy_light(b, SPR_SYNIGHTCLUB_LIGHTS, x, y, pos[k][0], pos[k][1], 1, ys[k], hue, 0.75f - 0.01f * k, 1);
+ }
+ }
+}
+static void scrapyard_window(Perm *p, WinOut *w) { (void)p; win_button(w, 0, "Change Machines", WA_CYCLE_0, true); }
+static void scrapyard_action(Perm *p, int a) {
+ if (a != WA_CYCLE_0) return;
+ ScrapyardState *s = ST(ScrapyardState, p);
+ if (is_scrapyard(P(p->left))) {
+ s->texOther = (uint8_t)((s->texOther + 1) % frames_of(SPR_SYNIGHTCLUB_MAINTEXTURES, 20));
+ s->shownLeft = 0;
+ } else {
+ s->texLeft = (uint8_t)((s->texLeft + 1) % frames_of(SPR_SYNIGHTCLUB_LEFTTEXTURES, 20));
+ s->shownLeft = 1;
+ }
+}
+const PermOps ops_ScrapyardNightClub = {.init = scrapyard_init, .work = scrapyard_work, .update = scrapyard_update,
+ .on_city_change = scrapyard_city_change, .is_open = scrapyard_open,
+ .entertainment_capacity = scrapyard_capacity,
+ .be_entertained = scrapyard_be_entertained, .draw = scrapyard_draw,
+ .window = scrapyard_window, .window_action = scrapyard_action};
+
+/* ---------------------------------------------------------------- ModernArtMuseum */
+extern uint8_t modern_artworks_unlocked; /* unlocks.numberOfModernArtMuseumArtworksUnlocked (bld_unique.c) */
+static uint8_t TH_TOUR_1, TH_TOUR_2, TH_TOUR_3, TH_TOUR_4;
+static void museum_init(Perm *p) { ST(ArtMuseumState, p)->texture = (uint8_t)rnd_int(modern_artworks_unlocked); }
+static void museum_on_build(Perm *p) { (void)p; unlocks_unlock("ArtColony"); }
+static float museum_capacity(const Perm *p) { return workers_times(p, 100); }
+static bool museum_open(const Perm *p) { return p->nworkers == 1 && first_worker_working(p) && hour_now() < 21.5f; }
+static void th_museum_move(Cit *c, uint16_t arg) { (void)arg; walk_wait(c, 3, 16, 100, 120, true); }
+static void museum_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (c->relativeY < 5) cit_change_floor(c, TH_MUSEUM_MOVE, 0);
+ else th_museum_move(c, 0);
+}
+/* the curator's tour: upstairs, to the far end and back, downstairs */
+static void th_tour_1(Cit *c, uint16_t arg) { (void)arg; cit_move(c, rnd_between(14, 15), TH_TOUR_2, 0, true); }
+static void th_tour_2(Cit *c, uint16_t arg) { (void)arg; cit_wait_random(c, 30, 60, TH_TOUR_3, 0); }
+static void th_tour_3(Cit *c, uint16_t arg) { (void)arg; cit_move(c, rnd_between(4, 6), TH_TOUR_4, 0, true); }
+static void th_tour_4(Cit *c, uint16_t arg) { (void)arg; cit_wait_random(c, 30, 60, TH_CHANGE_FLOOR, 0); }
+static void museum_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop) c->currentAction = 2;
+ else if (c->relativeX >= 4 && c->relativeX < 6) {
+ if (rnd_int(10) == 0) cit_change_floor_and_wait_random(c, 30, 60, TH_TOUR_1, 0);
+ else wait_ticks(c, 30, 60);
+ } else {
+ move_x(c, rnd_between(4, 6));
+ }
+}
+static void museum_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer == LAYER_BG) dr_frame(b, SPR_MODERNART, 20, STC(ArtMuseumState, p)->texture, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+static void museum_window(Perm *p, WinOut *w) { (void)p; win_button(w, 0, "Change Exhibition", WA_CYCLE_0, true); }
+static void museum_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0 && modern_artworks_unlocked) {
+ ArtMuseumState *s = ST(ArtMuseumState, p);
+ s->texture = (uint8_t)((s->texture + 1) % modern_artworks_unlocked);
+ }
+}
+const PermOps ops_ModernArtMuseum = {.init = museum_init, .on_build = museum_on_build, .work = museum_work,
+ .is_open = museum_open, .entertainment_capacity = museum_capacity,
+ .be_entertained = museum_be_entertained, .draw = museum_draw, .window = museum_window,
+ .window_action = museum_action};
+
+/* ---------------------------------------------------------------- Arcade */
+static float arcade_capacity(const Perm *p) { return workers_times(p, 120); }
+static bool arcade_open(const Perm *p) { return p->nworkers == 1 && first_worker_working(p) && hour_now() < 23; }
+static void th_arcade_move(Cit *c, uint16_t arg) {
+ (void)arg;
+ int xx = c->relativeY < 5 ? 5 + 4 * rnd_int(3) : 5 + 8 * rnd_int(2);
+ walk_wait(c, xx, xx + 1, 100, 120, false);
+}
+static void arcade_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (rnd_int(3) == 1) cit_change_floor(c, TH_ARCADE_MOVE, 0);
+ else th_arcade_move(c, 0);
+}
+static void arcade_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop) c->currentAction = 2;
+ else step_to_x(c, 6, timeMod);
+}
+const PermOps ops_Arcade = {.work = arcade_work, .is_open = arcade_open, .entertainment_capacity = arcade_capacity,
+ .be_entertained = arcade_be_entertained, .draw = plain_draw};
+
+/* ---------------------------------------------------------------- HoloGameHall */
+static uint8_t TH_HGH_BLOCK;
+static bool is_hall(const Perm *q) { return q && q->cls == CLS_HoloGameHall; }
+static Perm *hall_coordinator(Perm *p) {
+ while (is_hall(P(p->left))) p = P(p->left);
+ return p;
+}
+static int hall_total_width(Perm *coord) {
+ int w = 18;
+ for (Perm *q = coord; is_hall(P(q->right)); q = P(q->right)) w += 20;
+ return w;
+}
+static void hall_set_game_type(Perm *p) {
+ HoloState *s = ST(HoloState, p);
+ s->gameType = (is_hall(P(p->left)) || is_hall(P(p->right))) && rnd_int(2) == 0 ? 0 : 1;
+}
+static void hall_clear(Perm *p) {
+ HoloState *s = ST(HoloState, p);
+ memset(s->blocks, 0, sizeof s->blocks);
+ s->progress1 = s->progress2 = 0;
+}
+void hall_post_create(Perm *p) {
+ /* calculateCoordinatorBuilding, then setGameType */
+ hall_set_game_type(p);
+ Perm *coord = hall_coordinator(p);
+ ST(HoloState, p)->gameType = STC(HoloState, coord)->gameType;
+}
+static void hall_city_change(Perm *p) {
+ HoloState *s = ST(HoloState, p);
+ Perm *coord = hall_coordinator(p);
+ if (!is_hall(P(p->left)) && !is_hall(P(p->right)) && s->gameType == 0) {
+ s->gameType = 1;
+ hall_clear(p);
+ }
+ if (s->gameType != STC(HoloState, coord)->gameType) {
+ hall_clear(p);
+ s->gameType = STC(HoloState, coord)->gameType;
+ }
+ if (!is_hall(P(p->right))) s->blocks[4] = 0;
+}
+static float hall_capacity(const Perm *p) { (void)p; return 75; }
+static bool hall_open(const Perm *p) {
+ (void)p;
+ float h = hour_now();
+ return h >= 12 || h < 2;
+}
+/* the block game: a visitor adds a block in a column, or brightens the newest, or tints one */
+static void th_hgh_block(Cit *c, uint16_t arg) {
+ (void)c;
+ Perm *p = P(arg & 0x3FF);
+ int col = arg >> 12 & 7;
+ if (!is_hall(p) || STC(HoloState, hall_coordinator(p))->gameType != 1 || (col == 4 && !is_hall(P(p->right)))) return;
+ HoloState *s = ST(HoloState, p);
+ int n = s->blocks[col] & 7, alpha = s->blocks[col] >> 3;
+ if (n == 0 || alpha >= 10) {
+ s->gameInited = 1;
+ if (n < 4) s->blocks[col] = (uint8_t)((n + 1) | 1 << 3);
+ else s->hueShift++;
+ } else {
+ s->blocks[col] = (uint8_t)(n | (alpha + 1) << 3);
+ }
+}
+static void hall_be_entertained(Perm *p, Cit *c, float timeMod) {
+ Perm *coord = hall_coordinator(p);
+ HoloState *s = ST(HoloState, p);
+ bool hl = is_hall(P(p->left)), hr = is_hall(P(p->right));
+ if (STC(HoloState, coord)->gameType == 1) {
+ int k = rnd_int(4 + hr), r = rnd_int(6);
+ if (hl && r == 0) {
+ int16_t st[] = {2, 0, 4, 19};
+ cit_set_path(c, st, 2);
+ } else if (hr && r == 1) {
+ int16_t st[] = {3, 0, 4, 0};
+ cit_set_path(c, st, 2);
+ } else {
+ cit_move_and_wait(c, 3 + k * 4, rnd_between(45, 90), TH_HGH_BLOCK, (uint16_t)(pid(p) | k << 12), false, false);
+ }
+ } else {
+ /* the spaceship battle: two teams push their monsters toward each other (team by citizen) */
+ HoloState *cs = ST(HoloState, coord);
+ int team = (cid(c) + day_number()) & 1;
+ int total = hall_total_width(coord) - 28;
+ float pr1 = cs->progress1 / 65535.0f, pr2 = cs->progress2 / 65535.0f;
+ float x = (float)(perm_city_x(p) - perm_city_x(coord)) + c->relativeX;
+ float mpos = team == 0 ? 1 + floorf(pr1 * total) : hall_total_width(coord) - 14 + 1 - floorf(pr2 * total);
+ if (x > mpos && x < mpos + 13 && rnd_range(0, 30) > timeMod && total > 0) {
+ float *mine = team == 0 ? &pr1 : &pr2, *other = team == 0 ? &pr2 : &pr1;
+ *mine = fminf(*mine + timeMod / (total * (10 + 20 * *mine)), 1);
+ if (*mine + *other > 1) *other = 1 - *mine;
+ cs->progress1 = (uint16_t)(pr1 * 65535), cs->progress2 = (uint16_t)(pr2 * 65535);
+ } else {
+ int wx = perm_city_x(coord) + (int)mpos;
+ cit_move_towards_random_in_world_coords(c, wx, wx + 13, THEN_NONE, 0);
+ }
+ }
+ s->gameType = STC(HoloState, coord)->gameType;
+}
+static void hall_update(Perm *p, float timeMod) {
+ (void)timeMod;
+ HoloState *s = ST(HoloState, p);
+ if (!hall_open(p) && hour_now() > 4) {
+ /* after closing: the game is cleared and a new kind of game chosen */
+ if (s->gameInited || s->progress1 || s->progress2) {
+ hall_clear(p);
+ s->gameInited = 0;
+ if (hall_coordinator(p) == p) hall_set_game_type(p);
+ }
+ }
+}
+static void hall_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer != LAYER_BG) return;
+ const HoloState *s = STC(HoloState, p);
+ if (s->gameType == 1) {
+ for (int col = 0; col < 5; col++) {
+ int n = s->blocks[col] & 7, alpha = s->blocks[col] >> 3;
+ for (int i = 0; i < n; i++) {
+ uint32_t h = hash32((uint32_t)pid(p) * 131u + (uint32_t)col * 17u + (uint32_t)i);
+ float hue = (float)(h % 360) + 5.0f * ((s->hueShift * (h >> 12 & 3)) & 63);
+ float a = i == n - 1 ? alpha / 10.0f : 1;
+ dr_part(b, SPR_HGH_BLOCK, 0, 0, 4, 4, x, y, 2 + col * 4, 20 - 1 - 4 * (i + 1), 0, (uint8_t)(a * 255),
+ tint565(hsv_to_rgb(hue, 1, 1)));
+ }
+ }
+ } else if (hall_coordinator((Perm *)p) == p) {
+ /* the monsters of the run (drawn by its leftmost hall) */
+ int total = hall_total_width((Perm *)p) - 28;
+ if (total <= 0) return;
+ int x1 = 1 + (int)floorf(s->progress1 / 65535.0f * total);
+ int x2 = hall_total_width((Perm *)p) - 14 + 1 - (int)floorf(s->progress2 / 65535.0f * total);
+ dr_part(b, SPR_HGH_MONSTER_1, 0, 0, 14, 9, x, y, x1, 10, 0, 255, rgb565(0xFF0000));
+ dr_part(b, SPR_HGH_MONSTER_1, 0, 0, 14, 9, x, y, x2, 10, GFX_FLIPX, 255, rgb565(0x0000FF));
+ }
+}
+const PermOps ops_HoloGameHall = {.on_city_change = hall_city_change, .update = hall_update, .is_open = hall_open,
+ .entertainment_capacity = hall_capacity, .be_entertained = hall_be_entertained,
+ .draw = hall_draw};
+
+void bld_entertainment_init(void) {
+ TH_PUB_MOVE = then_register(th_pub_move);
+ TH_FACTORYPUB_MOVE = then_register(th_factory_pub_move);
+ TH_TABLE = then_register(th_table);
+ TH_LUX_TABLE = then_register(th_lux_table);
+ TH_ARCADE_MOVE = then_register(th_arcade_move);
+ TH_MUSEUM_MOVE = then_register(th_museum_move);
+ TH_TOUR_1 = then_register(th_tour_1);
+ TH_TOUR_2 = then_register(th_tour_2);
+ TH_TOUR_3 = then_register(th_tour_3);
+ TH_TOUR_4 = then_register(th_tour_4);
+ TH_HGH_BLOCK = then_register(th_hgh_block);
+}
diff --git a/games/finalearth2/src/bld_hobbies.c b/games/finalearth2/src/bld_hobbies.c
new file mode 100644
index 00000000..f4c001d1
--- /dev/null
+++ b/games/finalearth2/src/bld_hobbies.c
@@ -0,0 +1,305 @@
+/* The Final Earth 2: citizens' hobbies (simulation.CitizenSpecialAction and
+ * citizenSpecialActions.*): a few citizens climb trees and ruins at night,
+ * walk to the world's edge, watch the stars, protest or dance on a ball.
+ * Each hobby is given to one citizen at a time (CitySimulation's
+ * possibleCitizenHobbies), so its state is kept by hobby, not by citizen. */
+#include "bldi.h"
+#include "save.h"
+#include "view.h"
+
+enum {
+ H_NONE, H_CLIMB_TREE, H_MOVE_TO_EDGE, H_WATCH_STARS, H_PROTEST, H_PROTEST2, H_PROTEST3, H_PROTEST4, H_DANCE_BALL,
+ H_CLIMB_RUINS, H_COUNT
+};
+static const uint8_t hobby_min[H_COUNT] = {0, 1, 2, 5, 6, 12, 18, 24, 35, 80};
+/* the pool, in its order (the pick is random among those allowed, in this order) */
+static struct { uint8_t kind, min; } pool[H_COUNT - 1];
+static int npool;
+
+enum { HS_PROP = 1, HS_FLIP = 2, HS_HAPPY = 4, HS_LEFT = 8, HS_CANCEL = 16 };
+static struct {
+ uint8_t flags;
+ int16_t x; /* the prop's place on its world (telescope) */
+ float timer; /* goingIntoThisDirection */
+} hob[H_COUNT];
+
+static int hour(void) { return ((int)city.timeSinceStart / 60) % 24; }
+static int minute(void) { return (int)city.timeSinceStart % 60; }
+/* the citizen's x on its world (get_worldX) */
+static float world_x(const Cit *c) {
+ const Perm *in = P(c->inPermanent);
+ return in ? in->col * 20 + c->relativeX : c->relativeX;
+}
+
+static void pool_init(void) {
+ npool = 0;
+ for (int k = 1; k < H_COUNT; k++) pool[npool].kind = (uint8_t)k, pool[npool].min = hobby_min[k], npool++;
+}
+static void pool_remove(int kind) {
+ for (int i = 0; i < npool; i++)
+ if (pool[i].kind == kind) {
+ memmove(&pool[i], &pool[i + 1], sizeof pool[0] * (size_t)(npool - i - 1));
+ npool--;
+ return;
+ }
+}
+/* setHobby: a citizen with a hobby does not go to night clubs */
+static void set_hobby(Cit *c, int kind) {
+ c->hobby = (uint8_t)kind;
+ c->flags &= (uint16_t)~CF_LIKES_NIGHTCLUBS;
+ memset(&hob[kind], 0, sizeof hob[kind]);
+}
+void hobby_give(Cit *c) {
+ int allowed = 0;
+ for (int i = 0; i < npool; i++)
+ if (ncits >= pool[i].min) allowed++;
+ if (!allowed || (story_is("cityofthekey") && ncits <= 100)) return;
+ int pick = rnd_int(allowed);
+ for (int i = 0; i < npool; i++)
+ if (ncits >= pool[i].min && pick-- == 0) {
+ int kind = pool[i].kind;
+ set_hobby(c, kind);
+ pool_remove(kind);
+ return;
+ }
+}
+/* CitySimulation.createCitizen */
+uint16_t cit_create(int world, float age, uint16_t start_in, int start_x) {
+ if (start_x < 0) start_x = start_in ? rnd_int(20) : rnd_int(worlds[world].w - 2);
+ uint16_t id = cit_new(world, (float)start_x, age, start_in);
+ if (id) hobby_give(&cits[id]);
+ return id;
+}
+
+/* the steps of the original's setPath arrays */
+static void path2(Cit *c, int a, int b) {
+ int16_t s[2] = {(int16_t)a, (int16_t)b};
+ cit_set_path(c, s, 1);
+}
+static void path4(Cit *c, int a, int b, int d, int e) {
+ int16_t s[4] = {(int16_t)a, (int16_t)b, (int16_t)d, (int16_t)e};
+ cit_set_path(c, s, 2);
+}
+static void path_here(Cit *c, int a, int b) {
+ path2(c, a, b);
+ c->pathOnlyRelatedTo = c->inPermanent;
+}
+
+bool hobby_is_active(const Cit *c) {
+ int h = hour(), k = c->hobby;
+ if (k <= H_NONE || k >= H_COUNT) return false;
+ bool prop = hob[k].flags & HS_PROP;
+ switch (k) {
+ case H_CLIMB_TREE: return h <= 4 && c->currentAction != 3;
+ case H_MOVE_TO_EDGE: {
+ float t = (float)fmod(city.timeSinceStart / 60, 24);
+ return (t >= 23 || t < 5) && c->currentAction != 3;
+ }
+ case H_WATCH_STARS: return (h <= 4 && c->currentAction != 3) || prop;
+ case H_PROTEST: case H_PROTEST2: case H_PROTEST3: case H_PROTEST4: {
+ float hp = happiness.happiness;
+ bool happy = k == H_PROTEST && hp >= 99.99f;
+ bool sad = hp <= 10.01f;
+ if (k != H_PROTEST && sad) {
+ int days = k == H_PROTEST2 ? 2 : k == H_PROTEST3 ? 4 : 7;
+ sad = happiness.veryUnhappyFromDay < day_number() - days;
+ }
+ return (h <= 4 && c->currentAction != 3 && (happy || sad)) || prop;
+ }
+ case H_DANCE_BALL: return (h >= 1 && h <= 5 && c->currentAction != 3) || prop;
+ case H_CLIMB_RUINS: return h >= 1 && h <= 4 && !(hob[k].flags & HS_CANCEL) && c->currentAction != 3;
+ }
+ return false;
+}
+
+/* the nearest forest left untouched, or ruins, on the citizen's world (the signed distance, as written) */
+float resource_initial(const Perm *p);
+void resource_climb(const Perm *p, int *x, int *y);
+void ruins_climb(const Perm *p, int *x, int *y);
+static uint16_t nearest_on_world(const Cit *c, bool ruins) {
+ uint16_t best = NONE;
+ float bestd = 100000;
+ int w = c->onWorld;
+ for (int col = 0; col < worlds[w].ncols; col++) {
+ Perm *p = P(perm_at(w, col, 0));
+ if (!p) continue;
+ if (ruins ? !is_a(p, B_RUINS) : !is_a(p, B_FOREST) || STC(LimitedState, p)->materialsLeft != resource_initial(p)) continue;
+ float d = col * 20 - world_x(c);
+ if (d < bestd) best = pid(p), bestd = d;
+ }
+ return best;
+}
+static void climb(Cit *c, bool ruins) {
+ int k = c->hobby;
+ if (ruins && (hob[k].flags & HS_CANCEL)) return;
+ Perm *in = P(c->inPermanent);
+ if (in && (ruins ? is_a(in, B_RUINS) : is_a(in, B_FOREST))) {
+ /* (for the ruins the hour test is 4.5: never true, so the climber stays up) */
+ if (!ruins && hour() == 4 && minute() > 45) {
+ if (c->relativeY != 0) path2(c, 9, 0);
+ } else if (c->relativeY == 0) {
+ int x, y;
+ if (ruins) ruins_climb(in, &x, &y);
+ else resource_climb(in, &x, &y);
+ path4(c, 4, x, 9, y);
+ }
+ return;
+ }
+ uint16_t to = nearest_on_world(c, ruins);
+ if (to) path_find(c, to, THEN_NONE);
+ else if (ruins) hob[k].flags |= HS_CANCEL;
+}
+/* a prop put away: the citizen waits a little (setPath([8, 5])) */
+static void prop_off(Cit *c) {
+ hob[c->hobby].flags &= (uint8_t)~HS_PROP;
+ path_here(c, 8, 5);
+}
+static void walk_with_prop(Cit *c, float timeMod, float speed, bool turns) {
+ int k = c->hobby;
+ float maxx = worlds[c->onWorld].w - 2;
+ int dir = hob[k].flags & HS_LEFT ? -1 : 1;
+ c->relativeX += timeMod * speed * dir;
+ if ((dir == 1 && c->relativeX >= maxx) || (dir == -1 && c->relativeX <= 0)) {
+ hob[k].flags ^= HS_LEFT;
+ } else if (turns) {
+ if (hob[k].timer > 150 && rnd_int(90) == 1) hob[k].flags ^= HS_LEFT, hob[k].timer = 0;
+ else hob[k].timer += timeMod;
+ }
+}
+/* findNearestBestBuildingStack: the nearest column with nothing (1000), else with a forest (999) */
+static int best_column(const Cit *c) {
+ int w = c->onWorld, best = -1, bestv = -1;
+ float bestd = 1e9f;
+ for (int col = 0; col < worlds[w].ncols; col++) {
+ Perm *p = P(perm_at(w, col, 0));
+ int v = !p ? 1000 : is_a(p, B_FOREST) ? 999 : 0;
+ float d = fabsf(col * 20 + 9 - c->relativeX);
+ if (v > bestv || (v == bestv && d < bestd)) best = col, bestv = v, bestd = d;
+ }
+ return best < 0 ? 0 : best;
+}
+static uint8_t TH_TELESCOPE;
+static void th_telescope(Cit *c, uint16_t arg) {
+ int k = c->hobby;
+ if (k != H_WATCH_STARS) return;
+ int pos = arg;
+ hob[k].flags |= HS_PROP;
+ if (rnd_int(2) == 0) hob[k].x = (int16_t)(pos - 4), hob[k].flags &= (uint8_t)~HS_FLIP;
+ else hob[k].x = (int16_t)(pos + 2 + 4), hob[k].flags |= HS_FLIP;
+}
+
+void hobby_update(Cit *c, float timeMod) {
+ int k = c->hobby, h = hour();
+ switch (k) {
+ case H_CLIMB_TREE: climb(c, false); break;
+ case H_CLIMB_RUINS: climb(c, true); break;
+ case H_MOVE_TO_EDGE: {
+ float maxx = worlds[c->onWorld].w - 2;
+ if (c->inPermanent || (c->relativeX > 0 && c->relativeX < maxx)) {
+ if (!c->inPermanent) path_here(c, 4, c->relativeX < maxx / 2 ? 0 : (int)maxx);
+ else cit_go_down_towards_world_surface(c, timeMod);
+ }
+ break;
+ }
+ case H_WATCH_STARS:
+ if (h <= 4) {
+ if (hob[k].flags & HS_PROP) break;
+ if (c->inPermanent) {
+ cit_go_down_towards_world_surface(c, timeMod);
+ } else {
+ int pos = best_column(c) * 20 + rnd_between(4, 18 - 4);
+ int16_t s[2] = {4, (int16_t)pos};
+ cit_set_path_then(c, s, 1, TH_TELESCOPE, (uint16_t)pos);
+ c->pathOnlyRelatedTo = c->inPermanent;
+ }
+ } else if (hob[k].flags & HS_PROP) {
+ prop_off(c);
+ }
+ break;
+ case H_PROTEST: case H_PROTEST2: case H_PROTEST3: case H_PROTEST4: {
+ float hp = happiness.happiness;
+ bool happy = k == H_PROTEST && hp >= 99.99f, sad = hp <= 10.01f;
+ if (k != H_PROTEST && sad) sad = happiness.veryUnhappyFromDay < day_number() - (k == H_PROTEST2 ? 2 : k == H_PROTEST3 ? 4 : 7);
+ if (h <= 4 && (happy || sad)) {
+ if (c->inPermanent) {
+ cit_go_down_towards_world_surface(c, timeMod);
+ break;
+ }
+ if (!(hob[k].flags & HS_PROP)) {
+ hob[k].flags = (uint8_t)((hob[k].flags & HS_CANCEL) | HS_PROP | (rnd_int(2) ? 0 : HS_LEFT) | (happy ? HS_HAPPY : 0));
+ }
+ walk_with_prop(c, timeMod, 0.6666667f, true);
+ } else if (hob[k].flags & HS_PROP) {
+ prop_off(c);
+ }
+ break;
+ }
+ case H_DANCE_BALL:
+ if (h >= 1 && h <= 5) {
+ if (c->inPermanent) {
+ cit_go_down_towards_world_surface(c, timeMod);
+ break;
+ }
+ c->relativeY = 4;
+ if (!(hob[k].flags & HS_PROP)) hob[k].flags = (uint8_t)(HS_PROP | (rnd_int(2) ? 0 : HS_LEFT));
+ walk_with_prop(c, timeMod, 0.5f, false);
+ } else if (hob[k].flags & HS_PROP) {
+ prop_off(c);
+ c->relativeY = 0;
+ }
+ break;
+ }
+}
+
+/* onDie: the hobby goes back to the pool, for anyone */
+void hobby_on_die(Cit *c) {
+ int k = c->hobby;
+ if (k <= H_NONE || k >= H_COUNT) return;
+ hob[k].flags = 0;
+ if (npool < H_COUNT - 1) pool[npool].kind = (uint8_t)k, pool[npool].min = 0, npool++;
+ c->hobby = H_NONE;
+}
+
+/* the props (on the far foreground): telescope, protest signs, balls */
+void hobby_draw_free(const GfxBand *b, int layer) {
+ if (layer != LAYER_FRONT) return;
+ for (int i = 1; i < MAX_CITS; i++) {
+ const Cit *c = &cits[i];
+ int k = c->hobby;
+ if (!(c->flags & CF_ALIVE) || k <= H_NONE || k >= H_COUNT || !(hob[k].flags & HS_PROP)) continue;
+ const World *w = &worlds[c->onWorld];
+ uint16_t spr;
+ float x, y;
+ uint8_t flip = 0;
+ if (k == H_WATCH_STARS) {
+ spr = SPR_TELESCOPE, x = w->x + hob[k].x, y = w->y - 5;
+ if (hob[k].flags & HS_FLIP) flip = GFX_FLIPX, x -= spr_w(spr); /* (scale -1 draws to the left of x) */
+ } else if (k == H_DANCE_BALL) {
+ spr = SPR_CITIZEN_BALL, x = w->x + c->relativeX - 1, y = w->y - 4;
+ } else {
+ spr = hob[k].flags & HS_HAPPY ? SPR_PROTESTSIGN_HAPPY : SPR_PROTESTSIGN_SAD;
+ x = w->x + c->relativeX - (hob[k].flags & HS_LEFT ? 5 : 2), y = w->y - spr_h(spr);
+ }
+ int sx = bg_screen_x(&camera, x), sy = bg_screen_y(&camera, y);
+ gfx_band_sprite(b, spr, 0, 0, spr_w(spr), spr_h(spr), sx, sy, flip, 255, GFX_NO_TINT);
+ }
+}
+
+/* a new city: the whole pool; after a load: the pool without the living citizens' hobbies (the props are gone) */
+void hobbies_new_city(void) {
+ pool_init();
+ memset(hob, 0, sizeof hob);
+}
+void hobbies_after_load(void) {
+ pool_init();
+ memset(hob, 0, sizeof hob);
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].hobby) {
+ if (cits[i].hobby >= H_COUNT) cits[i].hobby = H_NONE;
+ else pool_remove(cits[i].hobby);
+ }
+}
+void hobbies_save(SaveIO *io) { (void)io; } /* (the citizens keep their hobbies) */
+bool hobbies_load(SaveIO *io) { (void)io; return true; }
+
+void bld_hobbies_init(void) { TH_TELESCOPE = then_register(th_telescope); }
diff --git a/games/finalearth2/src/bld_houses.c b/games/finalearth2/src/bld_houses.c
new file mode 100644
index 00000000..82b0d268
--- /dev/null
+++ b/games/finalearth2/src/bld_houses.c
@@ -0,0 +1,610 @@
+/* The Final Earth 2: houses (buildings.md 6): what residents do at home
+ * (walkAround), the homes that change with their neighbours (modern rustic
+ * homes, mechanical houses, mansions), community houses' production, private
+ * teleporters, and the looks the player can change. */
+#include "bldi.h"
+#include "lang_data.h"
+
+int rnd_getint(int a, int b) { return a + (int)floorf(rnd_float() * (float)(b - a)); }
+
+/* the house's resident waits (setPath([8, getInt(90, 120)]) in its building) */
+static void idle(Cit *c) { wait_ticks(c, 90, 120); }
+static void walk_wait(Cit *c, int xmin, int xmax, int tmin, int tmax) {
+ int x = rnd_between(xmin, xmax);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), THEN_NONE, 0, false, false);
+}
+
+/* ---------------------------------------------------------------- the frames of upgrades' sprites */
+static uint8_t *look_of(Perm *p, int upgrade) {
+ switch (upgrade) {
+ case U_Flowers: return p->cls == CLS_NormalHouse ? &ST(NormalHouseState, p)->flowersLook : NULL;
+ case U_LivingComputer: return p->cls == CLS_AlienHouse ? &ST(AlienHouseState, p)->look : NULL;
+ case U_ModernHomePlant: return p->cls == CLS_CuttingEdgeHome ? &ST(CuttingEdgeState, p)->plantLook : NULL;
+ case U_BetterTools: return p->cls == CLS_TinkerersHome ? &ST(TinkerersState, p)->toolsLook : NULL;
+ default: return NULL;
+ }
+}
+int upgrade_look(const Perm *p, int upgrade) {
+ const uint8_t *l = look_of((Perm *)p, upgrade);
+ return l ? *l : 0;
+}
+void upgrade_set_look(Perm *p, int upgrade, int look) {
+ uint8_t *l = look_of(p, upgrade);
+ if (l) *l = (uint8_t)look;
+}
+
+/* ---------------------------------------------------------------- NormalHouse */
+static void normal_house_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ /* the coloured door, on the ground floor */
+ if (layer == LAYER_MAIN && p->row == 0)
+ dr_frame(b, SPR_COLOREDDOORS, 20, STC(NormalHouseState, p)->doorMainTexture % 6, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+/* createWindowAddBottomButtons: the door's colour (a ground floor's), after the upgrades */
+static void normal_house_window(Perm *p, WinOut *w) {
+ win_later(w);
+ if (p->row == 0) win_button(w, 0, L_change_door_color, WA_CYCLE_0, true);
+}
+static void normal_house_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0 && p->row == 0) {
+ NormalHouseState *s = ST(NormalHouseState, p);
+ s->doorMainTexture = (uint8_t)((s->doorMainTexture + 1) % 6);
+ }
+}
+const PermOps ops_NormalHouse = {.draw = normal_house_draw, .window = normal_house_window, .window_action = normal_house_action};
+
+/* ---------------------------------------------------------------- simple homes */
+static void house_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ draw_upgrades(b, p, layer, x, y, true);
+}
+const PermOps ops_AlienHouse = {.draw = house_draw};
+const PermOps ops_ComfortableHouse = {.draw = house_draw};
+
+/* ModernRusticHome: +15 with three neighbours of community feeling */
+static void rustic_city_change(Perm *p) {
+ RusticState *s = ST(RusticState, p);
+ int now = adj_effect(p, EF_COMMUNITY) >= 3 ? 15 : 0;
+ p->bonusAttractiveness = (int8_t)(p->bonusAttractiveness + now - s->adjBonus);
+ if (now != s->adjBonus) sim_flags |= SIM_HOUSES_CHANGED;
+ s->adjBonus = (uint8_t)now;
+}
+const PermOps ops_ModernRusticHome = {.on_city_change = rustic_city_change, .draw = house_draw};
+
+/* ---------------------------------------------------------------- MechanicalHouse */
+enum { MH_NONE, MH_LEFTRIGHT, MH_LEFT, MH_TOP, MH_RIGHT, MH_BOTTOM };
+static bool is_mpf(const Perm *q) { return q && class_is(q->cls, CLS_MachinePartsFactory); }
+uint16_t mechanical_house_texture(const Perm *p) {
+ static const uint16_t t[6] = {SPR_MECHANICALHOUSE, SPR_MECHANICALHOUSE_LEFTRIGHT, SPR_MECHANICALHOUSE_LEFT,
+ SPR_MECHANICALHOUSE_TOP, SPR_MECHANICALHOUSE_RIGHT, SPR_MECHANICALHOUSE_BOTTOM};
+ return t[STC(MechanicalState, p)->variant % 6];
+}
+static void mechanical_city_change(Perm *p) {
+ MechanicalState *s = ST(MechanicalState, p);
+ int old_bonus = s->variant != MH_NONE ? 50 : 0;
+ const Perm *l = P(p->left), *r = P(p->right), *t = P(p->top), *bo = P(p->bottom);
+ s->movementType = 0;
+ s->pipeAlt = 0;
+ if (is_mpf(r)) {
+ if (is_mpf(l)) s->variant = MH_LEFTRIGHT, s->pipeAlt = l->bottom == NONE;
+ else s->variant = MH_LEFT;
+ s->movementType = 1;
+ } else if (is_mpf(bo)) {
+ s->variant = MH_TOP;
+ s->pipeAlt = is_mpf(t);
+ s->movementType = 2;
+ } else if (is_mpf(l)) {
+ s->variant = MH_RIGHT;
+ s->pipeAlt = l->bottom == NONE;
+ } else if (is_mpf(t)) {
+ s->variant = MH_BOTTOM;
+ s->movementType = 3;
+ } else {
+ s->variant = MH_NONE;
+ }
+ int now = s->variant != MH_NONE ? 50 : 0;
+ p->bonusAttractiveness = (int8_t)(p->bonusAttractiveness + now - old_bonus);
+ if (now != old_bonus) sim_flags |= SIM_HOUSES_CHANGED;
+}
+static void mechanical_walk(Perm *p, Cit *c, float steps) {
+ int mt = STC(MechanicalState, p)->movementType;
+ int r = rnd_int(4);
+ if (mt == 0) {
+ if (r == 0 && steps > 120) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1) walk_wait(c, 3, 7, 30, 60);
+ else if (r == 2) walk_wait(c, 12, 16, 30, 60);
+ else idle(c);
+ } else if (mt == 1) {
+ if (r == 0 && steps > 120 && c->relativeX < 11) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1) walk_wait(c, 3, 7, 30, 60);
+ else if (r == 2 && c->relativeY < 5) walk_wait(c, 12, 16, 30, 60);
+ else idle(c);
+ } else if (mt == 2) {
+ if (r == 0 && steps > 120 && c->relativeX > 11) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r <= 2 && c->relativeY < 5) walk_wait(c, 7, 16, 30, 60);
+ else if (r <= 2) walk_wait(c, 12, 16, 30, 60);
+ else idle(c);
+ } else {
+ if (r == 0 && steps > 120 && c->relativeX > 11) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if ((r == 1 || r == 2) && c->relativeY < 5) walk_wait(c, 7, 16, 30, 60);
+ else if (r == 2) walk_wait(c, 12, 16, 30, 60);
+ else idle(c);
+ }
+}
+static void mechanical_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ const MechanicalState *s = STC(MechanicalState, p);
+ draw_normal(b, p, layer, x, y, mechanical_house_texture(p), false);
+ if (layer == LAYER_BG) {
+ static const uint16_t anim[6] = {0, SPR_MECHANICALHOUSE_LEFTRIGHT_BGANIM, SPR_MECHANICALHOUSE_LEFT_BGANIM,
+ SPR_MECHANICALHOUSE_TOP_BGANIM, SPR_MECHANICALHOUSE_RIGHT_BGANIM,
+ SPR_MECHANICALHOUSE_BOTTOM_BGANIM};
+ if (s->variant != MH_NONE) {
+ /* its factory's back animation's phase */
+ const Perm *f = s->variant <= MH_LEFT ? P(p->right) : s->variant == MH_TOP ? P(p->bottom) : s->variant == MH_RIGHT ? P(p->left) : P(p->top);
+ uint16_t a = anim[s->variant % 6];
+ int n = frames_of(a, 20);
+ dr_frame(b, a, 20, f ? factory_frame(f, n) : 0, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ }
+ if (has_upgrade_bit(p, UB_MechanicalHouse_HeatedBed)) dr_sprite(b, SPR_MECHANICALHOUSE_HEATEDBED, x, y, 0, 0, 0, 255);
+ } else if (layer == LAYER_ABOVE) {
+ switch (s->variant) {
+ case MH_LEFTRIGHT: dr_sprite(b, s->pipeAlt ? SPR_MECHANICALHOUSE_PIPE_H3_BF : SPR_MECHANICALHOUSE_PIPE_H3, x, y, -3, 0, 0, 255); break;
+ case MH_LEFT: dr_sprite(b, SPR_MECHANICALHOUSE_PIPE_H, x, y, 20, 4, 0, 255); break;
+ case MH_TOP:
+ if (s->pipeAlt) dr_sprite(b, SPR_MECHANICALHOUSE_PIPE_V3, x, y, 1, -3, 0, 255);
+ else dr_sprite(b, SPR_MECHANICALHOUSE_PIPE_V1, x, y, 1, 20, 0, 255);
+ break;
+ case MH_RIGHT:
+ if (s->pipeAlt) dr_sprite(b, SPR_MECHANICALHOUSE_PIPE_H2_BF, x, y, -3, 5, 0, 255);
+ else dr_sprite(b, SPR_MECHANICALHOUSE_PIPE_H2, x, y, -3, 11, 0, 255);
+ break;
+ case MH_BOTTOM: dr_sprite(b, SPR_MECHANICALHOUSE_PIPE_V2, x, y, 3, -3, 0, 255); break;
+ default: break;
+ }
+ }
+}
+const PermOps ops_MechanicalHouse = {.on_city_change = mechanical_city_change, .walk_around = mechanical_walk,
+ .draw = mechanical_draw};
+
+/* ---------------------------------------------------------------- SpaciousHouse, CuttingEdgeHome */
+static void spacious_walk(Perm *p, Cit *c, float steps) {
+ (void)p;
+ int r = rnd_int(3);
+ if (r == 0 && steps > 120) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1) {
+ if (c->relativeY < 5) walk_wait(c, 3, 15, 30, 60);
+ else if (rnd_int(2) == 1) walk_wait(c, 3, 7, 30, 60);
+ else walk_wait(c, 12, 16, 30, 60);
+ } else idle(c);
+}
+const PermOps ops_SpaciousHouse = {.walk_around = spacious_walk, .draw = house_draw};
+
+static void cutting_edge_walk(Perm *p, Cit *c, float steps) {
+ (void)p;
+ int r = rnd_int(3);
+ if (r == 0 && steps > 120) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1) {
+ if (c->relativeY < 5) walk_wait(c, 3, 15, 30, 60);
+ else walk_wait(c, 5, 15, 30, 60);
+ } else idle(c);
+}
+static int cutting_edge_residents(const Perm *p) {
+ return PC(p)->residents + (has_upgrade_bit(p, UB_CuttingEdgeHome_BiggerTV) ? 1 : 0); /* extraCapacity */
+}
+static float cutting_edge_years(const Perm *p) { return has_upgrade_bit(p, UB_CuttingEdgeHome_ModernHomePlant) ? 0.05f : 0; }
+const PermOps ops_CuttingEdgeHome = {.walk_around = cutting_edge_walk, .residents = cutting_edge_residents,
+ .years_to_live_longer = cutting_edge_years, .draw = house_draw};
+
+/* ---------------------------------------------------------------- ParkPod, BlossomHut, TreeHuggerBase: residents disappear inside */
+static void vanish_at(Cit *c, int x) {
+ if (c->relativeX == x) c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ else move_x(c, x);
+}
+static void park_pod_init(Perm *p) {
+ ParkPodState *s = ST(ParkPodState, p);
+ s->podTexture = (uint8_t)rnd_int(frames_of(SPR_PARKPOD, 20));
+}
+static void park_pod_walk(Perm *p, Cit *c, float steps) { (void)p, (void)steps; vanish_at(c, 9); }
+static void park_pod_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer == LAYER_BG) dr_frame(b, SPR_PARKPOD, 20, STC(ParkPodState, p)->podTexture, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+static void park_pod_window(Perm *p, WinOut *w) {
+ (void)p;
+ win_button(w, 0, "Change Building Color", WA_CYCLE_0, true);
+ win_button(w, 0, "Change Variant", WA_CYCLE_1, true);
+}
+static void park_pod_action(Perm *p, int a) {
+ ParkPodState *s = ST(ParkPodState, p);
+ if (a == WA_CYCLE_0) s->mainTexture = (uint8_t)((s->mainTexture + 1) % 3);
+ else if (a == WA_CYCLE_1) s->podTexture = (uint8_t)((s->podTexture + 1) % frames_of(SPR_PARKPOD, 20));
+}
+const PermOps ops_ParkPod = {.init = park_pod_init, .walk_around = park_pod_walk, .draw = park_pod_draw,
+ .window = park_pod_window, .window_action = park_pod_action};
+
+static void blossom_hut_walk(Perm *p, Cit *c, float steps) { (void)p, (void)steps; vanish_at(c, 9); }
+const PermOps ops_BlossomHut = {.walk_around = blossom_hut_walk, .draw = draw_merging};
+
+static void tree_hugger_walk(Perm *p, Cit *c, float steps) { (void)p, (void)steps; vanish_at(c, 10); }
+static void tree_hugger_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer == LAYER_BG) dr_sprite(b, SPR_TREEHUGGERBASE, x, y, 0, 0, 0, 255);
+}
+const PermOps ops_TreeHuggerBase = {.walk_around = tree_hugger_walk, .draw = tree_hugger_draw};
+
+/* ---------------------------------------------------------------- Loft */
+static void loft_init(Perm *p) {
+ LoftState *s = ST(LoftState, p);
+ s->interior = (uint8_t)rnd_int(frames_of(SPR_LOFT_FURNISHINGS, 20));
+ p->flags |= PF_IS_ENTERTAINMENT;
+}
+static float loft_attractiveness(const Perm *p) { (void)p; return 88; }
+static float loft_capacity(const Perm *p) { return p->nresidents * 5; }
+static bool never_open(const Perm *p) { (void)p; return false; }
+static void loft_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ int x = rnd_between(3, 16);
+ cit_move_and_wait(c, x, rnd_between(200, 240), THEN_NONE, 0, false, true);
+}
+static void loft_walk(Perm *p, Cit *c, float steps) {
+ (void)steps;
+ if (c->relativeY >= 5) return;
+ bool mirrored = STC(LoftState, p)->mirrored;
+ if (mirrored ? c->relativeX >= 5 || rnd_float() < 0.5f : c->relativeX < 14 || rnd_float() < 0.5f)
+ walk_wait(c, 3, 16, 60, 90);
+}
+static void loft_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ const LoftState *s = STC(LoftState, p);
+ draw_custom(b, p, layer, x, y, PC(p)->sprite, s->mirrored, 0, 0, SPR_LOFT_FURNISHINGS, s->interior);
+}
+static void loft_window(Perm *p, WinOut *w) {
+ (void)p;
+ win_button(w, 0, "Mirror", WA_MIRROR, true);
+ win_button(w, 0, "Change Interior", WA_CYCLE_0, true);
+}
+static void loft_action(Perm *p, int a) {
+ LoftState *s = ST(LoftState, p);
+ if (a == WA_MIRROR) s->mirrored ^= 1;
+ else if (a == WA_CYCLE_0) s->interior = (uint8_t)((s->interior + 1) % frames_of(SPR_LOFT_FURNISHINGS, 20));
+}
+const PermOps ops_Loft = {.init = loft_init, .attractiveness = loft_attractiveness, .entertainment_capacity = loft_capacity,
+ .is_open = never_open, .is_open_for_existing_visitors = never_open,
+ .be_entertained = loft_be_entertained, .walk_around = loft_walk, .draw = loft_draw,
+ .window = loft_window, .window_action = loft_action};
+float loft_door_x(const Perm *p) { return STC(LoftState, p)->mirrored ? 4 : 14; }
+
+/* ---------------------------------------------------------------- TinkerersHome */
+static void tinkerers_init(Perm *p) {
+ TinkerersState *s = ST(TinkerersState, p);
+ s->front = (uint8_t)rnd_int(frames_of(SPR_TINKERERSHOUSE_FRONT_ALT, 20));
+ s->back = (uint8_t)rnd_int(frames_of(SPR_TINKERERSHOUSE_BACK_ALT, 20));
+}
+static void tinkerers_on_build(Perm *p) { (void)p; unlocks_unlock("MechanicalLiving"); }
+static void tinkerers_walk(Perm *p, Cit *c, float steps) {
+ (void)p;
+ educate(c, 0.01f, 1.25f);
+ int r = rnd_int(6);
+ if (r < 2 && steps > 120) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 2 || r == 3 || steps < 10) {
+ if (c->relativeY < 5) {
+ if (r == 2) walk_wait(c, 3, 6, 30, 60);
+ else walk_wait(c, 15, 16, 30, 60);
+ } else if (r == 2) walk_wait(c, 3, 6, 30, 60);
+ else walk_wait(c, 12, 16, 30, 60);
+ } else idle(c);
+}
+static void tinkerers_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ const TinkerersState *s = STC(TinkerersState, p);
+ draw_custom(b, p, layer, x, y, PC(p)->sprite, false, SPR_TINKERERSHOUSE_FRONT_ALT, s->front, SPR_TINKERERSHOUSE_BACK_ALT, s->back);
+ draw_upgrades(b, p, layer, x, y, false);
+}
+const PermOps ops_TinkerersHome = {.init = tinkerers_init, .on_build = tinkerers_on_build, .walk_around = tinkerers_walk,
+ .draw = tinkerers_draw};
+
+/* ---------------------------------------------------------------- FarmHouse (Community House) */
+static uint8_t TH_COMMUNITY;
+/* the material its mode makes: 0 stone, 1 wood, 2 food */
+static int material_type(const Perm *p) {
+ return p->mode == MODE_FarmHouse_CHProduceStone ? 0 : p->mode == MODE_FarmHouse_CHProduceWood ? 1 : 2;
+}
+static int phase(const Perm *p) { return STC(FarmHouseState, p)->bits & 3; }
+static void set_phase(Perm *p, int ph) {
+ FarmHouseState *s = ST(FarmHouseState, p);
+ s->bits = (uint8_t)((s->bits & ~3) | ph);
+}
+int farmhouse_farm_effects(const Perm *p) { return p->cls == CLS_FarmHouse ? STC(FarmHouseState, p)->bits >> 6 : 0; }
+static float original_materials(int type) { return type == 0 ? 20 : type == 1 ? 25 : 10; }
+/* a CHProduce* mode's constructor: progress reset if the type changes, then setMaterialType (food mode adds a farm
+ * effect each time; other modes remove one: the original's list can hold two) */
+void farmhouse_mode_set(Perm *p, int old_type, int type) {
+ FarmHouseState *s = ST(FarmHouseState, p);
+ if (old_type != type) {
+ set_phase(p, 0);
+ s->stageProgress = 0;
+ }
+ int fx = s->bits >> 6;
+ if (type == 2) fx = fx < 3 ? fx + 1 : 3;
+ else if (fx > 0) fx--;
+ s->bits = (uint8_t)((s->bits & 0x3F) | fx << 6);
+}
+static void farmhouse_init(Perm *p) {
+ /* Building's first mode (food), then the FarmHouse's random one */
+ p->mode = MODE_FarmHouse_CHProduceFood;
+ farmhouse_mode_set(p, -1, 2);
+ int m = rnd_int(3);
+ int old = material_type(p);
+ p->mode = (uint8_t)m;
+ farmhouse_mode_set(p, old, material_type(p));
+}
+static void farmhouse_update(Perm *p, float timeMod) {
+ if (phase(p) != 0) return;
+ FarmHouseState *s = ST(FarmHouseState, p);
+ int type = material_type(p);
+ if (type == 0) {
+ s->stageProgress += timeMod * 0.05f;
+ if (s->stageProgress >= 1) set_phase(p, 1), s->stageProgress = original_materials(0);
+ } else if (day_light()) {
+ s->stageProgress += (type == 1 ? 0.00018f : 0.00008f) * timeMod;
+ if (s->stageProgress >= 1) set_phase(p, 1), s->stageProgress = original_materials(type);
+ }
+}
+static void harvest(Perm *p, int m, float amount, int phase_after) {
+ FarmHouseState *s = ST(FarmHouseState, p);
+ float h = amount * boost();
+ s->stageProgress -= h;
+ produce(m, h);
+ s->totalMaterialsProduced += h;
+ if (s->stageProgress <= 0) s->stageProgress = 0, set_phase(p, phase_after);
+}
+static void th_community(Cit *c, uint16_t arg) {
+ (void)c;
+ Perm *p = P(arg & 0x3FF);
+ if (!p || p->cls != CLS_FarmHouse) return;
+ FarmHouseState *s = ST(FarmHouseState, p);
+ switch (material_type(p)) {
+ case 0:
+ if (phase(p) == 1) harvest(p, M_STONE, 0.1f, 0);
+ break;
+ case 1:
+ if (phase(p) == 0) {
+ s->stageProgress += 0.005f;
+ if (s->stageProgress >= 1) s->stageProgress = original_materials(1), set_phase(p, 1);
+ } else {
+ harvest(p, M_WOOD, 0.2f, 0);
+ }
+ break;
+ case 2:
+ if (phase(p) == 1) {
+ harvest(p, M_FOOD, 0.25f, 2);
+ } else if (phase(p) == 0) {
+ s->stageProgress += 0.01f;
+ if (s->stageProgress >= 1) s->stageProgress = original_materials(2), set_phase(p, 1);
+ } else if (phase(p) == 2) {
+ s->stageProgress += 0.1f;
+ if (s->stageProgress >= 1) s->stageProgress = 0, set_phase(p, 0);
+ }
+ break;
+ }
+}
+static void farmhouse_walk(Perm *p, Cit *c, float steps) {
+ if (steps < 180) {
+ if (c->relativeY > 5) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else {
+ int tmin = phase(p) == 2 ? 20 : 50, tmax = phase(p) == 2 ? 30 : 80;
+ int x = rnd_between(3, 7);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), TH_COMMUNITY, pid(p), true, false);
+ }
+ } else if (c->relativeX > 11 && rnd_int(3) == 1) {
+ cit_change_floor_and_wait_random(c, 60, 90, THEN_NONE, 0);
+ } else {
+ walk_wait(c, 12, 16, 60, 90);
+ }
+}
+static void farmhouse_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ if (layer != LAYER_BG) return;
+ /* setResourceSpriteTexture: 5-pixel frames at (3, 3) */
+ const FarmHouseState *s = STC(FarmHouseState, p);
+ int type = material_type(p), ph = phase(p);
+ static const uint16_t tex[3] = {SPR_COMMUNITYHOUSE_ROCK, SPR_COMMUNITYHOUSE_TREE, SPR_COMMUNITYHOUSE_CROP};
+ uint16_t spr = tex[type];
+ int n = frames_of(spr, 5), f = 0;
+ uint8_t alpha = 255;
+ if ((type == 0 || type == 1) && ph == 1) {
+ f = (int)ceilf((1 - s->stageProgress / original_materials(type)) * (n - 1));
+ } else if (type == 0) {
+ float a = s->stageProgress;
+ alpha = (uint8_t)(a <= 0 ? 0 : a >= 1 ? 255 : a * 255);
+ } else if (type == 2 && ph == 0) {
+ f = (int)(s->stageProgress * (n - 2));
+ } else if (type == 1 && ph == 0) {
+ spr = SPR_COMMUNITYHOUSE_TREE_GROW;
+ n = frames_of(spr, 5);
+ f = (int)(s->stageProgress * n);
+ } else if (type == 2) {
+ f = ph == 1 ? n - 2 : n - 1;
+ }
+ if (f < 0) f = 0;
+ if (f > n - 1) f = n - 1;
+ dr_frame(b, spr, 5, f, x, y, 3, 3, 0, alpha, GFX_NO_TINT);
+}
+static void farmhouse_window(Perm *p, WinOut *w) {
+ win_line1(w, "[0] resources produced.", (int)STC(FarmHouseState, p)->totalMaterialsProduced);
+}
+const PermOps ops_FarmHouse = {.init = farmhouse_init, .update = farmhouse_update, .walk_around = farmhouse_walk,
+ .draw = farmhouse_draw, .window = farmhouse_window};
+
+/* ---------------------------------------------------------------- homes with private teleporters */
+static bool yes(const Perm *p) { (void)p; return true; }
+static void teleport_lines(Perm *p, WinOut *w) {
+ const PrivateTeleporterState *s = STC(PrivateTeleporterState, p);
+ win_line1(w, "Teleported from [0] times.", s->timesUsed);
+ win_line1(w, "Teleported to [0] times.", s->timesUsedTo);
+}
+static void villa_walk(Perm *p, Cit *c, float steps, int gxmin, int gxmax, bool villa) {
+ float tx = transport_teleport_x(p);
+ int r = rnd_int(3);
+ if (r == 0 && steps > 120) {
+ if (c->relativeX < 5) cit_move(c, 5, TH_CHANGE_FLOOR_WAIT_30_60, 0, false);
+ else cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ } else if (r == 1 || (steps <= 10 && c->relativeX < tx + 0.5f)) {
+ if (c->relativeY < 5) walk_wait(c, gxmin, gxmax, 30, 60);
+ else if (!villa) walk_wait(c, 3, 16, 30, 60);
+ else if (rnd_int(2) == 1) walk_wait(c, 5, 8, 30, 60);
+ else walk_wait(c, 13, 16, 30, 60);
+ } else {
+ idle(c);
+ }
+}
+static void villa_walk_around(Perm *p, Cit *c, float steps) { villa_walk(p, c, steps, 10, 16, true); }
+static void villa_window(Perm *p, WinOut *w) {
+ teleport_lines(p, w);
+ teleporter_upkeep_lines(w);
+}
+void teleporter_upkeep_action(int a);
+static void villa_action(Perm *p, int a) { (void)p; teleporter_upkeep_action(a); }
+const PermOps ops_Villa = {.has_private_teleporter = yes, .walk_around = villa_walk_around, .draw = house_draw,
+ .window = villa_window, .window_action = villa_action};
+
+/* Mansion: pairs of mansions side by side are worth 25 more each (set from the leftmost of a run) */
+uint16_t mansion_texture(const Perm *p) {
+ int v = STC(PrivateTeleporterState, p)->variant;
+ return v == 1 ? SPR_MANSION_LEFT : v == 2 ? SPR_MANSION_RIGHT : SPR_MANSION;
+}
+static void mansion_city_change(Perm *p) {
+ if (p->left && P(p->left)->cls == CLS_Mansion) return;
+ bool has_left_pair = false;
+ for (Perm *b = p; b && b->cls == CLS_Mansion; b = P(b->right)) {
+ PrivateTeleporterState *s = ST(PrivateTeleporterState, b);
+ if (has_left_pair) {
+ s->variant = 2;
+ has_left_pair = false;
+ b->bonusAttractiveness = 25;
+ } else {
+ bool connected = b->right && P(b->right)->cls == CLS_Mansion;
+ s->variant = connected ? 1 : 0;
+ has_left_pair = true;
+ b->bonusAttractiveness = connected ? 25 : 0;
+ }
+ }
+}
+static void mansion_walk(Perm *p, Cit *c, float steps) {
+ educate(c, 0.01f, 1.25f);
+ villa_walk(p, c, steps, 3, 9, false);
+}
+static float mansion_years(const Perm *p) { (void)p; return 0.025f; }
+static void mansion_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, mansion_texture(p), false);
+}
+const PermOps ops_Mansion = {.has_private_teleporter = yes, .walk_around = mansion_walk, .years_to_live_longer = mansion_years,
+ .on_city_change = mansion_city_change, .draw = mansion_draw, .window = villa_window,
+ .window_action = villa_action};
+
+/* FlowerPenthouse */
+static float penthouse_attractiveness(const Perm *p) { (void)p; return 100; }
+static float penthouse_years(const Perm *p) { (void)p; return 0.05f; }
+static void penthouse_walk(Perm *p, Cit *c, float steps) {
+ (void)steps;
+ bool m = STC(PrivateTeleporterState, p)->mirrored;
+ if (c->relativeY < 5) {
+ if (m ? c->relativeX >= 5 || rnd_float() < 0.5f : c->relativeX < 14 || rnd_float() < 0.5f) walk_wait(c, 3, 16, 60, 90);
+ else cit_change_floor_and_wait(c, 60, THEN_NONE, 0);
+ } else if (m ? c->relativeX >= 5 || rnd_float() < 0.8f : c->relativeX < 14 || rnd_float() < 0.8f) {
+ float r = rnd_float();
+ if (r < 0.5f) walk_wait(c, m ? 15 : 1, m ? 18 : 4, 40, 60);
+ else if (r < 0.8f) walk_wait(c, m ? 10 : 7, m ? 12 : 9, 60, 90);
+ else walk_wait(c, m ? 3 : 14, m ? 5 : 16, 60, 90);
+ } else {
+ cit_change_floor_and_wait(c, 60, THEN_NONE, 0);
+ }
+}
+static void penthouse_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ bool m = STC(PrivateTeleporterState, p)->mirrored;
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, m);
+ /* the flower on top, when nothing is above */
+ if (layer == LAYER_MAIN && !perm_at(p->world, p->col, p->row + 1)) {
+ int h = spr_h(SPR_FLOWER_UP), w = spr_w(SPR_FLOWER_UP);
+ dr_sprite(b, SPR_FLOWER_UP, x, y, m ? 20 - w : 0, -h, m ? GFX_FLIPX : 0, 255);
+ }
+}
+static void penthouse_window(Perm *p, WinOut *w) {
+ teleport_lines(p, w);
+ win_button(w, 0, "Mirror", WA_MIRROR, true);
+ teleporter_upkeep_lines(w);
+}
+static void penthouse_action(Perm *p, int a) {
+ if (a == WA_MIRROR) ST(PrivateTeleporterState, p)->mirrored ^= 1;
+ else teleporter_upkeep_action(a);
+}
+const PermOps ops_FlowerPenthouse = {.attractiveness = penthouse_attractiveness, .has_private_teleporter = yes,
+ .years_to_live_longer = penthouse_years, .walk_around = penthouse_walk,
+ .draw = penthouse_draw, .window = penthouse_window, .window_action = penthouse_action};
+
+/* ---------------------------------------------------------------- LandedExplorationShip */
+static float ship_attractiveness(const Perm *p) { (void)p; return 50; }
+static void ship_walk(Perm *p, Cit *c, float steps) {
+ (void)steps;
+ bool m = STC(PrivateTeleporterState, p)->mirrored;
+ int r = rnd_int(3);
+ int mm = m ? -1 : 1, ma = m ? 20 : 0;
+ /* (as written: the mirrored tests compare the other way round) */
+ if (c->relativeX * mm > (ma + 11 * mm) * mm) c->relativeX = 11;
+ if (c->relativeX * mm <= (ma + mm) * mm) c->relativeX = 2;
+ if (r == 1) {
+ int x = rnd_getint(ma + mm * 4, ma + mm * 5);
+ cit_move_and_wait(c, x, rnd_between(30, 60), THEN_NONE, 0, false, false);
+ } else if (r == 2) {
+ int x = rnd_getint(ma + mm * 9, ma + mm * 12);
+ cit_move_and_wait(c, x, rnd_between(30, 60), THEN_NONE, 0, false, false);
+ } else {
+ idle(c);
+ }
+}
+static void ship_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, STC(PrivateTeleporterState, p)->mirrored);
+}
+static void ship_window(Perm *p, WinOut *w) {
+ (void)p;
+ win_line(w, "Used as a house.");
+ win_button(w, 0, "Mirror", WA_MIRROR, true);
+}
+static void ship_action(Perm *p, int a) {
+ if (a == WA_MIRROR) ST(PrivateTeleporterState, p)->mirrored ^= 1;
+}
+const PermOps ops_LandedExplorationShip = {.attractiveness = ship_attractiveness, .walk_around = ship_walk, .draw = ship_draw,
+ .window = ship_window, .window_action = ship_action};
+
+/* ---------------------------------------------------------------- HouseOfTheKeyFriends */
+static void key_friends_walk(Perm *p, Cit *c, float steps) {
+ (void)p;
+ int r = rnd_int(5);
+ if (r == 0 && steps > 120) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1 || (r == 2 && c->relativeY < 5)) walk_wait(c, 3, 7, 30, 60);
+ else if (r == 2) walk_wait(c, 12, 16, 30, 60);
+ else idle(c);
+}
+const PermOps ops_HouseOfTheKeyFriends = {.walk_around = key_friends_walk, .draw = house_draw};
+/* (SecretSocietyHouse walks around the same way) */
+void key_friends_walk_around(Perm *p, Cit *c, float steps) { key_friends_walk(p, c, steps); }
+
+/* a house's door x (doorX: mirrored homes move it) */
+float house_door_x(const Perm *p) {
+ switch (p->cls) {
+ case CLS_Loft: return loft_door_x(p);
+ case CLS_FlowerPenthouse: return STC(PrivateTeleporterState, p)->mirrored ? 4 : 14;
+ case CLS_LandedExplorationShip: return STC(PrivateTeleporterState, p)->mirrored ? 14 : 4;
+ default: return PC(p)->doorX;
+ }
+}
+
+/* mirror() of the mirrorable homes (the story's "Loft_mirrored", "LandedExplorationShip_mirrored") */
+void house_mirror(Perm *p) {
+ if (p->cls == CLS_Loft) ST(LoftState, p)->mirrored ^= 1;
+ else if (p->cls == CLS_FlowerPenthouse || p->cls == CLS_LandedExplorationShip) ST(PrivateTeleporterState, p)->mirrored ^= 1;
+}
+
+void bld_houses_init(void) { TH_COMMUNITY = then_register(th_community); }
diff --git a/games/finalearth2/src/bld_production.c b/games/finalearth2/src/bld_production.c
new file mode 100644
index 00000000..2c56e61f
--- /dev/null
+++ b/games/finalearth2/src/bld_production.c
@@ -0,0 +1,992 @@
+/* The Final Earth 2: production buildings (buildings.md 7): the woodcutters'
+ * and stone miners' centres (BlueCollarWork), farms, the exploration centre,
+ * the factories (Factory, MaterialConvertingFactory), labs, tree
+ * plantations, rock teleporters, eco farms (FarmGrowArea) and the farm
+ * by-product processor. */
+#include "bldi.h"
+
+static inline float speed(void) { return happiness.actionSpeedModifier; }
+static inline float edu(const Cit *c) { return cit_education_speed_modifier(c); }
+static inline int arg_perm(uint16_t arg) { return arg & 0x3FF; }
+
+/* ---------------------------------------------------------------- BlueCollarWork */
+enum { GATHER_WOOD, GATHER_STONE };
+static uint8_t TH_DROP_TOOLS, TH_TAKE_TOOLS, TH_CUT_WOOD, TH_MINE_STONE;
+
+static bool gather_option(const Perm *p, int kind) {
+ if (!p || !(p->flags & PF_USED)) return false;
+ if (kind == GATHER_WOOD) return is_a(p, B_FOREST) || p->cls == CLS_TreePlantation;
+ return is_a(p, B_ROCK) || p->cls == CLS_StoneTeleporter;
+}
+typedef struct { int kind; bool prioritized; } GatherGoal;
+static bool gather_goal(const Perm *p, const void *ctx) {
+ const GatherGoal *g = ctx;
+ if (!gather_option(p, g->kind) || limited_materials_left(p) <= 0 || limited_do_not_gather(p)) return false;
+ return !g->prioritized || resource_prioritized(p);
+}
+
+static void th_drop_tools(Cit *c, uint16_t arg) { (void)arg; c->flags &= (uint16_t)~CF_HAS_WORK_TOOLS; }
+static void th_take_tools(Cit *c, uint16_t arg) { (void)arg; c->flags |= CF_HAS_WORK_TOOLS; }
+
+/* after a gather action: the place may be empty now */
+static void gathered(Cit *c, Perm *res) {
+ Perm *centre = P(c->job);
+ BlueCollarState *bs = centre && (centre->cls == CLS_WoodcuttingCentre || centre->cls == CLS_StoneMine) ? ST(BlueCollarState, centre) : NULL;
+ if (limited_materials_left(res) <= 0 && !limited_stay_if_empty(res)) {
+ if (bs) bs->nearest = NONE;
+ if (limited_destroyed_on_empty(res)) perm_destroy(pid(res), false);
+ }
+}
+/* WoodcuttingCentre's getResource */
+static void th_cut_wood(Cit *c, uint16_t arg) {
+ Perm *res = P(arg_perm(arg));
+ if (!gather_option(res, GATHER_WOOD)) return;
+ if (limited_do_not_gather(res)) {
+ Perm *centre = P(c->job);
+ if (centre && centre->cls == CLS_WoodcuttingCentre) ST(BlueCollarState, centre)->nearest = NONE;
+ return;
+ }
+ float w = 0.2f * (story.hiddenBoost && city.materials.m[M_WOOD] <= 6 ? 1.75f : 1) * early_fix() * boost();
+ produce(M_WOOD, w);
+ limited_take(res, w);
+ gathered(c, res);
+}
+/* StoneMine's getResource */
+static float stone_mined_per_action_boost(const Perm *mine) {
+ float b = 1;
+ if (mine && mine->cls == CLS_StoneMine) {
+ if (has_upgrade_bit(mine, UB_StoneMine_BetterPickaxes)) b += 0.2f;
+ if (has_upgrade_bit(mine, UB_StoneMine_AIMining)) b += 0.3f;
+ }
+ return b;
+}
+static void th_mine_stone(Cit *c, uint16_t arg) {
+ Perm *res = P(arg_perm(arg));
+ if (!gather_option(res, GATHER_STONE)) return;
+ if (limited_do_not_gather(res)) {
+ Perm *centre = P(c->job);
+ if (centre && centre->cls == CLS_StoneMine) ST(BlueCollarState, centre)->nearest = NONE;
+ return;
+ }
+ float s = 0.2f * stone_mined_per_action_boost(P(c->job));
+ s = s * (story.hiddenBoost && city.materials.m[M_STONE] <= 4 ? 1.6f : 1) * upgrades.stoneMiningSpeed * early_fix() * boost();
+ produce(M_STONE, s);
+ limited_take(res, s);
+ gathered(c, res);
+}
+
+bool finder_can_query(void);
+typedef bool (*IsGoal)(const Perm *p, const void *ctx);
+typedef float (*Niceness)(const Perm *p);
+uint16_t finder_query(uint16_t from, int from_world, float from_x, IsGoal is_goal, const void *ctx, Niceness niceness,
+ float max_distance, const Cit *citizen, float best_expected);
+
+/* doBlueCollarJob */
+static void blue_collar_job(Perm *p, Cit *c, float timeMod, bool stop, int kind, int tmin, int tmax) {
+ BlueCollarState *s = ST(BlueCollarState, p);
+ bool tools = c->flags & CF_HAS_WORK_TOOLS;
+ if (stop) {
+ if (!tools) c->currentAction = 2;
+ else if (c->inPermanent == pid(p)) cit_move_and_wait(c, 4, 20, TH_DROP_TOOLS, 0, false, false);
+ else path_find(c, pid(p), THEN_NONE);
+ return;
+ }
+ if (!tools) {
+ if (c->inPermanent == pid(p)) cit_move_and_wait(c, 4, 20, TH_TAKE_TOOLS, 0, false, false);
+ else path_find_combined(c, pid(p), THEN_NONE);
+ return;
+ }
+ Perm *in = P(c->inPermanent);
+ if (gather_option(in, kind) && (limited_materials_left(in) > 0 || limited_stay_if_empty(in)) && !limited_do_not_gather(in)) {
+ if (limited_materials_left(in) > 0) {
+ int x = rnd_between(limited_min_x(in), limited_max_x(in));
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), kind == GATHER_WOOD ? TH_CUT_WOOD : TH_MINE_STONE, pid(in), true, false);
+ }
+ return;
+ }
+ bool perform = true;
+ Perm *near = P(s->nearest);
+ if (near && !gather_option(near, kind)) near = NULL, s->nearest = NONE; /* (gone, and its place taken) */
+ if (!near || (limited_materials_left(near) <= 0 && !limited_stay_if_empty(near)) || limited_do_not_gather(near)) {
+ s->nearest = NONE;
+ bool can = finder_can_query();
+ if (!can) perform = false;
+ uint8_t bit = kind == GATHER_WOOD ? WU_FOREST : WU_ROCK;
+ if (can && !s->searched && !(world_unavailable[p->world] & bit)) {
+ GatherGoal g = {kind, true};
+ if (resource_any_prioritized(kind == GATHER_WOOD ? B_FOREST : B_ROCK))
+ s->nearest = finder_query(pid(p), 0, 0, gather_goal, &g, NULL, -1, NULL, 1e8f);
+ if (!s->nearest) {
+ g.prioritized = false;
+ s->nearest = finder_query(pid(p), 0, 0, gather_goal, &g, NULL, -1, NULL, 1e8f);
+ }
+ if (!s->nearest) world_unavailable[p->world] |= bit;
+ s->searched = 1;
+ }
+ }
+ if (perform) {
+ if (s->nearest) path_find_combined(c, s->nearest, THEN_NONE);
+ else cit_wander(c, timeMod);
+ }
+}
+static void blue_collar_update(Perm *p, float timeMod) { (void)timeMod; ST(BlueCollarState, p)->searched = 0; }
+
+static void woodcutting_work(Perm *p, Cit *c, float timeMod, bool stop) { blue_collar_job(p, c, timeMod, stop, GATHER_WOOD, 60, 90); }
+static void stone_mine_work(Perm *p, Cit *c, float timeMod, bool stop) { blue_collar_job(p, c, timeMod, stop, GATHER_STONE, 90, 120); }
+
+static void draw_plain(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ draw_upgrades(b, p, layer, x, y, true);
+}
+
+const PermOps ops_WoodcuttingCentre = {.work = woodcutting_work, .update = blue_collar_update, .draw = draw_plain};
+const PermOps ops_StoneMine = {.work = stone_mine_work, .update = blue_collar_update, .draw = draw_plain};
+
+/* ---------------------------------------------------------------- IndoorFarm */
+static uint8_t TH_FARM_WORK;
+static float indoor_farm_harvest_size(const Perm *p) {
+ return 25 + bonuses.extraFoodFromFarms + adj_effect(p, EF_CROPS);
+}
+static void farm_grow(Perm *p, float amount) {
+ IndoorFarmState *s = ST(IndoorFarmState, p);
+ s->value += amount;
+ if (s->value >= 100) {
+ s->stage = 1;
+ s->value = indoor_farm_harvest_size(p);
+ }
+}
+static void indoor_farm_init(Perm *p) {
+ IndoorFarmState *s = ST(IndoorFarmState, p);
+ s->stage = 0;
+ s->value = 20;
+}
+static void th_farm_work(Cit *c, uint16_t arg) {
+ (void)c;
+ Perm *p = P(arg_perm(arg));
+ if (!p || p->cls != CLS_IndoorFarm) return;
+ IndoorFarmState *s = ST(IndoorFarmState, p);
+ switch (s->stage) {
+ case 0: farm_grow(p, 1.35f * bonuses.indoorFarmSpeed); break;
+ case 1: {
+ float h = 0.25f * boost();
+ s->value -= h;
+ produce(M_FOOD, h);
+ if (s->value <= 0) s->stage = 2, s->value = 0;
+ break;
+ }
+ case 2:
+ s->value += 5;
+ if (s->value >= 100) s->stage = 0, s->value = 0;
+ break;
+ }
+}
+static void indoor_farm_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ IndoorFarmState *s = ST(IndoorFarmState, p);
+ float np = happiness.actionSpeedModifierWithoutPenalties;
+ int tmin = (int)((s->stage == 1 ? 15 : 30) / np), tmax = (int)((s->stage == 1 ? 30 : 60) / np);
+ int x = rnd_between(3, 15);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), TH_FARM_WORK, pid(p), false, false);
+}
+static void indoor_farm_update(Perm *p, float timeMod) {
+ IndoorFarmState *s = ST(IndoorFarmState, p);
+ if (s->stage != 0) return;
+ if (day_light()) farm_grow(p, timeMod * 0.03f * bonuses.indoorFarmSpeed);
+ else if (dim_light()) farm_grow(p, timeMod * 0.015f * bonuses.indoorFarmSpeed);
+}
+static void indoor_farm_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer == LAYER_BG) {
+ const IndoorFarmState *s = STC(IndoorFarmState, p);
+ int n = frames_of(SPR_INDOORFARM_CROPS, 20);
+ int f = s->stage == 0 ? (int)floorf(s->value / 100 * (n - 2)) : s->stage == 1 ? n - 2 : n - 1;
+ if (f > n - 1) f = n - 1;
+ if (f < 0) f = 0;
+ dr_frame(b, SPR_INDOORFARM_CROPS, 20, f, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ }
+}
+static void indoor_farm_window(Perm *p, WinOut *w) {
+ const IndoorFarmState *s = STC(IndoorFarmState, p);
+ if (s->stage == 0) win_line1(w, "Crops [0]% grown.", floorf(s->value));
+ else if (s->stage == 1) win_line1(w, "[0] food left to harvest.", floorf(s->value));
+ else win_line1(w, "Old crops [0]% cleaned.", floorf(s->value));
+}
+const PermOps ops_IndoorFarm = {.init = indoor_farm_init, .work = indoor_farm_work, .update = indoor_farm_update,
+ .draw = indoor_farm_draw, .window = indoor_farm_window};
+
+/* ---------------------------------------------------------------- ExplorationCentre */
+static uint8_t TH_EXPLORE;
+static const int8_t standing_places[7] = {2, 3, 8, 9, 10, 15, 16};
+static bool ruins_goal(const Perm *p, const void *ctx) { (void)ctx; return is_a(p, B_RUINS) && ruins_explored(p) < 100; }
+
+static void th_explore(Cit *c, uint16_t arg) {
+ Perm *r = P(arg_perm(arg));
+ if (!r || !is_a(r, B_RUINS)) return;
+ Perm *centre = P(c->job);
+ ExplorationState *es = centre && centre->cls == CLS_ExplorationCentre ? ST(ExplorationState, centre) : NULL;
+ if (ruins_explored(r) < 100) {
+ ruins_explore(r, 0.25f);
+ produce(M_KNOWLEDGE, 0.25f * early_fix() * boost());
+ if (ruins_explored(r) >= 100 && c->inPermanent) {
+ leave_to_surface(c);
+ if (es) es->nearestRuins = NONE;
+ }
+ } else if (c->inPermanent) {
+ leave_to_surface(c);
+ if (es) es->nearestRuins = NONE;
+ }
+}
+static void exploration_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ ExplorationState *s = ST(ExplorationState, p);
+ if (stop) {
+ c->currentAction = 2;
+ c->flags &= (uint16_t)~CF_HAS_WORK_TOOLS;
+ return;
+ }
+ if (!(c->flags & CF_HAS_WORK_TOOLS)) {
+ if (c->inPermanent == pid(p)) cit_move_and_wait(c, 4, 30, TH_TAKE_TOOLS, 0, true, false);
+ else path_find(c, pid(p), THEN_NONE);
+ return;
+ }
+ Perm *in = P(c->inPermanent);
+ if (in && is_a(in, B_RUINS)) {
+ int x = standing_places[rnd_int(7)];
+ cit_move_and_wait(c, x, rnd_between(90, 180), TH_EXPLORE, pid(in), true, false);
+ return;
+ }
+ if (!s->nearestRuins && !s->searched && !(world_unavailable[p->world] & WU_RUINS)) {
+ if (!finder_can_query()) return;
+ s->nearestRuins = finder_query(pid(p), 0, 0, ruins_goal, NULL, NULL, -1, NULL, 1e8f);
+ s->searched = 1;
+ if (!s->nearestRuins) world_unavailable[p->world] |= WU_RUINS;
+ }
+ /* exploreOrInvestigate */
+ if (s->nearestRuins) {
+ path_find(c, s->nearestRuins, THEN_NONE);
+ s->currentAction = 1;
+ return;
+ }
+ s->currentAction = 2;
+ if (c->inPermanent != pid(p)) {
+ path_find(c, pid(p), THEN_NONE);
+ return;
+ }
+ int idx = worker_index(c);
+ if ((idx == 1 || idx == 2) && cit_is_at_ground_level(c)) {
+ cit_change_floor(c, THEN_NONE, 0);
+ return;
+ }
+ int xmin = idx == 2 ? 12 : 3, xmax = idx == 2 ? 16 : 7;
+ if (c->relativeX >= xmin && c->relativeX < xmax) produce(M_KNOWLEDGE, 0.001f * timeMod * speed() * edu(c) * boost());
+ else move_x(c, rnd_between(xmin, xmax));
+}
+static void exploration_update(Perm *p, float timeMod) { (void)timeMod; ST(ExplorationState, p)->searched = 0; }
+static void exploration_window(Perm *p, WinOut *w) {
+ static const char *const t[3] = {"Current task: looking for ruins.", "Current task: exploring ruins.",
+ "Current task: investigating findings."};
+ win_line(w, t[STC(ExplorationState, p)->currentAction % 3]);
+}
+const PermOps ops_ExplorationCentre = {.work = exploration_work, .update = exploration_update, .draw = draw_plain,
+ .window = exploration_window};
+
+/* ---------------------------------------------------------------- Factory and MaterialConvertingFactory */
+enum { FX_SHOW_ACTIVE = 1 };
+void factory_work(Perm *p, Cit *c, float timeMod, bool stop);
+static void work_animation(Perm *p, Cit *c, float timeMod) {
+ int idx = worker_index(c);
+ if (c->relativeY == 10) return;
+ switch (p->cls) {
+ case CLS_MachinePartsFactory:
+ case CLS_FarmByProductProcessor: set_rel(c, idx == 0 ? 12 : 15, 10); break;
+ case CLS_RefinedMetalFactory:
+ if (idx == 0) set_rel(c, 3, 10);
+ else step_to_x(c, 3, timeMod), c->relativeY = 0;
+ break;
+ case CLS_ComputerChipFactory:
+ if (idx == 1) set_rel(c, 3, 10);
+ else if (idx == 0) step_to_x(c, 3, timeMod), c->relativeY = 0;
+ else step_to_x(c, 13, timeMod), c->relativeY = 0;
+ break;
+ case CLS_ExperimentationLab:
+ if (idx == 0) set_rel(c, 4, 10);
+ else set_rel(c, 3, 0);
+ break;
+ case CLS_FactoryPub:
+ if (idx == 0) set_rel(c, 8, 10);
+ else set_rel(c, 3, 1);
+ break;
+ case CLS_ComputerResearchCenter: {
+ static const int8_t pos[5][2] = {{13, 10}, {6, 0}, {6, 10}, {15, 0}, {8, 0}};
+ if (idx < 5) set_rel(c, pos[idx][0], pos[idx][1]);
+ break;
+ }
+ default: break;
+ }
+}
+void factory_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ work_animation(p, c, timeMod);
+ FactoryState *s = ST(FactoryState, p);
+ s->activeWorkers++;
+ uint32_t e = s->totalEdu + (uint32_t)(edu(c) * 4096 + 0.5f);
+ s->totalEdu = (uint16_t)(e > 65535 ? 65535 : e);
+}
+static inline float total_edu(const FactoryState *s) { return s->totalEdu / 4096.0f; }
+
+/* a converting factory's numbers: from, to, materialsMadePerStepPerWorker, efficiency, bonus speed, enabled */
+typedef struct { int from, to; float rate, efficiency, bonus; bool enabled, show_active_ok; } Converter;
+static bool exp_lab_at(const Perm *q) { return q && q->cls == CLS_ExperimentationLab; }
+static void converter(const Perm *p, Converter *k) {
+ const FactoryState *s = STC(FactoryState, p);
+ float avg_edu = s->activeWorkers == 0 ? 1 : total_edu(s) / s->activeWorkers;
+ k->enabled = true;
+ k->show_active_ok = true;
+ k->bonus = 1;
+ switch (p->cls) {
+ case CLS_MachinePartsFactory: {
+ bool turbo = p->mode == MODE_MachinePartsFactory_MachinePartsFactoryTurbo;
+ k->from = M_STONE, k->to = M_MACHINEPARTS;
+ k->rate = 0.0015f + (turbo ? 0.0015f : 0);
+ k->efficiency = 3 - (has_upgrade_bit(p, UB_MachinePartsFactory_MachinePartsFactoryEfficiency) ? 1 : 0) + (turbo ? 2 : 0);
+ k->bonus = bonuses.machinePartsFactorySpeed;
+ k->enabled = p->mode != MODE_MachinePartsFactory_StoneUsingFactoryDisabled;
+ break;
+ }
+ case CLS_RefinedMetalFactory:
+ case CLS_FactoryPub: {
+ /* RefinedMetalFactory.onCityChange: the norms, then each experimentation lab above or below */
+ bool hack = p->mode == MODE_RefinedMetalFactory_RefinedMetalsFactoryHack;
+ bool eff = has_upgrade_bit(p, UB_RefinedMetalFactory_RefinedMetalFactoryEfficiency);
+ k->from = M_STONE, k->to = M_REFINEDMETAL;
+ k->efficiency = 5.0f + (hack ? 1 : 0) - (eff ? 1 : 0);
+ k->rate = 0.001f + (hack ? 0.0005f : 0) + (eff ? 0.00015f : 0);
+ if (exp_lab_at(P(p->bottom))) k->efficiency -= 0.5f, k->rate += 0.0001f;
+ if (exp_lab_at(P(p->top))) k->efficiency -= 0.5f, k->rate += 0.0001f;
+ k->enabled = p->mode != MODE_RefinedMetalFactory_StoneUsingFactoryDisabled;
+ break;
+ }
+ case CLS_ComputerChipFactory: {
+ bool die = has_upgrade_bit(p, UB_ComputerChipFactory_DieShrink);
+ k->from = M_REFINEDMETAL, k->to = M_COMPUTERCHIPS;
+ k->rate = 0.0001f + (die ? 0.00005f : 0);
+ k->efficiency = 7 - (die ? 2 : 0);
+ k->bonus = avg_edu * upgrades.computerChipFactorySpeed;
+ k->enabled = p->mode != MODE_ComputerChipFactory_RefinedStoneUsingFactoryDisabled;
+ break;
+ }
+ case CLS_ExperimentationLab:
+ k->from = M_MACHINEPARTS, k->to = M_KNOWLEDGE;
+ k->rate = 0.0023f;
+ k->efficiency = 0.2f - (has_upgrade_bit(p, UB_ExperimentationLab_UltimateScrewdriver) ? 0.058f : 0);
+ k->bonus = avg_edu;
+ k->enabled = p->mode != MODE_ExperimentationLab_LabDisabled;
+ k->show_active_ok = false;
+ break;
+ default:
+ k->from = k->to = -1;
+ k->rate = k->efficiency = 0;
+ }
+}
+/* MaterialConvertingFactory.possiblyBeActive */
+static bool convert(Perm *p, float timeMod, const Converter *k) {
+ FactoryState *s = ST(FactoryState, p);
+ double *from = &city.materials.m[k->from];
+ if (*from < 1) return false;
+ float made = timeMod * k->rate * s->activeWorkers * speed() * k->bonus * boost();
+ mat_add(k->to, made);
+ s->materialMade += made;
+ float used = made * k->efficiency;
+ *from -= used;
+ stats_add_used(k->from, used);
+ s->totalMaterialUsed += used;
+ return true;
+}
+/* Factory.update (MaterialConvertingFactory's possiblyBeActive, or the class's own) */
+static void factory_update(Perm *p, float timeMod) {
+ FactoryState *s = ST(FactoryState, p);
+ bool active = false, show_ok = false;
+ if (p->cls == CLS_FarmByProductProcessor) {
+ ByProductState *bs = ST(ByProductState, p);
+ if (bs->activeWorkers > 0) {
+ /* cachedAdjacencyExpiration: the farms are counted again every 72 calls */
+ int exp = bs->extra >> 1;
+ if (exp > 0) exp--;
+ float n = bs->cacheValue;
+ if (exp == 0) {
+ n = by_product_farms(p, true);
+ bs->cacheValue = n;
+ exp = 72;
+ }
+ bs->extra = (uint8_t)((bs->extra & 1) | exp << 1);
+ float wood = 0.0014f * (bs->totalEdu / 4096.0f) * speed() * boost() * timeMod * n;
+ produce(M_WOOD, wood);
+ bs->woodMade += wood;
+ active = wood > 0;
+ }
+ show_ok = true;
+ } else if (p->cls == CLS_ComputerResearchCenter) {
+ if (s->activeWorkers > 0) {
+ float k = 0.0014f * timeMod * speed() * total_edu(s) * boost();
+ produce(M_KNOWLEDGE, k);
+ s->materialMade += k; /* (its window's knowledge gathered) */
+ active = true;
+ }
+ show_ok = true;
+ } else {
+ Converter k;
+ converter(p, &k);
+ if (s->activeWorkers > 0 && k.enabled) active = convert(p, timeMod, &k);
+ show_ok = k.show_active_ok && city.materials.m[k.from] >= 3;
+ }
+ if (active && show_ok) s->extra |= FX_SHOW_ACTIVE;
+ else s->extra &= (uint8_t)~FX_SHOW_ACTIVE;
+ s->activeWorkers = 0;
+ s->totalEdu = 0;
+}
+/* the back animation: the factory's active or idle frames, 4 ticks each (Factory.timePerFrame) */
+static void factory_back(const GfxBand *b, const Perm *p, int x, int y, uint16_t active, uint16_t idle) {
+ bool on = STC(FactoryState, p)->extra & FX_SHOW_ACTIVE;
+ uint16_t spr = on ? active : idle;
+ int n = frames_of(spr, 20);
+ if (n <= 0) return;
+ int f = (int)((bld_anim + (hash32(pid(p)) & 255)) / 4) % n;
+ dr_frame(b, spr, 20, f, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+int factory_frame(const Perm *p, int nframes) { /* (MechanicalHouse shows its factory's phase) */
+ return nframes > 0 ? (int)((bld_anim + (hash32(pid(p)) & 255)) / 4) % nframes : 0;
+}
+static void factory_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ if (layer == LAYER_BG) {
+ switch (p->cls) {
+ case CLS_MachinePartsFactory: factory_back(b, p, x, y, SPR_MACHINEPARTSFACTORY_FRAMES, SPR_MACHINEPARTSFACTORY_IDLE); break;
+ case CLS_RefinedMetalFactory: factory_back(b, p, x, y, SPR_REFINEDMETALFACTORY_FRAMES, SPR_REFINEDMETALFACTORY_IDLE); break;
+ case CLS_ComputerChipFactory: factory_back(b, p, x, y, SPR_COMPUTERCHIPFACTORY_FRAMES, SPR_COMPUTERCHIPFACTORY_IDLE); break;
+ case CLS_ExperimentationLab: factory_back(b, p, x, y, SPR_EXPERIMENTATIONLAB_IDLE, SPR_EXPERIMENTATIONLAB_IDLE); break;
+ case CLS_FarmByProductProcessor:
+ factory_back(b, p, x, y, SPR_FARMBYPRODUCTPROCESSOR_FRAMES, SPR_FARMBYPRODUCTPROCESSOR_IDLE);
+ break;
+ default: break;
+ }
+ }
+ if (layer == LAYER_ABOVE && p->cls == CLS_ExperimentationLab) {
+ /* pipes to refined metal factories above and below (not factory pubs) */
+ const Perm *bo = P(p->bottom), *t = P(p->top);
+ if (bo && bo->cls == CLS_RefinedMetalFactory) dr_sprite(b, SPR_EXPERIMENTATIONLAB_PIPE_BOTTOM, x, y, 7, 17, 0, 255);
+ if (t && t->cls == CLS_RefinedMetalFactory) dr_sprite(b, SPR_EXPERIMENTATIONLAB_PIPE_TOP, x, y, 10, -11, 0, 255);
+ }
+ draw_upgrades(b, p, layer, x, y, true);
+}
+static void converter_window(Perm *p, WinOut *w) {
+ const FactoryState *s = STC(FactoryState, p);
+ char b[160];
+ switch (p->cls) {
+ case CLS_MachinePartsFactory:
+ lo2(b, sizeof b, "[0] stone used to make [1] machine parts.", (int)s->totalMaterialUsed, (int)s->materialMade);
+ win_line(w, b);
+ break;
+ case CLS_RefinedMetalFactory:
+ case CLS_FactoryPub:
+ win_line2(w, "[0] stone used to make [1] units of refined metals.", (int)s->totalMaterialUsed, (int)s->materialMade);
+ break;
+ case CLS_ComputerChipFactory:
+ win_line2(w, "[0] units of refined metals used to make [1] computer chips.", (int)s->totalMaterialUsed, (int)s->materialMade);
+ break;
+ case CLS_ExperimentationLab:
+ win_line2(w, "[0] machine parts used to gain [1] knowledge.", (int)s->totalMaterialUsed, (int)s->materialMade);
+ break;
+ default: break;
+ }
+}
+void factory_window_lines(Perm *p, WinOut *w) { converter_window(p, w); }
+
+static void mpf_on_build(Perm *p) { (void)p; unlocks_unlock("MechanicalHouse"); }
+static void rmf_on_build(Perm *p) {
+ (void)p;
+ unlocks_unlock("HyperElevator");
+ unlocks_unlock("ComputerResearchCenter");
+ unlocks_fully_unlock("MedicalClinic");
+ unlocks_fully_unlock("ModernArtMuseum");
+ unlocks_unlock("SpaciousHouse");
+ unlocks_unlock("StoneResearchCenter");
+}
+static void ccf_on_build(Perm *p) {
+ (void)p;
+ unlocks_unlock("AIMining");
+ unlocks_unlock("HeatedBed");
+ unlocks_unlock("Supercomputer");
+ unlocks_unlock("LivingResearchCenter");
+ unlocks_unlock("Teleporter");
+ unlocks_unlock("CuttingEdgeHome");
+ unlocks_fully_unlock("Arcade");
+ unlocks_unlock("ChipBinning");
+ unlocks_unlock("PickaxeTech");
+ unlocks_unlock("FossilScanner");
+}
+static void factory_init(Perm *p) { upgrade_first_mode(p); }
+const PermOps ops_MachinePartsFactory = {.init = factory_init, .on_build = mpf_on_build, .work = factory_work,
+ .update = factory_update, .draw = factory_draw, .window = converter_window};
+const PermOps ops_RefinedMetalFactory = {.init = factory_init, .on_build = rmf_on_build, .work = factory_work,
+ .update = factory_update, .draw = factory_draw, .window = converter_window};
+const PermOps ops_ComputerChipFactory = {.init = factory_init, .on_build = ccf_on_build, .work = factory_work,
+ .update = factory_update, .draw = factory_draw, .window = converter_window};
+const PermOps ops_ExperimentationLab = {.init = factory_init, .work = factory_work, .update = factory_update,
+ .draw = factory_draw, .window = converter_window};
+/* (ComputerResearchCenter and FactoryPub use these from their files) */
+void factory_update_any(Perm *p, float timeMod) { factory_update(p, timeMod); }
+void factory_draw_any(const GfxBand *b, const Perm *p, int layer, int x, int y) { factory_draw(b, p, layer, x, y); }
+void factory_back_any(const GfxBand *b, const Perm *p, int x, int y, uint16_t active, uint16_t idle) {
+ factory_back(b, p, x, y, active, idle);
+}
+
+/* ---------------------------------------------------------------- FarmByProductProcessor */
+static bool is_bpp(const Perm *q) { return q && q->cls == CLS_FarmByProductProcessor; }
+static float fill_ratio(const Perm *q, bool true_value) {
+ if (bld_effect(q, EF_FARM) <= 0.5f) return 0;
+ if (!true_value) return 1;
+ if (is_a(q, B_WORK)) {
+ int j = bld_jobs(q);
+ return j ? (float)q->nworkers / j : 0;
+ }
+ int r = bld_residents(q);
+ return r ? (float)q->nresidents / r : 0;
+}
+/* adjacentFarmNumber: each farm counted by one processor only */
+float by_product_farms(const Perm *p, bool true_value) {
+ float total = 0;
+ const Perm *l = P(p->left), *r = P(p->right), *t = P(p->top), *bo = P(p->bottom);
+ if (l) total += fill_ratio(l, true_value);
+ if (r && !is_bpp(P(r->right))) total += fill_ratio(r, true_value);
+ if (t && !is_bpp(P(t->left)) && !is_bpp(P(t->right))) total += fill_ratio(t, true_value);
+ if (bo && !is_bpp(P(bo->left)) && !is_bpp(P(bo->right)) && !is_bpp(P(bo->bottom))) total += fill_ratio(bo, true_value);
+ return total;
+}
+static void by_product_window(Perm *p, WinOut *w) {
+ int n = (int)by_product_farms(p, false);
+ if (n == 1) win_line(w, "Processing by-products for one farm.");
+ else win_line1(w, "Processing by-products for [0] farms.", n);
+ win_line1(w, "[0] wood produced.", (int)ST(ByProductState, p)->woodMade);
+}
+const PermOps ops_FarmByProductProcessor = {.work = factory_work, .update = factory_update, .draw = factory_draw,
+ .window = by_product_window};
+
+/* ---------------------------------------------------------------- Laboratory */
+enum { LAB_WORKED = 1, LAB_LIGHTS = 2 };
+static void lab_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ LabState *s = ST(LabState, p);
+ s->anyoneHasWorkedHere |= LAB_WORKED;
+ if (cit_is_at_ground_level(c)) {
+ set_rel(c, worker_index(c) == 0 ? 5 : 13, 9);
+ } else {
+ float k = 0.00125f * timeMod * speed() * bonuses.labSpeed * edu(c) * boost();
+ produce(M_KNOWLEDGE, k);
+ s->totalKnowledgeGenerated += k;
+ }
+}
+static void lab_update(Perm *p, float timeMod) {
+ (void)timeMod;
+ LabState *s = ST(LabState, p);
+ s->anyoneHasWorkedHere = (s->anyoneHasWorkedHere & LAB_WORKED) ? LAB_LIGHTS : 0;
+}
+static void lab_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ if (layer == LAYER_BG) {
+ if (STC(LabState, p)->anyoneHasWorkedHere & LAB_LIGHTS) dr_frame(b, SPR_LABORATORY, 20, 2, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ else dr_sprite(b, SPR_LABORATORY_LIGHTSOFF, x, y, 0, 0, 0, 255);
+ }
+ draw_upgrades(b, p, layer, x, y, true);
+}
+static void lab_window(Perm *p, WinOut *w) {
+ win_line1(w, "[0] knowledge gathered.", (int)STC(LabState, p)->totalKnowledgeGenerated);
+ /* gui.GlobalUpgradeWindow.addSmartUpgradeForLabs: the user interface shows it with upgrade_smart_labs_* */
+}
+const PermOps ops_Laboratory = {.work = lab_work, .update = lab_update, .draw = lab_draw, .window = lab_window};
+
+/* ---------------------------------------------------------------- TreePlantation */
+static uint8_t TH_PLANTATION;
+static float extra_tree_growth(const Perm *p) { return 1 + adj_effect(p, EF_TREE_GROWTH); }
+float plantation_regrow_speed(const Perm *p) {
+ float boost_ = 1 + (has_upgrade_bit(p, UB_TreePlantation_AutomaticWaterManagement) ? 2 : 0);
+ return 0.008f * extra_tree_growth(p) * boost_;
+}
+static void plantation_update(Perm *p, float timeMod) {
+ PlantationState *s = ST(PlantationState, p);
+ if (s->materialsLeft > 0) return;
+ if (day_light()) s->regrowProgress += plantation_regrow_speed(p) * timeMod;
+ else if (dim_light()) s->regrowProgress += plantation_regrow_speed(p) * timeMod * 0.5f;
+ if (s->regrowProgress >= 100) s->materialsLeft = 100, s->regrowProgress = 0;
+}
+static void th_plantation(Cit *c, uint16_t arg) {
+ (void)c;
+ Perm *p = P(arg_perm(arg));
+ if (!p || p->cls != CLS_TreePlantation) return;
+ PlantationState *s = ST(PlantationState, p);
+ if (arg & 0x8000) {
+ float w = boost() * 0.2f;
+ s->materialsLeft -= w;
+ produce(M_WOOD, w);
+ } else {
+ s->regrowProgress += 0.5f * extra_tree_growth(p);
+ }
+}
+static void plantation_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ bool any = ST(PlantationState, p)->materialsLeft > 0;
+ int x = rnd_between(4, 14);
+ int t = rnd_between(any ? 60 : 120, any ? 90 : 180);
+ cit_move_and_wait(c, x, t, TH_PLANTATION, (uint16_t)(pid(p) | (any ? 0x8000 : 0)), true, false);
+}
+/* LimitedWorldResource.updateTextureOfLimitedResourceSprite's frame */
+int limited_frame(float left, float initial, float regrow, int nframes, int nregrow) {
+ if (left <= 0.0000001f) return nregrow > 0 ? (int)(regrow / 100 * nregrow) : nframes - 1;
+ int i = (int)floorf((initial - left) / initial * nframes);
+ if (initial != left && i == 0 && nframes > 1) i = 1;
+ return i;
+}
+static void plantation_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ if (layer == LAYER_BG) {
+ const PlantationState *s = STC(PlantationState, p);
+ int n = frames_of(SPR_TREEPLANTATION_TREES, 20), ng = frames_of(SPR_TREEPLANTATION_TREES_GROW, 20);
+ int f = limited_frame(s->materialsLeft, 100, s->regrowProgress, n, ng);
+ if (s->materialsLeft <= 0.0000001f) dr_frame(b, SPR_TREEPLANTATION_TREES_GROW, 20, f < ng ? f : ng - 1, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ else dr_frame(b, SPR_TREEPLANTATION_TREES, 20, f < n ? f : n - 1, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ }
+ draw_upgrades(b, p, layer, x, y, true);
+}
+static void plantation_window(Perm *p, WinOut *w) {
+ const PlantationState *s = STC(PlantationState, p);
+ if (s->materialsLeft <= 0) win_line1(w, "Trees [0]% grown.", (int)s->regrowProgress);
+ else win_line2(w, "[0]/[1] wood left.", (int)s->materialsLeft, 100);
+}
+const PermOps ops_TreePlantation = {.work = plantation_work, .update = plantation_update, .draw = plantation_draw,
+ .window = plantation_window};
+
+/* ---------------------------------------------------------------- StoneTeleporter */
+static uint8_t TH_TELEPORTER_MINE;
+float stone_teleporter_initial(const Perm *p) { return STC(PlantationState, p)->flags & TP_INITIAL_BIG ? 150 : 50; }
+static void th_teleporter_mine(Cit *c, uint16_t arg) {
+ (void)c;
+ Perm *p = P(arg_perm(arg));
+ if (!p || p->cls != CLS_StoneTeleporter) return;
+ PlantationState *s = ST(PlantationState, p);
+ if (s->materialsLeft > 0) {
+ float st = boost() * 0.2f * upgrades.stoneMiningSpeed;
+ s->materialsLeft -= st;
+ produce(M_STONE, st);
+ }
+}
+static bool has_remote(const Perm *p) { return has_upgrade_bit(p, UB_StoneTeleporter_StoneTeleporterRemote); }
+static void stone_teleporter_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ PlantationState *s = ST(PlantationState, p);
+ if (!has_remote(p)) step_to_x(c, 3, timeMod);
+ if (s->materialsLeft <= 0) {
+ s->flags |= TP_PRESSED;
+ s->notPressedTime = 0;
+ } else if (has_remote(p)) {
+ int x = rnd_between(5, 13);
+ cit_move_and_wait(c, x, rnd_between(90, 120), TH_TELEPORTER_MINE, pid(p), true, false);
+ }
+}
+static void stone_teleporter_update(Perm *p, float timeMod) {
+ PlantationState *s = ST(PlantationState, p);
+ if (s->materialsLeft > 0) return;
+ if (s->flags & TP_PRESSED) {
+ if (s->regrowProgress == 0) {
+ if (upgrades.stoneTeleporterHasBigStones) s->flags |= TP_BIG;
+ else s->flags &= (uint8_t)~TP_BIG;
+ }
+ s->regrowProgress += 2 * timeMod;
+ if (s->regrowProgress >= 100) {
+ s->regrowProgress = 0;
+ if (s->flags & TP_BIG) s->flags |= TP_INITIAL_BIG;
+ float initial = stone_teleporter_initial(p);
+ s->materialsLeft = initial;
+ s->flags &= (uint8_t)~TP_PRESSED;
+ s->notPressedTime = 0;
+ if (upgrades.stoneResearchCenterWithFossils && rnd_float() < 0.00001f * initial) {
+ produce(M_KNOWLEDGE, 10000);
+ bonuses.fossilsCollected++;
+ }
+ }
+ } else if (has_remote(p) && p->nworkers > 0) {
+ s->flags |= TP_PRESSED;
+ s->notPressedTime = 0;
+ } else {
+ s->notPressedTime = tick_up(s->notPressedTime, timeMod);
+ }
+}
+static void stone_teleporter_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ if (layer == LAYER_BG) {
+ const PlantationState *s = STC(PlantationState, p);
+ uint16_t spr = (s->flags & TP_BIG) ? SPR_STONETELEPORTER_STONE_BIG : SPR_STONETELEPORTER_STONE;
+ int n = frames_of(spr, 20);
+ if (s->materialsLeft <= 0) {
+ float a = s->regrowProgress / 100;
+ dr_frame(b, spr, 20, 0, x, y, 0, 0, 0, (uint8_t)(a < 0 ? 0 : a > 1 ? 255 : a * 255), GFX_NO_TINT);
+ } else {
+ int f = limited_frame(s->materialsLeft, stone_teleporter_initial(p), 0, n, 0);
+ dr_frame(b, spr, 20, f < n ? f : n - 1, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ }
+ }
+ draw_upgrades(b, p, layer, x, y, true);
+}
+static void stone_teleporter_window(Perm *p, WinOut *w) {
+ const PlantationState *s = STC(PlantationState, p);
+ bool pressed = s->flags & TP_PRESSED;
+ if (s->materialsLeft > 0 || (!pressed && s->notPressedTime < 3)) win_line1(w, "[0] stone left in this meteoroid.", (int)s->materialsLeft);
+ else if (!pressed) win_line(w, "Waiting for a worker to press the teleport button...");
+ else win_line(w, "Teleporting a meteoroid...");
+}
+const PermOps ops_StoneTeleporter = {.work = stone_teleporter_work, .update = stone_teleporter_update,
+ .draw = stone_teleporter_draw, .window = stone_teleporter_window};
+
+/* ---------------------------------------------------------------- FarmGrowArea (EcoFarm, ExperimentalFarm) */
+static uint8_t TH_PLOT_WORK;
+typedef struct { int8_t x, y; uint8_t width; float food, mult, clean; uint8_t harvestPart; } PlotDef;
+static const uint16_t eco_crop2[3] = {SPR_ECOFARM_CROP2, SPR_ECOFARM_CROP2_ALT, SPR_ECOFARM_CROP2_ALT2};
+static const uint16_t eco_crop3[2] = {SPR_ECOFARM_CROP3, SPR_ECOFARM_CROP3_ALT};
+static bool eco(const Perm *p) { return p->cls == CLS_EcoFarm; }
+static void plot_def(const Perm *p, int i, PlotDef *d, uint16_t *spr) {
+ const GrowFarmState *s = STC(GrowFarmState, p);
+ if (eco(p)) {
+ static const PlotDef e[3] = {{3, 3, 6, 20, 0.7f, 0, 6}, {9, 3, 8, 10, 1.4f, 10, 1}, {9, 12, 8, 12, 0.6f, 7, 1}};
+ *d = e[i];
+ /* EcoFarmUpgrade: plot 1 gets 4 more (new farms too), plot 2 three more only on farms that existed then */
+ if (i == 0 && city_upgrade_bought(U_EcoFarmUpgrade)) d->food += 4;
+ if (i == 1) d->food += upgrades.extraEcoFarmFoodToPlot2 + ((s->eco >> 6 & 1) ? 3 : 0);
+ *spr = i == 0 ? SPR_ECOFARM_CROP1 : i == 1 ? eco_crop2[(s->eco >> 3 & 3) % 3] : eco_crop3[s->eco >> 5 & 1];
+ } else {
+ static const PlotDef x[3] = {{3, 3, 5, 12, 1, 5, 1}, {12, 3, 5, 10, 1.2f, 10, 1}, {12, 12, 5, 6, 1.5f, 10, 1}};
+ static const uint16_t sp[3] = {SPR_EXPERIMENTALFARM_CROP1, SPR_EXPERIMENTALFARM_CROP2, SPR_EXPERIMENTALFARM_CROP3};
+ *d = x[i];
+ *spr = sp[i];
+ }
+}
+/* 24-bit fixed point values (2^-17) */
+static float plot_value(const Perm *p, int i) {
+ const uint8_t *v = STC(GrowFarmState, p)->value[i];
+ return (float)((uint32_t)v[0] | (uint32_t)v[1] << 8 | (uint32_t)v[2] << 16) / 131072.0f;
+}
+static void plot_set_value(Perm *p, int i, float f) {
+ if (f < 0) f = 0;
+ if (f > 127.99f) f = 127.99f;
+ uint32_t u = (uint32_t)(f * 131072.0f + 0.5f);
+ uint8_t *v = ST(GrowFarmState, p)->value[i];
+ v[0] = (uint8_t)u, v[1] = (uint8_t)(u >> 8), v[2] = (uint8_t)(u >> 16);
+}
+int plot_stage(const Perm *p, int i) { return STC(GrowFarmState, p)->stages >> (2 * i) & 3; }
+static void plot_set_stage(Perm *p, int i, int st) {
+ GrowFarmState *s = ST(GrowFarmState, p);
+ s->stages = (uint8_t)((s->stages & ~(3 << (2 * i))) | st << (2 * i));
+}
+static float plot_harvest_size(const Perm *p, int i) {
+ PlotDef d;
+ uint16_t spr;
+ plot_def(p, i, &d, &spr);
+ return d.food + bonuses.extraFoodFromFarms + adj_effect(p, EF_CROPS);
+}
+static void plot_grow(Perm *p, int i, float amount) {
+ float v = plot_value(p, i) + amount;
+ if (v >= 100) {
+ plot_set_stage(p, i, 1);
+ v = plot_harvest_size(p, i);
+ }
+ plot_set_value(p, i, v);
+}
+static void plots_update(Perm *p, float timeMod) {
+ for (int i = 0; i < 3; i++) {
+ if (plot_stage(p, i) != 0) continue;
+ PlotDef d;
+ uint16_t spr;
+ plot_def(p, i, &d, &spr);
+ if (day_light()) plot_grow(p, i, timeMod * (0.012f * d.mult));
+ else if (dim_light()) plot_grow(p, i, timeMod * (0.006f * d.mult));
+ }
+}
+/* onCitizenWork */
+static void th_plot_work(Cit *c, uint16_t arg) {
+ (void)c;
+ Perm *p = P(arg_perm(arg));
+ int i = arg >> 12 & 3;
+ if (!p || (p->cls != CLS_EcoFarm && p->cls != CLS_ExperimentalFarm) || i > 2) return;
+ PlotDef d;
+ uint16_t spr;
+ plot_def(p, i, &d, &spr);
+ switch (plot_stage(p, i)) {
+ case 0: plot_grow(p, i, 0.85f * d.mult); break;
+ case 1: {
+ float h = 0.25f * boost();
+ float left = plot_value(p, i) - h;
+ produce(M_FOOD, h);
+ if (left <= 0) {
+ left = 0;
+ plot_set_stage(p, i, d.clean <= 0 ? 0 : 2);
+ }
+ plot_set_value(p, i, left);
+ break;
+ }
+ case 2: {
+ float v = plot_value(p, i) + d.clean;
+ if (v >= 100) plot_set_stage(p, i, 0), v = 0;
+ plot_set_value(p, i, v);
+ break;
+ }
+ }
+}
+static void plot_work(Perm *p, Cit *c, int i) {
+ PlotDef d;
+ uint16_t spr;
+ plot_def(p, i, &d, &spr);
+ float np = happiness.actionSpeedModifierWithoutPenalties;
+ int st = plot_stage(p, i);
+ int tmin = (int)((st == 1 ? 15 : 30) / np), tmax = (int)((st == 1 ? 30 : 60) / np);
+ int x = rnd_between(d.x, d.x + d.width - 2 + 1);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), TH_PLOT_WORK, (uint16_t)(pid(p) | i << 12), false, false);
+}
+static void plot_work_no_move(Perm *p, Cit *c, int i) {
+ int st = plot_stage(p, i);
+ cit_wait(c, rnd_between(st == 1 ? 15 : 30, st == 1 ? 30 : 60), TH_PLOT_WORK, (uint16_t)(pid(p) | i << 12));
+}
+static int plot_frame(const Perm *p, int i, int n) {
+ PlotDef d;
+ uint16_t spr;
+ plot_def(p, i, &d, &spr);
+ float v = plot_value(p, i);
+ switch (plot_stage(p, i)) {
+ case 0: return (int)floorf(v / 100 * (n - 1 - d.harvestPart));
+ case 1: {
+ float orig = plot_harvest_size(p, i); /* originalFoodLeft (as it is now) */
+ int val = n - 1 - (int)ceilf(v / orig * 0.9999f * d.harvestPart);
+ return val < 1 ? 1 : val > n - 2 ? n - 2 : val;
+ }
+ default: return n - 1;
+ }
+}
+static void plots_draw(const GfxBand *b, const Perm *p, int x, int y) {
+ for (int i = 0; i < 3; i++) {
+ PlotDef d;
+ uint16_t spr;
+ plot_def(p, i, &d, &spr);
+ int n = frames_of(spr, d.width);
+ int f = plot_frame(p, i, n);
+ if (f < 0) f = 0;
+ if (f >= n) f = n - 1;
+ dr_frame(b, spr, d.width, f, x, y, d.x, d.y, 0, 255, GFX_NO_TINT);
+ }
+}
+static void plots_window(Perm *p, WinOut *w) {
+ static const char *const name[3] = {"Left plot: ", "Top right plot: ", "Bottom right plot: "};
+ for (int i = 0; i < 3; i++) {
+ char t[96], b[160];
+ float v = plot_value(p, i);
+ int st = plot_stage(p, i);
+ lo1(t, sizeof t, st == 0 ? "Crops [0]% grown." : st == 1 ? "[0] food left to harvest." : "Old crops [0]% cleaned.", floorf(v));
+ int k = 0;
+ for (const char *s = name[i]; *s && k < 100; s++) b[k++] = *s;
+ for (const char *s = t; *s && k < 158; s++) b[k++] = *s;
+ b[k] = 0;
+ win_line(w, b);
+ }
+}
+
+/* EcoFarm */
+static int eco_open_day(const Perm *p) { return STC(GrowFarmState, p)->eco & 7; }
+static void eco_init(Perm *p) {
+ GrowFarmState *s = ST(GrowFarmState, p);
+ int c2 = rnd_int(3), c3 = rnd_int(2);
+ s->eco = (uint8_t)(c2 << 3 | c3 << 5);
+ s->eco |= (uint8_t)rnd_int(7);
+}
+static void eco_on_build(Perm *p) { (void)p; unlocks_unlock("EcoFarmUpgrade"); }
+static float eco_end_time(const Perm *p) { return day_number() % 7 == eco_open_day(p) ? 21 : 19; }
+bool first_worker_working(const Perm *p);
+static bool eco_is_open(const Perm *p) {
+ float h = hour_now();
+ return p->nworkers > 0 && first_worker_working(p) && day_number() % 7 == eco_open_day(p) && h < 20.5f && h > 12;
+}
+static float eco_capacity(const Perm *p) { return p->nworkers * 5; }
+static void eco_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ int x = rnd_between(3, 16);
+ cit_move_and_wait(c, x, rnd_between(50, 100), THEN_NONE, 0, false, true);
+}
+static void grow_farm_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ int idx = worker_index(c);
+ if (idx > 2) idx = 2;
+ if (idx == 1) {
+ if (c->relativeY < 5) cit_move(c, 18, TH_CHANGE_FLOOR, 0, false);
+ else plot_work(p, c, 1);
+ } else if (eco(p) && idx == 0 && plot_stage(p, 0) == 1) {
+ if (c->relativeY <= 1 || c->relativeX < 4 || c->relativeX > 6) {
+ static const int16_t s[] = {4, 5, 9, 8};
+ cit_set_path(c, s, 2);
+ } else {
+ plot_work_no_move(p, c, 0);
+ }
+ } else if (c->relativeY > 5) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else {
+ plot_work(p, c, idx);
+ }
+}
+static void grow_farm_update(Perm *p, float timeMod) { plots_update(p, timeMod); }
+static void grow_farm_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer == LAYER_BG) plots_draw(b, p, x, y);
+}
+const PermOps ops_EcoFarm = {.init = eco_init, .on_build = eco_on_build, .work = grow_farm_work, .update = grow_farm_update,
+ .end_time = eco_end_time, .is_open = eco_is_open, .entertainment_capacity = eco_capacity,
+ .be_entertained = eco_be_entertained, .draw = grow_farm_draw, .window = plots_window};
+/* ExperimentalFarm (a unique building, but its plots are these) */
+static void exp_farm_on_build(Perm *p) { (void)p; bonuses.indoorFarmSpeed += 0.1f; }
+static void exp_farm_destroy(Perm *p) { (void)p; bonuses.indoorFarmSpeed -= 0.1f; }
+const PermOps ops_ExperimentalFarm = {.on_build = exp_farm_on_build, .destroy = exp_farm_destroy, .work = grow_farm_work,
+ .update = grow_farm_update, .draw = grow_farm_draw, .window = plots_window};
+/* EcoFarmUpgrade's addToCity: every eco farm built so far gets 3 more food on its second plot */
+void eco_farms_upgrade(void) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == CLS_EcoFarm) ST(GrowFarmState, &perms[i])->eco |= 1 << 6;
+}
+
+void bld_production_init(void) {
+ TH_DROP_TOOLS = then_register(th_drop_tools);
+ TH_TAKE_TOOLS = then_register(th_take_tools);
+ TH_CUT_WOOD = then_register(th_cut_wood);
+ TH_MINE_STONE = then_register(th_mine_stone);
+ TH_FARM_WORK = then_register(th_farm_work);
+ TH_EXPLORE = then_register(th_explore);
+ TH_PLANTATION = then_register(th_plantation);
+ TH_TELEPORTER_MINE = then_register(th_teleporter_mine);
+ TH_PLOT_WORK = then_register(th_plot_work);
+}
diff --git a/games/finalearth2/src/bld_services.c b/games/finalearth2/src/bld_services.c
new file mode 100644
index 00000000..5babd44e
--- /dev/null
+++ b/games/finalearth2/src/bld_services.c
@@ -0,0 +1,179 @@
+/* The Final Earth 2: services (buildings.md 8): schools, libraries, herb
+ * gardens and medical clinics. */
+#include "bldi.h"
+
+static void plain_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ draw_upgrades(b, p, layer, x, y, true);
+}
+
+/* the sum of its workers' education speed modifiers */
+static float workers_education(const Perm *p) {
+ float sum = 0;
+ uint16_t id = pid(p);
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job == id) sum += cit_education_speed_modifier(&cits[i]);
+ return sum;
+}
+
+/* ---------------------------------------------------------------- School */
+static int school_capacity(const Perm *p) { (void)p; return (int)floorf(policies.schoolClassSizeMod * 30 + 0.5f); }
+static void school_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ step_to_x(c, 3, timeMod);
+}
+/* beAtSchool: a seat once a visit, and a day's education */
+static void school_be_at(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ if (c->flags & CF_BUILDING_INITED) return;
+ switch (student_index(p, c) % 3) {
+ case 0: move_x(c, rnd_between(6, 7)); break;
+ case 1: cit_change_floor_and_move_random(c, 3, 7, THEN_NONE, 0); break;
+ default: move_x(c, rnd_between(12, 16)); break;
+ }
+ float cap = policies.schoolMaxEdu, e = c->educationLevel + 0.07f * policies.schoolMaxEdu;
+ if (e > cap) e = cap;
+ if (e > c->educationLevel) c->educationLevel = e;
+ c->flags |= CF_BUILDING_INITED;
+}
+static void school_window(Perm *p, WinOut *w) { win_line2(w, "[0]/[1] students", p->nstudents, school_capacity(p)); }
+const PermOps ops_School = {.work = school_work, .be_at_school = school_be_at, .student_capacity = school_capacity,
+ .draw = plain_draw, .window = school_window};
+
+/* ---------------------------------------------------------------- Library */
+static uint8_t TH_LIBRARY_MOVE;
+static void th_library_move(Cit *c, uint16_t arg) {
+ (void)arg;
+ int x = c->relativeY < 5 ? rnd_between(3, 7) : rnd_between(3, 16);
+ cit_move_and_wait(c, x, rnd_between(30, 60), THEN_NONE, 0, false, false);
+}
+static bool library_open(const Perm *p) {
+ return p->nworkers == 1 && first_worker_working(p) && hours_in(hour_now(), 14 - 0.5f, 22);
+}
+static float zero_capacity(const Perm *p) { (void)p; return 0; }
+static void library_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (rnd_int(2) == 1) cit_change_floor(c, TH_LIBRARY_MOVE, 0);
+ else cit_wait_random(c, 120, 180, TH_LIBRARY_MOVE, 0);
+ educate(c, 0.025f, 1.5f);
+}
+static void library_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop && hour_now() > 22) c->currentAction = 2;
+ else step_to_x(c, 12, timeMod);
+}
+const PermOps ops_Library = {.work = library_work, .is_open = library_open, .entertainment_capacity = zero_capacity,
+ .be_entertained = library_be_entertained, .draw = draw_merging};
+
+/* ---------------------------------------------------------------- HerbGarden */
+static int herb_frames(void) { return frames_of(SPR_HERBGARDEN_PLANTS, 20); }
+/* the modes: culinary herbs (restaurants around take more people) or medicinal ones */
+void herb_garden_mode(Perm *p) {
+ if (p->mode == MODE_HerbGarden_MedicalHerbs) {
+ p->flags |= PF_IS_MEDICAL;
+ p->s[0] = (uint8_t)(rnd_int(herb_frames() / 2) * 2 + 1);
+ } else {
+ p->flags &= (uint8_t)~PF_IS_MEDICAL;
+ p->s[0] = (uint8_t)(rnd_int(herb_frames() / 2) * 2);
+ }
+}
+static void herb_init(Perm *p) {
+ p->s[0] = (uint8_t)(rnd_int(herb_frames() / 2) * 2);
+ upgrade_first_mode(p);
+}
+static float herb_quality(const Perm *p) { (void)p; return 100; }
+static float herb_medical_capacity(const Perm *p) { return p->mode == MODE_HerbGarden_MedicalHerbs ? 100 : 0; }
+static float herb_capacity(const Perm *p) { return 50.0f * p->nworkers; }
+static void herb_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (c->relativeY < 5 && worker_index(c) == 1) {
+ cit_change_floor(c, THEN_NONE, 0);
+ return;
+ }
+ int x = rnd_between(3, 16);
+ cit_move_and_wait(c, x, rnd_between(30, 60), THEN_NONE, 0, false, true);
+}
+static void herb_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_merging(b, p, layer, x, y);
+ if (layer == LAYER_BG) dr_frame(b, SPR_HERBGARDEN_PLANTS, 20, p->s[0] % herb_frames(), x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+static void herb_window(Perm *p, WinOut *w) {
+ (void)p;
+ char a[96], b[96], t[200];
+ lo2(a, sizeof a, "Herbs reduce your citizens' food consumption by [0]/[1]%", floorf(eating.currentFoodSaveByHerbsPct * 0.2f * 100 + 0.5f), 20);
+ lo1(b, sizeof b, "Total medical happiness from herb gardens: [0]/20%",
+ ncits ? floorf(100 * (happiness.healthCapacityByType[1] / ncits) + 0.5f) : 0);
+ int k = 0;
+ for (const char *s = a; *s && k < 190; s++) t[k++] = *s;
+ t[k++] = '\n';
+ for (const char *s = b; *s && k < 198; s++) t[k++] = *s;
+ t[k] = 0;
+ win_line(w, t);
+ win_button(w, 0, "Change Herb Plants", WA_CYCLE_0, true);
+}
+static void herb_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0) p->s[0] = (uint8_t)((p->s[0] + 2) % herb_frames());
+}
+const PermOps ops_HerbGarden = {.init = herb_init, .work = herb_work, .medical_quality = herb_quality,
+ .medical_capacity = herb_medical_capacity, .herb_capacity = herb_capacity,
+ .draw = herb_draw, .window = herb_window, .window_action = herb_action};
+
+/* ---------------------------------------------------------------- MedicalClinic and SpecializedMedicalClinic */
+static float clinic_quality(const Perm *p) {
+ float part = has_upgrade_bit(p, UB_MedicalClinic_MedicalEducation) ? 1 : 0;
+ float extra = has_upgrade_bit(p, UB_MedicalClinic_AIAssistedDiagnosis) ? 25 : 0;
+ return 50 + 0.25f * happiness.schoolHappiness * part + extra;
+}
+static float clinic_capacity(const Perm *p) {
+ float extra = has_upgrade_bit(p, UB_MedicalClinic_AIAssistedDiagnosis) ? 50 : 0;
+ return (50 + extra) * (p->nworkers == 0 ? 0 : workers_education(p));
+}
+static void clinic_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (c->relativeY < 5 && worker_index(c) == 1) cit_change_floor(c, THEN_NONE, 0);
+ else step_to_x(c, c->relativeY < 5 ? 5 : 3, timeMod);
+}
+static void clinic_window(Perm *p, WinOut *w) {
+ win_line1(w, "[0] capacity", floorf(bld_medical_capacity(p)));
+ win_line1(w, "Quality: [0]", floorf(bld_medical_quality(p)));
+ if (upgrades.hasBirthControl) win_button(w, 0, "Manage Birth Control", WA_UI_BIRTH_CONTROL, true);
+}
+const PermOps ops_MedicalClinic = {.work = clinic_work, .medical_quality = clinic_quality, .medical_capacity = clinic_capacity,
+ .draw = plain_draw, .window = clinic_window};
+
+static float special_quality(const Perm *p) { (void)p; return 100; }
+static float special_capacity(const Perm *p) { return 50 * (p->nworkers == 0 ? 0 : workers_education(p)); }
+static void special_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (c->relativeY < 5 && worker_index(c) == 1) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else {
+ int x = rnd_between(3, c->relativeY < 5 ? 17 : 8);
+ cit_move_and_wait(c, x, rnd_between(60, 90), THEN_NONE, 0, false, true);
+ }
+}
+static void special_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, SPR_ADVANCEDMEDICALCLINIC, false); /* (its class has no sprite of its own) */
+}
+const PermOps ops_SpecializedMedicalClinic = {.work = special_work, .medical_quality = special_quality,
+ .medical_capacity = special_capacity, .draw = special_draw,
+ .window = clinic_window};
+
+void bld_services_init(void) { TH_LIBRARY_MOVE = then_register(th_library_move); }
diff --git a/games/finalearth2/src/bld_transport.c b/games/finalearth2/src/bld_transport.c
new file mode 100644
index 00000000..e390b271
--- /dev/null
+++ b/games/finalearth2/src/bld_transport.c
@@ -0,0 +1,808 @@
+/* The Final Earth 2: transport (buildings.md 10): teleporters (and private
+ * ones in homes), hyper elevators, landing pads with their flying saucers and
+ * the flying pathfinder (pathfinder.FlyingPathfinder), saucers bringing new
+ * citizens (simulation.SpawnFlyingSaucer), and the teleport particles. */
+#include "bldi.h"
+#include "save.h"
+#include "scratch.h"
+#include "view.h"
+
+/* ---------------------------------------------------------------- particles (graphics.Particles) */
+#define MAX_PARTICLES 8
+static struct { int16_t x, y; uint16_t spr; uint8_t fw, frames; float frame; } particles[MAX_PARTICLES];
+void particle_add(uint16_t spr, int fw, int x, int y) {
+ for (int i = 0; i < MAX_PARTICLES; i++)
+ if (!particles[i].spr) {
+ particles[i].x = (int16_t)x, particles[i].y = (int16_t)y;
+ particles[i].spr = spr;
+ particles[i].fw = (uint8_t)fw;
+ particles[i].frames = (uint8_t)frames_of(spr, fw);
+ particles[i].frame = 0;
+ return;
+ }
+}
+static void particles_update(float timeMod) {
+ for (int i = 0; i < MAX_PARTICLES; i++) {
+ if (!particles[i].spr) continue;
+ particles[i].frame += 0.5f * timeMod;
+ if (particles[i].frame >= particles[i].frames) particles[i].spr = 0;
+ }
+}
+
+/* ---------------------------------------------------------------- teleporters */
+static void teleport_particle(const Perm *p) {
+ int x = perm_city_x(p), y = perm_city_y(p);
+ switch (p->cls) {
+ case CLS_Teleporter: particle_add(SPR_TELEPORTER_RAY, 4, x + 8, y + 4); break;
+ case CLS_Misdirector: particle_add(SPR_TELEPORTER_RAY_MISDIRECT, 4, x + 8, y + 4); break;
+ case CLS_Villa: particle_add(SPR_SMALLTELEPORTER_RAY, 3, x + 3, y + 12); break;
+ case CLS_Mansion: particle_add(SPR_SMALLTELEPORTER_RAY, 3, x + 14, y + 12); break;
+ case CLS_FlowerPenthouse: {
+ bool m = STC(PrivateTeleporterState, p)->mirrored;
+ particle_add(m ? SPR_SMALLTELEPORTER_RAY_PENTHOUSE_MIRROR : SPR_SMALLTELEPORTER_RAY_PENTHOUSE, 3, x + (m ? 3 : 14), y + 12);
+ break;
+ }
+ default: break;
+ }
+}
+/* teleportX: where a citizen stands to teleport */
+float transport_teleport_x(const Perm *p) {
+ switch (p->cls) {
+ case CLS_Villa: return 3;
+ case CLS_Mansion: return 14;
+ case CLS_FlowerPenthouse: return STC(PrivateTeleporterState, p)->mirrored ? 19 - 15 : 15;
+ default: return 9;
+ }
+}
+static uint16_t *times_used(Perm *p, bool to) {
+ /* both counters start their state (2-byte aligned: Perm is, and s[] is at an even offset) */
+ _Static_assert(offsetof(TeleporterState, timesUsedTo) == 2 && offsetof(PrivateTeleporterState, timesUsedTo) == 2 &&
+ offsetof(Perm, s) % 2 == 0, "counters at the start of the state");
+ if (p->cls == CLS_Teleporter || p->cls == CLS_Misdirector || p->cls == CLS_Villa || p->cls == CLS_Mansion ||
+ p->cls == CLS_FlowerPenthouse)
+ return (uint16_t *)(void *)&p->s[to ? 2 : 0];
+ return NULL;
+}
+void transport_teleport_used(Perm *p) {
+ teleport_particle(p);
+ uint16_t *n = times_used(p, false);
+ if (n && *n < 65535) (*n)++;
+}
+void transport_teleport_arrived(Perm *p) {
+ uint16_t *n = times_used(p, true);
+ if (n && *n < 65535) (*n)++;
+}
+static void teleporter_window(Perm *p, WinOut *w) {
+ const TeleporterState *s = STC(TeleporterState, p);
+ win_line1(w, "Teleported from [0] times.", s->timesUsed);
+ win_line1(w, "Teleported to [0] times.", s->timesUsedTo);
+ teleporter_upkeep_lines(w);
+}
+/* createUpkeepInfo: the teleporters' cost a day, and the button to switch them all on or off */
+void teleporter_upkeep_lines(WinOut *w) {
+ float k = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && is_building(p) && PC(p)->teleporterOperatingCost > 0)
+ k += PC(p)->teleporterOperatingCost * (bld_misdirector() ? 0.5f : 1) * (1 - upgrades.rocketTeleporterReward);
+ }
+ char b[96];
+ lo1(b, sizeof b, "Teleporters operating cost:\n[0] knowledge/day", floorf(k + 0.5f));
+ win_line(w, b);
+ const char *t = operating_cost.teleportersEnabled ? "Disable All Teleporters"
+ : operating_cost_user_enabled() ? "Keep Teleporters Disabled"
+ : "Enable All Teleporters";
+ win_button(w, 0, t, WA_SPECIAL_2, true);
+}
+void teleporter_upkeep_action(int a) {
+ if (a != WA_SPECIAL_2) return;
+ if (!(!operating_cost.teleportersEnabled && operating_cost_user_enabled()))
+ operating_cost_set_teleporters(!operating_cost.teleportersEnabled, true);
+ else if (operating_cost_user_enabled()) operating_cost_set_teleporters(false, true);
+ /* (else the original shows "cant_enable_teleporters") */
+}
+static void teleporter_action(Perm *p, int a) { (void)p; teleporter_upkeep_action(a); }
+static void teleporter_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+}
+const PermOps ops_Teleporter = {.draw = teleporter_draw, .window = teleporter_window, .window_action = teleporter_action};
+
+/* ---------------------------------------------------------------- HyperElevator */
+bool transport_elevator_open_door(Perm *p) {
+ if (p->cls != CLS_HyperElevator) return true;
+ ElevatorState *s = ST(ElevatorState, p);
+ s->doorOpenFor = 45;
+ return s->door >= (uint8_t)((frames_of(SPR_HYPERELEVATOR_DOOR, 10) - 1.01f) * 32 + 0.999f);
+}
+void transport_elevator_used(Perm *p) {
+ if (p->cls == CLS_HyperElevator && ST(ElevatorState, p)->timesUsed < 65535) ST(ElevatorState, p)->timesUsed++;
+}
+void transport_elevator_arrived(Perm *p) {
+ if (p->cls == CLS_HyperElevator && ST(ElevatorState, p)->timesUsedTo < 65535) ST(ElevatorState, p)->timesUsedTo++;
+}
+static void elevator_update(Perm *p, float timeMod) {
+ ElevatorState *s = ST(ElevatorState, p);
+ int max = (frames_of(SPR_HYPERELEVATOR_DOOR, 10) - 1) * 32;
+ int step = round_random(0.5f * timeMod * 32);
+ if (s->doorOpenFor > 0) {
+ s->doorOpenFor = tick_down(s->doorOpenFor, timeMod);
+ s->door = (uint8_t)(s->door + step > max ? max : s->door + step);
+ } else {
+ s->door = (uint8_t)(s->door > step ? s->door - step : 0);
+ }
+}
+static void elevator_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ /* the door: on the front on the ground floor, else behind */
+ if (layer == (p->row == 0 ? LAYER_MAIN : LAYER_BG))
+ dr_frame(b, SPR_HYPERELEVATOR_DOOR, 10, STC(ElevatorState, p)->door / 32, x, y, 5, 10, 0, 255, GFX_NO_TINT);
+}
+static void elevator_window(Perm *p, WinOut *w) {
+ win_line1(w, "Elevator entered here [0] times.", STC(ElevatorState, p)->timesUsed);
+ win_line1(w, "Elevator left here [0] times.", STC(ElevatorState, p)->timesUsedTo);
+}
+const PermOps ops_HyperElevator = {.update = elevator_update, .draw = elevator_draw, .window = elevator_window};
+
+/* ---------------------------------------------------------------- the flying pathfinder
+ * The air is cut into 20-pixel columns over the whole city. In each, the
+ * worlds' stacks and islands are obstructions; the free spans between them
+ * hold waypoints (the heights of landing pads, of the next column's
+ * obstructions' edges, and those carried over from the column before),
+ * linked up and down within a span and sideways at equal heights. A route is
+ * the shortest (Manhattan) way along them. The graph is made when a route is
+ * asked for, for the columns between the two pads (a few more on each side),
+ * in the search memory (scratch.h). */
+#define FLY_MAX_OB 32
+#define FLY_MAX_WP 64
+#define FLY_MARGIN 6
+static int grid_istart, grid_len;
+static uint8_t sorted_worlds[MAX_WORLDS];
+static int nsorted;
+
+static void grid_setup(void) {
+ int minx = 0, maxx = 20;
+ if (nworlds > 0) {
+ minx = 1 << 30, maxx = -(1 << 30);
+ for (int w = 0; w < nworlds; w++) {
+ if (worlds[w].x < minx) minx = worlds[w].x;
+ if (worlds[w].x + worlds[w].w > maxx) maxx = worlds[w].x + worlds[w].w;
+ }
+ minx -= 40, maxx += 40;
+ }
+ grid_istart = minx / 20;
+ grid_len = maxx / 20 - grid_istart + 1;
+ /* the worlds from the top down (a stable sort) */
+ nsorted = 0;
+ for (int w = 0; w < nworlds; w++) {
+ int k = nsorted++;
+ while (k > 0 && worlds[sorted_worlds[k - 1]].y > worlds[w].y) sorted_worlds[k] = sorted_worlds[k - 1], k--;
+ sorted_worlds[k] = (uint8_t)w;
+ }
+}
+static bool is_pad(const Perm *p) { return p && (p->flags & PF_USED) && p->cls == CLS_LandingSite; }
+static int pad_column(const Perm *p) { return perm_city_x(p) / 20 - grid_istart; }
+static bool pad_in_column_at(int i, int y) {
+ for (int k = 1; k < MAX_PERMS; k++)
+ if (is_pad(&perms[k]) && pad_column(&perms[k]) == i && perm_city_y(&perms[k]) == y) return true;
+ return false;
+}
+/* a column's obstructions: pairs of (top, bottom), from the top down */
+static int column_obstructions(int i, int16_t *ob) {
+ int n = 0, x = (i + grid_istart) * 20;
+ for (int k = 0; k < nsorted; k++) {
+ int w = sorted_worlds[k];
+ const World *wd = &worlds[w];
+ if (x < wd->x || x >= wd->x + wd->w) continue;
+ int idx = (x - wd->x) / 20;
+ int maxy = -1;
+ if (wd->h > 0)
+ for (int j = 0; j * 20 < wd->h; j++)
+ if (world_mask_at(w, idx, j)) maxy = j;
+ int len = col_stack_height(w, idx);
+ int start = wd->y - len * 20;
+ bool hole = false;
+ const Perm *top = len ? P(perm_at(w, idx, len - 1)) : NULL;
+ bool top_pad = is_pad(top);
+ for (int pm = len - 1; pm >= 0; pm--) {
+ const Perm *q = P(perm_at(w, idx, pm));
+ if (!q) {
+ if (!hole) {
+ if (pm != len - 1) {
+ int end = wd->y - (pm + 1) * 20;
+ if (top_pad) start += 20;
+ if (n == 0 || start > ob[n - 1]) {
+ if (n + 2 <= FLY_MAX_OB) ob[n++] = (int16_t)start, ob[n++] = (int16_t)end;
+ } else {
+ ob[n - 1] = (int16_t)end;
+ }
+ }
+ hole = true;
+ }
+ } else if (hole) {
+ start = wd->y - (pm + 1) * 20;
+ hole = false;
+ top_pad = is_pad(q);
+ }
+ }
+ if (hole) start = wd->y;
+ if (maxy >= 0) {
+ int end = (maxy + 1) * 20 + wd->y;
+ if (pad_in_column_at(i, start)) start += 20;
+ if (n == 0 || start > ob[n - 1]) {
+ if (n + 2 <= FLY_MAX_OB) ob[n++] = (int16_t)start, ob[n++] = (int16_t)end;
+ } else {
+ ob[n - 1] = (int16_t)end;
+ }
+ }
+ }
+ return n;
+}
+static void sort_unique(int16_t *v, int *n) {
+ for (int a = 1; a < *n; a++) {
+ int16_t k = v[a];
+ int b = a - 1;
+ while (b >= 0 && v[b] > k) v[b + 1] = v[b], b--;
+ v[b + 1] = k;
+ }
+ int m = 0;
+ for (int a = 0; a < *n; a++)
+ if (m == 0 || v[m - 1] != v[a]) v[m++] = v[a];
+ *n = m;
+}
+/* addNextWaypointToAvoidBlockers */
+static void avoid_blockers(int wp, const int16_t *next, int nn, int yfrom, int yto, int16_t *out, int *no) {
+ for (int b = 0; b < nn; b += 2) {
+ if (wp >= next[b] && wp < next[b + 1]) {
+ if (*no < FLY_MAX_WP) {
+ if (next[b] > yfrom) out[(*no)++] = (int16_t)(next[b] - 20);
+ else if (next[b + 1] < yto) out[(*no)++] = next[b + 1];
+ }
+ return;
+ }
+ if (next[b] > wp) return;
+ }
+}
+#define fly_y (scratch->u.fly.y)
+#define fly_col (scratch->u.fly.col)
+#define fly_seg (scratch->u.fly.seg)
+#define fly_start (scratch->u.fly.colstart)
+static int fly_lo, fly_n, fly_ncols;
+/* the waypoints of columns lo..hi (grid indexes); false if they do not fit */
+static bool build_waypoints(int lo, int hi) {
+ int16_t cur[FLY_MAX_OB], next[FLY_MAX_OB]; /* (on the stack: only while a route is looked for) */
+ int16_t prev_wp[FLY_MAX_WP], wp[FLY_MAX_WP];
+ if (hi - lo + 1 > 255) return false;
+ int nprev = 0, ncur, nnext;
+ fly_lo = lo;
+ fly_n = 0;
+ fly_ncols = hi - lo + 1;
+ ncur = column_obstructions(1, cur);
+ bool ok = true;
+ for (int i = 1; i < grid_len - 1 && i <= hi; i++) {
+ nnext = column_obstructions(i + 1, next);
+ int nwp = 0, segs = ncur / 2;
+ int prevpos = 0, k = 0;
+ bool store = i >= lo;
+ if (store) fly_start[i - lo] = (uint16_t)fly_n;
+ for (int j = 0; j <= segs; j++) {
+ int16_t these[FLY_MAX_WP];
+ int nt = 0;
+ int yfrom = -1000000, yto = 1000000;
+ if (segs != 0) {
+ if (j == 0) yto = cur[0];
+ else if (j == segs) yfrom = cur[segs * 2 - 1];
+ else yfrom = cur[j * 2 - 1], yto = cur[j * 2];
+ }
+ while (k < nnext) {
+ if (next[k] > yfrom && next[k + 1] < yto) {
+ if (nt + 2 <= FLY_MAX_WP) these[nt++] = (int16_t)(next[k] - 20), these[nt++] = next[k + 1];
+ } else if (next[k] > yfrom) {
+ break;
+ }
+ k += 2;
+ }
+ while (prevpos < nprev) {
+ int v = prev_wp[prevpos];
+ if (v >= yfrom && v < yto) {
+ if (nt < FLY_MAX_WP) these[nt++] = (int16_t)v;
+ avoid_blockers(v, next, nnext, yfrom, yto, these, &nt);
+ } else if (v >= yfrom) {
+ break;
+ }
+ prevpos++;
+ }
+ for (int q = 1; q < MAX_PERMS; q++) {
+ const Perm *pad = &perms[q];
+ if (!is_pad(pad) || pad_column(pad) != i) continue;
+ int py = perm_city_y(pad);
+ if (py >= yfrom && py <= yto - 20) {
+ if (nt < FLY_MAX_WP) these[nt++] = (int16_t)py;
+ avoid_blockers(py, next, nnext, yfrom, yto, these, &nt);
+ }
+ }
+ sort_unique(these, &nt);
+ for (int t = 0; t < nt; t++) {
+ if (nwp < FLY_MAX_WP) wp[nwp++] = these[t];
+ if (store) {
+ if (fly_n >= MAX_PERMS) {
+ ok = false;
+ continue;
+ }
+ fly_y[fly_n] = these[t];
+ fly_col[fly_n] = (uint8_t)(i - lo);
+ fly_seg[fly_n] = (uint8_t)j;
+ fly_n++;
+ }
+ }
+ }
+ memcpy(prev_wp, wp, sizeof wp[0] * (size_t)nwp);
+ nprev = nwp;
+ memcpy(cur, next, sizeof cur[0] * (size_t)nnext);
+ ncur = nnext;
+ }
+ fly_start[hi - lo + 1] = (uint16_t)fly_n;
+ return ok;
+}
+static int node_at(int col, int y) {
+ if (col < 0 || col >= fly_ncols) return -1;
+ for (int k = fly_start[col]; k < fly_start[col + 1]; k++)
+ if (fly_y[k] == y) return k;
+ return -1;
+}
+#define fprio (scratch->prio)
+#define fprev (scratch->prev)
+#define fseen (scratch->seen)
+static void fly_relax(int from, int to) {
+ int fx = (fly_col[from] + fly_lo + grid_istart) * 20, tx = (fly_col[to] + fly_lo + grid_istart) * 20;
+ float np = fprio[from] + (float)(abs(fx - tx) + abs(fly_y[from] - fly_y[to]));
+ if (fseen[to] == 0) {
+ fseen[to] = 1;
+ fprev[to] = (uint16_t)from;
+ fprio[to] = np;
+ heap_push((uint16_t)to);
+ } else if (fseen[to] == 1 && np < fprio[to]) {
+ fprev[to] = (uint16_t)from;
+ fprio[to] = np;
+ heap_up(heap_index((uint16_t)to));
+ }
+}
+/* findRoute: the waypoints from b back to a (out[0] is b), as turning points; -1 if none, 0 if too big to find */
+static int find_route(const Perm *a, const Perm *b, int16_t out[][2], int max) {
+ grid_setup();
+ int ca = pad_column(a), cb = pad_column(b);
+ int lo = (ca < cb ? ca : cb) - FLY_MARGIN, hi = (ca > cb ? ca : cb) + FLY_MARGIN;
+ if (lo < 1) lo = 1;
+ if (hi > grid_len - 2) hi = grid_len - 2;
+ if (ca < 1 || cb < 1 || ca > grid_len - 2 || cb > grid_len - 2) return -1;
+ if (!build_waypoints(lo, hi)) return 0;
+ int s = node_at(ca - lo, perm_city_y(a)), g = node_at(cb - lo, perm_city_y(b));
+ if (s < 0 || g < 0) return -1;
+ memset(fseen, 0, (size_t)fly_n);
+ heap_n = 0;
+ fprio[s] = 0;
+ fseen[s] = 1;
+ heap_push((uint16_t)s);
+ bool found = false;
+ while (heap_n) {
+ int v = heap_pop();
+ fseen[v] = 2;
+ if (v == g) {
+ found = true;
+ break;
+ }
+ if (v > 0 && fly_col[v - 1] == fly_col[v] && fly_seg[v - 1] == fly_seg[v]) fly_relax(v, v - 1);
+ if (v + 1 < fly_n && fly_col[v + 1] == fly_col[v] && fly_seg[v + 1] == fly_seg[v]) fly_relax(v, v + 1);
+ int l = node_at(fly_col[v] - 1, fly_y[v]), r = node_at(fly_col[v] + 1, fly_y[v]);
+ if (l >= 0 && fly_col[v] > 0) fly_relax(v, l);
+ if (r >= 0 && fly_col[v] + 1 <= hi - lo) fly_relax(v, r);
+ }
+ if (!found) return -1;
+ /* the route from the goal back to the start, without the points in straight runs */
+ int n = 0, v = g;
+ int16_t px = 0, py = 0;
+ bool first = true;
+ for (;;) {
+ int16_t x = (int16_t)((fly_col[v] + lo + grid_istart) * 20), y = fly_y[v];
+ if (!first && n >= 2 && ((out[n - 1][0] == x && out[n - 2][0] == x) || (out[n - 1][1] == y && out[n - 2][1] == y))) {
+ out[n - 1][0] = x, out[n - 1][1] = y;
+ } else if (n < max) {
+ out[n][0] = x, out[n][1] = y;
+ n++;
+ } else {
+ out[n - 1][0] = x, out[n - 1][1] = y; /* (too many turns: the last is cut straight to the start) */
+ }
+ first = false;
+ px = x, py = y;
+ if (v == s) break;
+ v = fprev[v];
+ }
+ (void)px, (void)py;
+ return n;
+}
+/* a pad in its column's open sky (no obstruction above it) */
+static bool pad_in_sky(const Perm *p) {
+ int16_t ob[FLY_MAX_OB];
+ int n = column_obstructions(pad_column(p), ob);
+ return n == 0 || perm_city_y(p) <= ob[0] - 20;
+}
+static bool pads_connected(const Perm *a, const Perm *b) {
+ grid_setup();
+ if (pad_in_sky(a) && pad_in_sky(b)) return true;
+ int16_t route[2][2];
+ int n = find_route(a, b, route, 2);
+ return n != -1;
+}
+/* findAnyOtherLandingSite (for CityConnections' landing groups): a pad already in a group it can fly to */
+uint16_t flying_find_any_other_landing_site(uint16_t ls) {
+ const Perm *a = P(ls);
+ if (!is_pad(a)) return NONE;
+ grid_setup();
+ int ca = pad_column(a);
+ if (ca < 1 || ca > grid_len - 2) return NONE;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (i != ls && is_pad(&perms[i]) && landing_group_of[i] && pads_connected(a, &perms[i])) return (uint16_t)i;
+ return NONE;
+}
+int flying_columns(void) {
+ grid_setup();
+ return grid_len > 2 ? grid_len - 2 : 0;
+}
+int flying_highest_y(int index, int *x) {
+ int16_t ob[FLY_MAX_OB];
+ int i = index + 1;
+ *x = (i + grid_istart) * 20;
+ int n = column_obstructions(i, ob);
+ return n == 0 ? -1000000 : ob[0];
+}
+
+/* ---------------------------------------------------------------- flying saucers (simulation.FlyingSaucer) */
+#define MAX_SAUCERS 12
+#define SAUCER_POINTS 8
+typedef struct {
+ uint16_t start, dest; /* landing sites (start 0: a free slot) */
+ float x, y;
+ uint8_t leavingIn; /* ticks x 8 */
+ uint8_t pathPos, npts, type;
+ int16_t pts[SAUCER_POINTS][2]; /* the route: pts[0] is the destination */
+} Saucer;
+static Saucer saucers[MAX_SAUCERS];
+#define PASSENGER 0x8000 /* a passenger's thenArg: PASSENGER | its saucer */
+
+static const uint16_t saucer_sprites[6] = {SPR_FLYINGSAUCER, SPR_FLYINGSAUCER_ALT, SPR_FLOWERCRAFT, SPR_FLYINGSAUCER_CUBE,
+ SPR_FLYINGSAUCER_DEEPBLUE, SPR_FLYINGSAUCER_SHADE};
+static void release(Cit *c) {
+ c->flags &= (uint16_t)~CF_CONTROLLED;
+ c->thenArg = 0;
+}
+/* cancel: the passengers stay where they were, without a path */
+static void saucer_cancel(int k) {
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if ((c->flags & CF_ALIVE) && (c->flags & CF_CONTROLLED) && c->thenArg == (PASSENGER | k)) {
+ release(c);
+ cit_reset_path(c, true);
+ }
+ }
+ saucers[k].start = 0;
+ saucers[k].dest = 0;
+}
+void saucer_on_landing_destroyed(uint16_t ls) {
+ for (int k = 0; k < MAX_SAUCERS; k++)
+ if (saucers[k].start && saucers[k].dest == ls) saucer_cancel(k);
+}
+static float pad_distance(const Perm *a, const Perm *b) { return bld_flying_distance(a, b); }
+static void pad_remove_saucer(Perm *ls) {
+ LandingState *s = ST(LandingState, ls);
+ if (s->hasSaucer) {
+ s->hasSaucer = 0;
+ s->newStage = 16 * 8;
+ s->newWait = 30;
+ }
+}
+static void pad_add_saucer(Perm *ls) {
+ LandingState *s = ST(LandingState, ls);
+ if (!s->hasSaucer) s->hasSaucer = 1, s->newStage = 0, s->newWait = 0;
+}
+static void add_passenger(int k, Cit *c) {
+ Perm *start = P(saucers[k].start);
+ if (is_pad(start) && ST(LandingState, start)->timesUsed < 65535) ST(LandingState, start)->timesUsed++;
+ c->flags |= CF_CONTROLLED;
+ c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ c->thenArg = (uint16_t)(PASSENGER | k);
+}
+/* a landing site's path step (Citizen.updatePath, step 11): board a saucer (false: the path was dropped) */
+bool flying_board(Cit *c, Perm *in, Perm *dest) {
+ if (!is_pad(in) || !is_pad(dest)) {
+ cit_reset_path(c, true);
+ return false;
+ }
+ LandingState *s = ST(LandingState, in);
+ int landed = s->landed - 1;
+ if (landed >= 0 && saucers[landed].start == pid(in) && saucers[landed].leavingIn > 0 &&
+ (saucers[landed].dest == pid(dest) || pad_distance(P(saucers[landed].dest), dest) < pad_distance(in, dest))) {
+ Saucer *sc = &saucers[landed];
+ add_passenger(landed, c);
+ if (sc->dest != pid(dest) && pad_distance(in, dest) < pad_distance(in, P(sc->dest))) {
+ int16_t pts[SAUCER_POINTS][2];
+ int n = find_route(in, dest, pts, SAUCER_POINTS);
+ if (n > 0) {
+ memcpy(sc->pts, pts, sizeof pts);
+ sc->npts = (uint8_t)n;
+ sc->pathPos = (uint8_t)(n - 1);
+ sc->dest = pid(dest);
+ }
+ }
+ return true;
+ }
+ if (s->hasSaucer) {
+ int k = -1;
+ for (int i = 0; i < MAX_SAUCERS && k < 0; i++)
+ if (!saucers[i].start) k = i;
+ if (k < 0) { /* (every saucer is in the air: wait for one) */
+ c->relativeY = -1;
+ return true;
+ }
+ int16_t pts[SAUCER_POINTS][2];
+ int n = find_route(in, dest, pts, SAUCER_POINTS);
+ if (n == 0) { /* too far to work out in memory: straight up, across and down */
+ int ax = perm_city_x(in) / 20 * 20, bx = perm_city_x(dest) / 20 * 20;
+ int top = perm_city_y(in) < perm_city_y(dest) ? perm_city_y(in) : perm_city_y(dest);
+ grid_setup();
+ int lo = pad_column(in) < pad_column(dest) ? pad_column(in) : pad_column(dest);
+ int hi = pad_column(in) > pad_column(dest) ? pad_column(in) : pad_column(dest);
+ for (int i = lo; i <= hi; i++) {
+ int16_t ob[FLY_MAX_OB];
+ int no = column_obstructions(i, ob);
+ if (no && ob[0] - 20 < top) top = ob[0] - 20;
+ }
+ pts[0][0] = (int16_t)bx, pts[0][1] = (int16_t)perm_city_y(dest);
+ pts[1][0] = (int16_t)bx, pts[1][1] = (int16_t)top;
+ pts[2][0] = (int16_t)ax, pts[2][1] = (int16_t)top;
+ pts[3][0] = (int16_t)ax, pts[3][1] = (int16_t)perm_city_y(in);
+ n = 4;
+ }
+ if (n < 0) {
+ cit_reset_path(c, true);
+ return false;
+ }
+ Saucer *sc = &saucers[k];
+ memset(sc, 0, sizeof *sc);
+ sc->start = pid(in), sc->dest = pid(dest);
+ memcpy(sc->pts, pts, sizeof pts);
+ sc->npts = (uint8_t)n;
+ sc->pathPos = (uint8_t)(n - 1);
+ sc->x = sc->pts[n - 1][0], sc->y = sc->pts[n - 1][1];
+ sc->leavingIn = 12 * 8;
+ sc->type = s->saucerType;
+ s->landed = (uint8_t)(k + 1);
+ add_passenger(k, c);
+ pad_remove_saucer(in);
+ c->relativeX = (float)rnd_between(10 - 3, 10 + 4);
+ return true;
+ }
+ c->relativeY = -1;
+ return true;
+}
+static void saucer_arrive(int k) {
+ Saucer *sc = &saucers[k];
+ Perm *dest = P(sc->dest);
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_CONTROLLED) || c->thenArg != (PASSENGER | k)) continue;
+ release(c);
+ if (!is_pad(dest)) continue;
+ cit_go_to_permanent(c, sc->dest);
+ c->onWorld = dest->world;
+ LandingState *ds = ST(LandingState, dest);
+ if (c->pathActionPerm != sc->dest) {
+ if (ds->timesUsedStopOver < 65535) ds->timesUsedStopOver++;
+ } else if (ds->timesUsedTo < 65535) {
+ ds->timesUsedTo++;
+ }
+ }
+ if (is_pad(dest)) pad_add_saucer(dest);
+ sc->start = 0;
+}
+static void saucers_update(float timeMod) {
+ for (int k = 0; k < MAX_SAUCERS; k++) {
+ Saucer *sc = &saucers[k];
+ if (!sc->start) continue;
+ if (sc->leavingIn > 0) {
+ int d = round_random(timeMod * 8);
+ sc->leavingIn = (uint8_t)(sc->leavingIn > d ? sc->leavingIn - d : 0);
+ if (sc->leavingIn == 0 && is_pad(P(sc->start)) && ST(LandingState, P(sc->start))->landed == k + 1)
+ ST(LandingState, P(sc->start))->landed = 0;
+ continue;
+ }
+ float left = timeMod * 3;
+ int guard = 0;
+ while (left > 0 && guard++ < 64) {
+ float gx = sc->pts[sc->pathPos][0], gy = sc->pts[sc->pathPos][1];
+ if (fabsf(sc->x - gx) > 0.01f) {
+ float d = gx - sc->x;
+ sc->x += (d > 0 ? 1 : -1) * fminf(left, fabsf(d));
+ left -= fabsf(d);
+ } else if (fabsf(sc->y - gy) > 0.01f) {
+ float d = gy - sc->y;
+ sc->y += (d > 0 ? 1 : -1) * fminf(left, fabsf(d));
+ left -= fabsf(d);
+ } else {
+ sc->x = gx, sc->y = gy;
+ if (sc->pathPos == 0) {
+ saucer_arrive(k);
+ break;
+ }
+ sc->pathPos--;
+ }
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- LandingSite */
+static void landing_init(Perm *p) { ST(LandingState, p)->hasSaucer = 1; }
+static void landing_destroy(Perm *p) { saucer_on_landing_destroyed(pid(p)); }
+static void landing_update(Perm *p, float timeMod) {
+ LandingState *s = ST(LandingState, p);
+ if (s->newWait > 0) {
+ s->newWait = tick_down(s->newWait, timeMod);
+ } else if (s->newStage > 0) {
+ int d = round_random(timeMod * 8);
+ s->newStage = (uint8_t)(s->newStage > d ? s->newStage - d : 0);
+ if (s->newStage == 0) s->hasSaucer = 1;
+ }
+}
+static uint16_t pad_texture(const Perm *p) {
+ int t = STC(LandingState, p)->saucerType;
+ return t == 1 ? SPR_LANDINGPLACE_ALT : t == 4 ? SPR_LANDINGPLACE_DEEPBLUE : SPR_LANDINGPLACE;
+}
+static void landing_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, pad_texture(p), false);
+ if (layer != LAYER_MID) return;
+ /* the saucer on the pad (aboveCitizensInBuildingStage), coming down when a new one arrives */
+ const LandingState *s = STC(LandingState, p);
+ uint16_t spr = saucer_sprites[s->saucerType % 6];
+ if (s->landed && saucers[s->landed - 1].start == pid(p)) {
+ dr_sprite(b, saucer_sprites[saucers[s->landed - 1].type % 6], x, y, 0, 0, 0, 255);
+ } else if (s->hasSaucer) {
+ dr_sprite(b, spr, x, y, 0, 0, 0, 255);
+ } else if (s->newWait == 0 && s->newStage > 0) {
+ float stage = s->newStage / 8.0f;
+ float a = 1 - stage / 16;
+ dr_sprite(b, spr, x, y, 0, -(int)(stage * 0.25f), 0, (uint8_t)(a < 0 ? 0 : a * 255));
+ }
+}
+static void landing_window(Perm *p, WinOut *w) {
+ const LandingState *s = STC(LandingState, p);
+ int from = s->timesUsed - s->timesUsedStopOver;
+ win_line1(w, "Transported from [0] times.", from > 0 ? from : 0);
+ win_line1(w, "Transported to [0] times.", s->timesUsedTo);
+ win_line1(w, "Used as stopover [0] times.", s->timesUsedStopOver);
+ if (bld_secret_hangar) win_button(w, 0, "Change Space Ship", WA_CYCLE_0, true);
+}
+static void landing_action(Perm *p, int a) {
+ if (a == WA_CYCLE_0 && bld_secret_hangar) {
+ LandingState *s = ST(LandingState, p);
+ s->saucerType = (uint8_t)((s->saucerType + 1) % 6);
+ }
+}
+const PermOps ops_LandingSite = {.init = landing_init, .destroy = landing_destroy, .update = landing_update,
+ .draw = landing_draw, .window = landing_window, .window_action = landing_action};
+
+/* ---------------------------------------------------------------- saucers bringing citizens (SpawnFlyingSaucer) */
+#define MAX_SPAWNERS 6
+typedef struct { uint8_t world, col, ageMin, ageMax; uint16_t amount; float above; } Spawner;
+static Spawner spawners[MAX_SPAWNERS];
+static int nspawners;
+int spawners_pending(void) {
+ int n = 0;
+ for (int i = 0; i < nspawners; i++) n += spawners[i].amount;
+ return n;
+}
+/* simulation.SpawnFlyingSaucer: toCol < 0 picks an empty column (or one with a building) at random */
+void saucer_spawn(int world, int amount, int ageMin, int ageMax, int toCol) {
+ if (world < 0 || world >= nworlds || amount <= 0) return;
+ const World *wd = &worlds[world];
+ if (toCol < 0) {
+ int best = -5, n = 0;
+ uint8_t options[255];
+ for (int x = 0; x < wd->ncols && x < 255; x++) {
+ int q = -1, h = col_stack_height(world, x);
+ const Perm *bottom = h ? P(perm_at(world, x, 0)) : NULL;
+ if (h == 0) q = 1;
+ else if (is_building(bottom) && !(bottom->flags & PF_ROOFTOP)) q = 0;
+ if (q > best) best = q, n = 0;
+ if (q >= best) options[n++] = (uint8_t)x;
+ }
+ if (!n) return;
+ toCol = options[rnd_int(n)];
+ }
+ if (nspawners >= MAX_SPAWNERS) { /* (no room for another in the air: they come at once) */
+ nspawners--;
+ }
+ Spawner *s = &spawners[nspawners++];
+ s->world = (uint8_t)world, s->col = (uint8_t)toCol;
+ s->ageMin = (uint8_t)ageMin, s->ageMax = (uint8_t)ageMax;
+ s->amount = (uint16_t)amount;
+ s->above = 1000.0f + col_stack_height(world, toCol) * 20;
+}
+uint16_t cit_create(int world, float age, uint16_t start_in, int start_x);
+static void spawn_citizens(const Spawner *s) {
+ int h = col_stack_height(s->world, s->col);
+ uint16_t start = NONE;
+ int x = -1;
+ if (h == 0) x = s->col * 20;
+ else start = perm_at(s->world, s->col, h - 1);
+ for (int i = 0; i < s->amount; i++) {
+ float age = s->ageMin;
+ if (s->ageMin != s->ageMax) age = rnd_range(s->ageMin, s->ageMax);
+ if (ncits + spawners_pending() < babies.softPopLimit) cit_create(s->world, age, start, x);
+ }
+}
+void spawners_update(float timeMod) {
+ for (int i = nspawners - 1; i >= 0; i--) {
+ Spawner *s = &spawners[i];
+ s->above -= timeMod * 3;
+ if (s->above <= col_stack_height(s->world, s->col) * 20) {
+ Spawner done = *s;
+ spawn_citizens(&done);
+ for (int k = i; k + 1 < nspawners; k++) spawners[k] = spawners[k + 1];
+ nspawners--;
+ }
+ }
+ festival_update(timeMod); /* (CitySimulation: festivalManager.update comes after the spawners) */
+}
+
+/* ---------------------------------------------------------------- each step, before the citizens */
+void flying_update(float timeMod) {
+ for (int k = 0; k < MAX_SAUCERS; k++) (void)k;
+ saucers_update(timeMod);
+ particles_update(timeMod);
+}
+
+/* the saucers in the air, the spawners' saucers and the particles */
+void flying_draw_free(const GfxBand *b, int layer) {
+ if (layer == LAYER_MID) {
+ for (int k = 0; k < MAX_SAUCERS; k++) {
+ const Saucer *sc = &saucers[k];
+ if (!sc->start || sc->leavingIn > 0) continue;
+ gfx_band_sprite(b, saucer_sprites[sc->type % 6], 0, 0, 20, 20, bg_screen_x(&camera, sc->x), bg_screen_y(&camera, sc->y), 0,
+ 255, GFX_NO_TINT);
+ }
+ for (int i = 0; i < MAX_PARTICLES; i++) {
+ if (!particles[i].spr) continue;
+ int f = (int)particles[i].frame;
+ gfx_band_sprite(b, particles[i].spr, (particles[i].fw + 2) * f, 0, particles[i].fw, spr_h(particles[i].spr),
+ bg_screen_x(&camera, particles[i].x), bg_screen_y(&camera, particles[i].y), 0, 255, GFX_NO_TINT);
+ }
+ } else if (layer == LAYER_FRONT) {
+ for (int i = 0; i < nspawners; i++) {
+ const Spawner *s = &spawners[i];
+ const World *wd = &worlds[s->world];
+ float x = (float)(wd->x + s->col * 20), y = wd->y - s->above - 20 + 1;
+ gfx_band_sprite(b, SPR_FLYINGSAUCER, 0, 0, 20, 20, bg_screen_x(&camera, x), bg_screen_y(&camera, y), 0, 255, GFX_NO_TINT);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- start, save, load */
+void saucers_new_city(void) {
+ memset(saucers, 0, sizeof saucers);
+ memset(spawners, 0, sizeof spawners);
+ memset(particles, 0, sizeof particles);
+ nspawners = 0;
+}
+void saucers_save(SaveIO *io) {
+ save_bytes(io, saucers, sizeof saucers);
+ save_u8(io, (uint8_t)nspawners);
+ save_bytes(io, spawners, sizeof spawners);
+}
+bool saucers_load(SaveIO *io) {
+ load_bytes(io, saucers, sizeof saucers);
+ nspawners = load_u8(io);
+ load_bytes(io, spawners, sizeof spawners);
+ if (nspawners > MAX_SPAWNERS) return false;
+ /* (a passenger was let go where they were when the city was saved: the flights land empty) */
+ return true;
+}
+
+void bld_transport_init(void) {}
diff --git a/games/finalearth2/src/bld_unique.c b/games/finalearth2/src/bld_unique.c
new file mode 100644
index 00000000..ee36b22f
--- /dev/null
+++ b/games/finalearth2/src/bld_unique.c
@@ -0,0 +1,1646 @@
+/* The Final Earth 2: unique buildings (buildings.md 11): the workshop, the
+ * research craft, observatory, art colony, city hall, research centers, the
+ * hackers', the Secret Society's and the hippies' missions, the escape room,
+ * the misdirector, the machine, the festival HQ and its music festivals
+ * (simulation.festival.*), the supercomputer, the fossil museum, the beacon. */
+#include <stdio.h>
+#include "bldi.h"
+#include "lang_data.h"
+#include "save.h"
+
+static inline float speed(void) { return happiness.actionSpeedModifier; }
+static inline float edu(const Cit *c) { return cit_education_speed_modifier(c); }
+static void walk_wait(Cit *c, int xmin, int xmax, int tmin, int tmax, bool slow) {
+ int x = rnd_between(xmin, xmax);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), THEN_NONE, 0, false, slow);
+}
+static void plain_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ draw_upgrades(b, p, layer, x, y, false);
+ draw_upgrades(b, p, layer, x, y, true);
+}
+static int count_class(int cls) {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == cls) n++;
+ return n;
+}
+static Perm *first_class(int cls) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == cls) return &perms[i];
+ return NULL;
+}
+static bool any_day_at_least(int m, double v) {
+ for (int d = 0; d < STATS_DAYS; d++)
+ if (stats.materialProduction[m][d] >= v) return true;
+ return false;
+}
+/* the knowledge it makes, also added to its total (TotalState, the start of its state) */
+typedef struct PACKED { float total; } TotalState;
+STATE_FITS(TotalState);
+static float knowledge(Perm *p, float k) {
+ produce(M_KNOWLEDGE, k);
+ if (p) ST(TotalState, p)->total += k;
+ return k;
+}
+uint8_t modern_artworks_unlocked = 4; /* unlocks.numberOfModernArtMuseumArtworksUnlocked */
+
+/* ---------------------------------------------------------------- Workshop */
+typedef struct PACKED { float totalKnowledge, totalMaterialUsed, materialMade; } WorkshopState;
+STATE_FITS(WorkshopState);
+static void workshop_init(Perm *p) { upgrade_first_mode(p); }
+static void workshop_on_build(Perm *p) { (void)p; bonuses.machinePartsFactorySpeed *= 1.25f; }
+static void workshop_destroy(Perm *p) { (void)p; bonuses.machinePartsFactorySpeed /= 1.25f; }
+static void workshop_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (worker_index(c) == 0) {
+ if (rnd_int(5) < 4) walk_wait(c, 4, 8, 60, 120, true);
+ else walk_wait(c, 11, 14, 60, 120, true);
+ } else if (c->relativeY < 2) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else if (rnd_int(2) == 0) {
+ walk_wait(c, 3, 6, 60, 120, true);
+ } else {
+ walk_wait(c, 13, 14, 60, 120, true);
+ }
+ WorkshopState *s = ST(WorkshopState, p);
+ if (p->mode == MODE_Workshop_WorkshopKnowledge) {
+ s->totalKnowledge += knowledge(NULL, 0.15f * edu(c) * boost());
+ } else if (city.materials.m[M_WOOD] >= 1) {
+ float made = 0.075f * edu(c) * boost();
+ produce(M_MACHINEPARTS, made);
+ s->materialMade += made;
+ float used = made * 2;
+ city.materials.m[M_WOOD] -= used;
+ stats_add_used(M_WOOD, used);
+ s->totalMaterialUsed += used;
+ }
+}
+static void workshop_window(Perm *p, WinOut *w) {
+ const WorkshopState *s = STC(WorkshopState, p);
+ char a[64], b[96], t[170];
+ lo1(a, sizeof a, "[0] knowledge gathered.", (int)s->totalKnowledge);
+ lo2(b, sizeof b, "[0] wood used to make [1] machine parts.", (int)s->totalMaterialUsed, (int)s->materialMade);
+ int k = 0;
+ for (const char *q = a; *q; q++) t[k++] = *q;
+ t[k++] = ' ';
+ for (const char *q = b; *q && k < 168; q++) t[k++] = *q;
+ t[k] = 0;
+ win_line(w, t);
+}
+const PermOps ops_Workshop = {.init = workshop_init, .on_build = workshop_on_build, .destroy = workshop_destroy,
+ .work = workshop_work, .draw = plain_draw, .window = workshop_window};
+
+/* ---------------------------------------------------------------- ResearchBot (the research craft) */
+typedef struct PACKED {
+ uint16_t timeWorking; /* ticks */
+ int16_t y4; /* flyingSaucerY x 4 */
+ int8_t xprog4; /* flyingSaucerXProg x 4 */
+ int16_t xi, target; /* flyingSaucerXI and flyingSaucerTargetX (indexes of highestYPositions) */
+ uint8_t waiting;
+ uint8_t flags; /* RB_FLYING, RB_RETURNING; above them timeWorking's 64ths */
+} BotState;
+STATE_FITS(BotState);
+enum { RB_FLYING = 1, RB_RETURNING = 2 };
+static float bot_time(const BotState *s) { return s->timeWorking + (s->flags >> 2) / 64.0f; }
+float research_bot_time_working(const Perm *p) { return bot_time(STC(BotState, p)); }
+static int bot_home_index(const Perm *p) {
+ (void)flying_columns(); /* (the grid of columns as now) */
+ int x;
+ flying_highest_y(0, &x);
+ return perm_city_x(p) / 20 - x / 20; /* (position.x / 20 | 0) - gridIStart - 1 */
+}
+/* the highest obstruction of a column, kept for the column the craft is over and the next */
+static struct { uint16_t bot; int16_t xi; int32_t y; } bot_cache[2];
+static int bot_highest(const Perm *p, int xi) {
+ for (int k = 0; k < 2; k++)
+ if (bot_cache[k].bot == pid(p) && bot_cache[k].xi == xi) return bot_cache[k].y;
+ int x, n = flying_columns();
+ int y = xi >= 0 && xi < n ? flying_highest_y(xi, &x) : -1000001;
+ bot_cache[1] = bot_cache[0];
+ bot_cache[0].bot = pid(p), bot_cache[0].xi = (int16_t)xi, bot_cache[0].y = y;
+ return y;
+}
+static void bot_init(Perm *p) {
+ BotState *s = ST(BotState, p);
+ s->y4 = (int16_t)(perm_city_y(p) * 4);
+}
+static void bot_city_change(Perm *p) {
+ BotState *s = ST(BotState, p);
+ memset(bot_cache, 0, sizeof bot_cache);
+ if (!(s->flags & RB_FLYING)) {
+ s->xi = (int16_t)bot_home_index(p);
+ s->y4 = (int16_t)(perm_city_y(p) * 4);
+ }
+}
+static void bot_update(Perm *p, float timeMod) {
+ BotState *s = ST(BotState, p);
+ if (!(s->flags & RB_FLYING)) return;
+ float t = bot_time(s) + timeMod;
+ if (t > 65535) t = 65535;
+ s->timeWorking = (uint16_t)t;
+ s->flags = (uint8_t)((s->flags & 3) | (int)((t - s->timeWorking) * 64) << 2);
+ if (s->waiting > 0) {
+ s->waiting = tick_down(s->waiting, timeMod);
+ } else {
+ float y = s->y4 / 4.0f, xprog = s->xprog4 / 4.0f;
+ int dir = s->target > s->xi ? 1 : s->target < s->xi ? -1 : 0;
+ if (dir == 0) {
+ float next = (float)bot_highest(p, s->xi) - 40;
+ if (s->flags & RB_RETURNING) next += 40;
+ if (y < next && next >= -1000000) {
+ y += 3 * timeMod;
+ if (y > next) y = next;
+ } else {
+ if (next >= -1000000) y = next;
+ if (s->flags & RB_RETURNING) {
+ s->flags &= (uint8_t)~(RB_FLYING | RB_RETURNING);
+ s->waiting = 60;
+ } else {
+ s->target = (int16_t)bot_home_index(p);
+ s->flags |= RB_RETURNING;
+ s->waiting = 60;
+ }
+ }
+ } else {
+ float next = (float)bot_highest(p, s->xi + dir) - 40;
+ if (y > next && next >= -100000) {
+ y -= 3 * timeMod;
+ if (y < next) y = next;
+ } else {
+ xprog += 3 * dir * timeMod;
+ if (dir * xprog > 20) xprog = 0, s->xi = (int16_t)(s->xi + dir);
+ }
+ }
+ if (y < -8000) y = -8000;
+ if (y > 8000) y = 8000;
+ s->y4 = (int16_t)(y * 4);
+ s->xprog4 = (int8_t)(xprog * 4);
+ }
+ /* the pilot rides in the craft */
+ Cit *pilot = worker_at(p, 0);
+ if (pilot && pilot->inPermanent == pid(p)) {
+ int x;
+ flying_highest_y(s->xi, &x);
+ float sx = x + s->xprog4 / 4.0f, sy = s->y4 / 4.0f;
+ set_rel(pilot, sx - perm_city_x(p) + 9, -(sy - perm_city_y(p)) + 3);
+ }
+}
+static void bot_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ BotState *s = ST(BotState, p);
+ if (stop && !(s->flags & RB_FLYING)) {
+ c->currentAction = 2;
+ return;
+ }
+ if (s->flags & RB_FLYING) {
+ produce(M_KNOWLEDGE, 0.00125f * timeMod * speed() * edu(c) * boost());
+ return;
+ }
+ float spd = c->pathWalkSpeed / 100.0f * timeMod;
+ if (fabsf(9 - c->relativeX) >= spd) {
+ c->relativeX += (9 > c->relativeX ? 1 : -1) * spd;
+ return;
+ }
+ c->relativeX = 9;
+ c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ s->flags |= RB_FLYING;
+ s->target = (int16_t)rnd_int(flying_columns());
+ s->xi = (int16_t)bot_home_index(p);
+ if (story_is("hackersandaliens") && s->timeWorking < 60) {
+ int x;
+ flying_highest_y(0, &x);
+ s->target = (int16_t)(-36 / 20 - x / 20); /* ((-36 | 0) / 20...) as written: the column of x -36 */
+ }
+ s->y4 = (int16_t)(perm_city_y(p) * 4);
+}
+static void bot_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer == LAYER_MAIN && !(STC(BotState, p)->flags & RB_FLYING)) dr_sprite(b, SPR_RESEARCHBOT, x, y, 0, 0, 0, 255);
+}
+const PermOps ops_ResearchBot = {.init = bot_init, .on_city_change = bot_city_change, .update = bot_update, .work = bot_work,
+ .draw = bot_draw};
+#include "view.h"
+/* the craft in the air (drawn wherever it is) */
+void research_bot_draw_free(const GfxBand *b, int layer) {
+ if (layer != LAYER_MAIN) return;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->cls != CLS_ResearchBot || !(STC(BotState, p)->flags & RB_FLYING)) continue;
+ const BotState *s = STC(BotState, p);
+ int x;
+ flying_highest_y(s->xi, &x);
+ float cx = x + s->xprog4 / 4.0f, cy = s->y4 / 4.0f;
+ gfx_band_sprite(b, SPR_RESEARCHBOT, 0, 0, 20, 20, bg_screen_x(&camera, cx), bg_screen_y(&camera, cy), 0, 255, GFX_NO_TINT);
+ }
+}
+
+/* ---------------------------------------------------------------- Observatory */
+static void observatory_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ switch (worker_index(c)) {
+ case 0: step_to_x(c, 5, timeMod); break;
+ case 1: step_to_x(c, 13, timeMod); break;
+ case 2: step_to_x(c, 9, timeMod); break;
+ }
+ float per = 0.002f * (has_upgrade_bit(p, UB_Observatory_StarDatabase) ? upgrades.starDatabaseIsMoreEffective ? 6 : 1.5f : 1);
+ knowledge(p, per * timeMod * speed() * bonuses.labSpeed * edu(c) * boost());
+}
+static void total_window(Perm *p, WinOut *w) { win_line1(w, "[0] knowledge gathered.", (int)STC(TotalState, p)->total); }
+const PermOps ops_Observatory = {.work = observatory_work, .draw = plain_draw, .window = total_window};
+
+/* ---------------------------------------------------------------- ArtColony */
+typedef struct PACKED { float progress; uint8_t texture; } ArtColonyState;
+static const uint8_t unlock_new_work_after[6] = {4, 7, 8, 10, 13, 13};
+static float art_colony_capacity(const Perm *p) { return p->nworkers * 50.0f; }
+static bool art_colony_open(const Perm *p) {
+ float h = hour_now();
+ return p->nworkers > 0 && first_worker_working(p) && day_number() % 3 == 0 && h < 21.5f && h > 15.0f;
+}
+static uint8_t TH_ART_MOVE;
+static void th_art_move(Cit *c, uint16_t arg) { (void)arg; walk_wait(c, 3, 16, 50, 100, true); }
+static void art_colony_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (c->relativeY < 5) cit_change_floor(c, TH_ART_MOVE, 0);
+ else th_art_move(c, 0);
+}
+static void art_colony_walk(Perm *p, Cit *c, float steps) {
+ (void)p;
+ int r = rnd_int(3);
+ if (r == 0 && steps > 120) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1) walk_wait(c, 3, 15, 30, 60, false);
+ else wait_ticks(c, 90, 120);
+}
+static void art_colony_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) c->currentAction = 2; /* (as written: it carries on) */
+ int place = (worker_index(c) + day_number()) % 5;
+ bool redo = rnd_float() < 0.015f * timeMod;
+ if (place == 0 || place == 3) {
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else if (place == 0) {
+ if (c->relativeX < 3 || c->relativeX > 6 || redo) walk_wait(c, 3, 7, 5, 10, false);
+ } else if (c->relativeX < 12 || c->relativeX > 15 || redo) walk_wait(c, 12, 16, 5, 10, false);
+ } else if (c->relativeY < 5) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else if (place == 1) {
+ if (c->relativeX < 3 || c->relativeX > 6 || redo) walk_wait(c, 3, 7, 5, 10, false);
+ } else if (place == 2) {
+ if (c->relativeX < 12 || c->relativeX > 15 || redo) walk_wait(c, 12, 16, 5, 10, false);
+ } else if (place == 4) {
+ if (c->relativeX < 8 || c->relativeX > 10 || redo) walk_wait(c, 8, 11, 5, 10, false);
+ }
+ ArtColonyState *s = ST(ArtColonyState, p);
+ if (s->progress >= 1.0f) {
+ s->texture++;
+ int n = 0;
+ for (int i = 0; i < 6; i++)
+ if (s->texture > unlock_new_work_after[i]) n++;
+ if (4 + n > modern_artworks_unlocked) modern_artworks_unlocked = (uint8_t)(4 + n);
+ s->texture %= (uint8_t)frames_of(SPR_ARTCOLONYWORK, 20);
+ s->progress = 0;
+ }
+ s->progress += timeMod * edu(c) * speed() * 0.00002f;
+}
+static void art_colony_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer == LAYER_BG) dr_frame(b, SPR_ARTCOLONYWORK, 20, STC(ArtColonyState, p)->texture, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+const PermOps ops_ArtColony = {.work = art_colony_work, .walk_around = art_colony_walk, .is_open = art_colony_open,
+ .entertainment_capacity = art_colony_capacity, .be_entertained = art_colony_be_entertained,
+ .draw = art_colony_draw};
+
+/* ---------------------------------------------------------------- CityHall */
+static void city_hall_init(Perm *p) { upgrade_first_mode(p); }
+static void city_hall_destroy(Perm *p) { (void)p; upgrades.nightClubEntertainmentQualityBonus = 0; }
+static void city_hall_update(Perm *p, float timeMod) {
+ upgrades.nightClubEntertainmentQualityBonus = 0;
+ if (p->mode == MODE_CityHall_CensusData) knowledge(p, p->nworkers * (float)ncits * timeMod * 0.0000005f);
+ else upgrades.nightClubEntertainmentQualityBonus = p->nworkers * 2.0f;
+}
+static void city_hall_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop) c->currentAction = 2; /* (as written: a walk starts anyway) */
+ int r = rnd_int(7);
+ if (c->relativeY < 5) {
+ if (r < 3) cit_change_floor_and_wait_random(c, 20, 30, THEN_NONE, 0);
+ else if (r < 5) walk_wait(c, 3, 7, 90, 180, false);
+ else walk_wait(c, 12, 15, 90, 180, false);
+ } else if (r < 1) cit_change_floor_and_wait_random(c, 20, 30, THEN_NONE, 0);
+ else if (r < 3) walk_wait(c, 3, 4, 90, 180, false);
+ else if (r < 5) walk_wait(c, 9, 10, 90, 180, false);
+ else walk_wait(c, 15, 16, 90, 180, false);
+}
+/* knowledge gathered; after the modes and policies (createWindowAddBottomButtons): the unhappiness warnings'
+ * setting, the city's name and its button */
+static void city_hall_window(Perm *p, WinOut *w) {
+ total_window(p, w);
+ win_later(w);
+ win_setting(w, happiness.ignoreUnhappyCitizens, WA_TOGGLE, L_ignore_unhappy_citizens);
+ win_space(w, 4);
+ win_heading(w, L_city_name, -1, -1, false, false, NULL, NULL);
+ win_para(w, FONT_15, city.cityName[0] ? city.cityName : L_unnamed_city, 300, 0);
+ win_button(w, 0, L_change_city_name, WA_UI_CITY_NAME, true);
+ win_space(w, 4);
+}
+static void city_hall_action(Perm *p, int a) {
+ (void)p;
+ if (a == WA_TOGGLE) happiness.ignoreUnhappyCitizens = !happiness.ignoreUnhappyCitizens;
+}
+const PermOps ops_CityHall = {.init = city_hall_init, .destroy = city_hall_destroy, .update = city_hall_update,
+ .work = city_hall_work, .draw = plain_draw, .window = city_hall_window, .window_action = city_hall_action};
+void city_hall_post_create(Perm *p) { (void)p; } /* (its first mode is already there) */
+
+/* ---------------------------------------------------------------- StoneResearchCenter */
+static float stone_bonus(Perm *p) {
+ bool tech = has_upgrade_bit(p, UB_StoneResearchCenter_PickaxeTech);
+ double k = stats.materialProduction[M_KNOWLEDGE][1];
+ double d = tech ? 195 : 200, m = tech ? 0.1 : 0.075, l = tech ? 1.65 : 2;
+ double bonus = k < d ? k / d * 0.15 : log(k / d) / log(l) * m + 0.15;
+ if (tech) bonus += 2.5e-5 * k;
+ int jobs = bld_jobs(p);
+ bonus *= jobs ? (double)p->nworkers / jobs : 0;
+ if (bonus < 0) bonus = 0;
+ upgrades.stoneMiningSpeed = (float)(1.0 + bonus);
+ ST(TotalState, p)->total = (float)bonus; /* currentBonus */
+ return (float)bonus;
+}
+static void stone_center_update(Perm *p, float timeMod) { (void)timeMod; stone_bonus(p); }
+static void stone_center_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ int r = rnd_int(3);
+ if (r == 0) cit_change_floor_and_wait(c, 50, THEN_NONE, 0);
+ else if (r == 1) walk_wait(c, 3, 7, 50, 80, false);
+ else walk_wait(c, 12, 16, 50, 80, false);
+}
+static void stone_center_window(Perm *p, WinOut *w) {
+ win_line1(w, "Current stone mining boost: [0]%", (int)(stone_bonus(p) * 100));
+ win_line(w, "This is based on the number of workers and on yesterday's knowledge production.");
+ if (upgrades.stoneResearchCenterWithFossils == pid(p)) win_line1(w, "Fossils found: [0]", bonuses.fossilsCollected);
+}
+static void stone_center_destroy(Perm *p) {
+ if (upgrades.stoneResearchCenterWithFossils == pid(p)) upgrades.stoneResearchCenterWithFossils = 0;
+}
+const PermOps ops_StoneResearchCenter = {.destroy = stone_center_destroy, .update = stone_center_update,
+ .work = stone_center_work, .draw = plain_draw, .window = stone_center_window};
+void stone_center_post_create(Perm *p) { stone_bonus(p); }
+
+/* ---------------------------------------------------------------- ComputerResearchCenter (a Factory) */
+void factory_work(Perm *p, Cit *c, float timeMod, bool stop);
+static void crc_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer == LAYER_BG) factory_back_any(b, p, x, y, SPR_COMPUTERRESEARCHCENTER_FRAMES, SPR_COMPUTERRESEARCHCENTER_IDLE);
+}
+static void crc_window(Perm *p, WinOut *w) { win_line1(w, "[0] knowledge gathered.", (int)STC(FactoryState, p)->materialMade); }
+const PermOps ops_ComputerResearchCenter = {.work = factory_work, .update = factory_update_any, .draw = crc_draw,
+ .window = crc_window};
+
+/* ---------------------------------------------------------------- LivingResearchCenter */
+static void lrc_walk(Perm *p, Cit *c, float steps) {
+ (void)p, (void)steps;
+ int r = rnd_int(3);
+ if (c->relativeY < 5) cit_change_floor_and_wait_random(c, 30, 60, THEN_NONE, 0);
+ else if (r == 1) {
+ if (rnd_int(2) == 0) walk_wait(c, 3, 7, 30, 60, false);
+ else walk_wait(c, 12, 16, 30, 60, false);
+ } else wait_ticks(c, 90, 120);
+}
+static void lrc_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (c->relativeY < 2) {
+ if (rnd_int(2) == 0) walk_wait(c, 3, 6, 60, 120, true);
+ else walk_wait(c, 13, 14, 60, 120, true);
+ } else if (rnd_int(2) == 0) {
+ walk_wait(c, 3, 15, 60, 120, true);
+ }
+ knowledge(p, 0.10799999999999998f * edu(c) * boost());
+}
+/* knowledge gathered; after the upgrades, the button to upgrade every basic house (ReplaceAllHousesWindow) */
+static void lrc_window(Perm *p, WinOut *w) {
+ total_window(p, w);
+ win_later(w);
+ win_button(w, 0, L_upgrade_basic_houses, WA_UI_REPLACE_HOUSES, true);
+}
+const PermOps ops_LivingResearchCenter = {.work = lrc_work, .walk_around = lrc_walk, .draw = plain_draw, .window = lrc_window};
+
+/* ---------------------------------------------------------------- missions (HackerHQ, SecretSocietyHouse, BlossomHippieHQ) */
+static const char *const hacker_missions[11] = {
+ "Collect the Knowledge:\nBuild twenty Labs.", "Spread the Knowledge:\nBuild three Libraries.",
+ "House the Smart:\nBuild five Tinkerers' Houses.",
+ "Factory Hack:\nResearch the Firmware Modding upgrade at a Refined Metals Factory.",
+ "Try our latest invention:\nBuild a Factory Pub.", "More of the basics:\nProduce at least 20 computer chips in a day.",
+ "Mechanical Party:\nBuild seven Scrapyard Nightclubs.", "Let's have even more fun!\nBuild the Lab Escape Room.",
+ "Watering Cans Are Overrated:\nResearch Automatic Water Management in a Tree Plantation.",
+ "Change the Game:\nBuild two Holo Game Halls.", "Build our Ultimate Invention:\nBuild the Misdirector."};
+static const char *const society_missions[8] = {
+ "Improve Our Home:\nResearch Secretive Living in the Living Research Center.",
+ "Increase Production:\nProduce 1000 Wood in one day.", "Green the City:\nBuild fifty Botanical Gardens.",
+ "Display the Statues:\nBuild twelve Sculpture Gardens.", "Improve Transportation:\nBuild seven Teleporters.",
+ "House the Rich:\nBuild five Villas.", "Know the Hidden:\nGain at least 1000 Knowledge in a day.",
+ "Finish Our Project:\nBuild the Machine."};
+static const char *const hippie_missions[8] = {
+ "Flower Link:\nBuild at least two teleporters each surrounded by Botanical Gardens.",
+ "Flowery Dining:\nBuild three Blossom Restaurants.", "Actual Nature:\nHave at least one protected forest.",
+ "Together in Harmony:\nBuild twenty Community Houses.", "Organicize:\nBuild thirty Eco Farms.",
+ "Don't Waste:\nBuild nine Farm By-Product Processors.",
+ "Peaceful Society:\nResearch Societal Living in the Living Research Center.", "Make the City Sing:\nBuild the Festival HQ."};
+
+typedef struct PACKED {
+ uint8_t mission;
+ uint8_t timeToCheck; /* timeToCheckBuildings (ticks, 0 when due) */
+ int8_t doingEvent;
+ uint8_t eventPhase;
+ uint16_t lastEventDay;
+ uint16_t target; /* SecretSocietyHouse: ownPub; BlossomHippieHQ: eventBotanicalGardens */
+ uint8_t extra; /* SecretSocietyHouse: manyTeleportAlpha x 20; hippies: canLeaveForBG */
+ uint8_t flags; /* SS_* */
+} MissionState;
+STATE_FITS(MissionState);
+enum { SS_STATUE_GIVEN = 1, SS_SCENARIO = 2 };
+static void check_time(MissionState *s, float timeMod) {
+ s->timeToCheck = tick_down(s->timeToCheck, timeMod);
+}
+static void mission_lines(WinOut *w, const MissionState *s, int done, const char *done_text, const char *gather,
+ const char *const *texts, const Perm *p) {
+ win_text(w, s->mission == done ? "Thank You" : "Current Task");
+ if (s->mission >= done) win_text(w, done_text);
+ else if (p->nworkers != bld_jobs(p)) win_text(w, gather);
+ else win_text(w, texts[s->mission]);
+}
+
+/* HackerHQ */
+int hacker_mission(const Perm *p) { return STC(MissionState, p)->mission; }
+static void hacker_check(Perm *p) {
+ MissionState *s = ST(MissionState, p);
+ for (;;) {
+ bool done = false;
+ switch (s->mission) {
+ case 3:
+ done = unlock_state_name("RefinedMetalsFactoryHack") == UNLOCK_RESEARCHED;
+ if (done) unlocks_unlock("FactoryPub");
+ break;
+ case 5:
+ done = any_day_at_least(M_COMPUTERCHIPS, 20);
+ if (done) unlocks_unlock("ScrapyardNightClub");
+ break;
+ case 8:
+ done = unlock_state_name("AutomaticWaterManagement") == UNLOCK_RESEARCHED;
+ if (done) unlocks_unlock("HoloGameHall");
+ break;
+ default:
+ if (s->timeToCheck == 0 && s->mission != 11) {
+ switch (s->mission) {
+ case 0:
+ done = count_class(CLS_Laboratory) + count_class(CLS_ExperimentationLab) >= 20;
+ if (done) unlocks_unlock("Library");
+ break;
+ case 1:
+ done = count_class(CLS_Library) >= 3;
+ if (done) unlocks_unlock("TinkerersHome");
+ break;
+ case 2:
+ done = count_class(CLS_TinkerersHome) >= 5;
+ if (done) unlocks_unlock("RefinedMetalsFactoryHack");
+ break;
+ case 4: done = count_class(CLS_FactoryPub) >= 1; break;
+ case 6:
+ done = count_class(CLS_ScrapyardNightClub) >= 7;
+ if (done) unlocks_unlock("EscapeRoom");
+ break;
+ case 7:
+ done = count_class(CLS_EscapeRoom) >= 1;
+ if (done) unlocks_unlock("AutomaticWaterManagement");
+ break;
+ case 9:
+ done = count_class(CLS_HoloGameHall) >= 2;
+ if (done) unlocks_unlock("Misdirector");
+ break;
+ case 10: done = count_class(CLS_Misdirector) >= 1; break;
+ }
+ s->timeToCheck = 30;
+ }
+ }
+ if (!done) break;
+ s->mission++;
+ s->timeToCheck = 0;
+ }
+}
+static void hacker_update(Perm *p, float timeMod) {
+ hacker_check(p);
+ check_time(ST(MissionState, p), timeMod);
+}
+static void hacker_walk_around(Perm *p, Cit *c, float steps) {
+ (void)p, (void)steps;
+ static const int8_t pos[4] = {3, 9, 12, 13};
+ if (c->relativeY > 5) {
+ if (rnd_int(4) == 1 && c->relativeX > 5) cit_change_floor(c, THEN_NONE, 0);
+ else {
+ int x = pos[rnd_int(4)];
+ cit_move_and_wait(c, x, rnd_between(60, 120), THEN_NONE, 0, false, false);
+ }
+ } else if (rnd_int(4) == 1) cit_change_floor(c, THEN_NONE, 0);
+ else if (rnd_int(3) == 1) walk_wait(c, 5, 7, 90, 150, false);
+ else walk_wait(c, 9, 15, 60, 150, false);
+}
+static void hacker_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ hacker_walk_around(p, c, 150);
+}
+static void hacker_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ plain_draw(b, p, layer, x, y);
+ /* the bolt, lit around 2:00 (not on the ground floor) */
+ if (layer == LAYER_MAIN && p->row != 0) {
+ int h = ((int)city.timeSinceStart / 60) % 24;
+ if (h < 4) {
+ float a = 4.0f - 4.0f * fabsf(1.0f - hour_now() / 2.0f);
+ a = a < 0 ? 0 : a > 1 ? 1 : a;
+ if (a > 0) dr_sprite(b, SPR_HACKERS_BOLT, x, y, 12, 11, 0, (uint8_t)(a * 255));
+ }
+ }
+}
+static void hacker_window(Perm *p, WinOut *w) {
+ mission_lines(w, STC(MissionState, p), 11, "We'll keep on hacking!", "Gather the Hackers:\nMake sure all 6 jobs are filled.",
+ hacker_missions, p);
+}
+const PermOps ops_HackerHQ = {.update = hacker_update, .work = hacker_work, .walk_around = hacker_walk_around,
+ .draw = hacker_draw, .window = hacker_window};
+
+/* SecretSocietyHouse */
+void key_friends_walk_around(Perm *p, Cit *c, float steps);
+static void society_init(Perm *p) {
+ MissionState *s = ST(MissionState, p);
+ s->doingEvent = -1;
+ if (story_is("cityofthekey")) s->flags |= SS_SCENARIO;
+}
+static void society_on_build(Perm *p) { (void)p; unlocks_unlock("SecretiveLiving"); }
+static void society_check(Perm *p) {
+ MissionState *s = ST(MissionState, p);
+ for (;;) {
+ bool done = false;
+ switch (s->mission) {
+ case 0: done = city_upgrade_bought(U_SecretiveLiving); break;
+ case 1: done = any_day_at_least(M_WOOD, 1000); break;
+ case 6:
+ done = any_day_at_least(M_KNOWLEDGE, 1000);
+ if (done) unlocks_unlock("TheMachine");
+ break;
+ }
+ if (s->mission != 0 && s->mission != 1 && s->mission != 6 && s->mission < 8 && s->timeToCheck == 0) {
+ switch (s->mission) {
+ case 2:
+ done = count_class(CLS_BotanicalGardens) >= 50;
+ if (done) unlocks_unlock("StatueGarden");
+ break;
+ case 3: done = count_class(CLS_StatueGarden) >= 12; break;
+ case 4:
+ done = count_class(CLS_Teleporter) >= 7;
+ if (done) unlocks_unlock("Villa");
+ break;
+ case 5: done = count_class(CLS_Villa) >= 5; break;
+ case 7: done = count_class(CLS_TheMachine) >= 1; break;
+ }
+ s->timeToCheck = 30;
+ }
+ if (!done) break;
+ s->mission++;
+ s->timeToCheck = 0;
+ }
+}
+static void society_update(Perm *p, float timeMod) {
+ MissionState *s = ST(MissionState, p);
+ if (s->doingEvent == 1 && s->eventPhase >= 1) {
+ /* the members fade in after the mass teleport */
+ if (s->extra < 20) s->extra++;
+ else s->doingEvent = -1, s->eventPhase = 0;
+ }
+ if (!(s->flags & SS_SCENARIO)) society_check(p);
+ check_time(s, timeMod);
+ if (!(s->flags & SS_STATUE_GIVEN)) {
+ uint16_t id = pid(p);
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job == id && cit_age(&cits[i]) >= 500) {
+ unlocks_unlock("StatueOfTheKey");
+ s->flags |= SS_STATUE_GIVEN;
+ break;
+ }
+ }
+}
+typedef bool (*IsGoal)(const Perm *p, const void *ctx);
+typedef float (*Niceness)(const Perm *p);
+uint16_t finder_quick_query(const Cit *c, IsGoal is_goal, const void *ctx, uint8_t key, float expiry_hours, Niceness niceness,
+ float max_distance);
+uint16_t finder_query(uint16_t from, int from_world, float from_x, IsGoal is_goal, const void *ctx, Niceness niceness,
+ float max_distance, const Cit *citizen, float best_expected);
+static bool goal_teleporter(const Perm *p, const void *ctx) { (void)ctx; return p->cls == CLS_Teleporter; }
+static bool goal_unmarked_pub(const Perm *p, const void *ctx) { (void)ctx; return p->cls == CLS_Pub && !STC(PubState, p)->marked; }
+static uint8_t TH_SOCIETY_FAIL;
+static void th_society_fail(Cit *c, uint16_t arg) {
+ (void)arg;
+ Perm *h = P(c->job);
+ if (h && h->cls == CLS_SecretSocietyHouse) ST(MissionState, h)->doingEvent = -1;
+}
+static void society_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ MissionState *s = ST(MissionState, p);
+ uint16_t id = pid(p);
+ if (s->doingEvent == 1) {
+ if (s->eventPhase == 0) {
+ /* all members standing at a teleporter: they all come out on the house's world */
+ bool all = true;
+ for (int i = 1; i < MAX_CITS && all; i++) {
+ Cit *w = &cits[i];
+ if (!(w->flags & CF_ALIVE) || w->job != id) continue;
+ Perm *in = P(w->inPermanent);
+ if (!in || in->cls != CLS_Teleporter || w->relativeX != 9 || (w->flags & (CF_HAS_PATH | CF_REQUESTING_PATH))) all = false;
+ }
+ if (all) {
+ s->eventPhase = 1;
+ s->extra = 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *w = &cits[i];
+ if (!(w->flags & CF_ALIVE) || w->job != id) continue;
+ Perm *in = P(w->inPermanent);
+ if (in) {
+ particle_add(SPR_TELEPORTER_RAY_KEY, 4, perm_city_x(in) + 8, perm_city_y(in) + 4);
+ transport_teleport_used(in);
+ leave_to_surface(w);
+ }
+ w->onWorld = p->world;
+ set_rel(w, (float)rnd_int(worlds[p->world].w - 2), 0);
+ }
+ } else if (!c->inPermanent || P(c->inPermanent)->cls != CLS_Teleporter) {
+ uint16_t tp = finder_quick_query(c, goal_teleporter, NULL, (uint8_t)(200 + (id & 31)), 3, NULL, -1);
+ if (!tp) s->doingEvent = -1;
+ else path_find(c, tp, THEN_NONE);
+ } else {
+ step_to_x(c, transport_teleport_x(P(c->inPermanent)), timeMod);
+ }
+ }
+ return;
+ }
+ if (s->doingEvent == 2) {
+ Perm *pub = P(s->target);
+ if (pub && pub->cls != CLS_Pub) pub = NULL, s->target = 0;
+ if (pub && c->inPermanent == s->target) {
+ if (!STC(PubState, pub)->marked) pub_set_marking(pub, true);
+ int h = ((int)city.timeSinceStart / 60) % 24;
+ if (h >= 5 && h < 10) s->doingEvent = -1;
+ else ent_be_entertained(pub, c, timeMod);
+ return;
+ }
+ bool no_pubs = true;
+ if (!pub) {
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *q = &perms[i];
+ if (!(q->flags & PF_USED) || q->cls != CLS_Pub) continue;
+ if (STC(PubState, q)->marked) {
+ s->target = (uint16_t)i;
+ pub = q;
+ break;
+ }
+ no_pubs = false;
+ }
+ }
+ if (!pub && !no_pubs) {
+ uint16_t np = finder_quick_query(c, goal_unmarked_pub, NULL, (uint8_t)(232 + (id & 15)), 3, NULL, -1);
+ if (!np) s->doingEvent = -1;
+ else s->target = np, pub = P(np);
+ }
+ if (pub) path_find(c, s->target, TH_SOCIETY_FAIL);
+ return;
+ }
+ if (c->inPermanent != id) {
+ path_find(c, id, THEN_NONE);
+ return;
+ }
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ key_friends_walk_around(p, c, 150);
+ int h = ((int)city.timeSinceStart / 60) % 24;
+ if (h > 15 && day_number() > s->lastEventDay) {
+ s->doingEvent = (int8_t)rnd_between(1, 3);
+ if (s->doingEvent == 1 && (worlds[p->world].h == 0 || worlds[p->world].surfaceShard != p->shard)) s->doingEvent = 2;
+ s->eventPhase = 0;
+ s->lastEventDay = (uint16_t)day_number();
+ }
+}
+static void society_window(Perm *p, WinOut *w) {
+ const MissionState *s = STC(MissionState, p);
+ if (s->flags & SS_SCENARIO) return;
+ mission_lines(w, s, 8, "We will be forever grateful.", "Give us the followers we need:\nMake sure all 8 jobs are filled.",
+ society_missions, p);
+}
+const PermOps ops_SecretSocietyHouse = {.init = society_init, .on_build = society_on_build, .update = society_update,
+ .work = society_work, .walk_around = key_friends_walk_around, .draw = plain_draw,
+ .window = society_window};
+
+/* BlossomHippieHQ */
+static void hippie_init(Perm *p) { ST(MissionState, p)->doingEvent = -1; }
+static bool any_protected_forest(void) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_a(&perms[i], B_FOREST) && STC(LimitedState, &perms[i])->managementMode == 1) return true;
+ return false;
+}
+static bool garden_at(const Perm *q) { return q && class_is(q->cls, CLS_BotanicalGardens); }
+static void hippie_check(Perm *p) {
+ MissionState *s = ST(MissionState, p);
+ for (;;) {
+ bool done = false;
+ switch (s->mission) {
+ case 0: {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const Perm *t = &perms[i];
+ if (!(t->flags & PF_USED) || t->cls != CLS_Teleporter) continue;
+ if (garden_at(P(t->left)) && garden_at(P(t->right)) && garden_at(P(t->bottom)) && garden_at(P(t->top))) n++;
+ }
+ if (n >= 2) {
+ done = true;
+ unlocks_unlock("BlossomRestaurant");
+ }
+ break;
+ }
+ case 2:
+ if (any_protected_forest()) {
+ done = true;
+ unlocks_unlock("FarmHouse");
+ }
+ break;
+ case 6:
+ done = city_upgrade_bought(U_SuperSpaciousLiving);
+ if (done) unlocks_unlock("FestivalHQ");
+ break;
+ }
+ if (s->timeToCheck == 0 && s->mission != 0 && s->mission != 2 && s->mission != 6 && s->mission != 8) {
+ switch (s->mission) {
+ case 1: done = count_class(CLS_BlossomRestaurant) >= 3; break;
+ case 3: done = count_class(CLS_FarmHouse) >= 20; break;
+ case 4:
+ done = count_class(CLS_EcoFarm) >= 30;
+ if (done) unlocks_unlock("FarmByProductProcessor");
+ break;
+ case 5:
+ done = count_class(CLS_FarmByProductProcessor) >= 9;
+ if (done) unlocks_unlock("SuperSpaciousLiving");
+ break;
+ case 7: done = count_class(CLS_FestivalHQ) >= 1; break;
+ }
+ s->timeToCheck = 30;
+ }
+ if (!done) break;
+ s->mission++;
+ s->timeToCheck = 0;
+ }
+}
+static void hippie_update(Perm *p, float timeMod) {
+ MissionState *s = ST(MissionState, p);
+ hippie_check(p);
+ check_time(s, timeMod);
+ s->extra = tick_down(s->extra, timeMod); /* canLeaveForBG */
+}
+static void hippie_walk(Perm *p, Cit *c, float steps) {
+ (void)p, (void)steps;
+ if (c->relativeX < 7 && rnd_float() < 0.3f) cit_change_floor_and_wait_random(c, 10, 30, THEN_NONE, 0);
+ else if (c->relativeY > 5 || rnd_float() > 0.5f) walk_wait(c, 3, 7, 60, 180, false);
+ else walk_wait(c, 12, 16, 60, 180, false);
+}
+static bool goal_tree_garden(const Perm *p, const void *ctx) {
+ (void)ctx;
+ return garden_at(p) && (!p->bottom || !garden_at(P(p->bottom))) && garden_is_tree(p);
+}
+static uint8_t TH_HIPPIE_FAIL;
+static void th_hippie_fail(Cit *c, uint16_t arg) {
+ (void)arg;
+ Perm *h = P(c->job);
+ if (h && h->cls == CLS_BlossomHippieHQ) ST(MissionState, h)->doingEvent = -1;
+}
+static void hippie_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ MissionState *s = ST(MissionState, p);
+ Perm *in = P(c->inPermanent);
+ if (garden_at(in) && garden_is_tree(in)) {
+ /* the daily climb: up the tree to the top of the stack, then down again */
+ if (s->eventPhase != 0) {
+ c->relativeY -= 0.4f * timeMod;
+ if (c->relativeY <= 0) {
+ if (garden_at(P(in->bottom))) {
+ c->relativeY += 20;
+ c->inPermanent = in->bottom;
+ return;
+ }
+ c->relativeY = 0;
+ s->doingEvent = -1;
+ } else {
+ return;
+ }
+ } else {
+ float spd = c->pathWalkSpeed / 100.0f * timeMod;
+ if (fabsf(9 - c->relativeX) >= spd) {
+ c->relativeX += (9 > c->relativeX ? 1 : -1) * spd;
+ return;
+ }
+ c->relativeX = 9;
+ c->relativeY += 0.4f * timeMod;
+ if (c->relativeY >= 10) {
+ if (garden_at(P(in->top))) {
+ c->relativeY -= 20;
+ c->inPermanent = in->top;
+ } else {
+ s->eventPhase = 1;
+ }
+ }
+ return;
+ }
+ } else if (s->doingEvent != -1) {
+ c->relativeY = 0;
+ if (!garden_at(P(s->target))) s->target = finder_query(pid(p), 0, 0, goal_tree_garden, NULL, NULL, -1, NULL, 1e8f);
+ if (s->target) {
+ if (s->extra == 0) {
+ path_find(c, s->target, TH_HIPPIE_FAIL);
+ s->extra = 20;
+ }
+ return;
+ }
+ s->doingEvent = -1;
+ }
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (c->inPermanent != pid(p)) {
+ c->relativeY = 0;
+ path_find(c, pid(p), THEN_NONE);
+ return;
+ }
+ hippie_walk(p, c, 150);
+ int h = ((int)city.timeSinceStart / 60) % 24;
+ if (h > 10 && day_number() > s->lastEventDay) {
+ s->doingEvent = 1;
+ s->eventPhase = 0;
+ s->lastEventDay = (uint16_t)day_number();
+ }
+}
+static void hippie_window(Perm *p, WinOut *w) {
+ const MissionState *s = STC(MissionState, p);
+ mission_lines(w, s, 8, "Peace out!", "Open the Flower Buds:\nMake sure all 6 jobs are filled.", hippie_missions, p);
+ if (s->mission == 2) win_button(w, 0, "... or bribe the Hippies and skip this\ntask for 10,000 food", WA_SPECIAL, true);
+}
+static void hippie_action(Perm *p, int a) {
+ MissionState *s = ST(MissionState, p);
+ if (a == WA_SPECIAL && s->mission == 2 && city.materials.m[M_FOOD] >= 10000) {
+ s->mission = 3;
+ unlocks_unlock("FarmHouse");
+ city.materials.m[M_FOOD] -= 10000;
+ }
+}
+const PermOps ops_BlossomHippieHQ = {.init = hippie_init, .update = hippie_update, .work = hippie_work, .walk_around = hippie_walk,
+ .draw = plain_draw, .window = hippie_window, .window_action = hippie_action};
+
+/* the missions a building gives (getGlobalGoal), for the user interface's list of goals */
+bool bld_global_goal(const Perm *p, const char **category, const char **text) {
+ const MissionState *s = STC(MissionState, p);
+ switch (p->cls) {
+ case CLS_HackerHQ:
+ if (s->mission == 11) return false;
+ *category = "Hackers Mission";
+ *text = s->mission >= 11 ? "We'll keep on hacking!" : p->nworkers != bld_jobs(p) ? "Gather the Hackers:\nMake sure all 6 jobs are filled." : hacker_missions[s->mission];
+ return true;
+ case CLS_SecretSocietyHouse:
+ if (s->mission == 8 || (s->flags & SS_SCENARIO)) return false;
+ *category = "Secret Society Mission";
+ *text = p->nworkers != bld_jobs(p) ? "Give us the followers we need:\nMake sure all 8 jobs are filled." : society_missions[s->mission];
+ return true;
+ case CLS_BlossomHippieHQ:
+ if (s->mission == 8) return false;
+ *category = "Hippie Mission";
+ *text = p->nworkers != bld_jobs(p) ? "Open the Flower Buds:\nMake sure all 6 jobs are filled." : hippie_missions[s->mission];
+ return true;
+ default: return false;
+ }
+}
+
+/* ---------------------------------------------------------------- AlienDecryptor */
+float decryptor_time_working(const Perm *p) { return STC(TotalState, p)->total; }
+static void decryptor_update(Perm *p, float timeMod) { ST(TotalState, p)->total += timeMod * city.minutesPerTick; }
+const PermOps ops_AlienDecryptor = {.update = decryptor_update, .draw = plain_draw};
+
+/* ---------------------------------------------------------------- EscapeRoom */
+#define CF_ESCAPE_PLAYER 0x8000
+enum { ER_START, ER_FIRST, ER_SECOND, ER_THIRD, ER_LASERS, ER_LAST, ER_DONE };
+typedef struct PACKED { uint8_t phase; float progress; } EscapeState;
+static int players(const Perm *p, int *index_of, const Cit *who) {
+ int n = 0;
+ uint16_t id = pid(p);
+ for (int i = 1; i < MAX_CITS; i++) {
+ const Cit *c = &cits[i];
+ if ((c->flags & CF_ALIVE) && (c->flags & CF_ESCAPE_PLAYER) && c->inPermanent == id) {
+ if (c == who && index_of) *index_of = n;
+ n++;
+ }
+ }
+ return n;
+}
+static float escape_capacity(const Perm *p) { return p->nworkers * 120.0f; }
+static bool escape_open(const Perm *p) {
+ return p->nworkers == 1 && first_worker_working(p) && hour_now() < 23.99f && players(p, NULL, NULL) < 10;
+}
+static bool escape_open_existing(const Perm *p) { return p->nworkers == 1 && first_worker_working(p); }
+static bool escape_finish(Perm *p, Cit *c, float timeMod) {
+ (void)timeMod;
+ int n = players(p, NULL, NULL);
+ if (!(n < 5 || !(c->flags & CF_ESCAPE_PLAYER) || STC(EscapeState, p)->phase == ER_DONE)) return !escape_open_existing(p);
+ return true;
+}
+static void escape_reset(Perm *p) {
+ EscapeState *s = ST(EscapeState, p);
+ s->phase = ER_START;
+ s->progress = 0;
+}
+static void escape_be_entertained(Perm *p, Cit *c, float timeMod) {
+ EscapeState *s = ST(EscapeState, p);
+ if (!(c->flags & CF_BUILDING_INITED)) {
+ if (!(c->flags & CF_ESCAPE_PLAYER)) {
+ if (players(p, NULL, NULL) > 10) {
+ c->flags &= (uint16_t)~CF_ENT_INITED; /* entertainment.stop() */
+ return;
+ }
+ c->flags |= CF_ESCAPE_PLAYER;
+ }
+ c->flags |= CF_BUILDING_INITED;
+ }
+ if (s->phase == ER_DONE) {
+ c->flags &= (uint16_t)~CF_ENT_INITED;
+ return;
+ }
+ int idx = 0, n = players(p, &idx, c);
+ if (n < 5) {
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 7, 16, 50, 70, false);
+ } else if (s->phase == ER_START) {
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 7, 16, 50, 70, false);
+ if (n < 8 && s->progress < 1) s->progress += 0.02f * timeMod;
+ else s->phase = ER_FIRST, s->progress = 0;
+ } else if (s->phase == ER_FIRST) {
+ if (c->relativeY < 5 && c->relativeX > 2 && c->relativeX < 7) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else {
+ walk_wait(c, 3, 6, 30, 60, false);
+ if (rnd_float() < 0.2f) {
+ s->progress += 0.2f;
+ if (s->progress > 1) s->phase = ER_SECOND, s->progress = 0;
+ }
+ }
+ } else if (s->phase == ER_SECOND) {
+ if (idx % 2 == 0) {
+ if (c->relativeY > 5) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else {
+ walk_wait(c, 3, 16, 50, 120, false);
+ if (rnd_float() < 0.3f) {
+ s->progress += 0.34f;
+ if (s->progress > 1) s->phase = ER_THIRD, s->progress = 0;
+ }
+ }
+ } else if (c->relativeY < 5 && c->relativeX > 2 && c->relativeX < 7) {
+ cit_change_floor(c, THEN_NONE, 0);
+ } else {
+ walk_wait(c, 3, 6, 30, 60, false);
+ }
+ } else if (s->phase == ER_THIRD) {
+ if (c->relativeY > 5) cit_change_floor(c, THEN_NONE, 0);
+ else if (c->relativeX > 4) move_x(c, rnd_between(3, 5));
+ } else if (s->phase == ER_LAST) {
+ if (c->relativeY < 5 && c->relativeX > 11 && c->relativeX < 16) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 11, 16, 20, 60, false);
+ }
+}
+static void escape_update(Perm *p, float timeMod) {
+ EscapeState *s = ST(EscapeState, p);
+ uint16_t id = pid(p);
+ if (s->phase == ER_DONE) {
+ s->progress += 0.02f * timeMod;
+ if (s->progress >= 1) escape_reset(p);
+ } else if (s->phase == ER_THIRD || s->phase == ER_LAST) {
+ bool all = true;
+ for (int i = 1; i < MAX_CITS && all; i++) {
+ const Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_ESCAPE_PLAYER) || c->inPermanent != id) continue;
+ if (s->phase == ER_THIRD ? !(c->relativeY < 5 && c->relativeX < 5) : !(c->relativeY > 5 && c->relativeX > 11)) all = false;
+ }
+ if (all) s->phase = s->phase == ER_THIRD ? ER_LASERS : ER_DONE, s->progress = 0;
+ }
+ if (s->phase == ER_LASERS) {
+ s->progress += 0.01f * timeMod;
+ if (s->progress >= 1) s->progress = 0, s->phase = ER_LAST;
+ }
+}
+static void escape_leave(Perm *p, Cit *c, uint16_t to) {
+ (void)p, (void)to;
+ c->flags &= (uint16_t)~CF_ESCAPE_PLAYER; /* onCitizenLeave: off the players' list */
+}
+static void escape_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) {
+ c->currentAction = 2;
+ escape_reset(p);
+ } else {
+ step_to_x(c, 3, timeMod);
+ }
+}
+static void escape_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ plain_draw(b, p, layer, x, y);
+ /* the lasers: a red line from x 7 to 16 at y 13 */
+ if (layer == LAYER_BG && STC(EscapeState, p)->phase == ER_LASERS)
+ for (int z = 0; z < b->zoom; z++) gfx_band_span(b, y + 13 * b->zoom + z, x + 7 * b->zoom, x + 17 * b->zoom, rgb565(0xFF0000), 179);
+}
+const PermOps ops_EscapeRoom = {.update = escape_update, .work = escape_work, .is_open = escape_open,
+ .is_open_for_existing_visitors = escape_open_existing, .finish_entertainment = escape_finish,
+ .be_entertained = escape_be_entertained, .on_citizen_leave = escape_leave,
+ .entertainment_capacity = escape_capacity, .draw = escape_draw};
+
+/* ---------------------------------------------------------------- Misdirector */
+typedef struct PACKED { uint16_t timesUsed, timesUsedTo; float knowledgeGenerated; } MisdirectorState;
+static void misdirector_init(Perm *p) { upgrade_first_mode(p); }
+uint16_t bld_misdirector(void) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == CLS_Misdirector) return (uint16_t)i;
+ return NONE;
+}
+bool bld_is_misdirector(const Perm *p) { return p && p->cls == CLS_Misdirector; }
+float bld_misdirect_chance(void) {
+ Perm *m = P(bld_misdirector());
+ if (!m) return 0;
+ switch (m->mode) {
+ case MODE_Misdirector_MisdirectorNormal: return 0.025f;
+ case MODE_Misdirector_MisdirectorAlways: return 1;
+ case MODE_Misdirector_MisdirectorMostlyDisabled: return 0.001f;
+ default: return 0;
+ }
+}
+void bld_misdirector_reward(Perm *p) {
+ if (!bld_is_misdirector(p)) return;
+ float k = p->mode == MODE_Misdirector_MisdirectorAlways ? 0.05f : 0.5f;
+ produce(M_KNOWLEDGE, k);
+ ST(MisdirectorState, p)->knowledgeGenerated += k;
+ particle_add(SPR_TELEPORTER_RAY_MISDIRECT, 4, perm_city_x(p) + 8, perm_city_y(p) + 4);
+}
+static void misdirector_window(Perm *p, WinOut *w) {
+ win_line1(w, "Misdirected [0] times.", STC(MisdirectorState, p)->timesUsedTo);
+ win_line1(w, "[0] knowledge generated.", floorf(STC(MisdirectorState, p)->knowledgeGenerated));
+}
+static void misdirector_on_build(Perm *p) { (void)p; operating_cost_recalculate(); }
+const PermOps ops_Misdirector = {.init = misdirector_init, .on_build = misdirector_on_build, .draw = plain_draw,
+ .window = misdirector_window};
+
+/* ---------------------------------------------------------------- TheMachine */
+static const uint8_t machine_mats[9] = {M_WOOD, M_STONE, M_FOOD, M_MACHINEPARTS, M_KNOWLEDGE, M_REFINEDMETAL, M_COMPUTERCHIPS,
+ M_GRAPHENE, M_ROCKETFUEL};
+static struct { float today[9], total[9]; int lastDay; } machine; /* (one Machine: it is unique) */
+static void set9(float *m, float a, float b, float c, float d, float e, float f, float g) {
+ memset(m, 0, sizeof(float) * 9);
+ m[0] = a, m[1] = b, m[2] = c, m[3] = d, m[4] = e, m[5] = f, m[6] = g; /* Materials(wood, stone, food, mp, k, rm, cc) */
+}
+static int ri(int a, int b) { return rnd_between(a, b); }
+static void machine_reward(Perm *p) {
+ float *m = machine.today;
+ switch (rnd_int(10)) {
+ case 0: set9(m, ri(150, 301), 0, 0, 0, 0, 0, 0); break;
+ case 1: set9(m, 0, ri(100, 501), 0, 0, 0, 0, 0); break;
+ case 2: set9(m, 0, 0, ri(200, 2001), 0, 0, 0, 0); break;
+ case 3: {
+ float a = ri(100, 301), b = ri(50, 301), c = ri(25, 201);
+ set9(m, a, b, c, 0, 0, 0, 0);
+ break;
+ }
+ case 4: {
+ float a = ri(100, 201), b = ri(150, 251);
+ set9(m, a, b, 0, 0, 0, 0, 0);
+ break;
+ }
+ case 5: set9(m, 0, 0, 0, ri(20, 31), 0, 0, 0); break;
+ case 6: set9(m, 0, 0, 0, 0, 0, ri(40, 81), 0); break;
+ case 7: set9(m, 0, 0, 0, 0, 0, 0, ri(5, 11)); break;
+ case 8: {
+ float a = ri(15, 31), b = ri(20, 51);
+ set9(m, 0, 0, 0, a, 0, b, 0);
+ break;
+ }
+ default:
+ switch (rnd_int(5)) {
+ case 0: {
+ float a = ri(500, 1501), b = ri(1000, 2001);
+ set9(m, a, 0, b, 0, 0, 0, 0);
+ break;
+ }
+ case 1: set9(m, 0, 0, 0, 0, ri(500, 1501), 0, 0); break;
+ case 2: {
+ float a = ri(1000, 2001), b = ri(50, 101);
+ set9(m, 0, a, 0, b, 0, 0, 0);
+ break;
+ }
+ case 3: set9(m, 0, 0, 0, 0, 0, ri(200, 301), 0); break;
+ default:
+ switch (rnd_int(5)) {
+ case 0: set9(m, 1000, 0, 1000, 20, 0, 40, 16); break;
+ case 1: set9(m, 0, 0, 0, 0, 0, 0, 100); break;
+ case 2: set9(m, 0, 0, 0, 0, 0, 1000, 0); break;
+ case 3: set9(m, 0, 10000, 0, 0, 0, 0, 0); break;
+ default: set9(m, 1000, 1000, 1000, 500, 0, 0, 0); break;
+ }
+ }
+ }
+ if (has_upgrade_bit(p, UB_TheMachine_TheMachineUpgrade)) {
+ for (int i = 0; i < 9; i++) m[i] *= 1.5f;
+ int r = rnd_int(100);
+ if (r == 0) m[7] = 50;
+ else if (r == 1) m[8] = 500;
+ else if (r < 5) m[7] = ri(5, 16);
+ else if (r < 10) m[8] = ri(100, 301);
+ else if (r < 20) m[7] = ri(1, 4);
+ else if (r < 30) m[8] = ri(10, 50);
+ }
+ /* (ConnectedMachines needs several connected cities: one here) */
+ for (int i = 0; i < 9; i++) {
+ m[i] = floorf(m[i] * boost() + 0.5f);
+ if (m[i]) mat_add(machine_mats[i], m[i]);
+ machine.total[i] += m[i];
+ }
+ machine.lastDay = day_number();
+}
+static void machine_update(Perm *p, float timeMod) {
+ (void)timeMod;
+ /* members of the Society and its friends live forever */
+ Perm *society = first_class(CLS_SecretSocietyHouse), *friends = first_class(CLS_HouseOfTheKeyFriends);
+ Perm *feather = first_class(CLS_FeatherAlliance);
+ float extra = has_upgrade_bit(p, UB_TheMachine_TheMachineUpgrade) ? 20 : 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ if ((society && c->job == pid(society)) || (friends && c->home == pid(friends))) {
+ float v = (cit_age(c) - 75 + 3 + extra) * 100;
+ c->dieAgeModifier = (int16_t)(v > 32000 ? 32000 : v < -32000 ? -32000 : v);
+ }
+ if (feather && c->home == pid(feather) && c->dieAgeModifier < 5000) c->dieAgeModifier = 5000;
+ }
+ if (machine.lastDay != day_number()) machine_reward(p);
+}
+static void machine_on_build(Perm *p) { machine_reward(p); }
+static void machine_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer != LAYER_BG) return;
+ int n = frames_of(SPR_SECRETSOCIETYMACHINE_ANIM, 20), len = n * 4 * 2 + 480 + 180;
+ float t = fmodf(bld_anim, (float)len);
+ int f;
+ if (t < 480) f = ((int)t / 4) % 2;
+ else if (t - 480 - 180 > n * 4) f = n - 1 - (int)(t - n * 4 - 480 - 180) / 4;
+ else if (t - 480 > n * 4) f = n - 1;
+ else f = (int)(t - 480) / 4;
+ f = f < 0 ? 0 : f > n - 1 ? n - 1 : f;
+ dr_frame(b, SPR_SECRETSOCIETYMACHINE_ANIM, 20, f, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+static void machine_window(Perm *p, WinOut *w) {
+ (void)p;
+ float a[M_COUNT] = {0}, t[M_COUNT] = {0};
+ for (int i = 0; i < 9; i++) a[machine_mats[i]] = machine.today[i], t[machine_mats[i]] = machine.total[i];
+ win_text(w, "Today's Production:");
+ win_cost(w, a);
+ win_text(w, "Total Production:");
+ win_cost(w, t);
+ int h = ((int)city.timeSinceStart / 60) % 24;
+ if (h == 23) win_line(w, "Next production in 1 hour.");
+ else win_line1(w, "Next production in [0] hours.", 24 - h);
+}
+const PermOps ops_TheMachine = {.on_build = machine_on_build, .update = machine_update, .draw = machine_draw,
+ .window = machine_window};
+
+/* ---------------------------------------------------------------- Supercomputer, FossilMuseum, Beacon */
+static float supercomputer_per_day(void) { return 2.0f * stats.peopleWorkingAtLabs * (1 + upgrades.superComputerUpgrade); }
+static void supercomputer_update(Perm *p, float timeMod) {
+ knowledge(p, timeMod * (supercomputer_per_day() / (1440 / city.minutesPerTick)) * boost());
+}
+static void supercomputer_window(Perm *p, WinOut *w) {
+ win_line1(w, "[0] knowledge gathered per day.", (int)supercomputer_per_day());
+ win_line1(w, "[0] knowledge gathered so far.", (int)STC(TotalState, p)->total);
+}
+const PermOps ops_Supercomputer = {.update = supercomputer_update, .draw = plain_draw, .window = supercomputer_window};
+
+static uint8_t TH_FOSSIL_MOVE;
+static void th_fossil_move(Cit *c, uint16_t arg) {
+ (void)arg;
+ if (c->relativeY < 5) move_x_slow(c, rnd_between(12, 16)); /* (getFloat() < 1: always) */
+ else move_x_slow(c, rnd_between(4, 15));
+}
+static bool fossil_open(const Perm *p) {
+ bool any = false;
+ uint16_t id = pid(p);
+ for (int i = 1; i < MAX_CITS && !any; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job == id && cits[i].currentAction == 0) any = true;
+ return p->nworkers >= 1 && any && hours_in(hour_now(), 14 - 0.5f, 23);
+}
+static float zero_capacity(const Perm *p) { (void)p; return 0; }
+static void fossil_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (rnd_int(2) == 1) cit_change_floor(c, TH_FOSSIL_MOVE, 0);
+ else cit_wait_random(c, 120, 180, TH_FOSSIL_MOVE, 0);
+ educate(c, 0.035f, 1.61f);
+}
+static void fossil_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ switch (worker_index(c)) {
+ case 0:
+ step_to_x(c, 6, timeMod);
+ knowledge(p, 0.001f * bonuses.fossilsCollected * timeMod * speed() * edu(c) * boost() * p->nworkers);
+ break;
+ case 1: walk_wait(c, 12, 16, 120, 180, false); break;
+ case 2:
+ if (c->relativeY < 5) cit_change_floor(c, THEN_NONE, 0);
+ else walk_wait(c, 4, 16, 120, 180, false);
+ break;
+ }
+}
+const PermOps ops_FossilMuseum = {.work = fossil_work, .is_open = fossil_open, .entertainment_capacity = zero_capacity,
+ .be_entertained = fossil_be_entertained, .draw = plain_draw, .window = total_window};
+
+/* the Beacon declares itself entertainment but never sets isEntertainment: never visited, its capacity still counts */
+static void beacon_init(Perm *p) { p->flags &= (uint8_t)~PF_IS_ENTERTAINMENT; }
+static float beacon_capacity(const Perm *p) { (void)p; return 50; }
+static void beacon_be_entertained(Perm *p, Cit *c, float timeMod) {
+ (void)p, (void)timeMod;
+ if (rnd_float() < 0.5f) walk_wait(c, 4, 8, 60, 90, false);
+ else walk_wait(c, 11, 15, 60, 90, false);
+}
+static void beacon_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ draw_normal(b, p, layer, x, y, PC(p)->sprite, false);
+ if (layer != LAYER_MAIN) return;
+ int h = ((int)city.timeSinceStart / 60) % 24;
+ float t = hour_now(), a;
+ if (h < 6 || h > 20.5f) a = 1;
+ else if (h < 6.5f) a = (6.5f - t) * 2;
+ else if (h > 20) a = (t - 20) * 2;
+ else a = 0;
+ if (a > 0) dr_sprite(b, SPR_BEACON_LIGHT, x, y, 8, 1, 0, (uint8_t)(a > 1 ? 255 : a * 255));
+}
+static void beacon_window(Perm *p, WinOut *w) {
+ (void)p;
+ win_text(w, "The Beacon has been designed together with Annabelle, who won the first building contest in the Discord!");
+}
+const PermOps ops_Beacon = {.init = beacon_init, .entertainment_capacity = beacon_capacity, .be_entertained = beacon_be_entertained,
+ .draw = beacon_draw, .window = beacon_window};
+
+/* IntergalacticLibrary and FeatherAlliance: never reachable in this version (a paid building unlocks them) */
+static bool galactic_open(const Perm *p) { return first_worker_working(p) && hours_in(hour_now(), 13 - 0.5f, 23); }
+static void galactic_update(Perm *p, float timeMod) {
+ (void)p;
+ produce(M_KNOWLEDGE, timeMod * (0.05f * p->nworkers / 3.0f * ncits) / (1440 / city.minutesPerTick) * boost());
+}
+static void galactic_be_entertained(Perm *p, Cit *c, float timeMod) {
+ fossil_be_entertained(p, c, timeMod);
+ c->flags &= (uint16_t)~CF_BUILDING_INITED;
+ educate(c, 0.033f, 1.81f);
+}
+const PermOps ops_IntergalacticLibrary = {.update = galactic_update, .is_open = galactic_open, .entertainment_capacity = zero_capacity,
+ .be_entertained = galactic_be_entertained, .draw = plain_draw};
+const PermOps ops_FeatherAlliance = {.walk_around = key_friends_walk_around, .draw = plain_draw};
+
+/* ---------------------------------------------------------------- FestivalHQ and the music festival */
+#define CF_FEST_WORKER 0x2000
+#define MAX_VENUES 64
+static struct {
+ bool planned, started;
+ double timeStart, timeEnd;
+ uint16_t center;
+ float coolDown; /* festivalManager.festivalCoolDown */
+ uint8_t nvenues;
+ uint16_t venues[MAX_VENUES];
+ uint8_t temp[MAX_VENUES]; /* temporary workers at each venue */
+} fest;
+static bool involved(const Cit *c) { return cit_age(c) > 18 && (!c->job || !class_is(P(c->job)->cls, CLS_School)); }
+static int involved_count(void) {
+ int n = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && involved(&cits[i])) n++;
+ return n;
+}
+static bool venue_kind(const Perm *p) {
+ if (!is_building(p) || !(p->flags & PF_IS_ENTERTAINMENT) || p->cls == CLS_EcoFarm) return false;
+ int t = ent_type(p);
+ if (t != 3 && t != 0 && t != 1) return false;
+ /* couldStandHere: not an all-direction merging building on one of its own kind */
+ Drawer d;
+ bld_drawer(p, &d);
+ return !(d.kind == DRW_ALLDIR && p->bottom && P(p->bottom)->cls == p->cls);
+}
+static uint16_t *relevant_out;
+static int relevant_n, relevant_max;
+static bool record_venue(const Perm *p, const void *ctx) {
+ (void)ctx;
+ if (venue_kind(p)) {
+ if (relevant_n < relevant_max) relevant_out[relevant_n] = pid(p);
+ relevant_n++;
+ }
+ return false;
+}
+/* MusicFestival.relevantBuildings: in the order the finder reaches them from the HQ */
+static int relevant_venues(uint16_t center, uint16_t *out, int max) {
+ relevant_out = out, relevant_n = 0, relevant_max = max;
+ finder_query(center, 0, 0, record_venue, NULL, NULL, -1, NULL, 1e8f);
+ return relevant_n;
+}
+static bool can_do(uint16_t center) {
+ int inv = involved_count();
+ return inv > 100 && relevant_venues(center, NULL, 0) > inv / 100;
+}
+bool festival_running(void) { return fest.planned && city.timeSinceStart >= fest.timeStart; }
+static bool is_venue(uint16_t id) {
+ for (int i = 0; i < fest.nvenues; i++)
+ if (fest.venues[i] == id) return true;
+ return false;
+}
+static int venue_index(uint16_t id) {
+ for (int i = 0; i < fest.nvenues; i++)
+ if (fest.venues[i] == id) return i;
+ return -1;
+}
+/* doStartRepeatables: the venues (the first involved / 20, and their neighbours that were left out) */
+static void festival_venues(void) {
+ uint16_t all[MAX_VENUES * 2];
+ int n = relevant_venues(fest.center, all, MAX_VENUES * 2);
+ if (n > MAX_VENUES * 2) n = MAX_VENUES * 2;
+ int want = involved_count() / 20;
+ int keep = n < want ? n : want;
+ if (keep > MAX_VENUES) keep = MAX_VENUES;
+ fest.nvenues = (uint8_t)keep;
+ memcpy(fest.venues, all, sizeof all[0] * (size_t)keep);
+ bool left_out[MAX_VENUES * 2];
+ for (int i = 0; i < n; i++) left_out[i] = i >= keep;
+ for (int i = 0; i < keep; i++) {
+ for (int dir = 0; dir < 2; dir++) {
+ const Perm *b = P(fest.venues[i]);
+ for (;;) {
+ uint16_t nb = dir ? b->right : b->left;
+ int k = -1;
+ for (int j = keep; j < n; j++)
+ if (left_out[j] && all[j] == nb) k = j;
+ if (!nb || k < 0 || fest.nvenues >= MAX_VENUES) break;
+ left_out[k] = false;
+ fest.venues[fest.nvenues++] = nb;
+ b = P(nb);
+ }
+ }
+ }
+ memset(fest.temp, 0, sizeof fest.temp);
+}
+static void festival_end(void) {
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_FEST_WORKER)) continue;
+ c->flags &= (uint16_t)~CF_FEST_WORKER;
+ Perm *in = P(c->inPermanent);
+ if (!is_building(in) || !is_venue(c->inPermanent)) continue;
+ if (park_like(in)) c->relativeY = 0;
+ else {
+ uint8_t ji = c->jobIndex;
+ c->jobIndex = 255;
+ bld_work(in, c, 0, true);
+ c->jobIndex = ji;
+ }
+ }
+ for (int i = 0; i < fest.nvenues; i++)
+ if (P(fest.venues[i]) && park_like(P(fest.venues[i]))) park_festival_stop(P(fest.venues[i]));
+ fest.planned = fest.started = false;
+ fest.nvenues = 0;
+}
+void festival_update(float timeMod) {
+ if (fest.planned && city.timeSinceStart >= fest.timeStart) {
+ if (city.timeSinceStart > fest.timeEnd) {
+ festival_end();
+ } else if (!fest.started) {
+ festival_venues();
+ happiness_add_boost(city.timeSinceStart + 10080, 25, true, HB_MUSIC_FESTIVAL);
+ fest.started = true;
+ }
+ }
+ if (fest.coolDown > -1) fest.coolDown -= timeMod * city.minutesPerTick;
+ if (festival_running()) {
+ /* the temporary workers of each venue, counted again (tempWorkers, without the dead and the uninvolved) */
+ memset(fest.temp, 0, sizeof fest.temp);
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_FEST_WORKER)) continue;
+ int v = venue_index(c->inPermanent);
+ if (v < 0 || !involved(c)) c->flags &= (uint16_t)~CF_FEST_WORKER;
+ else if (fest.temp[v] < 255) fest.temp[v]++;
+ }
+ }
+}
+/* the entertainment's times, as citizen.c keeps them (city times in 2-hour and 4-minute units that wrap) */
+static uint8_t at_units(double t, double unit) {
+ double now = city.timeSinceStart / unit, d = (t - city.timeSinceStart) / unit;
+ if (d > 120) d = 120;
+ if (d < -120) d = -120;
+ return (uint8_t)((int64_t)now + (int)floor(d + (t >= city.timeSinceStart ? 0.999 : 0)));
+}
+static bool past_units(uint8_t v, double unit) { return (int8_t)((uint8_t)(int64_t)(city.timeSinceStart / unit) - v) >= 0; }
+/* MusicFestival.citizenFestivalUpdate */
+static void festival_citizen_update(Cit *c, float timeMod) {
+ if (c->currentAction == 0) bld_work(P(c->job), c, timeMod, true); /* tryFinishWork */
+ if (c->currentAction == 0) return;
+ bool busy = false;
+ Perm *in = P(c->inPermanent);
+ int v = is_building(in) ? venue_index(c->inPermanent) : -1;
+ if (v >= 0) {
+ bool haver = park_like(in), work = is_a(in, B_WORK);
+ bool mine = c->flags & CF_FEST_WORKER;
+ int id = 0;
+ if (mine) {
+ for (int i = 1; i < cid(c); i++)
+ if ((cits[i].flags & CF_ALIVE) && (cits[i].flags & CF_FEST_WORKER) && cits[i].inPermanent == c->inPermanent) id++;
+ }
+ if (!mine && ((!haver && work && fest.temp[v] < bld_jobs(in)) || (haver && fest.temp[v] < 2))) {
+ mine = true;
+ c->flags |= CF_FEST_WORKER;
+ id = fest.temp[v]++;
+ }
+ if (mine) {
+ busy = true;
+ if (haver) {
+ park_festival_work(in, c, timeMod, id);
+ } else {
+ uint8_t ji = c->jobIndex;
+ c->jobIndex = 255; /* (not in its workers' list) */
+ bld_work(in, c, timeMod, false);
+ c->jobIndex = ji;
+ }
+ } else {
+ busy = true;
+ if (!(c->flags & CF_ENT_INITED)) {
+ float desirability = !c->job && !c->school ? 0.75f : 1.0f;
+ c->entFinished = at_units(city.timeSinceStart + 60.0 * rnd_range(ent_min_time(in), ent_max_time(in)), 4);
+ c->entRecent[ent_type(in) % 6] =
+ at_units(city.timeSinceStart + 1440.0 * rnd_range(ent_min_satisfy(in), ent_max_satisfy(in)) * desirability, 120);
+ c->flags |= CF_ENT_INITED;
+ }
+ if (past_units(c->entFinished, 4) && ent_finish(in, c, timeMod)) {
+ busy = false;
+ c->flags &= (uint16_t)~CF_ENT_INITED;
+ } else if (haver) {
+ park_festival_entertained(in, c);
+ } else {
+ ent_be_entertained(in, c, timeMod);
+ }
+ }
+ c->flags |= CF_CAN_VIEW_SELF;
+ }
+ if (!busy && fest.nvenues) {
+ uint16_t to = fest.venues[rnd_int(fest.nvenues)];
+ if (P(to) && (P(to)->flags & PF_USED)) path_find(c, to, THEN_NONE);
+ }
+}
+/* Festival.updateFestivalCitizen: one citizen's step while a festival is on (sim.c calls it instead of the usual) */
+void festival_citizen(Cit *c, float timeMod) {
+ if (c->flags & CF_DELAY_CAN_VIEW_SELF) c->flags &= (uint16_t)~CF_DELAY_CAN_VIEW_SELF;
+ cit_update_path(c, timeMod);
+ if (!(c->flags & CF_ALIVE) || (c->flags & (CF_HAS_PATH | CF_REQUESTING_PATH))) return;
+ if (involved(c)) festival_citizen_update(c, timeMod);
+ else cit_update_daily_life(c, timeMod);
+}
+static void festival_hq_update(Perm *p, float timeMod) {
+ TotalState *cd = ST(TotalState, p); /* festivalCoolDown */
+ int jobs = bld_jobs(p);
+ if (cd->total > -1) cd->total -= timeMod * (jobs ? (float)p->nworkers / jobs : 0) * city.minutesPerTick;
+}
+static void festival_hq_destroy(Perm *p) {
+ (void)p;
+ if (fest.planned) {
+ if (fest.started) festival_end();
+ fest.planned = false;
+ }
+}
+static void festival_hq_work(Perm *p, Cit *c, float timeMod, bool stop) {
+ (void)p, (void)timeMod;
+ if (stop) {
+ c->currentAction = 2;
+ return;
+ }
+ if (c->relativeY > 5) {
+ if (rnd_range(0, 1) < 0.5f) cit_change_floor(c, TH_CHANGE_FLOOR_WAIT_50_100, 0);
+ else {
+ static const int8_t up[8] = {3, 4, 5, 6, 12, 13, 14, 15};
+ int x = up[rnd_int(8)];
+ cit_move_and_wait(c, x, rnd_between(50, 100), THEN_NONE, 0, false, false);
+ }
+ } else if (rnd_range(0, 1) < 0.3f) {
+ cit_change_floor(c, TH_CHANGE_FLOOR_WAIT_50_100, 0);
+ } else {
+ static const int8_t down[4] = {3, 8, 13, 14};
+ int x = down[rnd_int(4)];
+ cit_move_and_wait(c, x, rnd_between(50, 100), THEN_NONE, 0, false, false);
+ }
+}
+static void festival_price(float m[M_COUNT]) {
+ memset(m, 0, sizeof(float) * M_COUNT);
+ m[M_WOOD] = (float)ncits, m[M_FOOD] = 3.0f * ncits;
+}
+static void basic_time(char *b, int size, float minutes) {
+ if (minutes > 2880) lo1(b, size, "[0] days", floorf(minutes / 1440));
+ else if (minutes > 1440) lo1(b, size, "one day", 0);
+ else if (minutes > 60) lo1(b, size, "[0] hours", floorf(minutes / 60));
+ else lo1(b, size, "one hour", 0);
+ if (b[0] >= 'a' && b[0] <= 'z') b[0] = (char)(b[0] - 'a' + 'A');
+}
+/* the festival part: Organize a Festival (its Music Festival button, always pressable: it says so when it can't be
+ * done), or the festival's state in Arial15 and its text */
+static void festival_hq_window(Perm *p, WinOut *w) {
+ float cd = STC(TotalState, p)->total;
+ if (!fest.planned && cd < 0 && fest.coolDown < 0) {
+ float m[M_COUNT];
+ festival_price(m);
+ win_heading(w, L_organize_a_festival, -1, -1, false, false, NULL, NULL);
+ win_button(w, 0, L_music_festival, WA_SPECIAL, true);
+ win_text(w, L_music_festival_help);
+ win_cost(w, m);
+ win_space(w, 3);
+ return;
+ }
+ win_space(w, 3);
+ win_para(w, FONT_15, festival_running() ? L_current_festival : fest.planned ? L_planned_festival : L_preparing, 250, 0);
+ if (festival_running()) win_text(w, L_music_festival_doing);
+ else if (fest.planned) win_text(w, L_music_festival_planned);
+ else if (p->nworkers == 0) win_text(w, L_assign_workers_to_prepare);
+ else {
+ char t[64], b[200];
+ basic_time(t, sizeof t, fmaxf(cd, fest.coolDown) * ((float)bld_jobs(p) / p->nworkers));
+ snprintf(b, sizeof b, "%s of preparation left.%s%s", t, p->nworkers < bld_jobs(p) ? " " : "",
+ p->nworkers < bld_jobs(p) ? L_assign_more_to_speed_up : "");
+ win_text(w, b);
+ }
+}
+static void festival_hq_action(Perm *p, int a) {
+ if (a != WA_SPECIAL) return;
+ float m[M_COUNT];
+ festival_price(m);
+ if (mat_can_afford(m) && !fest.planned && can_do(pid(p))) {
+ mat_pay(m);
+ fest.planned = true;
+ fest.started = false;
+ fest.center = pid(p);
+ fest.timeStart = city.timeSinceStart;
+ fest.timeEnd = fest.timeStart + 1440;
+ TotalState *cd = ST(TotalState, p);
+ cd->total += 8783.9999999999982f;
+ fest.coolDown = cd->total;
+ } else {
+ ui_show_simple(L_cant_organize);
+ }
+}
+const PermOps ops_FestivalHQ = {.destroy = festival_hq_destroy, .update = festival_hq_update, .work = festival_hq_work,
+ .draw = plain_draw, .window = festival_hq_window, .window_action = festival_hq_action};
+
+/* ---------------------------------------------------------------- start, save, load */
+uint8_t TH_CHANGE_FLOOR_WAIT_50_100;
+static void th_change_floor_wait_50_100(Cit *c, uint16_t arg) { (void)arg; wait_ticks(c, 50, 100); }
+void unique_new_city(void) {
+ modern_artworks_unlocked = 4;
+ memset(&machine, 0, sizeof machine);
+ machine.lastDay = -1;
+ memset(&fest, 0, sizeof fest);
+ memset(bot_cache, 0, sizeof bot_cache);
+}
+void unique_save(SaveIO *io) {
+ save_u8(io, modern_artworks_unlocked);
+ save_bytes(io, &machine, sizeof machine);
+ save_bytes(io, &fest, sizeof fest);
+}
+bool unique_load(SaveIO *io) {
+ modern_artworks_unlocked = load_u8(io);
+ load_bytes(io, &machine, sizeof machine);
+ load_bytes(io, &fest, sizeof fest);
+ return fest.nvenues <= MAX_VENUES;
+}
+void bld_unique_init(void) {
+ TH_ART_MOVE = then_register(th_art_move);
+ TH_SOCIETY_FAIL = then_register(th_society_fail);
+ TH_HIPPIE_FAIL = then_register(th_hippie_fail);
+ TH_FOSSIL_MOVE = then_register(th_fossil_move);
+ TH_CHANGE_FLOOR_WAIT_50_100 = then_register(th_change_floor_wait_50_100);
+}
diff --git a/games/finalearth2/src/bld_window.c b/games/finalearth2/src/bld_window.c
new file mode 100644
index 00000000..e2eb7bff
--- /dev/null
+++ b/games/finalearth2/src/bld_window.c
@@ -0,0 +1,67 @@
+/* The Final Earth 2: building windows' texts: the original's lang_en.csv
+ * lines with their "[0]" and "[1]" filled in (common.Localize.lo), numbers
+ * written as JavaScript writes them. */
+#include "bldi.h"
+
+/* a number as JavaScript's String(n) for the values windows show (integers, or a few decimals) */
+static int put_num(char *out, int size, double v) {
+ char tmp[32];
+ int n = 0;
+ if (v != v) v = 0;
+ bool neg = v < 0;
+ if (neg) v = -v;
+ double ip = floor(v);
+ double frac = v - ip;
+ /* up to 6 decimals, trailing zeros dropped */
+ long long scaled = (long long)(frac * 1e6 + 0.5);
+ if (scaled >= 1000000) ip += 1, scaled = 0;
+ unsigned long long whole = ip > 9e17 ? 900000000000000000ull : (unsigned long long)ip;
+ char digits[24];
+ int nd = 0;
+ do {
+ digits[nd++] = (char)('0' + whole % 10);
+ whole /= 10;
+ } while (whole);
+ if (neg && (ip > 0 || scaled > 0)) tmp[n++] = '-';
+ while (nd) tmp[n++] = digits[--nd];
+ if (scaled > 0) {
+ char fd[6];
+ for (int i = 5; i >= 0; i--) fd[i] = (char)('0' + scaled % 10), scaled /= 10;
+ int last = 5;
+ while (last >= 0 && fd[last] == '0') last--;
+ tmp[n++] = '.';
+ for (int i = 0; i <= last; i++) tmp[n++] = fd[i];
+ }
+ int k = 0;
+ for (; k < n && k < size - 1; k++) out[k] = tmp[k];
+ out[k] = 0;
+ return k;
+}
+
+static const char *lo(char *buf, int size, const char *text, int nv, const double *v) {
+ int o = 0;
+ for (const char *s = text; *s && o < size - 1;) {
+ if (s[0] == '[' && s[1] >= '0' && s[1] <= '9' && s[2] == ']' && s[1] - '0' < nv) {
+ o += put_num(buf + o, size - o, v[s[1] - '0']);
+ s += 3;
+ } else {
+ buf[o++] = *s++;
+ }
+ }
+ buf[o] = 0;
+ return buf;
+}
+const char *lo1(char *buf, int size, const char *text, double v0) { return lo(buf, size, text, 1, &v0); }
+const char *lo2(char *buf, int size, const char *text, double v0, double v1) {
+ double v[2] = {v0, v1};
+ return lo(buf, size, text, 2, v);
+}
+void win_line(WinOut *w, const char *text) { win_info(w, 0, text); }
+void win_line1(WinOut *w, const char *text, double v0) {
+ char b[160];
+ win_info(w, 0, lo1(b, sizeof b, text, v0));
+}
+void win_line2(WinOut *w, const char *text, double v0, double v1) {
+ char b[160];
+ win_info(w, 0, lo2(b, sizeof b, text, v0, v1));
+}
diff --git a/games/finalearth2/src/bld_world.c b/games/finalearth2/src/bld_world.c
new file mode 100644
index 00000000..d2b0ab80
--- /dev/null
+++ b/games/finalearth2/src/bld_world.c
@@ -0,0 +1,396 @@
+/* The Final Earth 2: world resources (worldResources.*): forests and rocks
+ * (LimitedWorldResource: cut or mined, forests grow back), the alien ruins
+ * and their findings, the player's priorities (ResourcePriorityManager), and
+ * the gather places in buildings (tree plantations, rock teleporters) seen
+ * as limited resources. */
+#include <stdio.h>
+#include "bldi.h"
+#include "lang_data.h"
+
+uint8_t world_unavailable[MAX_WORLDS];
+
+/* ---------------------------------------------------------------- the kinds */
+typedef struct {
+ uint16_t spr, grow; /* the cut stages and the regrowing stages (0: none) */
+ uint16_t initial;
+ float regrow; /* regrowSpeed per tick in day light */
+ int8_t climbX, climbY; /* treeClimbX and treeClimbY */
+} ResKind;
+static const ResKind kinds[] = {
+ [CLS_Forest] = {SPR_FOREST, SPR_FOREST_GROW, 200, 0.003f, 7, 13},
+ [CLS_PineForest] = {SPR_PINEFOREST, SPR_PINEFOREST_GROW, 200, 0.005f, 15, 3},
+ [CLS_BranchyForest] = {SPR_FOREST_BRANCHES, SPR_FOREST_BRANCHES_GROW, 200, 0.005f, 16, 12},
+ [CLS_RedForest] = {SPR_REDFOREST, SPR_REDFOREST_GROW, 200, 0.005f, 16, 12},
+ [CLS_PurpleForest] = {SPR_PURPLEFOREST, SPR_PURPLEFOREST_GROW, 200, 0.005f, 16, 12},
+ [CLS_BirchForest] = {SPR_BIRCHFOREST, SPR_PINEFOREST_GROW, 120, 0.01f, 12, 13},
+ [CLS_Rock] = {SPR_ROCK, 0, 250, 0, 0, 0},
+ [CLS_Boulder] = {SPR_BOULDER, 0, 200, 0, 0, 0},
+};
+static const ResKind *kind_of(const Perm *p) { return p->cls <= CLS_Boulder ? &kinds[p->cls] : &kinds[CLS_Forest]; }
+static bool is_forest(const Perm *p) { return is_a(p, B_FOREST); }
+static bool is_rock(const Perm *p) { return is_a(p, B_ROCK); }
+static bool is_limited(const Perm *p) { return is_forest(p) || is_rock(p); }
+static bool is_plantation(const Perm *p) { return p->cls == CLS_TreePlantation || p->cls == CLS_StoneTeleporter; }
+float resource_initial(const Perm *p) { return kind_of(p)->initial; }
+void resource_climb(const Perm *p, int *x, int *y) { *x = kind_of(p)->climbX, *y = kind_of(p)->climbY; }
+
+/* ---------------------------------------------------------------- ILimitedMaterialGatherPlace */
+float limited_materials_left(const Perm *p) {
+ if (is_limited(p)) return STC(LimitedState, p)->materialsLeft;
+ if (is_plantation(p)) return STC(PlantationState, p)->materialsLeft;
+ return 0;
+}
+void limited_take(Perm *p, float amount) {
+ if (is_limited(p)) ST(LimitedState, p)->materialsLeft -= amount;
+ else if (is_plantation(p)) ST(PlantationState, p)->materialsLeft -= amount;
+}
+bool limited_stay_if_empty(const Perm *p) { return p->cls == CLS_StoneTeleporter; }
+bool limited_do_not_gather(const Perm *p) { return is_limited(p) && STC(LimitedState, p)->managementMode == 1; }
+bool limited_destroyed_on_empty(const Perm *p) {
+ if (is_forest(p)) return STC(LimitedState, p)->managementMode == 2;
+ return is_rock(p);
+}
+int limited_min_x(const Perm *p) { return p->cls == CLS_TreePlantation ? 4 : p->cls == CLS_StoneTeleporter ? 5 : 1; }
+int limited_max_x(const Perm *p) { return p->cls == CLS_TreePlantation ? 14 : p->cls == CLS_StoneTeleporter ? 13 : 17; }
+
+/* ---------------------------------------------------------------- priorities (kept in each resource's state, saved with it) */
+bool resource_prioritized(const Perm *p) { return is_limited(p) && STC(LimitedState, p)->prioritized; }
+bool resource_any_prioritized(int base) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_a(&perms[i], (uint32_t)base) && STC(LimitedState, &perms[i])->prioritized) return true;
+ return false;
+}
+/* invalidatePathfindingAfterPrioritizeChange: the miners or woodcutters look again */
+static void priorities_changed(const Perm *res) {
+ int cls = is_rock(res) ? CLS_StoneMine : is_forest(res) ? CLS_WoodcuttingCentre : -1;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && class_is(perms[i].cls, cls)) ST(BlueCollarState, &perms[i])->nearest = NONE;
+}
+void resource_set_prioritized(Perm *p, bool on) {
+ if (!is_limited(p)) return;
+ LimitedState *s = ST(LimitedState, p);
+ if (on) {
+ s->prioritized = 1;
+ priorities_changed(p);
+ } else if (s->prioritized) {
+ priorities_changed(p);
+ s->prioritized = 0;
+ }
+}
+
+/* ---------------------------------------------------------------- forests and rocks */
+static void limited_init(Perm *p) {
+ LimitedState *s = ST(LimitedState, p);
+ s->materialsLeft = kind_of(p)->initial;
+ s->regrowProgress = 0;
+ s->managementMode = 0;
+ s->prioritized = 0;
+}
+static void limited_destroy(Perm *p) { resource_set_prioritized(p, false); }
+/* LimitedWorldResource.update: grows back once empty (rocks never: their speed is 0) */
+static void limited_update(Perm *p, float timeMod) {
+ LimitedState *s = ST(LimitedState, p);
+ if (s->materialsLeft > 0) return;
+ float speed = kind_of(p)->regrow;
+ if (day_light()) s->regrowProgress += speed * timeMod;
+ else if (dim_light()) s->regrowProgress += speed * timeMod * 0.5f;
+ if (s->regrowProgress >= 100) {
+ s->materialsLeft = kind_of(p)->initial;
+ s->regrowProgress = 0;
+ }
+}
+static void limited_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ if (layer != LAYER_MAIN) return;
+ const ResKind *k = kind_of(p);
+ const LimitedState *s = STC(LimitedState, p);
+ int n = frames_of(k->spr, 20), ng = k->grow ? frames_of(k->grow, 20) : 0;
+ int f = limited_frame(s->materialsLeft, k->initial, s->regrowProgress, n, ng);
+ if (s->materialsLeft <= 0.0000001f && ng) dr_frame(b, k->grow, 20, f < ng ? f : ng - 1, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+ else dr_frame(b, k->spr, 20, f < n ? f : n - 1, x, y, 0, 0, 0, 255, GFX_NO_TINT);
+}
+/* LimitedWorldResource.addWindowInfoLines: "[0]% grown." or "[0]/[1] [2] left." */
+static void left_line(const Perm *p, WinOut *w) {
+ const LimitedState *s = STC(LimitedState, p);
+ char t[64], n[16];
+ if (s->materialsLeft <= 0) {
+ win_text(w, lo1(t, sizeof t, L_pct_grown, (int)s->regrowProgress));
+ return;
+ }
+ /* (get_resourceName: "wood" or "stone", as written) */
+ lo2(t, sizeof t, L_pct_left, (int)s->materialsLeft, kind_of(p)->initial);
+ char *q = strstr(t, "[2]");
+ if (q) {
+ snprintf(n, sizeof n, "%s", q + 3);
+ snprintf(q, sizeof t - (size_t)(q - t), "%s%s", is_forest(p) ? "wood" : "stone", n);
+ }
+ win_text(w, t);
+}
+
+/* the management window: for this one or for all of its kind (gui_UpgradeWindowParts.hasMultiUpgradeModeOn) */
+static bool manage_all;
+static uint16_t uproot_confirm; /* the forest whose Uproot button asks "Really Uproot?" */
+static void set_mode(Perm *p, int mode) {
+ if (manage_all) {
+ bool forest = is_forest(p);
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *q = &perms[i];
+ if ((q->flags & PF_USED) && (forest ? is_forest(q) : is_rock(q))) ST(LimitedState, q)->managementMode = (uint8_t)mode;
+ }
+ } else {
+ ST(LimitedState, p)->managementMode = (uint8_t)mode;
+ }
+}
+static int count_kind(bool forest) {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && (forest ? is_forest(&perms[i]) : is_rock(&perms[i]))) n++;
+ return n;
+}
+/* the header with its One and All buttons (addOneAndMaxButtons, no cost), and the question */
+static void manage_header(WinOut *w, bool forest, char *all_tip, int size) {
+ snprintf(all_tip, (size_t)size, "%s (%d).", forest ? L_forest_management_all : L_set_management_all_rocks, count_kind(forest));
+ win_heading(w, forest ? L_forest_management : L_rock_mining, WA_SPECIAL, WA_SPECIAL_2, manage_all, false,
+ forest ? L_forest_management_only_this : L_set_management_rock, all_tip);
+ char t[80];
+ const char *q = forest ? (manage_all ? L_forest_management_question_1 : L_forest_management_question_2)
+ : (manage_all ? L_rock_management_question_1 : L_rock_management_question_2);
+ snprintf(t, sizeof t, "%s ", q);
+ win_text(w, t);
+}
+/* createActivatableButton: the mode chosen is the active box */
+static void mode_option(WinOut *w, const LimitedState *s, int mode, const char *name, const char *desc_all,
+ const char *desc_one) {
+ win_button(w, 0, name, WA_MODE_0 + mode, s->managementMode != mode);
+ win_text(w, manage_all ? desc_all : desc_one);
+}
+static const char texture_credit[] = "Texture by DT from the Discord, who won the first art contest!";
+static void forest_window(Perm *p, WinOut *w) {
+ const LimitedState *s = STC(LimitedState, p);
+ if (p->cls == CLS_BranchyForest) {
+ win_text(w, texture_credit);
+ win_space(w, 4);
+ }
+ left_line(p, w);
+ char all_tip[80];
+ manage_header(w, true, all_tip, sizeof all_tip);
+ mode_option(w, s, 0, L_forest_regrow, L_forest_regrow_description_1, L_forest_regrow_description_2);
+ mode_option(w, s, 1, L_forest_protect, L_forest_protect_description_1, L_forest_protect_description_2);
+ mode_option(w, s, 2, L_forest_uproot, L_forest_uproot_description_1, L_forest_uproot_description_2);
+ win_space(w, 4);
+ /* the bottom row: Uproot (then "Really Uproot?") once cut down, else Prioritize */
+ if (s->materialsLeft <= 0) {
+ bool confirm = uproot_confirm == pid(p);
+ win_bottom_button(w, confirm ? L_really_uproot : L_forest_instant_uproot, WA_PRIORITIZE, NULL,
+ confirm ? NULL : L_forest_instant_uproot_description);
+ } else if (s->prioritized) {
+ win_bottom_button(w, L_prioritized, WA_PRIORITIZE, L_prioritized, L_prioritize_description_1);
+ } else {
+ win_bottom_button(w, L_prioritize, WA_PRIORITIZE, L_prioritize, L_prioritize_description_2);
+ }
+}
+static void rock_window(Perm *p, WinOut *w) {
+ const LimitedState *s = STC(LimitedState, p);
+ if (p->cls == CLS_Boulder) {
+ win_text(w, texture_credit);
+ win_space(w, 4);
+ }
+ left_line(p, w);
+ char all_tip[80];
+ manage_header(w, false, all_tip, sizeof all_tip);
+ mode_option(w, s, 0, L_rock_management_mine, L_rock_management_mine_description_1, L_rock_management_mine_description_2);
+ mode_option(w, s, 1, L_forest_protect, L_rock_management_protect_description_1, L_rock_management_protect_description_2);
+ win_space(w, 4);
+ if (s->prioritized) win_bottom_button(w, L_prioritized, WA_PRIORITIZE, L_prioritized, L_rock_prioritized_description);
+ else win_bottom_button(w, L_prioritize, WA_PRIORITIZE, L_prioritize, L_rock_prioritized_description_2);
+}
+static void limited_action(Perm *p, int a) {
+ LimitedState *s = ST(LimitedState, p);
+ if (a == WA_SPECIAL) manage_all = false;
+ else if (a == WA_SPECIAL_2) manage_all = true;
+ else if (a >= WA_MODE_0 && a <= WA_MODE_0 + (is_forest(p) ? 2 : 1)) set_mode(p, a - WA_MODE_0);
+ else if (a == WA_PRIORITIZE) {
+ if (is_forest(p) && s->materialsLeft <= 0) {
+ /* Uproot, then "Really Uproot?" */
+ if (uproot_confirm == pid(p)) {
+ uproot_confirm = 0;
+ perm_destroy(pid(p), false);
+ } else {
+ uproot_confirm = pid(p);
+ }
+ return;
+ }
+ resource_set_prioritized(p, !s->prioritized);
+ }
+ if (a != WA_PRIORITIZE) uproot_confirm = 0;
+}
+#define LIMITED_OPS(win) \
+ {.init = limited_init, .destroy = limited_destroy, .update = limited_update, .draw = limited_draw, .window = win, \
+ .window_action = limited_action}
+const PermOps ops_Forest = LIMITED_OPS(forest_window);
+const PermOps ops_PineForest = LIMITED_OPS(forest_window);
+const PermOps ops_BranchyForest = LIMITED_OPS(forest_window);
+const PermOps ops_RedForest = LIMITED_OPS(forest_window);
+const PermOps ops_PurpleForest = LIMITED_OPS(forest_window);
+const PermOps ops_BirchForest = LIMITED_OPS(forest_window);
+const PermOps ops_Rock = LIMITED_OPS(rock_window);
+const PermOps ops_Boulder = LIMITED_OPS(rock_window);
+
+/* a forest or rock planted from the build menu (Builder): its stock and growth as buildableWorldResourcesInfo says */
+void resource_planted(Perm *p, float materials_left, float regrow) {
+ if (!p || !is_limited(p)) return;
+ ST(LimitedState, p)->materialsLeft = materials_left;
+ ST(LimitedState, p)->regrowProgress = regrow;
+}
+
+/* World.update: what a world knows is not there is forgotten each new day (and on every city change) */
+static int unavailable_day;
+void worlds_update(float timeMod) {
+ (void)timeMod;
+ int d = day_number();
+ if (d != unavailable_day) {
+ memset(world_unavailable, 0, sizeof world_unavailable);
+ unavailable_day = d;
+ }
+}
+
+/* ---------------------------------------------------------------- AlienRuins */
+typedef struct { const char *name, *text; uint8_t m1, m2; uint8_t a1, a2; } Finding;
+/* level by level: options a to d (AlienRuins) and e (ComputerAlienRuins) */
+static const Finding findings[4][5] = {
+ {{L_alien_ruins_find_1a, L_alien_ruins_description_1a, M_WOOD, 0, 20, 0},
+ {L_alien_ruins_find_1b, L_alien_ruins_description_1b, M_STONE, 0, 25, 0},
+ {L_alien_ruins_find_1c, L_alien_ruins_description_1c, M_STONE, 0, 22, 0},
+ {L_alien_ruins_find_1d, L_alien_ruins_description_1d, M_FOOD, M_MACHINEPARTS, 12, 5},
+ {L_alien_ruins_find_1e, L_alien_ruins_description_1e, M_STONE, 0, 35, 0}},
+ {{L_alien_ruins_find_2a, L_alien_ruins_description_2a, M_WOOD, 0, 40, 0},
+ {L_alien_ruins_find_2b, L_alien_ruins_description_2b, M_STONE, 0, 35, 0},
+ {L_alien_ruins_find_2c, L_alien_ruins_description_2c, M_MACHINEPARTS, 0, 20, 0},
+ {L_alien_ruins_find_2d, L_alien_ruins_description_2d, M_FOOD, 0, 42, 0},
+ {L_alien_ruins_find_2e, L_alien_ruins_description_2e, M_FOOD, 0, 55, 0}},
+ {{L_alien_ruins_find_3a, L_alien_ruins_description_3a, M_WOOD, M_MACHINEPARTS, 10, 5},
+ {L_alien_ruins_find_3b, L_alien_ruins_description_3b, M_WOOD, 0, 17, 0},
+ {L_alien_ruins_find_3c, L_alien_ruins_description_3c, M_STONE, 0, 15, 0},
+ {L_alien_ruins_find_3d, L_alien_ruins_description_3d, M_FOOD, 0, 22, 0},
+ {L_alien_ruins_find_3e, L_alien_ruins_description_3e, M_MACHINEPARTS, 0, 7, 0}},
+ {{L_alien_ruins_find_4a, L_alien_ruins_description_4a, 0, 0, 0, 0},
+ {L_alien_ruins_find_4b, L_alien_ruins_description_4b, 0, 0, 0, 0},
+ {L_alien_ruins_find_4c, L_alien_ruins_description_4c, 0, 0, 0, 0},
+ {L_alien_ruins_find_4d, L_alien_ruins_description_4d, 0, 0, 0, 0},
+ {L_alien_ruins_find_4e, L_alien_ruins_description_4e, 0, 0, 0, 0}}};
+/* alreadyFoundBonuses: the findings any ruins made (bit level * 5 + option), made again from the ruins on load */
+static uint32_t ruins_found;
+static const uint16_t ruins_sprites[3] = {SPR_ALIENRUINS, SPR_ALIENRUINS_2, SPR_ALIENRUINS_3};
+
+static void ruins_init(Perm *p) {
+ RuinsState *s = ST(RuinsState, p);
+ memset(s, 0, sizeof *s);
+ s->sprite = p->cls == CLS_ComputerAlienRuins ? 2 : (uint8_t)rnd_int(2);
+}
+float ruins_explored(const Perm *p) { return STC(RuinsState, p)->explored4 / 4.0f; }
+void ruins_climb(const Perm *p, int *x, int *y) {
+ int sp = STC(RuinsState, p)->sprite;
+ if (p->cls == CLS_ComputerAlienRuins) *x = 9, *y = 15;
+ else if (sp == 0) *x = 9, *y = 17;
+ else *x = 15, *y = 16;
+}
+static int count_ruins(void) {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_a(&perms[i], B_RUINS)) n++;
+ return n;
+}
+static void finding_get(int level, int opt) {
+ const Finding *f = &findings[level][opt];
+ if (f->a1) produce(f->m1, f->a1);
+ if (f->a2) produce(f->m2, f->a2);
+ if (level == 3) switch (opt) {
+ case 0: bonuses.extraFoodFromFarms += 5; break;
+ case 1:
+ unlocks_unlock("AlienHouse");
+ unlocks_unlock("SlimyLiving");
+ break;
+ case 2: bonuses.machinePartsFactorySpeed *= 1.1f; break;
+ case 3: bonuses.labSpeed *= 1.05f; break;
+ }
+}
+/* awardAnyBonuses: one level's finding once a quarter more is explored */
+static void ruins_award(Perm *p) {
+ RuinsState *s = ST(RuinsState, p);
+ float explored = ruins_explored(p);
+ if (!(s->bonusesAwarded < (int)explored / 25 && explored >= 25 * (s->bonusesAwarded + 1)) || s->bonusesAwarded >= 4) return;
+ int level = s->bonusesAwarded;
+ int first = p->cls == CLS_ComputerAlienRuins ? 4 : 0, last = p->cls == CLS_ComputerAlienRuins ? 4 : 3;
+ uint8_t options[5];
+ int n = 0;
+ for (int o = first; o <= last; o++)
+ if (!(ruins_found >> (level * 5 + o) & 1)) options[n++] = (uint8_t)o;
+ if (n > 0) {
+ int pick = options[rnd_int(n)];
+ bool housing = false;
+ for (int i = 0; i < n; i++)
+ if (level == 3 && options[i] == 1) housing = true;
+ if (housing && count_ruins() < 4) pick = 1;
+ finding_get(level, pick);
+ s->found[level] = (uint8_t)(pick + 1);
+ ruins_found |= 1u << (level * 5 + pick);
+ }
+ s->bonusesAwarded++;
+}
+void ruins_explore(Perm *p, float amount) {
+ RuinsState *s = ST(RuinsState, p);
+ float e = ruins_explored(p) + amount;
+ s->explored4 = (uint16_t)(e * 4 + 0.5f);
+ ruins_award(p);
+}
+static void ruins_draw(const GfxBand *b, const Perm *p, int layer, int x, int y) {
+ if (layer == LAYER_MAIN) dr_sprite(b, ruins_sprites[STC(RuinsState, p)->sprite % 3], x, y, 0, 0, 0, 255);
+}
+/* addWindowInfoLines: explored, the "Findings" heading and each find; explored ruins can move (createMoveWindow:
+ * the user interface picks an empty column and calls bld_move_resource) */
+static void ruins_window(Perm *p, WinOut *w) {
+ const RuinsState *s = STC(RuinsState, p);
+ char t[256];
+ win_text(w, lo1(t, sizeof t, L_n_pct_explored, (int)ruins_explored(p)));
+ win_heading(w, L_findings, -1, -1, false, false, NULL, NULL);
+ bool any = false;
+ for (int l = 0; l < 4; l++) {
+ if (!s->found[l]) continue;
+ const Finding *f = &findings[l][(s->found[l] - 1) % 5];
+ snprintf(t, sizeof t, "%s: %s", f->name, f->text);
+ win_text(w, t);
+ any = true;
+ }
+ if (!any) win_text(w, L_exploration_nothing_found);
+ if (ruins_explored(p) >= 100) win_bottom_button(w, L_move, WA_UI_MOVE_RUINS, NULL, NULL);
+}
+const PermOps ops_AlienRuins = {.init = ruins_init, .draw = ruins_draw, .window = ruins_window};
+const PermOps ops_ComputerAlienRuins = {.init = ruins_init, .draw = ruins_draw, .window = ruins_window};
+
+void ruins_new_city(void) { ruins_found = 0; }
+void ruins_after_load(void) {
+ ruins_found = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || !is_a(p, B_RUINS)) continue;
+ for (int l = 0; l < 4; l++)
+ if (STC(RuinsState, p)->found[l]) ruins_found |= 1u << (l * 5 + (STC(RuinsState, p)->found[l] - 1) % 5);
+ }
+}
+
+/* a world resource moved to an empty ground column (createWorldResourceBuilderMove): its state goes with it */
+uint16_t bld_move_resource(uint16_t id, int w, int col) {
+ Perm *p = P(id);
+ if (!p || PC(p)->kind != KIND_RESOURCE || w < 0 || w >= nworlds || col < 0 || col >= worlds[w].ncols) return NONE;
+ if (col_stack_height(w, col) != 0) return NONE;
+ uint8_t cls = p->cls, s[sizeof p->s];
+ memcpy(s, p->s, sizeof s);
+ perm_destroy(id, false);
+ uint16_t n = perm_new(cls, w, col, 0);
+ if (!n) return NONE;
+ memcpy(perms[n].s, s, sizeof s);
+ city_update_connections();
+ sim_update_pathfinder(true, n);
+ return n;
+}
+
+void bld_world_init(void) {}
diff --git a/games/finalearth2/src/bldi.h b/games/finalearth2/src/bldi.h
new file mode 100644
index 00000000..757f1a14
--- /dev/null
+++ b/games/finalearth2/src/bldi.h
@@ -0,0 +1,372 @@
+/* The Final Earth 2: what the buildings' files (bld*.c, upgrades.c) share:
+ * each class's own state in Perm.s, small helpers the original's classes
+ * have in common, and the parts of each file the others call. */
+#ifndef FE_BLDI_H
+#define FE_BLDI_H
+#include "bld.h"
+#include "build.h"
+#include "classes.h"
+#include "data.h"
+#include "story.h"
+#include "unlocks.h"
+#include "upgrades.h"
+#include "win.h"
+#include <stddef.h>
+
+/* a class's state, laid over Perm.s (12 bytes, 2-aligned: packed) */
+#define PACKED __attribute__((packed, may_alias))
+#define ST(T, p) ((T *)(void *)(p)->s)
+#define STC(T, p) ((const T *)(const void *)(p)->s)
+#define STATE_FITS(T) _Static_assert(sizeof(T) <= sizeof(((Perm *)0)->s), #T " does not fit in Perm.s")
+
+/* ---------------------------------------------------------------- small helpers */
+static inline float hour_now(void) { return city_hour(); }
+/* the original's time-of-day ranges, wrapping past midnight */
+static inline bool hours_in(float t, float start, float end) {
+ return start < end ? t >= start && t < end : t >= start || t < end;
+}
+static inline bool day_light(void) { return hours_in(hour_now(), 7, 20); }
+static inline bool dim_light(void) { return hours_in(hour_now(), 6, 21); }
+/* Config.earlyGameFix1: small cities produce faster */
+static inline float early_fix(void) { return ncits < 30 ? 1.3f - 0.3f * (ncits / 60.0f) : 1; }
+/* boostManager.currentGlobalBoostAmount: the ad boost, never on the calculator */
+static inline float boost(void) { return 1; }
+static inline int day_number(void) { return 1 + (int)((int64_t)city.timeSinceStart / 1440); }
+static inline bool is_class(const Perm *p, int cls) { return p && (p->flags & PF_USED) && class_is(p->cls, cls); }
+static inline bool has_upgrade_bit(const Perm *p, int bit) { return p->upgrades >> bit & 1; }
+
+/* the Building's adjacent effects (getEffectsOfAdjecentBuildings) */
+enum { EF_FARM, EF_ALIEN_HOUSE, EF_COMMUNITY, EF_CROPS, EF_TREE_GROWTH, EF_RESTAURANT_CAP };
+float bld_effect(const Perm *p, int effect); /* what p gives its neighbours */
+float adj_effect(const Perm *p, int effect); /* left, right, top and bottom */
+float adj_effect_lr(const Perm *p, int effect);
+
+/* the citizen's place in its job's list (workers.indexOf) */
+static inline int worker_index(const Cit *c) { return c->jobIndex; }
+/* students.indexOf: by citizen number (the order the assigner gives places in) */
+int student_index(const Perm *school, const Cit *c);
+
+/* moving a citizen straight toward x this tick (the original's inline steps in work()) */
+void step_to_x(Cit *c, float x, float timeMod);
+void set_rel(Cit *c, float x, float y); /* setRelativePos */
+void wait_ticks(Cit *c, int tmin, int tmax); /* setPath([8, getInt(tmin, tmax)]) in its building */
+void move_x(Cit *c, int x); /* setPath([4, x]) in its building */
+void move_x_slow(Cit *c, int x); /* [12, 50, 4, x] */
+bool educate(Cit *c, float amount, float cap); /* once per visit: true if it did */
+void leave_to_surface(Cit *c); /* out of its permanent onto the world, at the door */
+
+/* counters kept in whole ticks, stepped by timeMod (often 2/3): rounded at random, so that on average they go at
+ * the right pace */
+static inline int round_random(float x) { return x <= 0 ? 0 : (int)(x + rnd_float()); }
+static inline uint8_t tick_down(uint8_t left, float by) {
+ float t = left - by;
+ return t <= 0 ? 0 : (uint8_t)(t + rnd_float());
+}
+static inline uint8_t tick_up(uint8_t n, float by) {
+ float t = n + by + rnd_float();
+ return t >= 255 ? 255 : (uint8_t)t;
+}
+
+/* a material produced (stats too) */
+static inline void produce(int m, double amount) { mat_add(m, amount); }
+
+/* the closures of the original: functions run at the end of a citizen's scripted path (sim.h) */
+extern uint8_t TH_CHANGE_FLOOR, TH_CHANGE_FLOOR_WAIT_30_60, TH_CHANGE_FLOOR_WAIT_50_100;
+/* each file registers its own at start */
+void bld_houses_init(void);
+void bld_production_init(void);
+void bld_services_init(void);
+void bld_entertainment_init(void);
+void bld_transport_init(void);
+void bld_unique_init(void);
+void bld_world_init(void);
+void bld_hobbies_init(void);
+
+/* ---------------------------------------------------------------- drawing (bld_draw.c) */
+/* the drawers (buildings.buildingDrawers.*): what a building shows and merges with */
+enum { DRW_NORMAL, DRW_AUTOMERGE, DRW_ALLDIR, DRW_DIFFTYPE, DRW_ROOFTOP_AM, DRW_ROOFDOWN, DRW_DECORATION, DRW_NONE };
+typedef struct {
+ uint8_t kind; /* DRW_* */
+ uint16_t name, group; /* currentTextureName and currentTextureGroupName (SPR_*) */
+} Drawer;
+void bld_drawer(const Perm *p, Drawer *d);
+/* zoom-scaled helpers: a sprite's part, a frame of a strip of 20-wide frames 2 apart, a whole sprite */
+void dr_part(const GfxBand *b, uint16_t spr, int sx, int sy, int w, int h, int x, int y, int dx, int dy, uint8_t flags,
+ uint8_t alpha, uint16_t tint);
+void dr_frame(const GfxBand *b, uint16_t spr, int fw, int i, int x, int y, int dx, int dy, uint8_t flags, uint8_t alpha,
+ uint16_t tint);
+void dr_sprite(const GfxBand *b, uint16_t spr, int x, int y, int dx, int dy, uint8_t flags, uint8_t alpha);
+int frames_of(uint16_t spr, int fw); /* getTexturesByWidth(name, fw).length */
+/* the drawers' layers: background on LAYER_BG, front on LAYER_MAIN */
+void draw_normal(const GfxBand *b, const Perm *p, int layer, int x, int y, uint16_t spr, bool mirrored);
+void draw_custom(const GfxBand *b, const Perm *p, int layer, int x, int y, uint16_t spr, bool mirrored,
+ uint16_t front_spr, int front_frame, uint16_t back_spr, int back_frame);
+void draw_merging(const GfxBand *b, const Perm *p, int layer, int x, int y); /* any merging drawer */
+void draw_decoration(const GfxBand *b, const Perm *p, int layer, int x, int y, uint16_t spr, int sub, bool mirrored,
+ uint16_t tint);
+void draw_upgrades(const GfxBand *b, const Perm *p, int layer, int x, int y, bool no_cache);
+/* the AllDir drawer's secondary background (botanical gardens' plants): which row */
+void draw_garden_plants(const GfxBand *b, const Perm *p, int x, int y, uint16_t spr, int texture, bool top, bool bottom);
+uint32_t hsv_to_rgb(float h, float s, float v);
+uint32_t hsl_to_rgb(float h, float s, float l);
+static inline uint16_t tint565(uint32_t rgb) { return rgb565(rgb); }
+/* a time clock for animations: game ticks (timeMod units) since start, and a hash for per-building variety */
+extern float bld_anim;
+static inline uint32_t hash32(uint32_t x) {
+ x ^= x >> 16; x *= 0x7feb352dU; x ^= x >> 15; x *= 0x846ca68bU; x ^= x >> 16;
+ return x;
+}
+
+/* ---------------------------------------------------------------- windows (bld_window.c) */
+/* lang_en.csv's "[0]" and "[1]" replaced by numbers (Localize.lo) */
+const char *lo1(char *buf, int size, const char *text, double v0);
+const char *lo2(char *buf, int size, const char *text, double v0, double v1);
+void win_line(WinOut *w, const char *text);
+void win_line1(WinOut *w, const char *text, double v0);
+void win_line2(WinOut *w, const char *text, double v0, double v1);
+/* the window's buttons call window_action with these (WA_UI_*: the user interface opens a window of its own) */
+enum {
+ WA_CYCLE_0 = 1, WA_CYCLE_1, WA_CYCLE_2, WA_CYCLE_3, /* CycleValueButton: the next value */
+ WA_MIRROR = 8, WA_TOGGLE, WA_BUILD, WA_BUILD_2, WA_SPECIAL, WA_SPECIAL_2, WA_PRIORITIZE, WA_MODE_0 = 16
+};
+/* (WA_UI_* are in bld.h: the user interface answers them) */
+extern bool bld_secret_orchid, bld_secret_dance, bld_secret_hangar;
+
+/* ---------------------------------------------------------------- shared parts of the families */
+/* Factory (bld_production.c) */
+void factory_work(Perm *p, Cit *c, float timeMod, bool stop);
+void factory_window_lines(Perm *p, WinOut *w);
+/* Park walking (ParkWalk, bld_entertainment.c) */
+void park_walk(const Perm *left, const Perm *right, Cit *c);
+bool park_open(void);
+/* houses' private teleporters, teleporters and elevators (bld_transport.c) */
+float transport_teleport_x(const Perm *p);
+void transport_teleport_used(Perm *p);
+void transport_teleport_arrived(Perm *p);
+bool transport_elevator_open_door(Perm *p);
+void transport_elevator_used(Perm *p);
+void transport_elevator_arrived(Perm *p);
+void teleporter_upkeep_lines(WinOut *w);
+void saucers_new_city(void);
+void saucer_on_landing_destroyed(uint16_t ls);
+void flying_draw_free(const GfxBand *b, int layer);
+void research_bot_draw_free(const GfxBand *b, int layer);
+/* world resources (bld_world.c) */
+bool resource_prioritized(const Perm *p);
+bool resource_any_prioritized(int base); /* B_FOREST or B_ROCK */
+void resource_set_prioritized(Perm *p, bool on);
+float limited_materials_left(const Perm *p); /* forests, rocks, plantations and rock teleporters */
+void limited_take(Perm *p, float amount);
+bool limited_stay_if_empty(const Perm *p);
+bool limited_do_not_gather(const Perm *p);
+bool limited_destroyed_on_empty(const Perm *p);
+int limited_min_x(const Perm *p), limited_max_x(const Perm *p);
+float ruins_explored(const Perm *p);
+void ruins_explore(Perm *p, float amount); /* explored += amount, and any bonuses */
+void ruins_new_city(void);
+void ruins_after_load(void);
+extern uint8_t world_unavailable[MAX_WORLDS]; /* knownResourceInavailability: bits WU_* */
+enum { WU_FOREST = 1, WU_ROCK = 2, WU_RUINS = 4 };
+/* hobbies (bld_hobbies.c) */
+void hobbies_new_city(void);
+void hobbies_after_load(void);
+void hobby_give(Cit *c);
+void hobby_draw_free(const GfxBand *b, int layer);
+/* unique buildings (bld_unique.c) */
+void unique_new_city(void);
+void festival_update(float timeMod);
+bool festival_running(void);
+
+/* ---------------------------------------------------------------- building a building in place (World.build + City.onBuildBuilding) */
+uint16_t bld_build_at(int w, int col, int row, int cls, bool replace);
+
+/* ---------------------------------------------------------------- each class's state
+ * (fixed point where a float would not fit; floats are 4 bytes, packed) */
+
+/* world resources: forests, rocks (LimitedWorldResource) */
+typedef struct PACKED {
+ float materialsLeft, regrowProgress;
+ uint8_t managementMode; /* Forest: 0 CutDownAndRegrow, 1 Protect, 2 CutDownAndUproot; Rock: 0 Mine, 1 Protect */
+ uint8_t prioritized;
+} LimitedState;
+STATE_FITS(LimitedState);
+/* AlienRuins */
+typedef struct PACKED {
+ uint16_t explored4; /* explored x 4 (it grows by 0.25) */
+ uint8_t bonusesAwarded;
+ uint8_t sprite; /* 0 spr_alienruins, 1 _2, 2 _3 */
+ uint8_t found[4]; /* each level's find: 0 none, 1 to 5 = a to e */
+} RuinsState;
+STATE_FITS(RuinsState);
+
+/* Work buildings that gather from world resources (BlueCollarWork) */
+typedef struct PACKED {
+ uint16_t nearest; /* nearestResourceGatherPlace */
+ uint8_t searched; /* !hasNotSearchedForResourceGatherPlaceThisStep */
+} BlueCollarState;
+STATE_FITS(BlueCollarState);
+/* Factory and MaterialConvertingFactory */
+typedef struct PACKED {
+ uint8_t activeWorkers;
+ uint16_t totalEdu; /* activeWorkersTotalEducation x 4096 */
+ uint8_t extra; /* FX_SHOW_ACTIVE; FarmByProductProcessor: cachedAdjacencyExpiration << 1 */
+ float materialMade, totalMaterialUsed; /* (MaterialConvertingFactory) */
+} FactoryState;
+STATE_FITS(FactoryState);
+/* FarmByProductProcessor (a Factory) */
+typedef struct PACKED {
+ uint8_t activeWorkers;
+ uint16_t totalEdu;
+ uint8_t extra;
+ float cacheValue, woodMade; /* cachedAdjacencyValue */
+} ByProductState;
+STATE_FITS(ByProductState);
+/* IndoorFarm: the stage's value (percentGrown, foodLeft or percentCleaned; only one is in use at a time) */
+typedef struct PACKED {
+ uint8_t stage;
+ float value;
+} IndoorFarmState;
+STATE_FITS(IndoorFarmState);
+/* EcoFarm and ExperimentalFarm: three FarmGrowAreas, each value in 24-bit fixed point (2^-17) */
+typedef struct PACKED {
+ uint8_t value[3][3]; /* percentGrown, foodLeft or percentCleaned, by stage */
+ uint8_t stages; /* 2 bits each */
+ uint8_t eco; /* EcoFarm: openDay (3 bits), crop2Sprite (2), crop3Sprite (1), plot 2 bonus (1) */
+ uint8_t pad;
+} GrowFarmState;
+STATE_FITS(GrowFarmState);
+/* Laboratory */
+typedef struct PACKED {
+ float totalKnowledgeGenerated;
+ uint8_t anyoneHasWorkedHere;
+} LabState;
+STATE_FITS(LabState);
+/* TreePlantation and StoneTeleporter (gather places in buildings) */
+typedef struct PACKED {
+ float materialsLeft, regrowProgress;
+ uint8_t flags; /* StoneTeleporter: TP_* */
+ uint8_t notPressedTime; /* teleportButtonNotPressedTime (capped) */
+} PlantationState;
+STATE_FITS(PlantationState);
+enum { TP_PRESSED = 1, TP_BIG = 2, TP_INITIAL_BIG = 4 };
+/* ExplorationCentre */
+typedef struct PACKED {
+ uint16_t nearestRuins;
+ uint8_t searched; /* hasSearchedForRuinsThisStep */
+ uint8_t currentAction; /* 0 Unknown (looking), 1 Exploring, 2 Investigating */
+} ExplorationState;
+STATE_FITS(ExplorationState);
+
+/* ---------------------------------------------------------------- houses (bld_houses.c) */
+typedef struct PACKED { uint8_t doorMainTexture, flowersLook; } NormalHouseState;
+typedef struct PACKED { uint8_t look; } AlienHouseState; /* LivingComputer's frame */
+typedef struct PACKED { uint8_t adjBonus; } RusticState; /* currentAdjBonus */
+typedef struct PACKED { uint8_t variant, movementType, pipeAlt; } MechanicalState;
+typedef struct PACKED { uint8_t plantLook; } CuttingEdgeState; /* ModernHomePlant's frame */
+typedef struct PACKED { uint8_t mainTexture, podTexture; } ParkPodState;
+typedef struct PACKED { uint8_t interior, mirrored; } LoftState;
+typedef struct PACKED { uint8_t front, back, toolsLook; } TinkerersState;
+typedef struct PACKED {
+ uint8_t bits; /* materialPhase (2 bits), farmEffects << 6 */
+ float stageProgress, totalMaterialsProduced;
+} FarmHouseState;
+typedef struct PACKED {
+ uint16_t timesUsed, timesUsedTo;
+ uint8_t mirrored; /* FlowerPenthouse, LandedExplorationShip */
+ uint8_t variant; /* Mansion: 0 alone, 1 left of a pair, 2 right */
+} PrivateTeleporterState;
+STATE_FITS(FarmHouseState);
+int farmhouse_farm_effects(const Perm *p);
+int upgrade_look(const Perm *p, int upgrade); /* the frame an upgrade's sprite shows */
+void upgrade_set_look(Perm *p, int upgrade, int look);
+uint16_t mechanical_house_texture(const Perm *p);
+uint16_t mansion_texture(const Perm *p);
+int rnd_getint(int a, int b); /* random_Random.getInt(a, b), also when b < a */
+
+/* ---------------------------------------------------------------- production helpers (bld_production.c) */
+float by_product_farms(const Perm *p, bool true_value); /* adjacentFarmNumber */
+int factory_frame(const Perm *p, int nframes);
+int limited_frame(float left, float initial, float regrow, int nframes, int nregrow);
+float plantation_regrow_speed(const Perm *p);
+float stone_teleporter_initial(const Perm *p);
+int plot_stage(const Perm *p, int i);
+void eco_farms_upgrade(void);
+void factory_update_any(Perm *p, float timeMod);
+void factory_draw_any(const GfxBand *b, const Perm *p, int layer, int x, int y);
+void factory_back_any(const GfxBand *b, const Perm *p, int x, int y, uint16_t active, uint16_t idle);
+bool first_worker_working(const Perm *p); /* workers[0].currentAction == 0 */
+Cit *worker_at(const Perm *p, int index); /* workers[index], NULL if none */
+bool operating_cost_user_enabled(void); /* teleportersAreUserEnabled (systems.c) */
+/* ---------------------------------------------------------------- entertainment (bld_entertainment.c) */
+typedef struct PACKED { uint8_t marked; } PubState; /* the Secret Society's marking */
+typedef struct PACKED {
+ uint8_t mainTexture, texture; /* currentMainTexture, currentTexture (plants, sculptures, statue) */
+ uint8_t mirrored; /* StatueGarden */
+ uint8_t podium; /* festival: 0 none, 1 at x 3, 2 at x -3 */
+} ParkState;
+typedef struct PACKED {
+ uint8_t mainTexture, texture; /* the colour, the plants (0 to 14) */
+ uint8_t domeVersion, justBuilt;
+ uint8_t podium;
+} GardenState;
+typedef struct PACKED { uint8_t texture; } RooftopParkState;
+typedef struct PACKED {
+ float lastExpanded; /* (the primary's counts) */
+ uint8_t subImage, hasGrass, isPrimary;
+} RedwoodState;
+STATE_FITS(RedwoodState);
+typedef struct PACKED {
+ uint8_t lightsAreOn; /* ticks x 4 */
+ uint8_t color; /* nightClubColor */
+ uint16_t knownCitizen; /* knownEntertainedCitizen */
+ uint8_t knownSet; /* knownEntertainedCitizenSet (ticks) */
+} NightClubState;
+typedef struct PACKED {
+ uint8_t lightsAreOn;
+ uint8_t texLeft, texOther, hadLeft, shownLeft, active;
+} ScrapyardState;
+typedef struct PACKED { uint8_t texture; } ArtMuseumState;
+typedef struct PACKED {
+ uint8_t gameType; /* 0 spaceship battle, 1 block game (the coordinator's counts) */
+ uint8_t gameInited;
+ uint8_t blocks[5]; /* each column's blocks (low 3 bits) and its top block's alpha in tenths (<< 3) */
+ uint8_t hueShift;
+ uint16_t progress1, progress2; /* spaceship battle: progressTeam1 and 2 x 65535 */
+} HoloState;
+STATE_FITS(HoloState);
+void pub_set_marking(Perm *p, bool on);
+bool park_like(const Perm *p); /* Park or BotanicalGardens (and their kinds) */
+void park_festival_work(Perm *p, Cit *c, float timeMod, int id);
+void park_festival_entertained(Perm *p, Cit *c);
+void park_festival_stop(Perm *p);
+bool garden_is_tree(const Perm *p);
+void redwood_destroy_refusal(const Perm *p, const char **why);
+/* ---------------------------------------------------------------- decoration (bld_decoration.c) */
+typedef struct PACKED {
+ uint8_t look; /* currentTexture: the sub-image (GlassPiece: 0 farm, 1 plantation) */
+ uint8_t bits; /* DS_* */
+ uint8_t rgb[3]; /* currentRecolor, when DS_TINTED */
+} DecorState;
+STATE_FITS(DecorState);
+enum { DS_MIRRORED = 1, DS_FLIPPED = 2, DS_TINTED = 4, DS_DOOR_SET = 8, DS_DOOR14 = 16 };
+float decoration_door_x(const Perm *p);
+void decoration_post_create(Perm *p);
+/* ---------------------------------------------------------------- transport (bld_transport.c) */
+typedef struct PACKED { uint16_t timesUsed, timesUsedTo; } TeleporterState; /* Teleporter, Misdirector */
+typedef struct PACKED {
+ uint16_t timesUsed, timesUsedTo;
+ uint8_t doorOpenFor; /* doorFullyOpenFor (ticks) */
+ uint8_t door; /* currentDoorTexture x 32 */
+} ElevatorState;
+typedef struct PACKED {
+ uint16_t timesUsed, timesUsedTo, timesUsedStopOver;
+ uint8_t hasSaucer, saucerType;
+ uint8_t newStage; /* gettingNewFlyingSaucerStage x 8 */
+ uint8_t newWait; /* timeUntilCanGetNewFlyingSaucer (ticks) */
+ uint8_t landed; /* currentlyLandedSaucer + 1 */
+} LandingState;
+STATE_FITS(LandingState);
+void particle_add(uint16_t spr, int fw, int x, int y); /* city.particles.addParticle at a city position */
+int flying_columns(void); /* FlyingPathfinder.highestYPositions: how many */
+int flying_highest_y(int index, int *x); /* and one of them: the column's x, its first obstruction */
+#endif
diff --git a/games/finalearth2/src/build.c b/games/finalearth2/src/build.c
new file mode 100644
index 00000000..8616955b
--- /dev/null
+++ b/games/finalearth2/src/build.c
@@ -0,0 +1,239 @@
+/* The Final Earth 2: building and destroying (Builder.canBuildBuilding,
+ * tryBuildingAt, World.build, City.onBuildBuilding, Building.tryDestroy).
+ *
+ * A building goes on top of a column's stack, into a hole in it, between two
+ * buildings above a gap (a "bridge" position), inserted into a stack (those
+ * above move up to the next hole), or in place of another (replace mode). */
+#include "bld.h"
+#include "build.h"
+
+BuildingMode building_mode = BM_NORMAL;
+float recycling_amount; /* upgrades.vars.recyclingAmount */
+BuilderLook builder_look = {0, false, -1};
+
+static bool is_city_top(const Perm *p) { return is_building(p) && (PC(p)->base & B_CITY_TOP); }
+static bool no_insert(const Perm *p) { return is_building(p) && (PC(p)->base & B_NO_INSERT); }
+
+/* World.canBuildOnSurface, canBuildOnNotSurface */
+static bool can_build_on_surface(const World *w) { return !(w->flags & WF_PROTECTED_KEY) && w->h != 0 && !(w->flags & WF_UNBUILDABLE_ALIENS); }
+static bool can_build_on_not_surface(const World *w, bool is_machine) { return !(w->flags & WF_PROTECTED_KEY) || is_machine; }
+
+/* the permanent whose 20x20 cell holds the city point */
+uint16_t permanent_at_pos(int x, int y) {
+ for (int w = 0; w < nworlds; w++) {
+ World *wd = &worlds[w];
+ if (x < wd->x || x >= wd->x + wd->w) continue;
+ int col = (x - wd->x) / 20;
+ if (y >= wd->y) continue;
+ int row = (wd->y - 1 - y) / 20;
+ uint16_t p = perm_at(w, col, row);
+ if (p) return p;
+ }
+ return NONE;
+}
+
+static bool another_world_body_at(int w, int x, int y) {
+ for (int o = 0; o < nworlds; o++) {
+ World *ow = &worlds[o];
+ if (o == w || ow->h == 0) continue;
+ if (x + 20 <= ow->x || x >= ow->x + ow->w || y + 20 <= ow->y || y >= ow->y + ow->h) continue;
+ if (world_mask_at(o, (x - ow->x) / 20, (y - ow->y) / 20)) return true;
+ }
+ return false;
+}
+
+/* Builder.canRemoveFromLRPerspective (without the paid version's advanced building) */
+static bool can_remove_lr(const Perm *b) {
+ const Perm *l = P(b->left), *r = P(b->right);
+ if (!l || l->row == 0 || l->bottom) return !r || r->row == 0 || r->bottom;
+ return false;
+}
+/* Builder.canRemoveLeavingHoleFromStructuralPerspective */
+static bool can_remove_leaving_hole(const Perm *b) {
+ const Perm *l = P(b->left), *r = P(b->right), *t = P(b->top);
+ if ((!l || l->row == 0 || l->bottom) && (!r || r->row == 0 || r->bottom) && ((!l && !r && !t) || (l && r) || !t)) {
+ if (t) return t->left && t->right;
+ return true;
+ }
+ return false;
+}
+
+/* Builder.canBuildBuilding */
+BuildPossibility builder_can_build(int w, int x, int y, int cls) {
+ if (w < 0 || w >= nworlds || x < 0 || x >= worlds[w].ncols || y < 0) return BP_IMPOSSIBLE;
+ World *wd = &worlds[w];
+ const PermClass *pc = &pcls[cls];
+ bool rooftop = pc->base & B_ROOFTOP;
+ if (y == 0 && !can_build_on_surface(wd)) return BP_WORLD_NOT_ALLOWED;
+ if (!can_build_on_not_surface(wd, !strcmp(pc->name, "TheMachine") && !building_mode_can_replace())) return BP_WORLD_NOT_ALLOWED;
+ int h = col_stack_height(w, x);
+ if (pc->base & B_BUILD_ON_GROUND) {
+ if (y != 0) return BP_IMPOSSIBLE;
+ if (h > 0 && perm_at(w, x, 0)) return BP_IMPOSSIBLE;
+ }
+ int y_top = wd->y - 20 * (h + 1);
+ int bx = wd->x + 20 * x, by = wd->y - 20 * (y + 1);
+ bool none_yet = h == 0;
+ Perm *top = h ? P(perm_at(w, x, h - 1)) : NULL;
+ Perm *bottom = h ? P(perm_at(w, x, 0)) : NULL;
+ bool top_is_building = !none_yet && is_building(top);
+ bool bottom_not_resource = none_yet || !bottom || is_building(bottom);
+ bool top_rooftop = top_is_building && (top->flags & PF_NO_BUILD_ON_TOP);
+ int y_top_ex = top_rooftop ? y_top + 20 : y_top;
+ bool allow_bridge = false;
+ bool can_insert = building_mode == BM_INSERT;
+ bool can_replace = building_mode_can_replace();
+ Perm *here = y < h ? P(perm_at(w, x, y)) : NULL;
+ Perm *below = y > 0 && y - 1 < h ? P(perm_at(w, x, y - 1)) : NULL;
+ if (!can_replace && is_building(here) && (here->flags & PF_NO_BUILD_ON_TOP)) can_insert = true;
+ bool building_here = is_building(here);
+ bool rooftop_here = false, has_lr = false, same = false;
+ if (building_here) {
+ /* DragReplace: not over one of its own class that already looks the same */
+ same = building_mode == BM_DRAG_REPLACE && here->cls == cls &&
+ bld_same_customizations(here, builder_look.decor, builder_look.mirrored, builder_look.color);
+ rooftop_here = here->flags & PF_NO_BUILD_ON_TOP;
+ if (no_insert(here)) return BP_IMPOSSIBLE;
+ }
+ if (story_is("cityofthekey") && building_here && can_replace && is_a(here, B_LANDINGSITE) &&
+ (perm_city_x(here) == 100 || perm_city_x(here) == -100))
+ return BP_IMPOSSIBLE;
+ if (!here && y > 0 && !rooftop) {
+ Perm *l = P(permanent_at_pos(bx - 20, by)), *r = P(permanent_at_pos(bx + 20, by));
+ if (is_building(l) && is_building(r)) {
+ has_lr = true;
+ if (!(l->flags & PF_NO_BUILD_ON_TOP) && !(r->flags & PF_NO_BUILD_ON_TOP)) allow_bridge = true;
+ }
+ if (allow_bridge) {
+ /* not over another world that is nearer below */
+ for (int o = 0; o < nworlds; o++) {
+ World *ow = &worlds[o];
+ if (o != w && bx >= ow->x && bx < ow->x + ow->w && ow->y - by > 0 && ow->y - by < wd->y - by) { allow_bridge = false; break; }
+ }
+ }
+ }
+ bool null_between = false;
+ if (can_insert) {
+ for (int i = y; i < h - 1; i++) {
+ Perm *q = P(perm_at(w, x, i));
+ if (!q) { null_between = true; break; }
+ if (is_building(q) && (q->flags & PF_NO_BUILD_ON_TOP) && perm_at(w, x, i + 1)) return BP_IMPOSSIBLE;
+ }
+ }
+ if (pc->base & B_CITY_TOP) {
+ if (y != h) return BP_IMPOSSIBLE;
+ for (int o = 0; o < nworlds; o++) {
+ World *ow = &worlds[o];
+ if (ow->y < by && ow->x <= bx && ow->x + ow->w > bx) return BP_IMPOSSIBLE;
+ }
+ } else if (y != 0 && y >= h && h && is_city_top(top)) {
+ return BP_IMPOSSIBLE;
+ }
+ bool ok =
+ (can_replace && building_here && (!rooftop || rooftop_here) && !same) ||
+ ((none_yet || top_is_building || allow_bridge) && (y != 0 || bottom_not_resource) &&
+ (((can_insert || (y < h && !here)) && (by >= y_top_ex && by < wd->y) &&
+ (y == 0 || has_lr || (y > 0 && building_here) || (y > 0 && is_building(below) && !(below->flags & PF_NO_BUILD_ON_TOP)))) ||
+ (!can_insert && (by >= y_top_ex && by < y_top_ex + 20)) || allow_bridge) &&
+ (y >= h || (!here && allow_bridge) || y == 0 || below || can_insert) &&
+ (!rooftop || y == h || !here ||
+ (y == h - 1 && can_replace && building_here && !same &&
+ (y == 0 || (here->bottom && !(P(here->bottom)->flags & PF_NO_BUILD_ON_TOP))) &&
+ can_remove_lr(here))));
+ if (!ok) return BP_IMPOSSIBLE;
+ int check_y = can_insert ? (by < y_top ? by : y_top) : by;
+ if (null_between) return BP_OK;
+ if (can_insert && y < h && !here) return BP_OK;
+ if (y < h && !here) return BP_OK;
+ return another_world_body_at(w, bx, check_y) ? BP_IN_WORLD : BP_OK;
+}
+
+/* the cost now: the class's, without its research price once researched */
+void builder_cost(int cls, Materials *out) {
+ for (int i = 0; i < M_COUNT; i++) out->m[i] = pcls[cls].cost[i]; /* (floats into doubles) */
+ building_cost_scale(cls, out);
+ if (unlock_state(cls) == UNLOCK_RESEARCHED) out->m[M_KNOWLEDGE] = 0;
+}
+bool can_afford(const Materials *m) {
+ for (int i = 0; i < M_COUNT; i++)
+ if (city.materials.m[i] < m->m[i]) return false;
+ return true;
+}
+/* Builder.buildingPrerequirementsValid: affordable, and not a second unique (or more than its limit) */
+bool builder_prerequisites(int cls) {
+ const PermClass *pc = &pcls[cls];
+ int count = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == cls) count++;
+ bool ok = !(pc->base & B_UNIQUE) || count == 0 || unique_not_unique(cls);
+ if (ok && pc->limitedTo > 0) ok = count < pc->limitedTo;
+ if (ok && pc->limitedPerCitizens > 0) ok = count < (ncits + pc->limitedPerCitizens - 1) / pc->limitedPerCitizens;
+ Materials cost;
+ builder_cost(cls, &cost);
+ return ok && can_afford(&cost);
+}
+
+/* Building.giveRecycleReward */
+void give_recycle_reward(const Perm *p, bool full) {
+ Materials m = {{0}};
+ if (full)
+ for (int i = 0; i < M_COUNT; i++) m.m[i] = PC(p)->cost[i]; /* (floats into doubles) */
+ building_upgrades_cost_sum(p, &m);
+ m.m[M_KNOWLEDGE] = 0;
+ for (int i = 0; i < M_COUNT; i++) city.materials.m[i] += m.m[i] * recycling_amount;
+}
+
+/* tryBuildingAt and World.build: returns the new building */
+uint16_t builder_build(int w, int x, int y, int cls) {
+ Materials cost;
+ builder_cost(cls, &cost);
+ int h = col_stack_height(w, x);
+ Perm *here = y < h ? P(perm_at(w, x, y)) : NULL;
+ bool replace = building_mode_can_replace() && here;
+ bool insert = !building_mode_can_replace() && here;
+ bool pay = true;
+ if (replace) {
+ pay = here->cls != cls;
+ if (pay && is_building(here)) give_recycle_reward(here, pay);
+ perm_destroy(pid(here), true);
+ } else if (insert) {
+ /* the run above moves up a row, into the first hole */
+ int top = y;
+ while (top < h && perm_at(w, x, top)) top++;
+ for (int i = top - 1; i >= y; i--) perm_move(perm_at(w, x, i), i + 1);
+ }
+ if (y == 0) col_deco[worlds[w].col0 + x] = 0; /* removeDecoration */
+ uint16_t id = perm_new(cls, w, x, y);
+ if (!id) return NONE;
+ bld_on_build(P(id));
+ if (pay)
+ for (int i = 0; i < M_COUNT; i++) city.materials.m[i] -= cost.m[i];
+ /* City.onBuildBuilding */
+ city_update_connections();
+ sim_update_pathfinder(insert || replace, id);
+ unlocks_research(cls);
+ bld_post_create(P(id));
+ unlocks_check_build_related();
+ return id;
+}
+
+/* Building.tryDestroy: false (and why) when the structure would not hold */
+DestroyResult building_try_destroy(uint16_t id) {
+ Perm *p = P(id);
+ if (worlds[p->world].flags & WF_PROTECTED_KEY) return DR_PROTECTED;
+ const char *why;
+ int refused = bld_destroy_check(p, &why); /* (the class's own tryDestroy) */
+ if (refused != DR_OK) return (DestroyResult)refused;
+ bool failed = false;
+ if (!(p->flags & PF_ROOFTOP)) {
+ Perm *top = p;
+ while (top->top && !(P(top->top)->flags & PF_ROOFTOP)) top = P(top->top);
+ failed = building_mode == BM_DESTROY_LEAVING_HOLE ? !can_remove_leaving_hole(p) : !can_remove_lr(top);
+ if (p->top && (P(p->top)->flags & PF_ROOFTOP) && !p->bottom && p->row != 0) failed = true;
+ }
+ if (failed) return building_mode == BM_DESTROY_LEAVING_HOLE ? DR_INVALID_STRUCTURE_HOLE : DR_INVALID_STRUCTURE;
+ give_recycle_reward(p, true);
+ bool keep_hole = ((p->flags & PF_ROOFTOP) || building_mode == BM_DESTROY_LEAVING_HOLE) && p->row != col_stack_height(p->world, p->col) - 1;
+ perm_destroy_keep_hole(id, keep_hole);
+ return DR_OK;
+}
diff --git a/games/finalearth2/src/build.h b/games/finalearth2/src/build.h
new file mode 100644
index 00000000..91dee7c6
--- /dev/null
+++ b/games/finalearth2/src/build.h
@@ -0,0 +1,44 @@
+/* The Final Earth 2: building and destroying (build.c). */
+#ifndef FE_BUILD_H
+#define FE_BUILD_H
+#include "fe.h"
+
+/* the original's BuildingMode: Drag and DragReplace build on every cell the cursor passes while OK is held */
+typedef enum { BM_NORMAL, BM_INSERT, BM_REPLACE, BM_DRAG, BM_DRAG_REPLACE, BM_DESTROY, BM_DESTROY_LEAVING_HOLE } BuildingMode;
+#define BM_COUNT 7
+typedef enum { BP_OK, BP_WORLD_NOT_ALLOWED, BP_IMPOSSIBLE, BP_IN_WORLD } BuildPossibility;
+typedef enum { DR_OK, DR_PROTECTED, DR_INVALID_STRUCTURE, DR_INVALID_STRUCTURE_HOLE, DR_REFUSED } DestroyResult;
+enum { UNLOCK_LOCKED, UNLOCK_UNLOCKED, UNLOCK_RESEARCHED };
+
+extern BuildingMode building_mode;
+extern float recycling_amount;
+/* the builder's look (decorationAppearance, mirrored, decorationAppearanceColor): DragReplace leaves alone a
+ * building of the same class that already looks so */
+typedef struct { int decor; bool mirrored; int32_t color; } BuilderLook;
+extern BuilderLook builder_look;
+static inline bool building_mode_can_replace(void) { return building_mode == BM_REPLACE || building_mode == BM_DRAG_REPLACE; }
+static inline bool building_mode_can_drag(void) { return building_mode == BM_DRAG || building_mode == BM_DRAG_REPLACE; }
+bool bld_same_customizations(const Perm *p, int decor, bool mirrored, int32_t color); /* areSameCustomizations */
+
+uint16_t permanent_at_pos(int x, int y);
+BuildPossibility builder_can_build(int w, int x, int y, int cls);
+void builder_cost(int cls, Materials *out);
+bool can_afford(const Materials *m);
+bool builder_prerequisites(int cls);
+uint16_t builder_build(int w, int x, int y, int cls);
+DestroyResult building_try_destroy(uint16_t id);
+void give_recycle_reward(const Perm *p, bool full);
+
+/* from other parts */
+bool world_mask_at(int w, int cx, int cy); /* the island's collision mask (bg.c) */
+int unlock_state(int cls);
+void unlocks_research(int cls);
+void unlocks_check_build_related(void);
+bool unique_not_unique(int cls); /* notUniqueIfGalacticLibrary */
+void building_cost_scale(int cls, Materials *cost); /* progress.BuildingCost */
+void building_upgrades_cost_sum(const Perm *p, Materials *m);
+void bld_on_build(Perm *p);
+void bld_post_create(Perm *p);
+void perm_move(uint16_t id, int row);
+void perm_destroy_keep_hole(uint16_t id, bool keep_hole);
+#endif
diff --git a/games/finalearth2/src/citizen.c b/games/finalearth2/src/citizen.c
new file mode 100644
index 00000000..235a10a6
--- /dev/null
+++ b/games/finalearth2/src/citizen.c
@@ -0,0 +1,950 @@
+/* The Final Earth 2: citizens (Citizen and simulation.CitizenEntertainment).
+ *
+ * A citizen is on a world's surface (inPermanent 0, relativeX from the
+ * world's left) or in a permanent (relativeX from its left, relativeY up from
+ * its floor). What they do comes from their path: a list of steps, each a type
+ * and a value. Steps from the pathfinder walk between permanents, steps from
+ * scripts move, wait or change floor in place:
+ * 0 up, 1 down, 2 left, 3 right (to the neighbouring building)
+ * 4 move to x, 5 to a permanent's door from outside (or out of one)
+ * 7 teleport to, 8 wait, 9 change floor to y, 10 nothing, 11 fly to (landing sites)
+ * 12 set the walking speed (percent), 13 hyper elevator to, 15/16 bridge left/right */
+#include "sim.h"
+#include "bld.h"
+#include "scratch.h"
+
+Cit cits[MAX_CITS];
+int ncits;
+ThenFn then_fns[THEN_COUNT_];
+static uint8_t nthen = 1;
+uint8_t then_register(void (*fn)(Cit *c, uint16_t arg)) {
+ if (nthen >= THEN_COUNT_) return THEN_NONE;
+ then_fns[nthen] = fn;
+ return nthen++;
+}
+
+static inline uint16_t now_ticks(void) { return (uint16_t)(int64_t)(city.timeSinceStart * 2.0); }
+static inline uint16_t now_minutes(void) { return (uint16_t)(int64_t)city.timeSinceStart; }
+/* the entertainment times: 2-hour and 4-minute units that wrap (kept near now by cit_infrequent_update) */
+static inline uint8_t now_2h(void) { return (uint8_t)(int64_t)(city.timeSinceStart / 120.0); }
+static inline uint8_t now_4m(void) { return (uint8_t)(int64_t)(city.timeSinceStart / 4.0); }
+static inline uint8_t at_2h(double t) {
+ double d = (t - city.timeSinceStart) / 120.0;
+ if (d > 120) d = 120;
+ if (d < -120) d = -120;
+ return (uint8_t)(now_2h() + (int)floor(d + (t >= city.timeSinceStart ? 0.999 : 0)));
+}
+static inline uint8_t at_4m(double t) {
+ double d = (t - city.timeSinceStart) / 4.0;
+ if (d > 120) d = 120;
+ if (d < -120) d = -120;
+ return (uint8_t)(now_4m() + (int)floor(d + (t >= city.timeSinceStart ? 0.999 : 0)));
+}
+static inline bool past_2h(uint8_t v) { return (int8_t)(now_2h() - v) >= 0; }
+static inline bool past_4m(uint8_t v) { return (int8_t)(now_4m() - v) >= 0; }
+/* a past time far back moves up to 64 units back, so it never wraps around to look ahead */
+static inline void keep_near(uint8_t *v, uint8_t now) { if ((int8_t)(now - *v) > 64) *v = (uint8_t)(now - 64); }
+static inline void die_add(Cit *c, float years) {
+ float v = c->dieAgeModifier + years * 100;
+ c->dieAgeModifier = (int16_t)(v > 32000 ? 32000 : v < -32000 ? -32000 : v);
+}
+static inline bool in_hours(float t, float start, float end) {
+ return start < end ? t >= start && t < end : t >= start || t < end;
+}
+
+/* ---------------------------------------------------------------- the path pool
+ * every citizen's steps, packed in one array: a step is its type (5 bits)
+ * and its value + 256 (11 bits) */
+#define PATH_MEM 3072
+static uint16_t path_mem[PATH_MEM];
+static int path_top = 1; /* 0 is never used, so pathOff 0 means none */
+
+static inline uint16_t step_pack(int type, int value) {
+ int v = value + 256;
+ if (v < 0) v = 0;
+ if (v > 2047) v = 2047;
+ return (uint16_t)(type << 11 | v);
+}
+static inline int step_type(uint16_t s) { return s >> 11; }
+static inline int step_value(uint16_t s) { return (int)(s & 2047) - 256; }
+
+static int cmp_off(const void *a, const void *b);
+static void path_compact(void) {
+ /* move every live path down, in order of where it is */
+ uint16_t *order = scratch->u.compact.order;
+ int n = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].pathOff) order[n++] = (uint16_t)i;
+ /* insertion sort by offset (paths are mostly in order already) */
+ for (int i = 1; i < n; i++) {
+ uint16_t k = order[i];
+ int j = i - 1;
+ while (j >= 0 && cits[order[j]].pathOff > cits[k].pathOff) order[j + 1] = order[j], j--;
+ order[j + 1] = k;
+ }
+ int top = 1;
+ for (int i = 0; i < n; i++) {
+ Cit *c = &cits[order[i]];
+ if (c->pathOff != top) memmove(path_mem + top, path_mem + c->pathOff, sizeof path_mem[0] * c->pathLen);
+ c->pathOff = (uint16_t)top;
+ top += c->pathLen;
+ }
+ path_top = top;
+ (void)cmp_off;
+}
+static int cmp_off(const void *a, const void *b) { (void)a; (void)b; return 0; }
+
+/* room for n steps (0 if there is none even after compacting) */
+static uint16_t path_room(int n) {
+ if (path_top + n > PATH_MEM) path_compact();
+ if (path_top + n > PATH_MEM) return 0;
+ uint16_t off = (uint16_t)path_top;
+ path_top += n;
+ return off;
+}
+uint16_t *cit_steps(const Cit *c) { return path_mem + c->pathOff; }
+
+static inline bool has_path(const Cit *c) { return (c->flags & CF_HAS_PATH) != 0; }
+static inline int path_type_at(const Cit *c, int pos) { return step_type(path_mem[c->pathOff + pos]); }
+static inline int path_value_at(const Cit *c, int pos) { return step_value(path_mem[c->pathOff + pos]); }
+
+/* ---------------------------------------------------------------- basics */
+float cit_age(const Cit *c) { return (float)((city.timeSinceStart - c->bornOn) / 1440.0); }
+float cit_steps_in_building(const Cit *c) { return (float)(uint16_t)(now_ticks() - c->inBuildingSince); }
+float cit_work_time_preference(const Cit *c) {
+ float p = c->workTimePref / 127.0f;
+ return c->job ? p * PC(P(c->job))->workTimePreferenceMod : p;
+}
+float cit_education_speed_modifier(const Cit *c) { return 1 + c->educationLevel / 2; }
+
+bool cit_should_work_now(const Cit *c) {
+ if (!c->job) return false;
+ Perm *j = P(c->job);
+ float t = city_hour();
+ float start = bld_start_time(j) + cit_work_time_preference(c);
+ float end = fmodf(bld_end_time(j) + cit_work_time_preference(c) + policies.workTimeChange, 24);
+ return in_hours(t, start, end);
+}
+bool cit_should_school_now(const Cit *c) {
+ if (!c->school) return false;
+ Perm *s = P(c->school);
+ return in_hours(city_hour(), bld_school_start(s), bld_school_end(s));
+}
+
+/* the citizen's position in the city (getCityPosition) */
+void cit_city_position(const Cit *c, float *x, float *y) {
+ if (c->inPermanent) {
+ Perm *p = P(c->inPermanent);
+ *x = (float)perm_city_x(p) + c->relativeX;
+ *y = (float)perm_city_y(p) + 20 - c->relativeY - (is_building(p) ? 1 : 0);
+ } else {
+ World *w = &worlds[c->onWorld];
+ *x = w->x + c->relativeX;
+ *y = w->y - c->relativeY;
+ }
+ if (has_path(c)) {
+ if (c->currentPathAction == 0) *y -= cit_vpp(c);
+ else if (c->currentPathAction == 1) *y += cit_vpp(c);
+ }
+}
+
+/* ---------------------------------------------------------------- entering and leaving */
+static void on_leave(Cit *c, uint16_t to) {
+ Perm *p = P(c->inPermanent);
+ if (p && PC(p)->ops && PC(p)->ops->on_citizen_leave) PC(p)->ops->on_citizen_leave(p, c, to);
+}
+void cit_go_to_permanent(Cit *c, uint16_t perm) {
+ if (c->inPermanent) on_leave(c, perm);
+ c->inBuildingSince = now_ticks();
+ c->inPermanent = perm;
+ c->flags &= (uint16_t)~CF_BUILDING_INITED;
+}
+/* out of the permanent, onto its world's surface at its door */
+void cit_instant_leave_permanent(Cit *c) {
+ Perm *p = P(c->inPermanent);
+ if (is_building(p)) c->relativeX = (float)(p->col * 20 + bld_door_x(p));
+ else c->relativeX += p->col * 20;
+ on_leave(c, NONE);
+ c->inBuildingSince = now_ticks();
+ c->inPermanent = NONE;
+ c->relativeY = 0;
+}
+bool cit_move_towards_x(Cit *c, float x, float timeMod) {
+ float spd = c->pathWalkSpeed / 100.0f * timeMod;
+ if (fabsf(x - c->relativeX) < spd) {
+ c->relativeX = x;
+ return true;
+ }
+ c->relativeX += (x > c->relativeX ? 1 : -1) * spd;
+ return false;
+}
+/* leavePermanent: walk to the door, then out (true once out) */
+bool cit_leave_permanent(Cit *c, float timeMod) {
+ Perm *p = P(c->inPermanent);
+ if (is_building(p)) {
+ if (!cit_move_towards_x(c, bld_door_x(p), timeMod)) return false;
+ }
+ cit_instant_leave_permanent(c);
+ return true;
+}
+
+/* ---------------------------------------------------------------- paths */
+void cit_reset_path(Cit *c, bool reset_can_view_self) {
+ c->flags &= (uint16_t)~CF_HAS_PATH;
+ c->pathOff = 0;
+ c->pathLen = c->pathPos = 0;
+ c->currentPathAction = -2;
+ if (reset_can_view_self) {
+ if (!(c->flags & CF_CAN_VIEW_SELF)) c->flags |= CF_DELAY_CAN_VIEW_SELF;
+ c->flags |= CF_CAN_VIEW_SELF;
+ }
+ cit_set_vpp(c, 0);
+ c->then = THEN_NONE;
+ c->requestingPathGoal = NONE;
+ c->pathOnlyRelatedTo = NONE;
+ c->pathWalkSpeed = 100;
+ c->flags |= CF_PATH_RECONSIDER;
+ cit_set_timer(c, 0);
+}
+
+/* setPath with packed steps; failed (a path of -1) when n < 0 */
+static void set_path_packed(Cit *c, const uint16_t *steps, int n, bool from_pathfinder) {
+ if (n < 0) {
+ c->flags &= (uint16_t)~CF_REQUESTING_PATH;
+ if (c->requestingPathGoal && c->requestingPathGoal == c->home) cit_evict_from_home(c);
+ else if (c->requestingPathGoal && c->requestingPathGoal == c->job) cit_lose_job(c, false);
+ else if (c->requestingPathGoal && c->requestingPathGoal == c->school) cit_leave_school(c);
+ uint8_t fail = c->onFail;
+ c->onFail = THEN_NONE;
+ if (fail && then_fns[fail]) then_fns[fail](c, c->thenArg);
+ cit_reset_path(c, false);
+ return;
+ }
+ c->pathDestination = c->requestingPathGoal;
+ cit_reset_path(c, false);
+ if (n) {
+ uint16_t off = path_room(n);
+ if (!off) { /* no room: as if the path is still coming (asked again later) */
+ if (from_pathfinder) c->pathDestination = NONE;
+ c->flags &= (uint16_t)~CF_REQUESTING_PATH;
+ return;
+ }
+ memcpy(path_mem + off, steps, sizeof *steps * n);
+ c->pathOff = off;
+ c->pathLen = (uint8_t)n;
+ c->pathPos = 0;
+ c->currentPathAction = -1;
+ c->flags |= CF_HAS_PATH;
+ if (c->inPermanent && (c->relativeX < 0 || c->relativeX > 18)) {
+ int t = step_type(steps[0]);
+ if (t != 15 && t != 16) c->relativeX = c->relativeX < 0 ? 0 : 18;
+ }
+ }
+ c->flags &= (uint16_t)~CF_REQUESTING_PATH;
+ c->pathStartTime = now_minutes();
+}
+
+/* a path from the pathfinder: (type, value) pairs, or n < 0 if none was found */
+void cit_set_found_path(Cit *c, const int16_t *pairs, int n) {
+ uint16_t buf[128];
+ if (n > 128) n = -1; /* longer than a citizen can hold: as no path */
+ for (int i = 0; i < n; i++) buf[i] = step_pack(pairs[2 * i], pairs[2 * i + 1]);
+ set_path_packed(c, buf, n, true);
+}
+
+/* a scripted path (type, value pairs) */
+void cit_set_path(Cit *c, const int16_t *pairs, int n) {
+ uint16_t buf[CIT_SCRIPTED_MAX];
+ if (n > CIT_SCRIPTED_MAX) n = CIT_SCRIPTED_MAX;
+ for (int i = 0; i < n; i++) buf[i] = step_pack(pairs[2 * i], pairs[2 * i + 1]);
+ set_path_packed(c, buf, n, false);
+}
+void cit_set_path_then(Cit *c, const int16_t *pairs, int n, uint8_t then, uint16_t arg) {
+ cit_set_path(c, pairs, n);
+ c->then = then;
+ c->thenArg = arg;
+}
+static void scripted(Cit *c, const int16_t *pairs, int n, uint8_t then, uint16_t arg) {
+ cit_set_path(c, pairs, n);
+ c->then = then;
+ c->thenArg = arg;
+ c->pathOnlyRelatedTo = c->inPermanent;
+}
+
+void cit_wait(Cit *c, int time, uint8_t then, uint16_t arg) {
+ int16_t s[] = {8, (int16_t)time};
+ scripted(c, s, 1, then, arg);
+}
+void cit_wait_random(Cit *c, int tmin, int tmax, uint8_t then, uint16_t arg) {
+ int16_t s[] = {8, (int16_t)rnd_between(tmin, tmax)};
+ scripted(c, s, 1, then, arg);
+}
+void cit_move(Cit *c, int x, uint8_t then, uint16_t arg, bool slow) {
+ if (slow) {
+ int16_t s[] = {12, 50, 4, (int16_t)x};
+ scripted(c, s, 2, then, arg);
+ } else {
+ int16_t s[] = {4, (int16_t)x};
+ scripted(c, s, 1, then, arg);
+ }
+}
+void cit_move_random(Cit *c, int xmin, int xmax, uint8_t then, uint16_t arg, bool slow) {
+ cit_move(c, rnd_between(xmin, xmax), then, arg, slow);
+}
+void cit_move_and_wait(Cit *c, int x, int time, uint8_t then, uint16_t arg, bool modify_with_happiness, bool slow) {
+ if (modify_with_happiness) time = (int)(time / happiness.actionSpeedModifier);
+ if (slow) {
+ int16_t s[] = {12, 50, 4, (int16_t)x, 8, (int16_t)time};
+ scripted(c, s, 3, then, arg);
+ } else {
+ int16_t s[] = {4, (int16_t)x, 8, (int16_t)time};
+ scripted(c, s, 2, then, arg);
+ }
+}
+void cit_move_and_wait_random(Cit *c, int xmin, int xmax, int tmin, int tmax, uint8_t then, uint16_t arg,
+ bool modify_with_happiness, bool slow) {
+ int x = rnd_between(xmin, xmax);
+ cit_move_and_wait(c, x, rnd_between(tmin, tmax), then, arg, modify_with_happiness, slow);
+}
+void cit_wait_and_move_and_wait_random(Cit *c, int t1min, int t1max, int xmin, int xmax, int tmin, int tmax,
+ uint8_t then, uint16_t arg, bool modify_with_happiness, bool slow) {
+ int t1 = rnd_between(t1min, t1max), t2 = rnd_between(tmin, tmax), x = rnd_between(xmin, xmax);
+ if (modify_with_happiness) {
+ t1 = (int)(t1 / happiness.actionSpeedModifier);
+ t2 = (int)(t2 / happiness.actionSpeedModifier);
+ }
+ if (slow) {
+ int16_t s[] = {8, (int16_t)t1, 12, 50, 4, (int16_t)x, 8, (int16_t)t2};
+ scripted(c, s, 4, then, arg);
+ } else {
+ int16_t s[] = {8, (int16_t)t1, 4, (int16_t)x, 8, (int16_t)t2};
+ scripted(c, s, 3, then, arg);
+ }
+}
+void cit_move_towards_random_in_world_coords(Cit *c, int xmin, int xmax, uint8_t then, uint16_t arg) {
+ int to = rnd_between(xmin, xmax);
+ Perm *p = P(c->inPermanent);
+ if (p) {
+ float diff = to - c->relativeX - perm_city_x(p);
+ if (diff < -c->relativeX) {
+ if (p->left) {
+ int16_t s[] = {2, 0, 4, 18};
+ cit_set_path(c, s, 2);
+ } else {
+ int16_t s[] = {4, 0};
+ scripted(c, s, 1, THEN_NONE, 0);
+ }
+ } else if (diff >= 20 - c->relativeX) {
+ if (p->right) {
+ int16_t s[] = {3, 0, 4, 0};
+ cit_set_path(c, s, 2);
+ } else {
+ int16_t s[] = {4, 18};
+ scripted(c, s, 1, THEN_NONE, 0);
+ }
+ } else {
+ int16_t s[] = {4, (int16_t)floorf(diff + c->relativeX)};
+ scripted(c, s, 1, THEN_NONE, 0);
+ }
+ c->then = then;
+ c->thenArg = arg;
+ } else {
+ World *w = &worlds[c->onWorld];
+ int16_t s[] = {4, (int16_t)rnd_between(xmin - w->x, xmax - w->x)};
+ scripted(c, s, 1, then, arg);
+ }
+}
+bool cit_is_at_ground_level(const Cit *c) { return c->relativeY < 5; }
+void cit_change_floor(Cit *c, uint8_t then, uint16_t arg) {
+ int16_t s[] = {9, (int16_t)(cit_is_at_ground_level(c) ? 10 : 0)};
+ scripted(c, s, 1, then, arg);
+}
+void cit_change_floor_and_wait(Cit *c, int wait, uint8_t then, uint16_t arg) {
+ int16_t s[] = {9, (int16_t)(c->relativeY == 0 ? 10 : 0), 8, (int16_t)wait};
+ scripted(c, s, 2, then, arg);
+}
+void cit_change_floor_and_wait_random(Cit *c, int tmin, int tmax, uint8_t then, uint16_t arg) {
+ cit_change_floor_and_wait(c, rnd_between(tmin, tmax), then, arg);
+}
+void cit_change_floor_and_move_random(Cit *c, int xmin, int xmax, uint8_t then, uint16_t arg) {
+ int16_t s[] = {9, (int16_t)(cit_is_at_ground_level(c) ? 10 : 0), 4, (int16_t)rnd_between(xmin, xmax)};
+ scripted(c, s, 2, then, arg);
+}
+
+void cit_wander(Cit *c, float timeMod) {
+ if (!c->inPermanent) {
+ int rx = (int)c->relativeX;
+ int lo = rx - 100 > 0 ? rx - 100 : 0;
+ int hi = worlds[c->onWorld].w - 2 < rx + 100 ? worlds[c->onWorld].w - 2 : rx + 100;
+ cit_move_and_wait(c, rnd_between(lo, hi), rnd_between(30, 60), THEN_NONE, 0, false, false);
+ } else {
+ cit_go_down_towards_world_surface(c, timeMod);
+ }
+}
+
+static uint8_t impossible_surface_world[MAX_CITS]; /* impossibleToReachWorldSurfaceForWorld + 1 */
+void cit_go_down_towards_world_surface(Cit *c, float timeMod) {
+ Perm *p = P(c->inPermanent);
+ if (p->row == 0 && worlds[p->world].h > 0) {
+ cit_leave_permanent(c, timeMod);
+ impossible_surface_world[cid(c)] = 0;
+ return;
+ }
+ if (impossible_surface_world[cid(c)] == c->onWorld + 1) return;
+ /* (a path holds CIT_SCRIPTED_MAX steps: from higher up, the citizen goes that far down, then on from there) */
+ int16_t s[2 * CIT_SCRIPTED_MAX];
+ int n = 0;
+ Perm *pm = p;
+ while (pm->row != 0 && n < CIT_SCRIPTED_MAX - 1) {
+ if (!pm->bottom) {
+ if (pm->left) s[2 * n] = 2, s[2 * n + 1] = 0, n++, pm = P(pm->left);
+ else if (pm->right) s[2 * n] = 3, s[2 * n + 1] = 0, n++, pm = P(pm->right);
+ }
+ if (pm->bottom) {
+ s[2 * n] = 1, s[2 * n + 1] = 0, n++;
+ pm = P(pm->bottom);
+ } else {
+ n = 0;
+ impossible_surface_world[cid(c)] = (uint8_t)(c->onWorld + 1);
+ break;
+ }
+ }
+ if (n > 0) cit_set_path(c, s, n);
+}
+
+/* ---------------------------------------------------------------- following the path */
+static void path_end(Cit *c) {
+ uint8_t then = c->then;
+ uint16_t arg = c->thenArg;
+ cit_reset_path(c, true);
+ if (then && then_fns[then]) then_fns[then](c, arg);
+ if (c->inPermanent && c->inPermanent == c->job && c->currentAction != 0 && cit_should_work_now(c))
+ stats_on_commute((float)(uint16_t)(now_minutes() - c->pathStartTime));
+}
+
+void cit_update_path(Cit *c, float timeMod) {
+ if (c->currentPathAction < -1) return;
+ if (c->currentPathAction == -1) {
+ while (path_type_at(c, c->pathPos) == 12) {
+ c->pathWalkSpeed = (uint8_t)path_value_at(c, c->pathPos);
+ c->pathPos++;
+ }
+ int a = path_type_at(c, c->pathPos);
+ c->currentPathAction = (int8_t)a;
+ Perm *in = P(c->inPermanent);
+ if (a == 0 || a == 1 || a == 9) c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ else if (!c->pathOnlyRelatedTo && a != 4 && a != 8) {
+ if (!is_building(in) || !(PC(in)->base & B_HIDE_WALKERS)) c->flags |= CF_CAN_VIEW_SELF;
+ else c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ }
+ if (a <= 1 && c->relativeY > 0) {
+ cit_set_vpp(c, c->relativeY * (a - 0.5f) * -2);
+ c->relativeY = 0;
+ } else if (a != 4 && a != 8 && a != 9) {
+ c->relativeY = 0;
+ }
+ cit_set_timer(c, 0);
+ if (a == 5 || a == 7 || a == 11 || (a >= 13 && a <= 16)) c->pathActionPerm = (uint16_t)path_value_at(c, c->pathPos);
+ else if (a == 4 || a == 9 || a == 8) cit_set_timer(c, (float)path_value_at(c, c->pathPos));
+ }
+ bool reached = false;
+ Perm *in = P(c->inPermanent);
+ float spd = c->pathWalkSpeed / 100.0f * timeMod;
+ switch (c->currentPathAction) {
+ case 0:
+ case 1:
+ cit_set_vpp(c, cit_vpp(c) + (timeMod));
+ if (cit_vpp(c) >= 20) {
+ cit_go_to_permanent(c, c->currentPathAction == 0 ? in->top : in->bottom);
+ cit_set_vpp(c, cit_vpp(c) - (20));
+ reached = true;
+ }
+ break;
+ case 2:
+ c->relativeX -= spd;
+ if (c->relativeX < -2) {
+ cit_go_to_permanent(c, in->left);
+ c->onWorld = P(c->inPermanent)->world;
+ c->relativeX += 20;
+ reached = true;
+ }
+ break;
+ case 3:
+ c->relativeX += spd;
+ if (c->relativeX > 20) {
+ cit_go_to_permanent(c, in->right);
+ c->onWorld = P(c->inPermanent)->world;
+ c->relativeX -= 20;
+ reached = true;
+ }
+ break;
+ case 4:
+ reached = cit_move_towards_x(c, cit_timer(c), timeMod);
+ break;
+ case 5: {
+ if (in) {
+ if (is_building(in)) {
+ if (cit_move_towards_x(c, bld_door_x(in), timeMod)) cit_instant_leave_permanent(c);
+ } else {
+ cit_instant_leave_permanent(c);
+ }
+ /* (out of it; the next tick walks to the goal) */
+ } else {
+ Perm *to = P(c->pathActionPerm);
+ if (is_building(to)) {
+ reached = cit_move_towards_x(c, (float)(to->col * 20 + bld_door_x(to)), timeMod);
+ if (reached) {
+ cit_go_to_permanent(c, c->pathActionPerm);
+ c->relativeX = bld_door_x(to);
+ }
+ } else {
+ float px = (float)(to->col * 20);
+ float num = px + 10.0f - c->relativeX;
+ c->relativeX += (num > 0 ? 1 : num < 0 ? -1 : 0) * (timeMod * c->pathWalkSpeed / 100.0f);
+ if (c->relativeX > px && c->relativeX < px + 20 - 2) {
+ cit_go_to_permanent(c, c->pathActionPerm);
+ c->relativeX -= to->col * 20;
+ reached = true;
+ }
+ }
+ }
+ break;
+ }
+ case 7:
+ if (cit_timer(c) > 0) {
+ cit_set_timer(c, cit_timer(c) + (0.1f * timeMod));
+ if (cit_timer(c) >= 1) {
+ if (bld_is_misdirector(in)) {
+ cit_reset_path(c, true);
+ cit_wait_and_move_and_wait_random(c, 30, 45, 3, 16, 120, 180, THEN_NONE, 0, false, true);
+ c->flags &= (uint16_t)~CF_PATH_RECONSIDER;
+ bld_misdirector_reward(in);
+ return;
+ }
+ reached = true;
+ }
+ } else if (!operating_cost.teleportersEnabled) {
+ cit_reset_path(c, true);
+ return;
+ } else {
+ float tx = bld_teleport_x(in);
+ if (cit_move_towards_x(c, tx, timeMod)) {
+ bld_teleport_used(in);
+ uint16_t to = c->pathActionPerm;
+ uint16_t mis = bld_misdirector();
+ if (mis && bld_misdirect_chance() > 0 && rnd_float() < bld_misdirect_chance()) to = c->pathActionPerm = mis;
+ cit_go_to_permanent(c, to);
+ bld_teleport_arrived(P(to));
+ c->onWorld = P(to)->world;
+ c->relativeX = bld_teleport_x(P(to));
+ cit_set_timer(c, 0.1f * timeMod);
+ }
+ }
+ break;
+ case 8:
+ cit_set_timer(c, cit_timer(c) - (timeMod));
+ reached = cit_timer(c) <= 0.5f * (timeMod - 0.6666667f);
+ break;
+ case 9:
+ if (fabsf(cit_timer(c) - c->relativeY) < timeMod) {
+ c->relativeY = cit_timer(c);
+ reached = true;
+ } else {
+ c->relativeY += (cit_timer(c) > c->relativeY ? 1 : -1) * timeMod;
+ }
+ break;
+ case 10:
+ reached = true;
+ break;
+ case 11:
+ if (c->inPermanent == c->pathActionPerm) reached = true;
+ else if (!flying_board(c, in, P(c->pathActionPerm))) return; /* (no route: the path is dropped) */
+ break;
+ case 13: {
+ Perm *to = P(c->pathActionPerm);
+ float diff = 20.0f * ((int)to->row - (int)in->row);
+ if (in == to) {
+ if (cit_timer(c) > 3) {
+ if (c->pathPos + 1 < c->pathLen) {
+ int nt = path_type_at(c, c->pathPos + 1);
+ if (nt == 0 || nt == 1) {
+ if (cit_move_towards_x(c, c->relativeX > 10 ? 18 : 0, timeMod)) reached = true;
+ } else {
+ reached = true;
+ }
+ } else {
+ reached = true;
+ }
+ } else {
+ cit_set_timer(c, cit_timer(c) + (timeMod));
+ }
+ } else if (cit_timer(c) > 0) {
+ if (fabsf(cit_vpp(c)) < fabsf(diff)) {
+ cit_set_vpp(c, cit_vpp(c) + (timeMod * 20 * (diff > 0 ? 1 : diff < 0 ? -1 : 0)));
+ c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ }
+ if (fabsf(cit_vpp(c)) >= fabsf(diff) && bld_elevator_open_door(to)) {
+ cit_go_to_permanent(c, c->pathActionPerm);
+ bld_elevator_arrived(to);
+ cit_set_vpp(c, 0);
+ c->flags |= CF_CAN_VIEW_SELF;
+ c->relativeX += rnd_between(-2, 3);
+ }
+ } else {
+ c->flags |= CF_CAN_VIEW_SELF;
+ if (cit_move_towards_x(c, 9, timeMod) && bld_elevator_open_door(in)) {
+ bld_elevator_used(in);
+ cit_set_timer(c, 1);
+ c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ }
+ }
+ break;
+ }
+ default: /* 12 and 14 do nothing; 15 and 16 (bridges) are only in the paid version */
+ break;
+ }
+ if (!reached) return;
+ if (c->pathPos + 1 >= c->pathLen) {
+ path_end(c);
+ return;
+ }
+ c->pathPos++;
+ c->currentPathAction = -1;
+ int t = path_type_at(c, c->pathPos);
+ if (t == 13 || t == 14)
+ while (c->pathPos + 1 < c->pathLen && path_type_at(c, c->pathPos + 1) == t) c->pathPos++;
+ if (path_type_at(c, c->pathPos) == 10) {
+ if (c->pathPos + 1 >= c->pathLen) path_end(c);
+ else {
+ c->flags |= CF_CAN_VIEW_SELF;
+ c->pathPos++;
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- entertainment */
+
+static void set_age_related_entertainment(Cit *c) {
+ if (cit_age(c) < 16 && rnd_int(1000) < 998)
+ c->entRecent[0] = at_2h(city.timeSinceStart + 1440.0 * (cit_age(c) - rnd_range(14, 16)));
+}
+static float normally_at_home_from(const Cit *c) {
+ float base = c->job ? fmodf(bld_end_time(P(c->job)) + 4, 24) : 23;
+ return cit_work_time_preference(c) + base;
+}
+static float normally_at_home_to(const Cit *c) {
+ return cit_work_time_preference(c) + (c->job ? bld_start_time(P(c->job)) : 8);
+}
+static bool search_night_entertainment(Cit *c) {
+ if (!past_4m(c->entTry)) return false;
+ if (!path_may_request_now(NONE)) return true;
+ path_find_entertainment(c, rnd_float() < 0.02f ? 480 : 320, -1);
+ c->onFail = THEN_NONE;
+ c->flags &= (uint16_t)~CF_ENT_INITED;
+ c->entTry = at_4m(city.timeSinceStart + 120 * city.minutesPerTick);
+ return true;
+}
+static bool search_day_entertainment(Cit *c) {
+ if (!past_4m(c->entTryDay)) return false;
+ if (!path_may_request_now(NONE)) return true;
+ int bits = 0;
+ for (int i = 0; i < 6; i++)
+ if (past_2h(c->entRecent[i])) bits |= 1 << i;
+ path_find_entertainment(c, rnd_float() < 0.02f ? 480 : 320, bits);
+ c->onFail = THEN_NONE;
+ c->flags &= (uint16_t)~CF_ENT_INITED;
+ c->entTryDay = at_4m(city.timeSinceStart + 120 * city.minutesPerTick);
+ return true;
+}
+/* updateEntertainment: true while busy with it */
+static bool update_entertainment(Cit *c, float timeMod) {
+ Perm *in = P(c->inPermanent);
+ if (is_building(in) && (in->flags & PF_IS_ENTERTAINMENT)) {
+ bool busy = true;
+ if (!(c->flags & CF_ENT_INITED)) {
+ if (ent_is_open(in)) {
+ float desirability = (!c->job && !c->school) ? 0.75f : 1.0f;
+ c->entFinished = at_4m(city.timeSinceStart + 60.0 * rnd_range(ent_min_time(in), ent_max_time(in)));
+ c->entRecent[ent_type(in)] =
+ at_2h(city.timeSinceStart + 1440.0 * rnd_range(ent_min_satisfy(in), ent_max_satisfy(in)) * desirability);
+ c->flags |= CF_ENT_INITED;
+ } else {
+ c->entFinished = at_4m(city.timeSinceStart - 1000);
+ }
+ }
+ if (!ent_is_open_for_existing_visitors(in) || past_4m(c->entFinished)) {
+ if (ent_finish(in, c, timeMod)) {
+ busy = false;
+ c->flags &= (uint16_t)~CF_ENT_INITED;
+ } else {
+ ent_be_entertained(in, c, timeMod);
+ }
+ } else {
+ ent_be_entertained(in, c, timeMod);
+ }
+ if (busy) return true;
+ }
+ float t = city_hour();
+ if (cit_age(c) > 16 && (c->flags & CF_LIKES_NIGHTCLUBS) &&
+ in_hours(t, 23 + cit_work_time_preference(c), 6 + cit_work_time_preference(c)) && c->wantsNightEntertainmentIn == 0)
+ return search_night_entertainment(c);
+ if (!in_hours(t, normally_at_home_from(c), normally_at_home_to(c))) return search_day_entertainment(c);
+ return false;
+}
+/* the entertainment building lets the citizen go (true) or keeps them a little longer */
+static bool finish_entertainment_if_in(Cit *c, float timeMod) {
+ Perm *in = P(c->inPermanent);
+ return (is_building(in) && (in->flags & PF_IS_ENTERTAINMENT)) ? ent_finish(in, c, timeMod) : true;
+}
+
+/* ---------------------------------------------------------------- daily life */
+void cit_update_daily_life(Cit *c, float timeMod) {
+ float time = city_hour();
+ if (c->currentAction == 0) {
+ Perm *j = P(c->job);
+ float start = bld_start_time(j) + cit_work_time_preference(c);
+ float end = bld_end_time(j) + cit_work_time_preference(c) + policies.workTimeChange;
+ bld_work(j, c, timeMod, !in_hours(time, start, end));
+ } else if (c->currentAction == 1) {
+ Perm *s = P(c->school);
+ if (in_hours(time, bld_school_start(s), bld_school_end(s))) bld_be_at_school(s, c, timeMod);
+ else c->currentAction = 2;
+ } else if (c->hobby && hobby_is_active(c)) {
+ hobby_update(c, timeMod);
+ } else if (c->currentAction != 3) {
+ if (cit_should_work_now(c)) {
+ if (c->inPermanent == c->job) c->currentAction = 0;
+ else if (path_may_request_now(c->inPermanent) && finish_entertainment_if_in(c, timeMod))
+ path_find_combined(c, bld_first_building_to_go_to(P(c->job)), THEN_NONE);
+ } else if (cit_should_school_now(c)) {
+ if (c->inPermanent == c->school) c->currentAction = 1;
+ else if (path_may_request_now(c->inPermanent) && finish_entertainment_if_in(c, timeMod)) {
+ if (bld_workers(P(c->school)) == 0) cit_leave_school(c);
+ else path_find_combined(c, c->school, THEN_NONE);
+ }
+ } else if (!update_entertainment(c, timeMod)) {
+ bool go_home;
+ if (c->home) {
+ if (!c->job) {
+ float s = 8 + cit_work_time_preference(c), e = 21 + cit_work_time_preference(c);
+ go_home = !in_hours(time, s, e);
+ } else {
+ go_home = true;
+ }
+ } else {
+ go_home = false;
+ }
+ if (go_home) {
+ if (c->inPermanent != c->home) {
+ if (path_may_request_now(c->inPermanent)) path_find_combined(c, c->home, THEN_NONE);
+ } else {
+ float st, en;
+ if (!c->job) st = 8, en = 21;
+ else st = bld_start_time(P(c->job)), en = bld_end_time(P(c->job));
+ float s = fmodf(st + cit_work_time_preference(c) - 1, 24);
+ float e = fmodf(en + cit_work_time_preference(c) + 1, 24);
+ if (in_hours(time, s, e) || cit_steps_in_building(c) < 240) {
+ c->flags |= CF_CAN_VIEW_SELF;
+ bld_walk_around(P(c->home), c, cit_steps_in_building(c));
+ } else {
+ c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ }
+ }
+ } else {
+ cit_wander(c, timeMod);
+ }
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- jobs, homes, schools */
+void cit_evict_from_home(Cit *c) {
+ if (!c->home) return;
+ P(c->home)->nresidents--;
+ c->home = NONE;
+ sim_flags |= SIM_HOUSES_CHANGED;
+}
+void cit_leave_school(Cit *c) {
+ if (!c->school) return;
+ P(c->school)->nstudents--;
+ c->school = NONE;
+ sim_flags |= SIM_SCHOOLS_CHANGED;
+ if (c->currentAction == 1) c->currentAction = 2;
+}
+void cit_lose_job(Cit *c, bool instant_replace) {
+ if (!c->job) return;
+ bld_on_lose_job(P(c->job), c);
+ P(c->job)->nworkers--;
+ c->job = NONE;
+ if (!instant_replace) {
+ sim_flags |= SIM_JOBS_CHANGED;
+ c->flags |= CF_WITHOUT_JOB;
+ }
+ c->flags &= (uint16_t)~CF_HAS_WORK_TOOLS;
+ if (c->currentAction == 0) c->currentAction = 2;
+}
+void cit_add_to_workers(Cit *c) {
+ c->flags |= CF_WITHOUT_JOB;
+ sim_flags |= SIM_JOBS_CHANGED;
+ if (c->school) cit_leave_school(c);
+}
+
+void cit_infrequent_update(Cit *c) {
+ float age = cit_age(c);
+ /* lastInfrequentUpdateAge < 16: a child that just turned 16 */
+ if (age >= 16 && !(c->flags & CF_WITHOUT_JOB) && !c->job && age - 16 < 1) cit_add_to_workers(c);
+ else if (age >= 16 && c->job && c->school) cit_leave_school(c);
+ for (int i = 0; i < 6; i++) keep_near(&c->entRecent[i], now_2h());
+ keep_near(&c->entTry, now_4m());
+ keep_near(&c->entTryDay, now_4m());
+ keep_near(&c->entFinished, now_4m());
+ if (age >= 75 + c->dieAgeModifier / 100.0f && !city.disableDying) {
+ cit_try_remove(c, false);
+ return;
+ }
+ if (has_path(c) && (c->flags & CF_PATH_RECONSIDER)) {
+ bool work = c->currentAction != 0 && cit_should_work_now(c);
+ bool school = c->currentAction != 1 && cit_should_school_now(c);
+ if ((work && c->pathDestination != c->job) || (school && c->pathDestination != c->school)) cit_reset_path(c, false);
+ }
+}
+
+void cit_mid_day_update(Cit *c) {
+ if (c->wantsNightEntertainmentIn > 0) c->wantsNightEntertainmentIn--;
+ die_add(c, 0.2f * (happiness.medicalHappiness / 100.0f) + 0.05f * (happiness.specializedMedicalHappiness / 100.0f));
+ if (happiness.happiness < 10 && !c->home && city.materials.m[M_FOOD] < 1) {
+ if (!c->job) die_add(c, -10);
+ die_add(c, -1);
+ }
+ if (c->home) die_add(c, bld_years_to_live_longer(P(c->home)));
+ die_add(c, upgrades.extendAgeBy);
+ impossible_surface_world[cid(c)] = 0;
+}
+
+void cit_try_remove(Cit *c, bool for_send_away) {
+ if (c->flags & CF_CONTROLLED) return;
+ if (c->currentAction == 3) return;
+ if (!for_send_away) baby_on_citizen_death();
+ c->flags &= (uint16_t)~CF_WITHOUT_JOB;
+ if (c->job) bld_on_lose_job(P(c->job), c), P(c->job)->nworkers--, sim_flags |= SIM_JOBS_CHANGED;
+ if (c->home) P(c->home)->nresidents--, sim_flags |= SIM_HOUSES_CHANGED;
+ if (c->school) P(c->school)->nstudents--, sim_flags |= SIM_SCHOOLS_CHANGED;
+ if (c->hobby) hobby_on_die(c);
+ if (c->inPermanent) on_leave(c, NONE);
+ c->job = c->home = c->school = NONE;
+ c->flags = 0;
+ c->pathOff = 0;
+ ncits--;
+}
+
+/* ---------------------------------------------------------------- a permanent's citizens */
+void cits_lose_job_at(uint16_t perm) {
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job == perm) cit_lose_job(&cits[i], false);
+}
+void cits_evict_from(uint16_t perm) {
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].home == perm) cit_evict_from_home(&cits[i]);
+}
+void cits_leave_school(uint16_t perm) {
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].school == perm) cit_leave_school(&cits[i]);
+}
+/* the citizens in a permanent that goes: to a neighbouring building, or out onto a world */
+void cits_leave_destroyed(uint16_t perm) {
+ Perm *p = P(perm);
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || c->inPermanent != perm) continue;
+ if (p->row == 0) {
+ cit_instant_leave_permanent(c);
+ } else {
+ uint16_t to = NONE;
+ if (is_building(p)) to = p->bottom ? p->bottom : p->left ? p->left : p->right ? p->right : p->top;
+ if (to) {
+ cit_go_to_permanent(c, to);
+ c->onWorld = P(to)->world;
+ } else if (worlds[c->onWorld].h > 0) {
+ cit_instant_leave_permanent(c);
+ } else {
+ /* a building below at its x, or the nearest world */
+ float cx, cy;
+ cit_city_position(c, &cx, &cy);
+ uint16_t below = NONE;
+ for (int j = 1; j < MAX_PERMS && !below; j++) {
+ Perm *q = &perms[j];
+ if (!(q->flags & PF_USED) || j == perm) continue;
+ if (cx >= perm_city_x(q) && cx < perm_city_x(q) + 20 && perm_city_y(q) > cy) below = (uint16_t)j;
+ }
+ if (below) {
+ cit_go_to_permanent(c, below);
+ c->onWorld = P(below)->world;
+ } else {
+ int best = 0;
+ float bd = 1e30f;
+ for (int w = 0; w < nworlds; w++) {
+ if (worlds[w].h <= 0) continue;
+ float d = fabsf(worlds[w].x + worlds[w].w / 2.0f - cx) + fabsf(worlds[w].y + worlds[w].h / 2.0f - cy);
+ if (d < bd) bd = d, best = w;
+ }
+ cit_instant_leave_permanent(c);
+ c->onWorld = (uint8_t)best;
+ c->relativeX = 0;
+ }
+ }
+ c->relativeY = 0;
+ }
+ cit_reset_path(c, true);
+ }
+}
+
+/* after loading: the count of the living */
+void cits_recount(void) {
+ ncits = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) ncits++;
+}
+
+void cits_reset(void) {
+ memset(cits, 0, sizeof cits);
+ ncits = 0;
+ path_top = 1;
+ memset(impossible_surface_world, 0, sizeof impossible_surface_world);
+}
+
+/* a new citizen (the Citizen constructor) */
+uint16_t cit_new(int world, float x, float age, uint16_t start_in) {
+ int id = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if (!(cits[i].flags & CF_ALIVE)) { id = i; break; }
+ if (!id) return NONE;
+ Cit *c = &cits[id];
+ memset(c, 0, sizeof *c);
+ c->flags = CF_ALIVE | CF_CAN_VIEW_SELF | CF_PATH_RECONSIDER;
+ c->currentAction = 2;
+ c->currentPathAction = -2;
+ c->pathWalkSpeed = 100;
+ c->spriteIndex = (uint8_t)rnd_int(NCITIZEN_SPRITES - 2);
+ c->nameIndex = (uint16_t)rnd_between(1, NCITIZEN_NAMES);
+ if (c->nameIndex == NAME_WALDO) c->spriteIndex = NCITIZEN_SPRITES - 1;
+ if (c->nameIndex == NAME_DRACULA) c->spriteIndex = NCITIZEN_SPRITES - 2;
+ c->onWorld = (uint8_t)world;
+ c->relativeX = x;
+ sim_flags |= SIM_HOUSES_CHANGED | SIM_SCHOOLS_CHANGED;
+ c->bornOn = (float)(city.timeSinceStart - age * 1440.0);
+ c->dieAgeModifier = (int16_t)(rnd_between(-5, 5) * 100);
+ c->workTimePref = (int8_t)(rnd_range(-1, 1) * 127);
+ /* likesNightclubs: the original's spriteIndex mixes the name in (nameIndex << 14) */
+ if (((uint32_t)c->spriteIndex + ((uint32_t)c->nameIndex << 14)) % 5 != 0) c->flags |= CF_LIKES_NIGHTCLUBS;
+ ncits++;
+ if (age >= 16) cit_add_to_workers(c);
+ if (start_in) {
+ c->inBuildingSince = now_ticks();
+ c->inPermanent = start_in;
+ c->flags &= (uint16_t)~CF_CAN_VIEW_SELF;
+ }
+ set_age_related_entertainment(c);
+ c->wantsNightEntertainmentIn = (uint8_t)rnd_int(5);
+ c->inBuildingSince = now_ticks();
+ return (uint16_t)id;
+}
diff --git a/games/finalearth2/src/city.c b/games/finalearth2/src/city.c
new file mode 100644
index 00000000..ba31c292
--- /dev/null
+++ b/games/finalearth2/src/city.c
@@ -0,0 +1,393 @@
+/* The Final Earth 2: worlds, their columns of permanents, and how they
+ * connect (World, Permanent and simulation.CityConnections). */
+#include "sim.h"
+#include "scratch.h"
+#include "bg.h"
+
+World worlds[MAX_WORLDS];
+int nworlds;
+Perm perms[MAX_PERMS];
+uint8_t col_height[MAX_COLS];
+uint8_t col_deco[MAX_COLS]; /* each column's ground decoration (bg.h: kind << 4 | frame, 0 none) */
+BgWorld bgworlds[MAX_WORLDS]; /* the worlds' looks (bg.c) */
+static int ncols_used;
+City city;
+
+/* ---------------------------------------------------------------- random */
+static uint32_t rng_state = 0x2545F491u;
+uint32_t rnd(void) {
+ rng_state ^= rng_state << 13;
+ rng_state ^= rng_state >> 17;
+ rng_state ^= rng_state << 5;
+ return rng_state;
+}
+void rnd_seed(uint32_t s) { rng_state = s ? s : 1; }
+float rnd_float(void) { return (float)(rnd() >> 8) * (1.0f / 16777216.0f); }
+float rnd_range(float a, float b) { return a + rnd_float() * (b - a); }
+int rnd_int(int n) { return n > 0 ? (int)(rnd_float() * n) : 0; }
+int rnd_between(int a, int b) { return a + rnd_int(b - a); }
+
+/* ---------------------------------------------------------------- where permanents are
+ * a hash of (world, column, row) to the permanent there */
+#define HASH_SIZE 1024
+static uint16_t hash_tab[HASH_SIZE];
+static inline uint32_t key_of(int w, int col, int row) { return (uint32_t)w << 16 | (uint32_t)col << 8 | (uint32_t)row; }
+static inline uint32_t hash_of(uint32_t k) { return (k * 2654435761u) >> 22; }
+
+static void hash_put(uint16_t id) {
+ Perm *p = &perms[id];
+ uint32_t h = hash_of(key_of(p->world, p->col, p->row));
+ while (hash_tab[h]) h = (h + 1) & (HASH_SIZE - 1);
+ hash_tab[h] = id;
+}
+static void hash_del(uint16_t id) {
+ Perm *p = &perms[id];
+ uint32_t h = hash_of(key_of(p->world, p->col, p->row));
+ while (hash_tab[h] != id) {
+ if (!hash_tab[h]) return;
+ h = (h + 1) & (HASH_SIZE - 1);
+ }
+ /* close the gap (linear probing) */
+ hash_tab[h] = 0;
+ uint32_t j = h;
+ for (;;) {
+ j = (j + 1) & (HASH_SIZE - 1);
+ uint16_t q = hash_tab[j];
+ if (!q) break;
+ uint32_t k = hash_of(key_of(perms[q].world, perms[q].col, perms[q].row));
+ if ((j > h && (k <= h || k > j)) || (j < h && (k <= h && k > j))) {
+ hash_tab[h] = q;
+ hash_tab[j] = 0;
+ h = j;
+ }
+ }
+}
+uint16_t perm_at(int w, int col, int row) {
+ if (w < 0 || w >= nworlds || col < 0 || col >= worlds[w].ncols || row < 0) return NONE;
+ uint32_t k = key_of(w, col, row), h = hash_of(k);
+ for (uint16_t id; (id = hash_tab[h]); h = (h + 1) & (HASH_SIZE - 1)) {
+ Perm *p = &perms[id];
+ if (p->world == w && p->col == col && p->row == row) return id;
+ }
+ return NONE;
+}
+int perm_city_x(const Perm *p) { return worlds[p->world].x + 20 * p->col; }
+int perm_city_y(const Perm *p) { return worlds[p->world].y - 20 * (p->row + 1); }
+int col_stack_height(int w, int col) { return col_height[worlds[w].col0 + col]; }
+
+/* ---------------------------------------------------------------- worlds */
+int world_add(int x, int y, int w, int h, uint32_t seed, uint8_t appearance) {
+ int ncols = (w + 19) / 20;
+ if (nworlds >= MAX_WORLDS || ncols_used + ncols > MAX_COLS) return -1;
+ World *wd = &worlds[nworlds];
+ memset(wd, 0, sizeof *wd);
+ wd->x = (int16_t)x, wd->y = (int16_t)y, wd->w = (int16_t)w, wd->h = (int16_t)h;
+ wd->seed = seed;
+ wd->appearance = appearance;
+ wd->col0 = (uint16_t)ncols_used;
+ wd->ncols = (uint16_t)ncols;
+ int maxid = -1;
+ for (int i = 0; i < nworlds; i++)
+ if (worlds[i].id > maxid) maxid = worlds[i].id;
+ wd->id = (uint8_t)(maxid + 1);
+ memset(col_height + ncols_used, 0, (size_t)ncols);
+ memset(col_deco + ncols_used, 0, (size_t)ncols);
+ BgWorld *bw = &bgworlds[nworlds];
+ memset(bw, 0, sizeof *bw);
+ bw->x = (int16_t)x, bw->y = (int16_t)y, bw->w = (int16_t)w, bw->h = (int16_t)h;
+ bw->seed = (int32_t)seed;
+ bw->look = appearance;
+ if (h > 0) bg_world_decorate(bw, col_deco + ncols_used);
+ ncols_used += ncols;
+ return nworlds++;
+}
+
+/* ---------------------------------------------------------------- permanents */
+static int nperms;
+int perm_count(void) { return nperms; }
+
+/* a new permanent of class cls at (w, col, row): row is the stack's height (on top) or a hole in it */
+uint16_t perm_new(int cls, int w, int col, int row) {
+ uint16_t id = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (!(perms[i].flags & PF_USED)) { id = (uint16_t)i; break; }
+ if (!id) return NONE;
+ Perm *p = &perms[id];
+ memset(p, 0, sizeof *p);
+ p->cls = (uint16_t)cls;
+ p->world = (uint8_t)w, p->col = (uint8_t)col, p->row = (uint8_t)row;
+ const PermClass *pc = &pcls[cls];
+ p->flags = PF_USED;
+ if (pc->kind == KIND_BUILDING) {
+ p->flags |= PF_BUILDING;
+ if (pc->base & B_ROOFTOP) p->flags |= PF_ROOFTOP | PF_NO_BUILD_ON_TOP;
+ if (pc->base & B_NO_BUILD_ON_TOP) p->flags |= PF_NO_BUILD_ON_TOP;
+ if (pc->base & B_ENTERTAINMENT) p->flags |= PF_IS_ENTERTAINMENT;
+ if (pc->base & B_MEDICAL) p->flags |= PF_IS_MEDICAL;
+ sim_flags |= SIM_JOBS_CHANGED | SIM_HOUSES_CHANGED | SIM_SCHOOLS_CHANGED;
+ }
+ uint8_t *h = &col_height[worlds[w].col0 + col];
+ if (row >= *h) *h = (uint8_t)(row + 1);
+ hash_put(id);
+ nperms++;
+ if (pc->ops && pc->ops->init) pc->ops->init(p);
+ return id;
+}
+
+/* Permanent.destroy: the permanent goes; those above it come down a row
+ * (unless it is replaced, or a world resource under a stack); citizens in it
+ * move to a neighbour or out onto the world */
+static bool destroying_for_replacement;
+static void perm_destroy_ex(uint16_t id, bool for_replacement, bool keep_hole) {
+ Perm *p = &perms[id];
+ const PermClass *pc = PC(p);
+ int w = p->world, col = p->col, row = p->row;
+ uint8_t *h = &col_height[worlds[w].col0 + col];
+ bool disable_move_down = for_replacement || keep_hole || (pc->kind == KIND_RESOURCE && *h > 1);
+ destroying_for_replacement = for_replacement;
+ p->flags |= PF_DESTROYED;
+ /* the class's own leaving (homes evict, work places fire) happens first, as Building.destroy calls up */
+ if (pc->ops && pc->ops->destroy) pc->ops->destroy(p);
+ cits_leave_destroyed(id);
+ if (pc->base & B_WORK) cits_lose_job_at(id);
+ if (pc->base & B_HOUSE) cits_evict_from(id);
+ if (pc->base & B_SCHOOL) cits_leave_school(id);
+ hash_del(id);
+ p->flags = 0;
+ nperms--;
+ if (!disable_move_down) {
+ /* everything above comes down until a hole (or a rooftop building, under which a hole is kept) */
+ for (int y = row + 1; y < *h; y++) {
+ uint16_t q = perm_at(w, col, y);
+ if (!q) break;
+ hash_del(q);
+ perms[q].row--;
+ hash_put(q);
+ if ((perms[q].flags & PF_ROOFTOP) && y + 1 < *h) break;
+ }
+ /* drop holes left at the top */
+ while (*h > 0 && !perm_at(w, col, *h - 1)) (*h)--;
+ } else if (row == *h - 1) {
+ while (*h > 0 && !perm_at(w, col, *h - 1)) (*h)--;
+ }
+ if (!for_replacement) {
+ city_update_connections();
+ sim_update_pathfinder(true, id);
+ }
+ destroying_for_replacement = false;
+}
+void perm_destroy(uint16_t id, bool for_replacement) { perm_destroy_ex(id, for_replacement, false); }
+void perm_destroy_keep_hole(uint16_t id, bool keep_hole) { perm_destroy_ex(id, false, keep_hole); }
+
+/* a saved permanent back in its place (save.c) */
+bool perm_restore(uint16_t id, const Perm *p) {
+ if (perms[id].flags & PF_USED) return false;
+ if (p->world >= nworlds || p->col >= worlds[p->world].ncols) return false;
+ perms[id] = *p;
+ perms[id].left = perms[id].right = perms[id].top = perms[id].bottom = NONE;
+ hash_put(id);
+ nperms++;
+ return true;
+}
+
+/* a permanent to another row of its column (a building inserted below it) */
+void perm_move(uint16_t id, int row) {
+ hash_del(id);
+ perms[id].row = (uint8_t)row;
+ hash_put(id);
+ uint8_t *h = &col_height[worlds[perms[id].world].col0 + perms[id].col];
+ if (row >= *h) *h = (uint8_t)(row + 1);
+}
+
+/* ---------------------------------------------------------------- connections
+ * simulation.CityConnections.updateCityConnections: the buildings' neighbours,
+ * which worlds citizens can reach from each other, and the groups (shards) of
+ * permanents they can walk between */
+uint8_t landing_group_of[MAX_PERMS]; /* landingSiteGroup + 1 */
+int nlanding_groups;
+
+static void set_neighbours(void) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (perms[i].flags & PF_BUILDING) perms[i].left = perms[i].right = perms[i].top = perms[i].bottom = NONE;
+ for (int w = 0; w < nworlds; w++) {
+ World *wd = &worlds[w];
+ for (int x = 0; x + 1 < wd->ncols; x++) {
+ int n = col_height[wd->col0 + x], m = col_height[wd->col0 + x + 1];
+ for (int y = 0; y < n && y < m; y++) {
+ Perm *a = P(perm_at(w, x, y)), *b = P(perm_at(w, x + 1, y));
+ if (is_building(a) && is_building(b) && !(a->flags & PF_NO_BUILD_ON_TOP) && !(b->flags & PF_NO_BUILD_ON_TOP))
+ a->right = pid(b), b->left = pid(a);
+ }
+ }
+ for (int x = 0; x < wd->ncols; x++)
+ for (int y = 0; y + 1 < col_height[wd->col0 + x]; y++) {
+ Perm *a = P(perm_at(w, x, y)), *b = P(perm_at(w, x, y + 1));
+ if (is_building(a) && is_building(b) && !(a->flags & PF_ROOFTOP)) a->top = pid(b), b->bottom = pid(a);
+ }
+ }
+}
+
+int direct_world_connections;
+static uint8_t reach[MAX_WORLDS]; /* each world's reachable-worlds set, as a set number (worlds sharing it reach each other) */
+
+static void merge_reach(int a, int b) {
+ uint8_t ra = reach[a], rb = reach[b];
+ if (ra == rb) return;
+ for (int i = 0; i < nworlds; i++)
+ if (reach[i] == rb) reach[i] = ra;
+}
+
+/* worlds next to each other, aligned on the 20-pixel grid: the buildings of
+ * one's edge column and the other's neighbouring column join at equal heights */
+static void direct_connections(int w, int edge_col, int dir) {
+ World *wd = &worlds[w];
+ int edge_x = wd->x + 20 * edge_col;
+ for (int o = 0; o < nworlds; o++) {
+ World *ow = &worlds[o];
+ if (!(ow->y > wd->y || (ow->y == wd->y && ow->x > wd->x))) continue;
+ if (((ow->x % 20) + 20) % 20 != ((wd->x % 20) + 20) % 20 || ((ow->y % 20) + 20) % 20 != ((wd->y % 20) + 20) % 20) continue;
+ int ox = (edge_x - ow->x) / 20 + dir;
+ if (edge_x - ow->x < 0 && (edge_x - ow->x) % 20) ox = -((ow->x - edge_x) / 20) + dir; /* truncation toward zero, as | 0 */
+ if (ox < 0 || ox >= ow->ncols) continue;
+ int between = (ow->y - wd->y) / 20;
+ int oh = col_height[ow->col0 + ox], th = col_height[wd->col0 + edge_col];
+ if (oh <= between) continue;
+ bool any = false;
+ int n = oh - between < th ? oh - between : th;
+ for (int i = 0; i < n; i++) {
+ Perm *a = P(perm_at(w, edge_col, i)), *b = P(perm_at(o, ox, i + between));
+ if (is_building(a) && is_building(b) && !(a->flags & PF_NO_BUILD_ON_TOP) && !(b->flags & PF_NO_BUILD_ON_TOP)) {
+ if (dir == 1) a->right = pid(b), b->left = pid(a);
+ else a->left = pid(b), b->right = pid(a);
+ any = true;
+ direct_world_connections += 2;
+ }
+ }
+ if (any) merge_reach(o, w);
+ }
+}
+
+static void flood_fill_shards(void) {
+ uint16_t *stack = scratch->u.flood.stack;
+ uint8_t *seen = scratch->u.flood.seen;
+ static uint8_t seen_world[MAX_WORLDS];
+ memset(seen, 0, MAX_PERMS);
+ memset(seen_world, 0, sizeof seen_world);
+ for (int w = 0; w < nworlds; w++) worlds[w].surfaceShard = 0xFFFF;
+ bool handled_tp = false;
+ uint8_t *handled_ls = scratch->u.flood.handled_ls;
+ memset(handled_ls, 0, MAX_PERMS);
+ uint16_t shard = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ if (!(perms[i].flags & PF_USED) || seen[i]) continue;
+ int sp = 0;
+ stack[sp++] = (uint16_t)i;
+ seen[i] = 1;
+ while (sp) {
+ uint16_t id = stack[--sp];
+ Perm *pm = &perms[id];
+ pm->shard = shard;
+#define PUSH(q) do { uint16_t q_ = (q); if (q_ && !seen[q_]) { seen[q_] = 1; stack[sp++] = q_; } } while (0)
+ if (pm->flags & PF_BUILDING) {
+ PUSH(pm->left);
+ PUSH(pm->top);
+ PUSH(pm->bottom);
+ PUSH(pm->right);
+ if (!handled_tp && is_a(pm, B_TELEPORTER)) {
+ for (int j = 1; j < MAX_PERMS; j++)
+ if ((perms[j].flags & PF_USED) && is_a(&perms[j], B_TELEPORTER)) PUSH((uint16_t)j);
+ handled_tp = true;
+ }
+ if (is_a(pm, B_LANDINGSITE) && landing_group_of[id]) {
+ int g = landing_group_of[id] - 1;
+ if (!handled_ls[g]) {
+ for (int j = 1; j < MAX_PERMS; j++)
+ if ((perms[j].flags & PF_USED) && landing_group_of[j] == g + 1) PUSH((uint16_t)j);
+ handled_ls[g] = 1;
+ }
+ }
+ }
+ if (pm->row == 0 && !seen_world[pm->world]) {
+ seen_world[pm->world] = 1;
+ worlds[pm->world].surfaceShard = shard;
+ World *wd = &worlds[pm->world];
+ for (int x = 0; x < wd->ncols; x++) PUSH(perm_at(pm->world, x, 0));
+ }
+#undef PUSH
+ }
+ shard++;
+ }
+ for (int w = 0; w < nworlds; w++)
+ if (worlds[w].surfaceShard == 0xFFFF) worlds[w].surfaceShard = shard++;
+}
+
+void city_update_connections(void) {
+ set_neighbours();
+ /* worlds with a teleporter reach each other */
+ bool tp_world[MAX_WORLDS] = {0};
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_a(&perms[i], B_TELEPORTER)) tp_world[perms[i].world] = true;
+ for (int w = 0; w < nworlds; w++) reach[w] = (uint8_t)w;
+ int first_tp = -1;
+ for (int w = 0; w < nworlds; w++)
+ if (tp_world[w]) {
+ if (first_tp < 0) first_tp = w;
+ reach[w] = (uint8_t)first_tp;
+ }
+ /* landing sites that can fly to each other form groups, and join their worlds */
+ memset(landing_group_of, 0, sizeof landing_group_of);
+ nlanding_groups = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ if (!(perms[i].flags & PF_USED) || !is_a(&perms[i], B_LANDINGSITE)) continue;
+ uint16_t other = flying_find_any_other_landing_site((uint16_t)i);
+ if (other && landing_group_of[other]) landing_group_of[i] = landing_group_of[other];
+ else landing_group_of[i] = (uint8_t)++nlanding_groups;
+ }
+ for (int g = 1; g <= nlanding_groups; g++) {
+ int first = -1;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && landing_group_of[i] == g) {
+ if (first < 0) first = perms[i].world;
+ else merge_reach(first, perms[i].world);
+ }
+ }
+ direct_world_connections = 0;
+ for (int w = 0; w < nworlds; w++) {
+ direct_connections(w, 0, -1);
+ direct_connections(w, worlds[w].ncols - 1, 1);
+ }
+ /* world groups, in the order of the worlds */
+ uint8_t group_of_set[MAX_WORLDS];
+ memset(group_of_set, 0xFF, sizeof group_of_set);
+ uint8_t groups = 0;
+ for (int w = 0; w < nworlds; w++) {
+ if (group_of_set[reach[w]] == 0xFF) group_of_set[reach[w]] = groups++;
+ worlds[w].group = group_of_set[reach[w]];
+ }
+ for (int w = 0; w < nworlds; w++) {
+ bool tp = false;
+ for (int v = 0; v < nworlds; v++)
+ if (worlds[v].group == worlds[w].group && tp_world[v]) tp = true;
+ if (tp) worlds[w].flags |= WF_HAS_TELEPORTER_ON_GROUP;
+ else worlds[w].flags &= (uint8_t)~WF_HAS_TELEPORTER_ON_GROUP;
+ }
+ flood_fill_shards();
+}
+
+void city_reset(void) {
+ memset(worlds, 0, sizeof worlds);
+ memset(perms, 0, sizeof perms);
+ memset(hash_tab, 0, sizeof hash_tab);
+ memset(col_height, 0, sizeof col_height);
+ memset(col_deco, 0, sizeof col_deco);
+ memset(bgworlds, 0, sizeof bgworlds);
+ bg_forget_shapes();
+ nworlds = ncols_used = nperms = 0;
+ memset(&city, 0, sizeof city);
+ city.minutesPerTick = 0.5f;
+ city.timeSinceStart = 120;
+ city.simulationSpeed = 1;
+}
+
+/* the island's collision mask (Builder: no building in another world's body) */
+bool world_mask_at(int w, int cx, int cy) { return bg_world_mask(&bgworlds[w], cx, cy); }
diff --git a/games/finalearth2/src/classes.c b/games/finalearth2/src/classes.c
new file mode 100644
index 00000000..926c243f
--- /dev/null
+++ b/games/finalearth2/src/classes.c
@@ -0,0 +1,203 @@
+/* The Final Earth 2: the classes of permanents, made by tools/gen_classes.py from the original's
+ * buildinginfo.json, buildableWorldResourcesInfo.json and classes. Don't edit: edit the generator. */
+#include "classes.h"
+#include "data.h"
+extern const PermOps ops_AlienDecryptor;
+extern const PermOps ops_AlienHouse;
+extern const PermOps ops_AlienRuins;
+extern const PermOps ops_Arcade;
+extern const PermOps ops_ArtColony;
+extern const PermOps ops_Beacon;
+extern const PermOps ops_BirchForest;
+extern const PermOps ops_BlossomHippieHQ;
+extern const PermOps ops_BlossomHut;
+extern const PermOps ops_BlossomRestaurant;
+extern const PermOps ops_BotanicalGardens;
+extern const PermOps ops_BotanicalGardensDome;
+extern const PermOps ops_Boulder;
+extern const PermOps ops_BranchyForest;
+extern const PermOps ops_CarrotJuiceBar;
+extern const PermOps ops_CityHall;
+extern const PermOps ops_ColoredBlock;
+extern const PermOps ops_ComfortableHouse;
+extern const PermOps ops_ComputerAlienRuins;
+extern const PermOps ops_ComputerChipFactory;
+extern const PermOps ops_ComputerResearchCenter;
+extern const PermOps ops_CuttingEdgeHome;
+extern const PermOps ops_EcoFarm;
+extern const PermOps ops_EscapeRoom;
+extern const PermOps ops_ExperimentalFarm;
+extern const PermOps ops_ExperimentationLab;
+extern const PermOps ops_ExplorationCentre;
+extern const PermOps ops_FactoryPub;
+extern const PermOps ops_FarmByProductProcessor;
+extern const PermOps ops_FarmHouse;
+extern const PermOps ops_FeatherAlliance;
+extern const PermOps ops_FestivalHQ;
+extern const PermOps ops_FlowerPenthouse;
+extern const PermOps ops_Forest;
+extern const PermOps ops_FossilMuseum;
+extern const PermOps ops_GlassPiece;
+extern const PermOps ops_HackerHQ;
+extern const PermOps ops_HerbGarden;
+extern const PermOps ops_HoloGameHall;
+extern const PermOps ops_HouseOfTheKeyFriends;
+extern const PermOps ops_HyperElevator;
+extern const PermOps ops_IndoorFarm;
+extern const PermOps ops_IntergalacticLibrary;
+extern const PermOps ops_Laboratory;
+extern const PermOps ops_LandedExplorationShip;
+extern const PermOps ops_LandingSite;
+extern const PermOps ops_Library;
+extern const PermOps ops_LivingResearchCenter;
+extern const PermOps ops_Loft;
+extern const PermOps ops_LuxuryRestaurant;
+extern const PermOps ops_MachinePartsFactory;
+extern const PermOps ops_Mansion;
+extern const PermOps ops_MechanicalHouse;
+extern const PermOps ops_MedicalClinic;
+extern const PermOps ops_Misdirector;
+extern const PermOps ops_ModernArtMuseum;
+extern const PermOps ops_ModernRusticHome;
+extern const PermOps ops_NightClub;
+extern const PermOps ops_NormalHouse;
+extern const PermOps ops_Observatory;
+extern const PermOps ops_Park;
+extern const PermOps ops_ParkPod;
+extern const PermOps ops_PineForest;
+extern const PermOps ops_Pub;
+extern const PermOps ops_PurpleForest;
+extern const PermOps ops_RedForest;
+extern const PermOps ops_RedwoodTree;
+extern const PermOps ops_RedwoodTreeHouse;
+extern const PermOps ops_RefinedMetalFactory;
+extern const PermOps ops_ResearchBot;
+extern const PermOps ops_Restaurant;
+extern const PermOps ops_Rock;
+extern const PermOps ops_RooftopDecoration;
+extern const PermOps ops_RooftopDecoration2;
+extern const PermOps ops_RooftopDecoration3;
+extern const PermOps ops_RooftopDecoration4;
+extern const PermOps ops_RooftopPark;
+extern const PermOps ops_School;
+extern const PermOps ops_ScrapyardNightClub;
+extern const PermOps ops_SecretSocietyHouse;
+extern const PermOps ops_SpaciousHouse;
+extern const PermOps ops_SpecializedMedicalClinic;
+extern const PermOps ops_StoneMine;
+extern const PermOps ops_StoneResearchCenter;
+extern const PermOps ops_StoneTeleporter;
+extern const PermOps ops_Supercomputer;
+extern const PermOps ops_Teleporter;
+extern const PermOps ops_TheMachine;
+extern const PermOps ops_TinkerersHome;
+extern const PermOps ops_TreeHuggerBase;
+extern const PermOps ops_TreePlantation;
+extern const PermOps ops_Villa;
+extern const PermOps ops_WoodcuttingCentre;
+extern const PermOps ops_Workshop;
+const PermClass pcls[] = {
+ {.name = "Forest", .kind = KIND_RESOURCE, .base = B_FOREST, .category = 6, .cost = {[M_WOOD] = 20}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_FOREST, .ops = &ops_Forest},
+ {.name = "PineForest", .kind = KIND_RESOURCE, .base = B_FOREST, .category = 6, .cost = {[M_WOOD] = 20}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = 0, .sprite = SPR_PINEFOREST, .ops = &ops_PineForest},
+ {.name = "BranchyForest", .kind = KIND_RESOURCE, .base = B_FOREST, .category = 6, .cost = {[M_WOOD] = 20}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = 0, .sprite = SPR_FOREST_BRANCHES, .ops = &ops_BranchyForest},
+ {.name = "RedForest", .kind = KIND_RESOURCE, .base = B_FOREST, .category = 6, .cost = {[M_WOOD] = 20}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = 0, .sprite = SPR_REDFOREST, .ops = &ops_RedForest},
+ {.name = "PurpleForest", .kind = KIND_RESOURCE, .base = B_FOREST, .category = 6, .cost = {[M_WOOD] = 20}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = 0, .sprite = SPR_PURPLEFOREST, .ops = &ops_PurpleForest},
+ {.name = "BirchForest", .kind = KIND_RESOURCE, .base = B_FOREST, .category = 6, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = 0, .sprite = 0, .ops = &ops_BirchForest},
+ {.name = "Rock", .kind = KIND_RESOURCE, .base = B_ROCK, .category = 6, .cost = {[M_STONE] = 250}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_ROCK, .ops = &ops_Rock},
+ {.name = "Boulder", .kind = KIND_RESOURCE, .base = B_ROCK, .category = 6, .cost = {[M_STONE] = 200}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = 6, .sprite = SPR_BOULDER, .ops = &ops_Boulder},
+ {.name = "AlienRuins", .kind = KIND_RESOURCE, .base = B_RUINS, .category = 6, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = 0, .ops = &ops_AlienRuins},
+ {.name = "ComputerAlienRuins", .kind = KIND_RESOURCE, .base = B_RUINS, .category = 6, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = 8, .sprite = 0, .ops = &ops_ComputerAlienRuins},
+ {.name = "NormalHouse", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 4, [M_STONE] = 4}, .residents = 4, .quality = 50, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_NORMALHOUSE, .ops = &ops_NormalHouse},
+ {.name = "AlienHouse", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_FOOD] = 10, [M_WOOD] = 5}, .residents = 5, .quality = 55, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_ALIENHOUSE, .ops = &ops_AlienHouse},
+ {.name = "ModernRusticHome", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_FOOD] = 7, [M_WOOD] = 10, [M_STONE] = 4, [M_KNOWLEDGE] = 10}, .residents = 2, .quality = 70, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_MODERNRUSTICHOME, .ops = &ops_ModernRusticHome},
+ {.name = "ComfortableHouse", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 15, [M_KNOWLEDGE] = 20}, .residents = 4, .quality = 65, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_COMFORTABLEHOUSE, .ops = &ops_ComfortableHouse},
+ {.name = "MechanicalHouse", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 10, [M_STONE] = 2, [M_MACHINEPARTS] = 2, [M_KNOWLEDGE] = 35}, .residents = 4, .quality = 30, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_MECHANICALHOUSE, .ops = &ops_MechanicalHouse},
+ {.name = "SpaciousHouse", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 4, [M_REFINEDMETAL] = 10, [M_KNOWLEDGE] = 100}, .residents = 6, .quality = 60, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_SPACIOUSHOUSE, .ops = &ops_SpaciousHouse},
+ {.name = "CuttingEdgeHome", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 2, [M_MACHINEPARTS] = 2, [M_REFINEDMETAL] = 4, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 500}, .residents = 4, .quality = 75, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_CUTTINGEDGEHOME, .ops = &ops_CuttingEdgeHome},
+ {.name = "ParkPod", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 50, [M_KNOWLEDGE] = 300}, .residents = 1, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_BOTANICALGARDENS, .ops = &ops_ParkPod},
+ {.name = "Loft", .kind = KIND_BUILDING, .base = B_HOUSE | B_ENTERTAINMENT | B_ROOFTOP, .category = 0, .cost = {[M_WOOD] = 20, [M_REFINEDMETAL] = 5, [M_KNOWLEDGE] = 1500}, .residents = 2, .quality = 88, .startTime = 6, .endTime = 19, .doorX = 14, .workTimePreferenceMod = 1, .entType = 2, .entMinTime = 1.0f, .entMaxTime = 2.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.5f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_LOFT, .ops = &ops_Loft},
+ {.name = "TinkerersHome", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 100, [M_STONE] = 10, [M_MACHINEPARTS] = 20, [M_COMPUTERCHIPS] = 2, [M_KNOWLEDGE] = 2000}, .residents = 4, .quality = 80, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_TINKERERSHOUSE, .ops = &ops_TinkerersHome},
+ {.name = "FarmHouse", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_FOOD] = 100, [M_WOOD] = 100, [M_STONE] = 100, [M_MACHINEPARTS] = 30, [M_REFINEDMETAL] = 10, [M_KNOWLEDGE] = 7500}, .residents = 5, .quality = 85, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_FARMHOUSE, .ops = &ops_FarmHouse},
+ {.name = "BlossomHut", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_FOOD] = 100, [M_WOOD] = 200, [M_KNOWLEDGE] = 1500}, .residents = 2, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_BLOOMRESTAURANT, .ops = &ops_BlossomHut},
+ {.name = "Villa", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_FOOD] = 1000, [M_WOOD] = 1000, [M_MACHINEPARTS] = 20, [M_REFINEDMETAL] = 40, [M_COMPUTERCHIPS] = 16, [M_KNOWLEDGE] = 5000}, .residents = 5, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .teleporterOperatingCost = 2.0f, .parent = -1, .sprite = SPR_VILLA, .ops = &ops_Villa},
+ {.name = "Mansion", .kind = KIND_BUILDING, .base = B_HOUSE, .category = 0, .cost = {[M_WOOD] = 1000, [M_STONE] = 2000, [M_REFINEDMETAL] = 30, [M_COMPUTERCHIPS] = 20, [M_GRAPHENE] = 3, [M_KNOWLEDGE] = 150000}, .residents = 4, .quality = 75, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .teleporterOperatingCost = 2.0f, .parent = -1, .sprite = SPR_MANSION, .ops = &ops_Mansion},
+ {.name = "FlowerPenthouse", .kind = KIND_BUILDING, .base = B_HOUSE | B_ROOFTOP, .category = 0, .cost = {[M_FOOD] = 2000, [M_WOOD] = 3000, [M_MACHINEPARTS] = 20, [M_REFINEDMETAL] = 50, [M_COMPUTERCHIPS] = 16, [M_KNOWLEDGE] = 100000}, .residents = 4, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 14, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .teleporterOperatingCost = 2.0f, .parent = -1, .sprite = SPR_FLOWERPENTHOUSE, .ops = &ops_FlowerPenthouse},
+ {.name = "LandingSite", .kind = KIND_BUILDING, .base = B_LANDINGSITE | B_ROOFTOP, .category = 4, .cost = {[M_WOOD] = 5, [M_STONE] = 10, [M_MACHINEPARTS] = 20, [M_KNOWLEDGE] = 50}, .startTime = 6, .endTime = 19, .doorX = 15, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_LANDINGPLACE, .ops = &ops_LandingSite},
+ {.name = "LandedExplorationShip", .kind = KIND_BUILDING, .base = B_HOUSE | B_UNIQUE | B_ROOFTOP, .category = 0, .cost = {[M_WOOD] = 5, [M_STONE] = 10, [M_MACHINEPARTS] = 5}, .residents = 3, .startTime = 6, .endTime = 19, .doorX = 4, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_EXPLORATIONSHIP, .ops = &ops_LandedExplorationShip},
+ {.name = "HyperElevator", .kind = KIND_BUILDING, .base = B_ELEVATOR, .category = 4, .cost = {[M_MACHINEPARTS] = 25, [M_REFINEDMETAL] = 5, [M_KNOWLEDGE] = 200}, .startTime = 6, .endTime = 19, .doorX = 8, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_HYPERELEVATOR, .ops = &ops_HyperElevator},
+ {.name = "Teleporter", .kind = KIND_BUILDING, .base = B_TELEPORTER, .category = 4, .cost = {[M_WOOD] = 4, [M_STONE] = 100, [M_MACHINEPARTS] = 150, [M_COMPUTERCHIPS] = 15, [M_KNOWLEDGE] = 5000}, .startTime = 6, .endTime = 19, .doorX = 12, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .teleporterOperatingCost = 20.0f, .parent = -1, .sprite = SPR_TELEPORTER, .ops = &ops_Teleporter},
+ {.name = "WoodcuttingCentre", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_STONE] = 4}, .jobs = 4, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_WOODCUTTINGCENTRE, .ops = &ops_WoodcuttingCentre},
+ {.name = "StoneMine", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_WOOD] = 4}, .jobs = 6, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_STONEMINE, .ops = &ops_StoneMine},
+ {.name = "IndoorFarm", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_WOOD] = 5, [M_STONE] = 3}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 12, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_INDOORFARM, .ops = &ops_IndoorFarm},
+ {.name = "ExplorationCentre", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_WOOD] = 8, [M_STONE] = 4}, .jobs = 3, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_EXPLORATIONCENTRE, .ops = &ops_ExplorationCentre},
+ {.name = "MachinePartsFactory", .kind = KIND_BUILDING, .base = B_WORK | B_HIDE_WALKERS, .category = 1, .cost = {[M_WOOD] = 10, [M_STONE] = 35, [M_KNOWLEDGE] = 25}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_MACHINEPARTSFACTORY, .ops = &ops_MachinePartsFactory},
+ {.name = "Laboratory", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_WOOD] = 10, [M_STONE] = 10, [M_MACHINEPARTS] = 10}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_LABORATORY, .ops = &ops_Laboratory},
+ {.name = "TreePlantation", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_STONE] = 10, [M_KNOWLEDGE] = 30}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_TREEPLANTATION, .ops = &ops_TreePlantation},
+ {.name = "StoneTeleporter", .kind = KIND_BUILDING, .base = B_WORK, .category = 1, .cost = {[M_WOOD] = 30, [M_MACHINEPARTS] = 30, [M_KNOWLEDGE] = 75}, .jobs = 1, .startTime = 6, .endTime = 19, .doorX = 12, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_STONETELEPORTER, .ops = &ops_StoneTeleporter},
+ {.name = "RefinedMetalFactory", .kind = KIND_BUILDING, .base = B_WORK | B_HIDE_WALKERS, .category = 1, .cost = {[M_WOOD] = 30, [M_STONE] = 90, [M_MACHINEPARTS] = 40, [M_KNOWLEDGE] = 150}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_REFINEDMETALFACTORY, .ops = &ops_RefinedMetalFactory},
+ {.name = "ComputerChipFactory", .kind = KIND_BUILDING, .base = B_WORK | B_HIDE_WALKERS, .category = 1, .cost = {[M_STONE] = 200, [M_MACHINEPARTS] = 100, [M_REFINEDMETAL] = 20, [M_KNOWLEDGE] = 300}, .jobs = 3, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_COMPUTERCHIPFACTORY, .ops = &ops_ComputerChipFactory},
+ {.name = "EcoFarm", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 1, .cost = {[M_WOOD] = 10, [M_STONE] = 2, [M_KNOWLEDGE] = 250}, .jobs = 3, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 2.0f, .entMaxTime = 3.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.5f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_ECOFARM, .ops = &ops_EcoFarm},
+ {.name = "FarmByProductProcessor", .kind = KIND_BUILDING, .base = B_WORK | B_HIDE_WALKERS, .category = 1, .cost = {[M_WOOD] = 200, [M_MACHINEPARTS] = 100, [M_COMPUTERCHIPS] = 10, [M_KNOWLEDGE] = 10000}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_FARMBYPRODUCTPROCESSOR, .ops = &ops_FarmByProductProcessor},
+ {.name = "ExperimentationLab", .kind = KIND_BUILDING, .base = B_WORK | B_HIDE_WALKERS, .category = 1, .cost = {[M_MACHINEPARTS] = 100, [M_REFINEDMETAL] = 50, [M_COMPUTERCHIPS] = 15, [M_KNOWLEDGE] = 5000}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_EXPERIMENTATIONLAB, .ops = &ops_ExperimentationLab},
+ {.name = "School", .kind = KIND_BUILDING, .base = B_WORK | B_SCHOOL, .category = 2, .cost = {[M_WOOD] = 20, [M_STONE] = 10}, .jobs = 1, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_SCHOOL, .ops = &ops_School},
+ {.name = "Library", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 2, .cost = {[M_WOOD] = 20, [M_STONE] = 10}, .jobs = 1, .startTime = 14, .endTime = 22, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 5, .entMinTime = 2.0f, .entMaxTime = 5.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_LIBRARY, .ops = &ops_Library},
+ {.name = "HerbGarden", .kind = KIND_BUILDING, .base = B_WORK | B_MEDICAL, .category = 2, .cost = {[M_WOOD] = 20, [M_STONE] = 10, [M_KNOWLEDGE] = 10}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 1, .medicalTypeLimit = 0.2f, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_HERBGARDEN, .ops = &ops_HerbGarden},
+ {.name = "MedicalClinic", .kind = KIND_BUILDING, .base = B_WORK | B_MEDICAL, .category = 2, .cost = {[M_WOOD] = 10, [M_STONE] = 50, [M_MACHINEPARTS] = 5, [M_REFINEDMETAL] = 20, [M_KNOWLEDGE] = 200}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .medicalTypeLimit = 1.0f, .unlockFlags = UF_DEFAULT | UF_HINT, .parent = -1, .sprite = SPR_MEDICALCLINIC, .ops = &ops_MedicalClinic},
+ {.name = "SpecializedMedicalClinic", .kind = KIND_BUILDING, .base = B_WORK | B_MEDICAL, .category = 2, .cost = {[M_MACHINEPARTS] = 2500, [M_REFINEDMETAL] = 2500, [M_COMPUTERCHIPS] = 100, [M_GRAPHENE] = 100, [M_KNOWLEDGE] = 50000}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .medicalTypeLimit = 1.0f, .limitedPerCitizens = 1000, .parent = -1, .sprite = SPR_ADVANCEDMEDICALCLINIC, .ops = &ops_SpecializedMedicalClinic},
+ {.name = "Pub", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 12, [M_STONE] = 5}, .jobs = 1, .startTime = 20, .endTime = 5.5, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 1, .entMinTime = 2.0f, .entMaxTime = 6.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_PUB, .ops = &ops_Pub},
+ {.name = "CarrotJuiceBar", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 7, .cost = {[M_WOOD] = 12, [M_STONE] = 5}, .jobs = 3, .startTime = 20, .endTime = 5.5, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 1, .entMinTime = 2.0f, .entMaxTime = 6.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_CARROTJUICEBAR, .ops = &ops_CarrotJuiceBar},
+ {.name = "Restaurant", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_FOOD] = 10, [M_WOOD] = 30, [M_STONE] = 10, [M_KNOWLEDGE] = 10}, .jobs = 2, .startTime = 16, .endTime = 1, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 1, .entMinTime = 1.0f, .entMaxTime = 3.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_RESTAURANT, .ops = &ops_Restaurant},
+ {.name = "LuxuryRestaurant", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_FOOD] = 100, [M_WOOD] = 10, [M_REFINEDMETAL] = 100, [M_KNOWLEDGE] = 2500}, .jobs = 2, .startTime = 16, .endTime = 1, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 1, .entMinTime = 2.0f, .entMaxTime = 4.0f, .entMinSatisfy = 2.0f, .entMaxSatisfy = 4.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_LUXURYRESTAURANT, .ops = &ops_LuxuryRestaurant},
+ {.name = "FactoryPub", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT | B_HIDE_WALKERS, .category = 3, .cost = {[M_WOOD] = 200, [M_STONE] = 50, [M_MACHINEPARTS] = 50, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 1000}, .jobs = 2, .startTime = 16.5, .endTime = 5.5, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 1, .entMinTime = 2.0f, .entMaxTime = 5.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .parent = 37, .sprite = SPR_REFINEDMETALFACTORYPUB, .ops = &ops_FactoryPub},
+ {.name = "BlossomRestaurant", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_FOOD] = 500, [M_WOOD] = 500, [M_KNOWLEDGE] = 2500}, .jobs = 1, .startTime = 16, .endTime = 1, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 1, .entMinTime = 1.0f, .entMaxTime = 2.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_BLOOMRESTAURANT, .ops = &ops_BlossomRestaurant},
+ {.name = "Park", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 20, [M_KNOWLEDGE] = 5}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 1.5f, .entMaxTime = 2.5f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.75f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_BOTANICALGARDENS, .ops = &ops_Park},
+ {.name = "BotanicalGardens", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 25, [M_KNOWLEDGE] = 100}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 2.5f, .entMaxTime = 4.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.5f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_BOTANICALGARDENS, .ops = &ops_BotanicalGardens},
+ {.name = "BotanicalGardensDome", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT | B_ROOFTOP, .category = 3, .cost = {[M_WOOD] = 25, [M_REFINEDMETAL] = 1, [M_KNOWLEDGE] = 2500}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 2.5f, .entMaxTime = 4.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.5f, .entQuality = 100, .medicalTypeID = 0, .parent = 54, .sprite = SPR_DOME_BOTANICALGARDEN, .ops = &ops_BotanicalGardensDome},
+ {.name = "RooftopPark", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT | B_ROOFTOP, .category = 3, .cost = {[M_WOOD] = 25, [M_KNOWLEDGE] = 10000}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 1.5f, .entMaxTime = 2.5f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.75f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_ROOFTOPPARK, .ops = &ops_RooftopPark},
+ {.name = "RedwoodTree", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT | B_NO_INSERT | B_NO_BUILD_ON_TOP | B_BUILD_ON_GROUND, .category = 3, .cost = {[M_FOOD] = 50, [M_WOOD] = 100, [M_KNOWLEDGE] = 5000}, .startTime = 6, .endTime = 19, .doorX = 9, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 3.0f, .entMaxTime = 4.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.5f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_REDWOOD, .ops = &ops_RedwoodTree},
+ {.name = "RedwoodTreeHouse", .kind = KIND_BUILDING, .base = B_HOUSE | B_ENTERTAINMENT | B_NO_INSERT | B_NO_BUILD_ON_TOP | B_BUILD_ON_GROUND, .category = 7, .cost = {[M_FOOD] = 50, [M_WOOD] = 150, [M_MACHINEPARTS] = 20, [M_REFINEDMETAL] = 10, [M_KNOWLEDGE] = 7500}, .residents = 2, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 9, .workTimePreferenceMod = 1, .entType = 3, .entMinTime = 3.0f, .entMaxTime = 4.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.5f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = 57, .sprite = SPR_REDWOODTREEHOUSE, .ops = &ops_RedwoodTreeHouse},
+ {.name = "NightClub", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 20, [M_STONE] = 60, [M_MACHINEPARTS] = 20, [M_KNOWLEDGE] = 50}, .jobs = 1, .startTime = 20, .endTime = 5.5, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 0, .entMinTime = 5.0f, .entMaxTime = 7.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_NIGHTCLUB, .ops = &ops_NightClub},
+ {.name = "ScrapyardNightClub", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 500, [M_MACHINEPARTS] = 250, [M_REFINEDMETAL] = 50, [M_COMPUTERCHIPS] = 10, [M_KNOWLEDGE] = 2000}, .jobs = 1, .startTime = 20, .endTime = 5.5, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 0, .entMinTime = 5.0f, .entMaxTime = 7.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_SCRAPYARDNIGHTCLUB, .ops = &ops_ScrapyardNightClub},
+ {.name = "ModernArtMuseum", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 40, [M_STONE] = 40, [M_REFINEDMETAL] = 10, [M_KNOWLEDGE] = 100}, .jobs = 1, .startTime = 9, .endTime = 22, .doorX = 13, .workTimePreferenceMod = 0.1, .entType = 2, .entMinTime = 2.0f, .entMaxTime = 3.0f, .entMinSatisfy = 2.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT | UF_HINT, .parent = -1, .sprite = SPR_MODERNARTMUSEUM, .ops = &ops_ModernArtMuseum},
+ {.name = "StatueGarden", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 60, [M_STONE] = 40, [M_REFINEDMETAL] = 5, [M_KNOWLEDGE] = 1000}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 2, .entMinTime = 1.5f, .entMaxTime = 2.5f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.75f, .entQuality = 100, .medicalTypeID = 0, .parent = 53, .sprite = SPR_BOTANICALGARDENS, .ops = &ops_Park},
+ {.name = "Arcade", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 20, [M_STONE] = 100, [M_MACHINEPARTS] = 10, [M_REFINEDMETAL] = 20, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 300}, .jobs = 1, .startTime = 12, .endTime = 23.5, .doorX = 13, .workTimePreferenceMod = 0.1, .entType = 4, .entMinTime = 2.5f, .entMaxTime = 3.0f, .entMinSatisfy = 4.0f, .entMaxSatisfy = 7.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT | UF_HINT, .parent = -1, .sprite = SPR_ARCADE, .ops = &ops_Arcade},
+ {.name = "HoloGameHall", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT, .category = 3, .cost = {[M_WOOD] = 100, [M_STONE] = 500, [M_MACHINEPARTS] = 50, [M_COMPUTERCHIPS] = 40, [M_KNOWLEDGE] = 10000}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 4, .entMinTime = 4.0f, .entMaxTime = 5.0f, .entMinSatisfy = 2.0f, .entMaxSatisfy = 5.0f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_HOLOGAMEHALL, .ops = &ops_HoloGameHall},
+ {.name = "Workshop", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 60, [M_KNOWLEDGE] = 30}, .jobs = 2, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_WORKSHOP, .ops = &ops_Workshop},
+ {.name = "ResearchBot", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE | B_ROOFTOP | B_CITY_TOP, .category = 5, .cost = {[M_STONE] = 10, [M_MACHINEPARTS] = 1, [M_KNOWLEDGE] = 20}, .jobs = 1, .startTime = 6, .endTime = 19, .doorX = 15, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_RESEARCHBOT_LANDINGPLACE, .ops = &ops_ResearchBot},
+ {.name = "ExperimentalFarm", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 60, [M_STONE] = 30, [M_MACHINEPARTS] = 5, [M_KNOWLEDGE] = 50}, .jobs = 3, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_EXPERIMENTALFARM, .ops = &ops_ExperimentalFarm},
+ {.name = "Observatory", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE | B_ROOFTOP, .category = 5, .cost = {[M_WOOD] = 30, [M_STONE] = 40, [M_MACHINEPARTS] = 40, [M_KNOWLEDGE] = 75}, .jobs = 3, .startTime = 21, .endTime = 4, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_OBSERVATORY, .ops = &ops_Observatory},
+ {.name = "ArtColony", .kind = KIND_BUILDING, .base = B_HOUSE | B_WORK | B_ENTERTAINMENT | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 90, [M_STONE] = 10, [M_KNOWLEDGE] = 125}, .residents = 5, .jobs = 5, .quality = 100, .startTime = 10, .endTime = 22, .doorX = 13, .workTimePreferenceMod = 0.3, .entType = 2, .entMinTime = 1.0f, .entMaxTime = 2.0f, .entMinSatisfy = 2.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_ARTCOLONY, .ops = &ops_ArtColony},
+ {.name = "CityHall", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE, .category = 5, .cost = {[M_FOOD] = 100, [M_WOOD] = 200, [M_STONE] = 100, [M_KNOWLEDGE] = 150}, .jobs = 4, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_CITYHALL, .ops = &ops_CityHall},
+ {.name = "StoneResearchCenter", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 500, [M_MACHINEPARTS] = 30, [M_REFINEDMETAL] = 10, [M_KNOWLEDGE] = 750}, .jobs = 4, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_STONERESEARCHCENTRE, .ops = &ops_StoneResearchCenter},
+ {.name = "ComputerResearchCenter", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE | B_HIDE_WALKERS, .category = 5, .cost = {[M_STONE] = 100, [M_MACHINEPARTS] = 40, [M_REFINEDMETAL] = 30, [M_KNOWLEDGE] = 300}, .jobs = 5, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_COMPUTERRESEARCHCENTER, .ops = &ops_ComputerResearchCenter},
+ {.name = "LivingResearchCenter", .kind = KIND_BUILDING, .base = B_HOUSE | B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 100, [M_STONE] = 100, [M_MACHINEPARTS] = 5, [M_REFINEDMETAL] = 25, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 250}, .residents = 2, .jobs = 6, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_LIVINGRESEARCHCENTER, .ops = &ops_LivingResearchCenter},
+ {.name = "HackerHQ", .kind = KIND_BUILDING, .base = B_HOUSE | B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 1000, [M_MACHINEPARTS] = 25, [M_REFINEDMETAL] = 100, [M_COMPUTERCHIPS] = 25, [M_KNOWLEDGE] = 2000}, .residents = 6, .jobs = 6, .quality = 100, .startTime = 14, .endTime = 3, .doorX = 13, .workTimePreferenceMod = 0.3, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_HACKERHQ, .ops = &ops_HackerHQ},
+ {.name = "AlienDecryptor", .kind = KIND_BUILDING, .base = B_UNIQUE, .category = 5, .cost = {[M_STONE] = 1000, [M_MACHINEPARTS] = 900, [M_REFINEDMETAL] = 300, [M_COMPUTERCHIPS] = 100, [M_KNOWLEDGE] = 3000}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_ALIENDECRYPTOR, .ops = &ops_AlienDecryptor},
+ {.name = "EscapeRoom", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 1000, [M_MACHINEPARTS] = 100, [M_REFINEDMETAL] = 500, [M_COMPUTERCHIPS] = 30, [M_KNOWLEDGE] = 7500}, .jobs = 1, .startTime = 13, .endTime = 3, .doorX = 13, .workTimePreferenceMod = 0.1, .entType = 4, .entMinTime = 2.5f, .entMaxTime = 3.5f, .entMinSatisfy = 4.0f, .entMaxSatisfy = 7.0f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_LABESCAPEROOM, .ops = &ops_EscapeRoom},
+ {.name = "Misdirector", .kind = KIND_BUILDING, .base = B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 400, [M_STONE] = 10000, [M_MACHINEPARTS] = 500, [M_COMPUTERCHIPS] = 500, [M_KNOWLEDGE] = 30000}, .startTime = 6, .endTime = 19, .doorX = 12, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_MISDIRECTOR, .ops = &ops_Misdirector},
+ {.name = "SecretSocietyHouse", .kind = KIND_BUILDING, .base = B_HOUSE | B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 3000, [M_STONE] = 1000, [M_MACHINEPARTS] = 25, [M_REFINEDMETAL] = 100, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 2000}, .residents = 8, .jobs = 8, .quality = 75, .startTime = 12, .endTime = 2, .doorX = 13, .workTimePreferenceMod = 0.3, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_SECRETSOCIETYHOUSE, .ops = &ops_SecretSocietyHouse},
+ {.name = "TheMachine", .kind = KIND_BUILDING, .base = B_UNIQUE, .category = 5, .cost = {[M_FOOD] = 20000, [M_WOOD] = 10000, [M_STONE] = 5000, [M_MACHINEPARTS] = 10000, [M_COMPUTERCHIPS] = 250, [M_KNOWLEDGE] = 25000}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_SECRETSOCIETYMACHINE, .ops = &ops_TheMachine},
+ {.name = "HouseOfTheKeyFriends", .kind = KIND_BUILDING, .base = B_HOUSE | B_UNIQUE, .category = 5, .residents = 8, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_HOUSEOFTHEKEYFRIENDS, .ops = &ops_HouseOfTheKeyFriends},
+ {.name = "BlossomHippieHQ", .kind = KIND_BUILDING, .base = B_HOUSE | B_WORK | B_UNIQUE, .category = 5, .cost = {[M_FOOD] = 5000, [M_WOOD] = 5000, [M_REFINEDMETAL] = 50, [M_KNOWLEDGE] = 5000}, .residents = 6, .jobs = 6, .quality = 100, .startTime = 11, .endTime = 23, .doorX = 13, .workTimePreferenceMod = 0.3, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_HINT, .parent = -1, .sprite = SPR_BLOSSOMHIPPIEHQ, .ops = &ops_BlossomHippieHQ},
+ {.name = "FestivalHQ", .kind = KIND_BUILDING, .base = B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 100000, [M_KNOWLEDGE] = 25000}, .jobs = 5, .startTime = 6, .endTime = 19, .doorX = 14, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_FESTIVALHQ, .ops = &ops_FestivalHQ},
+ {.name = "FeatherAlliance", .kind = KIND_BUILDING, .base = B_HOUSE | B_WORK | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 100000, [M_COMPUTERCHIPS] = 2000, [M_GRAPHENE] = 500, [M_ROCKETFUEL] = 2000, [M_KNOWLEDGE] = 100000}, .residents = 7, .jobs = 7, .quality = 100, .startTime = 12, .endTime = 2, .doorX = 13, .workTimePreferenceMod = 0.3, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_FEATHERALLIANCE, .ops = &ops_FeatherAlliance},
+ {.name = "IntergalacticLibrary", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT | B_UNIQUE, .category = 5, .cost = {[M_FOOD] = 100000, [M_WOOD] = 200000, [M_COMPUTERCHIPS] = 15000, [M_GRAPHENE] = 2000, [M_KNOWLEDGE] = 200000}, .jobs = 3, .startTime = 13, .endTime = 23, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 5, .entMinTime = 2.0f, .entMaxTime = 5.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .parent = -1, .sprite = SPR_INTERGALACTICLIBRARY, .ops = &ops_IntergalacticLibrary},
+ {.name = "Supercomputer", .kind = KIND_BUILDING, .base = B_UNIQUE, .category = 5, .cost = {[M_STONE] = 10000, [M_MACHINEPARTS] = 1000, [M_REFINEDMETAL] = 2000, [M_COMPUTERCHIPS] = 1000, [M_KNOWLEDGE] = 10000}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .parent = -1, .sprite = SPR_SUPERCOMPUTER, .ops = &ops_Supercomputer},
+ {.name = "TreeHuggerBase", .kind = KIND_BUILDING, .base = B_HOUSE | B_UNIQUE, .category = 5, .cost = {[M_FOOD] = 100, [M_WOOD] = 100, [M_KNOWLEDGE] = 5000}, .residents = 3, .quality = 100, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_BLOOMRESTAURANT, .ops = &ops_TreeHuggerBase},
+ {.name = "FossilMuseum", .kind = KIND_BUILDING, .base = B_WORK | B_ENTERTAINMENT | B_UNIQUE, .category = 5, .cost = {[M_WOOD] = 1000, [M_STONE] = 1000, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 25000}, .jobs = 3, .startTime = 14, .endTime = 23, .doorX = 13, .workTimePreferenceMod = 0.5, .entType = 5, .entMinTime = 2.0f, .entMaxTime = 5.0f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_FOSSILMUSEUM, .ops = &ops_FossilMuseum},
+ {.name = "StatueOfHappiness", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT | B_UNIQUE, .category = 5, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 2, .entMinTime = 1.5f, .entMaxTime = 2.5f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.75f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = 53, .sprite = SPR_BOTANICALGARDENS, .ops = &ops_Park},
+ {.name = "StatueOfTheKey", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT | B_UNIQUE, .category = 5, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 2, .entMinTime = 1.5f, .entMaxTime = 2.5f, .entMinSatisfy = 1.0f, .entMaxSatisfy = 1.75f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_NOT_WITH_ALL, .parent = 53, .sprite = SPR_BOTANICALGARDENS, .ops = &ops_Park},
+ {.name = "Beacon", .kind = KIND_BUILDING, .base = B_ENTERTAINMENT | B_UNIQUE | B_ROOFTOP, .category = 5, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = 2, .entMinTime = 1.5f, .entMaxTime = 3.0f, .entMinSatisfy = 2.0f, .entMaxSatisfy = 3.0f, .entQuality = 100, .medicalTypeID = 0, .unlockFlags = UF_HINT | UF_NOT_WITH_ALL, .parent = -1, .sprite = SPR_BEACON, .ops = &ops_Beacon},
+ {.name = "ColoredBlock", .kind = KIND_BUILDING, .base = 0, .category = 6, .cost = {[M_WOOD] = 4, [M_STONE] = 4}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_COLOREDBLOCK, .ops = &ops_ColoredBlock},
+ {.name = "GlassPiece", .kind = KIND_BUILDING, .base = 0, .category = 6, .cost = {[M_WOOD] = 4, [M_STONE] = 4}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_INDOORFARM, .ops = &ops_GlassPiece},
+ {.name = "RooftopDecoration", .kind = KIND_BUILDING, .base = B_ROOFTOP, .category = 6, .cost = {[M_WOOD] = 2, [M_STONE] = 2}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_SLANTEDROOF, .ops = &ops_RooftopDecoration},
+ {.name = "RooftopDecoration2", .kind = KIND_BUILDING, .base = B_ROOFTOP, .category = 6, .cost = {[M_WOOD] = 1, [M_STONE] = 1}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_SLANTEDROOFTOP, .ops = &ops_RooftopDecoration2},
+ {.name = "RooftopDecoration3", .kind = KIND_BUILDING, .base = B_ROOFTOP, .category = 6, .cost = {[M_WOOD] = 2, [M_STONE] = 2}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_DOMEROOF, .ops = &ops_RooftopDecoration3},
+ {.name = "RooftopDecoration4", .kind = KIND_BUILDING, .base = B_ROOFTOP, .category = 6, .cost = {[M_WOOD] = 3, [M_STONE] = 3}, .startTime = 6, .endTime = 19, .doorX = 13, .workTimePreferenceMod = 1, .entType = -1, .medicalTypeID = 0, .unlockFlags = UF_DEFAULT, .parent = -1, .sprite = SPR_ROOFBOTTOM, .ops = &ops_RooftopDecoration4},
+};
+const int npcls = sizeof pcls / sizeof pcls[0];
+int pcls_find(const char *name) {
+ for (int i = 0; i < npcls; i++)
+ if (!strcmp(pcls[i].name, name)) return i;
+ return -1;
+}
diff --git a/games/finalearth2/src/classes.h b/games/finalearth2/src/classes.h
new file mode 100644
index 00000000..3baf621c
--- /dev/null
+++ b/games/finalearth2/src/classes.h
@@ -0,0 +1,105 @@
+/* The Final Earth 2: class numbers (made by tools/gen_classes.py). */
+#ifndef FE_CLASSES_H
+#define FE_CLASSES_H
+#include "pcls.h"
+enum {
+ CLS_Forest = 0,
+ CLS_PineForest = 1,
+ CLS_BranchyForest = 2,
+ CLS_RedForest = 3,
+ CLS_PurpleForest = 4,
+ CLS_BirchForest = 5,
+ CLS_Rock = 6,
+ CLS_Boulder = 7,
+ CLS_AlienRuins = 8,
+ CLS_ComputerAlienRuins = 9,
+ CLS_NormalHouse = 10,
+ CLS_AlienHouse = 11,
+ CLS_ModernRusticHome = 12,
+ CLS_ComfortableHouse = 13,
+ CLS_MechanicalHouse = 14,
+ CLS_SpaciousHouse = 15,
+ CLS_CuttingEdgeHome = 16,
+ CLS_ParkPod = 17,
+ CLS_Loft = 18,
+ CLS_TinkerersHome = 19,
+ CLS_FarmHouse = 20,
+ CLS_BlossomHut = 21,
+ CLS_Villa = 22,
+ CLS_Mansion = 23,
+ CLS_FlowerPenthouse = 24,
+ CLS_LandingSite = 25,
+ CLS_LandedExplorationShip = 26,
+ CLS_HyperElevator = 27,
+ CLS_Teleporter = 28,
+ CLS_WoodcuttingCentre = 29,
+ CLS_StoneMine = 30,
+ CLS_IndoorFarm = 31,
+ CLS_ExplorationCentre = 32,
+ CLS_MachinePartsFactory = 33,
+ CLS_Laboratory = 34,
+ CLS_TreePlantation = 35,
+ CLS_StoneTeleporter = 36,
+ CLS_RefinedMetalFactory = 37,
+ CLS_ComputerChipFactory = 38,
+ CLS_EcoFarm = 39,
+ CLS_FarmByProductProcessor = 40,
+ CLS_ExperimentationLab = 41,
+ CLS_School = 42,
+ CLS_Library = 43,
+ CLS_HerbGarden = 44,
+ CLS_MedicalClinic = 45,
+ CLS_SpecializedMedicalClinic = 46,
+ CLS_Pub = 47,
+ CLS_CarrotJuiceBar = 48,
+ CLS_Restaurant = 49,
+ CLS_LuxuryRestaurant = 50,
+ CLS_FactoryPub = 51,
+ CLS_BlossomRestaurant = 52,
+ CLS_Park = 53,
+ CLS_BotanicalGardens = 54,
+ CLS_BotanicalGardensDome = 55,
+ CLS_RooftopPark = 56,
+ CLS_RedwoodTree = 57,
+ CLS_RedwoodTreeHouse = 58,
+ CLS_NightClub = 59,
+ CLS_ScrapyardNightClub = 60,
+ CLS_ModernArtMuseum = 61,
+ CLS_StatueGarden = 62,
+ CLS_Arcade = 63,
+ CLS_HoloGameHall = 64,
+ CLS_Workshop = 65,
+ CLS_ResearchBot = 66,
+ CLS_ExperimentalFarm = 67,
+ CLS_Observatory = 68,
+ CLS_ArtColony = 69,
+ CLS_CityHall = 70,
+ CLS_StoneResearchCenter = 71,
+ CLS_ComputerResearchCenter = 72,
+ CLS_LivingResearchCenter = 73,
+ CLS_HackerHQ = 74,
+ CLS_AlienDecryptor = 75,
+ CLS_EscapeRoom = 76,
+ CLS_Misdirector = 77,
+ CLS_SecretSocietyHouse = 78,
+ CLS_TheMachine = 79,
+ CLS_HouseOfTheKeyFriends = 80,
+ CLS_BlossomHippieHQ = 81,
+ CLS_FestivalHQ = 82,
+ CLS_FeatherAlliance = 83,
+ CLS_IntergalacticLibrary = 84,
+ CLS_Supercomputer = 85,
+ CLS_TreeHuggerBase = 86,
+ CLS_FossilMuseum = 87,
+ CLS_StatueOfHappiness = 88,
+ CLS_StatueOfTheKey = 89,
+ CLS_Beacon = 90,
+ CLS_ColoredBlock = 91,
+ CLS_GlassPiece = 92,
+ CLS_RooftopDecoration = 93,
+ CLS_RooftopDecoration2 = 94,
+ CLS_RooftopDecoration3 = 95,
+ CLS_RooftopDecoration4 = 96,
+ CLS_COUNT = 97
+};
+#endif
diff --git a/games/finalearth2/src/data.S b/games/finalearth2/src/data.S
new file mode 100644
index 00000000..4aaf848c
--- /dev/null
+++ b/games/finalearth2/src/data.S
@@ -0,0 +1,19 @@
+/* data.bin (tools/pack.py) in the app's read-only data */
+#ifdef __APPLE__
+ .const_data
+ .p2align 2
+ .globl _fe_data
+_fe_data:
+ .incbin DATA_BIN
+ .p2align 2
+#else
+ .section .rodata.fe_data,"a"
+ .balign 4
+ .global fe_data
+fe_data:
+ .incbin DATA_BIN
+ .balign 4
+#endif
+#ifdef __ELF__
+ .section .note.GNU-stack,"",%progbits
+#endif
diff --git a/games/finalearth2/src/data.bin b/games/finalearth2/src/data.bin
new file mode 100644
index 00000000..d15a38c6
Binary files /dev/null and b/games/finalearth2/src/data.bin differ
diff --git a/games/finalearth2/src/data.h b/games/finalearth2/src/data.h
new file mode 100644
index 00000000..f45abfd7
--- /dev/null
+++ b/games/finalearth2/src/data.h
@@ -0,0 +1,1281 @@
+/* The Final Earth 2: what tools/pack.py packed in data.bin (made by it: do not edit). */
+#ifndef FE_DATA_H
+#define FE_DATA_H
+#include <stdint.h>
+
+extern const uint8_t fe_data[]; /* data.bin (data.S) */
+
+/* sprites: each frame of the original's atlas (often a strip of frames, 2 pixels apart) */
+enum {
+ SPR_9P_BUTTON_ACTIVE, /* spr_9p_button_active.png, 22 x 22 */
+ SPR_9P_BUTTON_DISABLED, /* spr_9p_button_disabled.png, 22 x 22 */
+ SPR_9P_HINTINFO, /* spr_9p_hintinfo.png, 60 x 60 */
+ SPR_9P_INFO, /* spr_9p_info.png, 32 x 32 */
+ SPR_9P_TOOLTIP, /* spr_9p_tooltip.png, 10 x 10 */
+ SPR_9P_WINDOW, /* spr_9p_window.png, 60 x 60 */
+ SPR_9P_WINDOW_MOREOPAQUE, /* spr_9p_window_moreopaque.png, 60 x 60 */
+ SPR_9P_WINDOW_PURPLE, /* spr_9p_window_purple.png, 60 x 60 */
+ SPR_ADVANCEDMEDICALCLINIC, /* spr_advancedmedicalclinic.png, 64 x 20 */
+ SPR_AIMINING, /* spr_aiMining.png, 20 x 20 */
+ SPR_ALIENDECRYPTOR, /* spr_aliendecryptor.png, 64 x 20 */
+ SPR_ALIENHOUSE, /* spr_alienhouse.png, 64 x 20 */
+ SPR_ALIENHOUSE_LIVINGCOMPUTER, /* spr_alienhouse_livingcomputer.png, 152 x 20 */
+ SPR_ALIENRUINS, /* spr_alienruins.png, 20 x 20 */
+ SPR_ALIENRUINS_2, /* spr_alienruins_2.png, 20 x 20 */
+ SPR_ALIENRUINS_3, /* spr_alienruins_3.png, 20 x 20 */
+ SPR_ARCADE, /* spr_arcade.png, 64 x 20 */
+ SPR_ARROW_BACK, /* spr_arrow_back.png, 20 x 20 */
+ SPR_ARROWDOWN, /* spr_arrowdown.png, 7 x 5 */
+ SPR_ARROWDOWN_BIG, /* spr_arrowdown_big.png, 16 x 16 */
+ SPR_ARROWUP, /* spr_arrowup.png, 7 x 5 */
+ SPR_ARROWUP_BIG, /* spr_arrowup_big.png, 16 x 16 */
+ SPR_ARTCOLONY, /* spr_artcolony.png, 64 x 20 */
+ SPR_ARTCOLONY_BUTTONBACK, /* spr_artcolony_buttonback.png, 20 x 20 */
+ SPR_ARTCOLONYWORK, /* spr_artcolonywork.png, 306 x 20 */
+ SPR_BEACON, /* spr_beacon.png, 64 x 20 */
+ SPR_BEACON_LIGHT, /* spr_beacon_light.png, 4 x 11 */
+ SPR_BIGGERTV, /* spr_biggertv.png, 20 x 20 */
+ SPR_BIRCHFOREST, /* spr_birchforest.png, 20 x 20 */
+ SPR_BLOOMHOUSE, /* spr_bloomhouse.png, 108 x 20 */
+ SPR_BLOOMHUT_BUTTONBACK, /* spr_bloomhut_buttonback.png, 20 x 20 */
+ SPR_BLOOMRESTAURANT, /* spr_bloomrestaurant.png, 328 x 20 */
+ SPR_BLOOMRESTAURANT_FOREGROUND, /* spr_bloomrestaurant_foreground.png, 108 x 20 */
+ SPR_BLOSSOMHIPPIEHQ, /* spr_blossomhippiehq.png, 64 x 20 */
+ SPR_BLUEWORLDGLOW, /* spr_blueworldglow.png, 20 x 5 */
+ SPR_BOARDGAMESTORE, /* spr_boardgamestore.png, 64 x 20 */
+ SPR_BONUSRANGE_PLUS, /* spr_bonusrange_plus.png, 9 x 10 */
+ SPR_BONUSRANGE_TOPBOTTOM, /* spr_bonusrange_topbottom.png, 9 x 10 */
+ SPR_BOTANICALGARDEN_DOME_BUTTONBACK, /* spr_botanicalgarden_dome_buttonback.png, 20 x 20 */
+ SPR_BOTANICALGARDENS, /* spr_botanicalgardens.png, 328 x 20 */
+ SPR_BOTANICALGARDENS_BUTTONBACK, /* spr_botanicalgardens_buttonback.png, 20 x 20 */
+ SPR_BOTANICALGARDENS_PLANTS, /* spr_botanicalgardens_plants.png, 300 x 80 */
+ SPR_BOULDER, /* spr_boulder.png, 164 x 20 */
+ SPR_BUILDHEREOUTLINE, /* spr_buildhereoutline.png, 20 x 20 */
+ SPR_BUILDINGBUTTON, /* spr_buildingbutton.png, 70 x 22 */
+ SPR_BUTTON, /* spr_button.png, 70 x 22 */
+ SPR_BUTTON_ACTIVABLE, /* spr_button_activable.png, 70 x 22 */
+ SPR_BUTTON_CHECKED, /* spr_button_checked.png, 70 x 22 */
+ SPR_BUTTON_GRAY, /* spr_button_gray.png, 70 x 22 */
+ SPR_BUTTON_MEDIUM, /* spr_button_medium.png, 70 x 22 */
+ SPR_BUTTON_SMALL, /* spr_button_small.png, 58 x 18 */
+ SPR_BUTTON_SMALLER, /* spr_button_smaller.png, 49 x 15 */
+ SPR_BUTTON_SMALLER_MOBILE, /* spr_button_smaller_mobile.png, 61 x 19 */
+ SPR_BUTTON_WINDOWHEADER, /* spr_button_windowheader.png, 73 x 17 */
+ SPR_BUTTON_WINDOWHEADER_MOBI, /* spr_button_windowheader_mobi.png, 79 x 19 */
+ SPR_BUTTONNOTIFICATION, /* spr_buttonnotification.png, 22 x 22 */
+ SPR_CACAOFARM, /* spr_cacaofarm.png, 64 x 20 */
+ SPR_CACAOFARM_TREES, /* spr_cacaofarm_trees.png, 152 x 20 */
+ SPR_CAMERA, /* spr_camera.png, 14 x 14 */
+ SPR_CARROTJUICEBAR, /* spr_carrotjuicebar.png, 64 x 20 */
+ SPR_CHECKBOX, /* spr_checkbox.png, 18 x 8 */
+ SPR_CHILDREN, /* spr_children.png, 202 x 5 */
+ SPR_CHOCOLATEFACTORY, /* spr_chocolatefactory.png, 64 x 20 */
+ SPR_CHOCOLATEFACTORY_FRAMES, /* spr_chocolatefactory_frames.png, 240 x 20 */
+ SPR_CHOCOLATEFACTORY_IDLE, /* spr_chocolatefactory_idle.png, 20 x 20 */
+ SPR_CITIZEN_BALL, /* spr_citizen_ball.png, 4 x 4 */
+ SPR_CITYHALL, /* spr_cityhall.png, 64 x 20 */
+ SPR_CLOUDS, /* spr_clouds.png, 990 x 122 */
+ SPR_COLORCIRCLE, /* spr_colorcircle.png, 200 x 223 */
+ SPR_COLOREDBLOCK, /* spr_coloredblock.png, 438 x 20 */
+ SPR_COLOREDDOORS, /* spr_coloreddoors.png, 130 x 20 */
+ SPR_COLORPICKER_CIRCLE, /* spr_colorpicker_circle.png, 12 x 12 */
+ SPR_COLORPICKER_COLORPICKED, /* spr_colorpicker_colorpicked.png, 10 x 10 */
+ SPR_COLORPICKER_TRIANGLE, /* spr_colorpicker_triangle.png, 12 x 12 */
+ SPR_COMFORTABLECOUCH, /* spr_comfortablecouch.png, 20 x 20 */
+ SPR_COMFORTABLEHOUSE, /* spr_comfortablehouse.png, 64 x 20 */
+ SPR_COMMUNITYHOUSE_BUTTONBACK, /* spr_communityhouse_buttonback.png, 20 x 20 */
+ SPR_COMMUNITYHOUSE_CROP, /* spr_communityhouse_crop.png, 68 x 14 */
+ SPR_COMMUNITYHOUSE_INDOORPOND, /* spr_communityhouse_indoorpond.png, 20 x 20 */
+ SPR_COMMUNITYHOUSE_ROCK, /* spr_communityhouse_rock.png, 61 x 14 */
+ SPR_COMMUNITYHOUSE_TREE, /* spr_communityhouse_tree.png, 47 x 14 */
+ SPR_COMMUNITYHOUSE_TREE_GROW, /* spr_communityhouse_tree_grow.png, 75 x 14 */
+ SPR_COMPUTER_OBSERVATORY, /* spr_computer_observatory.png, 20 x 20 */
+ SPR_COMPUTERCHIPFACTORY, /* spr_computerchipfactory.png, 64 x 20 */
+ SPR_COMPUTERCHIPFACTORY_FRAMES, /* spr_computerchipfactory_frames.png, 526 x 20 */
+ SPR_COMPUTERCHIPFACTORY_IDLE, /* spr_computerchipfactory_idle.png, 20 x 20 */
+ SPR_COMPUTERRESEARCHCENTER, /* spr_computerresearchcenter.png, 64 x 20 */
+ SPR_COMPUTERRESEARCHCENTER_FRAMES, /* spr_computerresearchcenter_frames.png, 372 x 20 */
+ SPR_COMPUTERRESEARCHCENTER_IDLE, /* spr_computerresearchcenter_idle.png, 20 x 20 */
+ SPR_CONTRAPTION, /* spr_contraption.png, 64 x 20 */
+ SPR_CREDITS, /* spr_credits.png, 14 x 14 */
+ SPR_CUTTINGEDGEHOME, /* spr_cuttingedgehome.png, 64 x 20 */
+ SPR_DECORATION_KEYCITY, /* spr_decoration_keycity.png, 86 x 20 */
+ SPR_DECORATION_ROCKS, /* spr_decoration_rocks.png, 64 x 20 */
+ SPR_DESTROYING, /* spr_destroying.png, 20 x 20 */
+ SPR_DIESHRINK, /* spr_dieshrink.png, 20 x 20 */
+ SPR_DOME_BOTANICALGARDEN, /* spr_dome_botanicalgarden.png, 130 x 20 */
+ SPR_DOME_BOTANICALGARDEN_ALT1, /* spr_dome_botanicalgarden_alt1.png, 130 x 20 */
+ SPR_DOME_BOTANICALGARDEN_ALT1B, /* spr_dome_botanicalgarden_alt1b.png, 130 x 20 */
+ SPR_DOME_BOTANICALGARDEN_ALT2, /* spr_dome_botanicalgarden_alt2.png, 130 x 20 */
+ SPR_DOME_BOTANICALGARDEN_ALT2B, /* spr_dome_botanicalgarden_alt2b.png, 130 x 20 */
+ SPR_DOME_BOTANICALGARDEN_B, /* spr_dome_botanicalgarden_b.png, 130 x 20 */
+ SPR_DOME_BOTANICALGARDEN_PLANTS, /* spr_dome_botanicalgarden_plants.png, 300 x 40 */
+ SPR_DOMEROOF, /* spr_domeroof.png, 460 x 20 */
+ SPR_DRACULA_ADULT, /* spr_dracula_adult.png, 2 x 5 */
+ SPR_DRACULA_CHILD, /* spr_dracula_child.png, 2 x 5 */
+ SPR_ECOFARM, /* spr_ecofarm.png, 64 x 20 */
+ SPR_ECOFARM_BUTTONBACK, /* spr_ecofarm_buttonback.png, 20 x 20 */
+ SPR_ECOFARM_CROP1, /* spr_ecofarm_crop1.png, 94 x 14 */
+ SPR_ECOFARM_CROP2, /* spr_ecofarm_crop2.png, 68 x 5 */
+ SPR_ECOFARM_CROP2_ALT, /* spr_ecofarm_crop2_alt.png, 58 x 5 */
+ SPR_ECOFARM_CROP2_ALT2, /* spr_ecofarm_crop2_alt2.png, 78 x 5 */
+ SPR_ECOFARM_CROP3, /* spr_ecofarm_crop3.png, 78 x 5 */
+ SPR_ECOFARM_CROP3_ALT, /* spr_ecofarm_crop3_alt.png, 58 x 5 */
+ SPR_EXPERIMENTALFARM, /* spr_experimentalfarm.png, 64 x 20 */
+ SPR_EXPERIMENTALFARM_BUTTONBACK, /* spr_experimentalfarm_buttonback.png, 20 x 20 */
+ SPR_EXPERIMENTALFARM_CROP1, /* spr_experimentalfarm_crop1.png, 75 x 14 */
+ SPR_EXPERIMENTALFARM_CROP2, /* spr_experimentalfarm_crop2.png, 61 x 5 */
+ SPR_EXPERIMENTALFARM_CROP3, /* spr_experimentalfarm_crop3.png, 33 x 5 */
+ SPR_EXPERIMENTATIONLAB, /* spr_experimentationlab.png, 64 x 20 */
+ SPR_EXPERIMENTATIONLAB_IDLE, /* spr_experimentationlab_idle.png, 42 x 20 */
+ SPR_EXPERIMENTATIONLAB_PIPE_BOTTOM, /* spr_experimentationlab_pipe_bottom.png, 5 x 9 */
+ SPR_EXPERIMENTATIONLAB_PIPE_TOP, /* spr_experimentationlab_pipe_top.png, 5 x 14 */
+ SPR_EXPERIMENTATIONLAB_SCREWDRIVER, /* spr_experimentationlab_screwdriver.png, 20 x 20 */
+ SPR_EXPLORATIONCENTRE, /* spr_explorationcentre.png, 64 x 20 */
+ SPR_EXPLORATIONSHIP, /* spr_explorationship.png, 64 x 20 */
+ SPR_FARMBYPRODUCTPROCESSOR, /* spr_farmbyproductprocessor.png, 64 x 20 */
+ SPR_FARMBYPRODUCTPROCESSOR_FRAMES, /* spr_farmbyproductprocessor_frames.png, 988 x 20 */
+ SPR_FARMBYPRODUCTPROCESSOR_IDLE, /* spr_farmbyproductprocessor_idle.png, 20 x 20 */
+ SPR_FARMHOUSE, /* spr_farmhouse.png, 64 x 20 */
+ SPR_FEATHERALLIANCE, /* spr_featheralliance.png, 64 x 20 */
+ SPR_FESTIVAL_PODIUM_SMALL, /* spr_festival_podium_small.png, 5 x 4 */
+ SPR_FESTIVALHQ, /* spr_festivalhq.png, 64 x 20 */
+ SPR_FISH, /* spr_fish.png, 18 x 1 */
+ SPR_FISH_BIG, /* spr_fish_big.png, 16 x 3 */
+ SPR_FISH_BIG2, /* spr_fish_big2.png, 5 x 3 */
+ SPR_FISH_JELLY, /* spr_fish_jelly.png, 5 x 5 */
+ SPR_FISH_SNAKE, /* spr_fish_snake.png, 8 x 2 */
+ SPR_FLOATINGPLATFORM, /* spr_floatingplatform.png, 20 x 20 */
+ SPR_FLOWER_UP, /* spr_flower_up.png, 14 x 3 */
+ SPR_FLOWERCRAFT, /* spr_flowercraft.png, 20 x 20 */
+ SPR_FLOWERPENTHOUSE, /* spr_flowerpenthouse.png, 64 x 20 */
+ SPR_FLOWERS, /* spr_flowers.png, 86 x 20 */
+ SPR_FLOWERS_BLUE, /* spr_flowers_blue.png, 64 x 20 */
+ SPR_FLOWERS_KEYCITY, /* spr_flowers_keycity.png, 86 x 20 */
+ SPR_FLYINGSAUCER, /* spr_flyingsaucer.png, 20 x 20 */
+ SPR_FLYINGSAUCER_ALT, /* spr_flyingsaucer_alt.png, 20 x 20 */
+ SPR_FLYINGSAUCER_CUBE, /* spr_flyingsaucer_cube.png, 20 x 20 */
+ SPR_FLYINGSAUCER_DEEPBLUE, /* spr_flyingsaucer_deepblue.png, 20 x 20 */
+ SPR_FLYINGSAUCER_SHADE, /* spr_flyingsaucer_shade.png, 20 x 20 */
+ SPR_FORCEDBUILDINGLOCATION, /* spr_forcedbuildinglocation.png, 22 x 52 */
+ SPR_FOREST, /* spr_forest.png, 262 x 20 */
+ SPR_FOREST_BRANCHES, /* spr_forest_branches.png, 262 x 20 */
+ SPR_FOREST_BRANCHES_GROW, /* spr_forest_branches_grow.png, 284 x 20 */
+ SPR_FOREST_GROW, /* spr_forest_grow.png, 284 x 20 */
+ SPR_FOSSILMUSEUM, /* spr_fossilmuseum.png, 64 x 20 */
+ SPR_FROG, /* spr_frog.png, 16 x 7 */
+ SPR_FULLSCREEN, /* spr_fullscreen.png, 14 x 14 */
+ SPR_GRASS, /* spr_grass.png, 64 x 20 */
+ SPR_GREENOUTLINE, /* spr_greenoutline.png, 22 x 22 */
+ SPR_HACKERHQ, /* spr_hackerhq.png, 64 x 20 */
+ SPR_HACKERS_BOLT, /* spr_hackers_bolt.png, 4 x 7 */
+ SPR_HAPPINESS, /* spr_happiness.png, 10 x 10 */
+ SPR_HERBGARDEN, /* spr_herbgarden.png, 196 x 20 */
+ SPR_HERBGARDEN_BUTTONBACK, /* spr_herbgarden_buttonback.png, 20 x 20 */
+ SPR_HERBGARDEN_MEDIC, /* spr_herbgarden_medic.png, 196 x 20 */
+ SPR_HERBGARDEN_PLANTS, /* spr_herbgarden_plants.png, 130 x 20 */
+ SPR_HGH_BLOCK, /* spr_hgh_block.png, 4 x 4 */
+ SPR_HGH_BOOSTER, /* spr_hgh_booster.png, 9 x 8 */
+ SPR_HGH_CITIZENCLOTHES_1, /* spr_hgh_citizenclothes_1.png, 2 x 5 */
+ SPR_HGH_MONSTER_1, /* spr_hgh_monster_1.png, 14 x 9 */
+ SPR_HIDEUI, /* spr_hideui.png, 26 x 12 */
+ SPR_HINTINFO_ARROW, /* spr_hintinfo_arrow.png, 10 x 6 */
+ SPR_HOLOGAMEHALL, /* spr_hologamehall.png, 130 x 20 */
+ SPR_HOUSEOFTHEKEYFRIENDS, /* spr_houseofthekeyfriends.png, 64 x 20 */
+ SPR_HOUSING, /* spr_housing.png, 10 x 10 */
+ SPR_HOVERHINT, /* spr_hoverhint.png, 70 x 22 */
+ SPR_HOVERHINTS_CITIZEN, /* spr_hoverhints_citizen.png, 94 x 22 */
+ SPR_HUMANS, /* spr_humans.png, 202 x 5 */
+ SPR_HYPERELEVATOR, /* spr_hyperelevator.png, 64 x 20 */
+ SPR_HYPERELEVATOR_DOOR, /* spr_hyperelevator_door.png, 46 x 10 */
+ SPR_ICON_BOOST, /* spr_icon_boost.png, 10 x 14 */
+ SPR_ICON_BUILD, /* spr_icon_build.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_DESTROY, /* spr_icon_buildingmode_destroy.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_DESTROYLEAVINGHOLE, /* spr_icon_buildingmode_destroyleavinghole.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_DRAG, /* spr_icon_buildingmode_drag.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_DRAGREPLACE, /* spr_icon_buildingmode_dragreplace.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_INSERT, /* spr_icon_buildingmode_insert.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_ONTOP, /* spr_icon_buildingmode_ontop.png, 20 x 20 */
+ SPR_ICON_BUILDINGMODE_REPLACE, /* spr_icon_buildingmode_replace.png, 20 x 20 */
+ SPR_ICON_CLOSE, /* spr_icon_close.png, 21 x 15 */
+ SPR_ICON_ENTERTAINMENT, /* spr_icon_entertainment.png, 20 x 20 */
+ SPR_ICON_FINDBUILDING, /* spr_icon_findbuilding.png, 20 x 20 */
+ SPR_ICON_FOLLOWCITIZEN, /* spr_icon_followcitizen.png, 20 x 20 */
+ SPR_ICON_HALFSPEED, /* spr_icon_halfspeed.png, 12 x 12 */
+ SPR_ICON_HELP, /* spr_icon_help.png, 12 x 12 */
+ SPR_ICON_HOUSES, /* spr_icon_houses.png, 20 x 20 */
+ SPR_ICON_INVITEPEOPLE, /* spr_icon_invitepeople.png, 20 x 20 */
+ SPR_ICON_MANAGEMENT, /* spr_icon_management.png, 20 x 20 */
+ SPR_ICON_MENU, /* spr_icon_menu.png, 12 x 12 */
+ SPR_ICON_PAUSE, /* spr_icon_pause.png, 12 x 12 */
+ SPR_ICON_PLAY_BIG, /* spr_icon_play_big.png, 36 x 36 */
+ SPR_ICON_PLAY_NORMALSPEED, /* spr_icon_play_normalspeed.png, 12 x 12 */
+ SPR_ICON_ROCKET, /* spr_icon_rocket.png, 12 x 12 */
+ SPR_ICON_SCHOOL, /* spr_icon_school.png, 10 x 10 */
+ SPR_ICON_SERVICES, /* spr_icon_services.png, 20 x 20 */
+ SPR_ICON_SLIGHTLYSLOWERSPEED, /* spr_icon_slightlyslowerspeed.png, 12 x 12 */
+ SPR_ICON_SPECIALBUILDINGS, /* spr_icon_specialbuildings.png, 20 x 20 */
+ SPR_ICON_SPEEDUP, /* spr_icon_speedup.png, 12 x 12 */
+ SPR_ICON_TRANSPORT, /* spr_icon_transport.png, 20 x 20 */
+ SPR_ICON_UNLIMITED, /* spr_icon_unlimited.png, 13 x 13 */
+ SPR_ICON_UPGRADE, /* spr_icon_upgrade.png, 20 x 20 */
+ SPR_ICON_WORK, /* spr_icon_work.png, 20 x 20 */
+ SPR_IMPROVEDPICKAXES, /* spr_improvedpickaxes.png, 20 x 20 */
+ SPR_INDOORFARM, /* spr_indoorfarm.png, 64 x 20 */
+ SPR_INDOORFARM_BUTTONBACK, /* spr_indoorfarm_buttonback.png, 20 x 20 */
+ SPR_INDOORFARM_CROPS, /* spr_indoorfarm_crops.png, 240 x 20 */
+ SPR_INDOORPARK, /* spr_indoorpark.png, 328 x 20 */
+ SPR_INDOORPARK_ALT1, /* spr_indoorpark_alt1.png, 328 x 20 */
+ SPR_INSERTBUILDINGHERE, /* spr_insertbuildinghere.png, 20 x 21 */
+ SPR_INTERGALACTICLIBRARY, /* spr_intergalacticlibrary.png, 64 x 20 */
+ SPR_LABESCAPEROOM, /* spr_labescaperoom.png, 64 x 20 */
+ SPR_LABORATORY, /* spr_laboratory.png, 64 x 20 */
+ SPR_LABORATORY_LIGHTSOFF, /* spr_laboratory_lightsoff.png, 20 x 20 */
+ SPR_LANDINGPLACE, /* spr_landingplace.png, 64 x 20 */
+ SPR_LANDINGPLACE_ALT, /* spr_landingplace_alt.png, 64 x 20 */
+ SPR_LANDINGPLACE_DEEPBLUE, /* spr_landingplace_deepblue.png, 64 x 20 */
+ SPR_LIBRARY, /* spr_library.png, 130 x 20 */
+ SPR_LIVINGRESEARCHCENTER, /* spr_livingresearchcenter.png, 64 x 20 */
+ SPR_LOCKEDBUILDING, /* spr_lockedbuilding.png, 42 x 20 */
+ SPR_LOFT, /* spr_loft.png, 64 x 20 */
+ SPR_LOFT_FURNISHINGS, /* spr_loft_furnishings.png, 130 x 20 */
+ SPR_LUXURYRESTAURANT, /* spr_luxuryrestaurant.png, 64 x 20 */
+ SPR_MACHINEPARTSFACTORY, /* spr_machinepartsfactory.png, 64 x 20 */
+ SPR_MACHINEPARTSFACTORY_FRAMES, /* spr_machinepartsfactory_frames.png, 86 x 20 */
+ SPR_MACHINEPARTSFACTORY_IDLE, /* spr_machinepartsfactory_idle.png, 42 x 20 */
+ SPR_MANSION, /* spr_mansion.png, 64 x 20 */
+ SPR_MANSION_LEFT, /* spr_mansion_left.png, 64 x 20 */
+ SPR_MANSION_RIGHT, /* spr_mansion_right.png, 64 x 20 */
+ SPR_MECHANICALHOUSE, /* spr_mechanicalhouse.png, 64 x 20 */
+ SPR_MECHANICALHOUSE_BOTTOM, /* spr_mechanicalhouse_bottom.png, 64 x 20 */
+ SPR_MECHANICALHOUSE_BOTTOM_BGANIM, /* spr_mechanicalhouse_bottom_bganim.png, 174 x 20 */
+ SPR_MECHANICALHOUSE_HEATEDBED, /* spr_mechanicalhouse_heatedbed.png, 20 x 20 */
+ SPR_MECHANICALHOUSE_LEFT, /* spr_mechanicalhouse_left.png, 64 x 20 */
+ SPR_MECHANICALHOUSE_LEFT_BGANIM, /* spr_mechanicalhouse_left_bganim.png, 130 x 20 */
+ SPR_MECHANICALHOUSE_LEFTRIGHT, /* spr_mechanicalhouse_leftright.png, 64 x 20 */
+ SPR_MECHANICALHOUSE_LEFTRIGHT_BGANIM, /* spr_mechanicalhouse_leftright_bganim.png, 130 x 20 */
+ SPR_MECHANICALHOUSE_PIPE_H, /* spr_mechanicalhouse_pipe_h.png, 3 x 5 */
+ SPR_MECHANICALHOUSE_PIPE_H2, /* spr_mechanicalhouse_pipe_h2.png, 3 x 5 */
+ SPR_MECHANICALHOUSE_PIPE_H2_BF, /* spr_mechanicalhouse_pipe_h2_bf.png, 5 x 11 */
+ SPR_MECHANICALHOUSE_PIPE_H3, /* spr_mechanicalhouse_pipe_h3.png, 26 x 20 */
+ SPR_MECHANICALHOUSE_PIPE_H3_BF, /* spr_mechanicalhouse_pipe_h3_bf.png, 26 x 20 */
+ SPR_MECHANICALHOUSE_PIPE_V1, /* spr_mechanicalhouse_pipe_v1.png, 5 x 3 */
+ SPR_MECHANICALHOUSE_PIPE_V2, /* spr_mechanicalhouse_pipe_v2.png, 5 x 3 */
+ SPR_MECHANICALHOUSE_PIPE_V3, /* spr_mechanicalhouse_pipe_v3.png, 7 x 26 */
+ SPR_MECHANICALHOUSE_RIGHT, /* spr_mechanicalhouse_right.png, 64 x 20 */
+ SPR_MECHANICALHOUSE_RIGHT_BGANIM, /* spr_mechanicalhouse_right_bganim.png, 130 x 20 */
+ SPR_MECHANICALHOUSE_TOP, /* spr_mechanicalhouse_top.png, 64 x 20 */
+ SPR_MECHANICALHOUSE_TOP_BGANIM, /* spr_mechanicalhouse_top_bganim.png, 42 x 20 */
+ SPR_MEDICALCLINIC, /* spr_medicalclinic.png, 64 x 20 */
+ SPR_MINIBUTTON, /* spr_minibutton.png, 31 x 7 */
+ SPR_MIRROR, /* spr_mirror.png, 20 x 20 */
+ SPR_MISDIRECTOR, /* spr_misdirector.png, 64 x 20 */
+ SPR_MODERNART, /* spr_modernart.png, 218 x 20 */
+ SPR_MODERNARTMUSEUM, /* spr_modernartmuseum.png, 64 x 20 */
+ SPR_MODERNARTMUSEUM_BUTTONBACK, /* spr_modernartmuseum_buttonback.png, 20 x 20 */
+ SPR_MODERNCONVENIENCES, /* spr_modernconveniences.png, 20 x 20 */
+ SPR_MODERNHOMEPLANT, /* spr_modernhomeplant.png, 218 x 20 */
+ SPR_MODERNRUSTICHOME, /* spr_modernrustichome.png, 64 x 20 */
+ SPR_MOREBUILDINGMODEBUTTONS, /* spr_morebuildingmodebuttons.png, 40 x 22 */
+ SPR_MOREBUILDINGMODES_ARROWUP, /* spr_morebuildingmodes_arrowup.png, 10 x 20 */
+ SPR_MORESETTINGS, /* spr_moresettings.png, 14 x 14 */
+ SPR_NATURE, /* spr_nature.png, 20 x 20 */
+ SPR_NIGHTCLUB, /* spr_nightclub.png, 130 x 20 */
+ SPR_NIGHTCLUB_LASER, /* spr_nightclub_laser.png, 358 x 16 */
+ SPR_NIGHTCLUB_LIGHT, /* spr_nightclub_light.png, 5 x 15 */
+ SPR_NIGHTCLUB_LIGHT_RAINBOW, /* spr_nightclub_light_rainbow.png, 5 x 15 */
+ SPR_NORMALHOUSE, /* spr_normalhouse.png, 64 x 20 */
+ SPR_OBSERVATORY, /* spr_observatory.png, 64 x 20 */
+ SPR_ONEANDHALFSPEED, /* spr_oneandhalfspeed.png, 12 x 12 */
+ SPR_PARK_BUTTONBG, /* spr_park_buttonbg.png, 20 x 20 */
+ SPR_PARK_PLANTS, /* spr_park_plants.png, 284 x 20 */
+ SPR_PARKPOD, /* spr_parkpod.png, 152 x 20 */
+ SPR_PARKPOD_BUTTONBACK, /* spr_parkpod_buttonback.png, 20 x 20 */
+ SPR_PINEFOREST, /* spr_pineforest.png, 262 x 20 */
+ SPR_PINEFOREST_GROW, /* spr_pineforest_grow.png, 240 x 20 */
+ SPR_PIXEL, /* spr_pixel.png, 1 x 1 */
+ SPR_PLANET_RING_BIG, /* spr_planet_ring_big.png, 835 x 200 */
+ SPR_PLANET_RING_SMALL, /* spr_planet_ring_small.png, 580 x 110 */
+ SPR_PLANETS_BIG, /* spr_planets_big.png, 1018 x 100 */
+ SPR_PLANETS_BIGGER, /* spr_planets_bigger.png, 730 x 120 */
+ SPR_PLANETS_GIANT, /* spr_planets_giant.png, 566 x 140 */
+ SPR_PLANETS_MEDIUM, /* spr_planets_medium.png, 654 x 80 */
+ SPR_PLANETS_SMALL, /* spr_planets_small.png, 250 x 40 */
+ SPR_POPULATION, /* spr_population.png, 10 x 10 */
+ SPR_PROTESTSIGN_HAPPY, /* spr_protestsign_happy.png, 9 x 14 */
+ SPR_PROTESTSIGN_SAD, /* spr_protestsign_sad.png, 9 x 14 */
+ SPR_PUB, /* spr_pub.png, 64 x 20 */
+ SPR_PUB_MARKING_KEY, /* spr_pub_marking_key.png, 9 x 9 */
+ SPR_PURPLEFOREST, /* spr_purpleforest.png, 284 x 20 */
+ SPR_PURPLEFOREST_GROW, /* spr_purpleforest_grow.png, 218 x 20 */
+ SPR_PURPLEGRASS, /* spr_purplegrass.png, 64 x 20 */
+ SPR_RECOLORABLE, /* spr_recolorable.png, 22 x 22 */
+ SPR_REDFOREST, /* spr_redforest.png, 262 x 20 */
+ SPR_REDFOREST_GROW, /* spr_redforest_grow.png, 284 x 20 */
+ SPR_REDGRASS, /* spr_redgrass.png, 64 x 20 */
+ SPR_REDWOOD, /* spr_redwood.png, 262 x 20 */
+ SPR_REDWOODTREEHOUSE, /* spr_redwoodtreehouse.png, 64 x 20 */
+ SPR_REFINEDMETALFACTORY, /* spr_refinedmetalfactory.png, 64 x 20 */
+ SPR_REFINEDMETALFACTORY_FRAMES, /* spr_refinedmetalfactory_frames.png, 306 x 20 */
+ SPR_REFINEDMETALFACTORY_IDLE, /* spr_refinedmetalfactory_idle.png, 42 x 20 */
+ SPR_REFINEDMETALFACTORYPUB, /* spr_refinedmetalfactorypub.png, 130 x 20 */
+ SPR_REFINEDMETALFACTORYPUB_FRAMES, /* spr_refinedmetalfactorypub_frames.png, 482 x 20 */
+ SPR_REFINEDMETALFACTORYPUB_IDLE, /* spr_refinedmetalfactorypub_idle.png, 42 x 20 */
+ SPR_REMOVEDECORATION, /* spr_removedecoration.png, 20 x 20 */
+ SPR_REPLACEBUILDINGHERE, /* spr_replacebuildinghere.png, 20 x 21 */
+ SPR_RESEARCHBOT, /* spr_researchbot.png, 20 x 20 */
+ SPR_RESEARCHBOT_LANDINGPLACE, /* spr_researchbot_landingplace.png, 64 x 20 */
+ SPR_RESIDENTS, /* spr_residents.png, 8 x 10 */
+ SPR_RESOURCE_COMPUTERCHIPS, /* spr_resource_computerchips.png, 10 x 10 */
+ SPR_RESOURCE_DOWNTREND, /* spr_resource_downtrend.png, 10 x 10 */
+ SPR_RESOURCE_FOOD, /* spr_resource_food.png, 10 x 10 */
+ SPR_RESOURCE_GRAPHENE, /* spr_resource_graphene.png, 10 x 10 */
+ SPR_RESOURCE_KNOWLEDGE, /* spr_resource_knowledge.png, 10 x 10 */
+ SPR_RESOURCE_MACHINEPARTS, /* spr_resource_machineparts.png, 10 x 10 */
+ SPR_RESOURCE_REFINEDMETAL, /* spr_resource_refinedmetal.png, 10 x 10 */
+ SPR_RESOURCE_ROCKETFUEL, /* spr_resource_rocketfuel.png, 10 x 10 */
+ SPR_RESOURCE_STONE, /* spr_resource_stone.png, 10 x 10 */
+ SPR_RESOURCE_WOOD, /* spr_resource_wood.png, 10 x 10 */
+ SPR_RESTAURANT, /* spr_restaurant.png, 130 x 20 */
+ SPR_ROCK, /* spr_rock.png, 152 x 20 */
+ SPR_ROOFBOTTOM, /* spr_roofbottom.png, 438 x 20 */
+ SPR_ROOFTOPPARK, /* spr_rooftoppark.png, 130 x 20 */
+ SPR_ROOFTOPPARK_BUTTONBG, /* spr_rooftoppark_buttonbg.png, 20 x 20 */
+ SPR_ROOFTOPPARK_ONBUILD, /* spr_rooftoppark_onbuild.png, 20 x 20 */
+ SPR_ROOFTOPPARK_PLANTS, /* spr_rooftoppark_plants.png, 130 x 20 */
+ SPR_SCHOOL, /* spr_school.png, 64 x 20 */
+ SPR_SCRAPYARDNIGHTCLUB, /* spr_scrapyardnightclub.png, 130 x 20 */
+ SPR_SECRETSOCIETYHOUSE, /* spr_secretsocietyhouse.png, 64 x 20 */
+ SPR_SECRETSOCIETYMACHINE, /* spr_secretsocietymachine.png, 64 x 20 */
+ SPR_SECRETSOCIETYMACHINE_ANIM, /* spr_secretsocietymachine_anim.png, 548 x 20 */
+ SPR_SELECTEDBUILDING, /* spr_selectedbuilding.png, 22 x 22 */
+ SPR_SELECTEDFISH, /* spr_selectedfish.png, 10 x 10 */
+ SPR_SELECTEDHUMAN, /* spr_selectedhuman.png, 4 x 7 */
+ SPR_SHADYHOUSE, /* spr_shadyhouse.png, 64 x 20 */
+ SPR_SLANTEDROOF, /* spr_slantedroof.png, 460 x 20 */
+ SPR_SLANTEDROOFTOP, /* spr_slantedrooftop.png, 438 x 20 */
+ SPR_SLIDER_BG, /* spr_slider_bg.png, 22 x 22 */
+ SPR_SLIDER_FILL, /* spr_slider_fill.png, 22 x 22 */
+ SPR_SMALLTELEPORTER_RAY, /* spr_smallteleporter_ray.png, 28 x 5 */
+ SPR_SMALLTELEPORTER_RAY_PENTHOUSE, /* spr_smallteleporter_ray_penthouse.png, 33 x 5 */
+ SPR_SMALLTELEPORTER_RAY_PENTHOUSE_MIRROR, /* spr_smallteleporter_ray_penthouse_mirror.png, 33 x 5 */
+ SPR_SMARTCHAIRS, /* spr_smartchairs.png, 20 x 20 */
+ SPR_SMARTDIAGNOSE, /* spr_smartdiagnose.png, 20 x 20 */
+ SPR_SMARTLIGHTS, /* spr_smartlights.png, 20 x 20 */
+ SPR_SMARTSPEAKER, /* spr_smartspeaker.png, 20 x 20 */
+ SPR_SOFTERBEDS, /* spr_softerbeds.png, 20 x 20 */
+ SPR_SPACIOUSHOUSE, /* spr_spacioushouse.png, 64 x 20 */
+ SPR_STATUEGARDEN_BUTTONBACK, /* spr_statuegarden_buttonback.png, 20 x 20 */
+ SPR_STATUEGARDEN_STATUES, /* spr_statuegarden_statues.png, 174 x 20 */
+ SPR_STATUEOFHAPPINESS, /* spr_statueofhappiness.png, 64 x 20 */
+ SPR_STATUEOFHAPPINESS_BG, /* spr_statueofhappiness_bg.png, 20 x 20 */
+ SPR_STATUEOFTHEKEY, /* spr_statueofthekey.png, 64 x 20 */
+ SPR_STATUEOFTHEKEY_BG, /* spr_statueofthekey_bg.png, 20 x 20 */
+ SPR_STONEMINE, /* spr_stonemine.png, 64 x 20 */
+ SPR_STONERESEARCHCENTRE, /* spr_stoneresearchcentre.png, 64 x 20 */
+ SPR_STONERESEARCHCENTRE_COMPUTER, /* spr_stoneresearchcentre_computer.png, 20 x 20 */
+ SPR_STONERESEARCHCENTRE_PICKAXETECH, /* spr_stoneresearchcentre_pickaxetech.png, 20 x 20 */
+ SPR_STONETELEPORTER, /* spr_stoneteleporter.png, 64 x 20 */
+ SPR_STONETELEPORTER_REMOTE, /* spr_stoneteleporter_remote.png, 20 x 20 */
+ SPR_STONETELEPORTER_STONE, /* spr_stoneteleporter_stone.png, 196 x 20 */
+ SPR_STONETELEPORTER_STONE_BIG, /* spr_stoneteleporter_stone_big.png, 196 x 20 */
+ SPR_SUPERCOMPUTER, /* spr_supercomputer.png, 64 x 20 */
+ SPR_SYNIGHTCLUB_BG, /* spr_synightclub_bg.png, 20 x 20 */
+ SPR_SYNIGHTCLUB_LEFTTEXTURES, /* spr_synightclub_lefttextures.png, 64 x 19 */
+ SPR_SYNIGHTCLUB_LIGHTS, /* spr_synightclub_lights.png, 1 x 10 */
+ SPR_SYNIGHTCLUB_LIGHTS_H, /* spr_synightclub_lights_h.png, 10 x 1 */
+ SPR_SYNIGHTCLUB_MAINTEXTURES, /* spr_synightclub_maintextures.png, 64 x 19 */
+ SPR_SYNIGHTCLUB_MINILIGHT, /* spr_synightclub_minilight.png, 3 x 3 */
+ SPR_SYNIGHTCLUB_WATERFALLLIGHT, /* spr_synightclub_waterfalllight.png, 7 x 2 */
+ SPR_SYNIGHTCLUB_WATERFALLLIGHT_LAST, /* spr_synightclub_waterfalllight_last.png, 5 x 6 */
+ SPR_TECH_NIGHTCLUB, /* spr_tech_nightclub.png, 328 x 20 */
+ SPR_TECH_NIGHTCLUB_HOVERER, /* spr_tech_nightclub_hoverer.png, 4 x 4 */
+ SPR_TELEPORTER, /* spr_teleporter.png, 64 x 20 */
+ SPR_TELEPORTER_RAY, /* spr_teleporter_ray.png, 34 x 15 */
+ SPR_TELEPORTER_RAY_KEY, /* spr_teleporter_ray_key.png, 46 x 15 */
+ SPR_TELEPORTER_RAY_MISDIRECT, /* spr_teleporter_ray_misdirect.png, 34 x 15 */
+ SPR_TELESCOPE, /* spr_telescope.png, 4 x 5 */
+ SPR_TINKERERSHOUSE, /* spr_tinkerershouse.png, 64 x 20 */
+ SPR_TINKERERSHOUSE_BACK_ALT, /* spr_tinkerershouse_back_alt.png, 108 x 20 */
+ SPR_TINKERERSHOUSE_BETTERTOOLS, /* spr_tinkerershouse_bettertools.png, 86 x 20 */
+ SPR_TINKERERSHOUSE_FRONT_ALT, /* spr_tinkerershouse_front_alt.png, 196 x 20 */
+ SPR_TITLE, /* spr_title.png, 261 x 55 */
+ SPR_TRANSPARENTBUTTON, /* spr_transparentbutton.png, 70 x 22 */
+ SPR_TRANSPARENTBUTTON_INFO, /* spr_transparentbutton_info.png, 70 x 22 */
+ SPR_TRANSPARENTBUTTON_INFO_MINI, /* spr_transparentbutton_info_mini.png, 46 x 14 */
+ SPR_TRANSPARENTBUTTON_INFO_MINIPLUS, /* spr_transparentbutton_info_miniplus.png, 64 x 20 */
+ SPR_TREEGROWTHBOOST, /* spr_treegrowthboost.png, 20 x 20 */
+ SPR_TREEHUGGERBASE, /* spr_treehuggerbase.png, 20 x 20 */
+ SPR_TREEPLANTATION, /* spr_treeplantation.png, 64 x 20 */
+ SPR_TREEPLANTATION_BUTTONBACK, /* spr_treeplantation_buttonback.png, 20 x 20 */
+ SPR_TREEPLANTATION_TREES, /* spr_treeplantation_trees.png, 262 x 20 */
+ SPR_TREEPLANTATION_TREES_GROW, /* spr_treeplantation_trees_grow.png, 240 x 20 */
+ SPR_TUTORIALARROWDOWN, /* spr_tutorialarrowdown.png, 20 x 30 */
+ SPR_TUTORIALARROWLEFT, /* spr_tutorialarrowleft.png, 30 x 20 */
+ SPR_UNIQUEBUILDING, /* spr_uniquebuilding.png, 10 x 10 */
+ SPR_UNKNOWNBUILDING, /* spr_unknownbuilding.png, 64 x 20 */
+ SPR_UPGRADE_FARMBOOST, /* spr_upgrade_farmboost.png, 20 x 20 */
+ SPR_UPGRADE_FLOWERS, /* spr_upgrade_flowers.png, 64 x 20 */
+ SPR_VILLA, /* spr_villa.png, 64 x 20 */
+ SPR_WALDO_ADULT, /* spr_waldo_adult.png, 2 x 5 */
+ SPR_WALDO_CHILD, /* spr_waldo_child.png, 2 x 5 */
+ SPR_WHITEOUTLINE, /* spr_whiteoutline.png, 22 x 22 */
+ SPR_WINDOWPARTS, /* spr_windowparts.png, 62 x 24 */
+ SPR_WINDOWPARTS_PURPLE, /* spr_windowparts_purple.png, 62 x 24 */
+ SPR_WOODCUTTINGCENTRE, /* spr_woodcuttingcentre.png, 64 x 20 */
+ SPR_WORK, /* spr_work.png, 10 x 10 */
+ SPR_WORK_HOUSING, /* spr_work_housing.png, 21 x 10 */
+ SPR_WORKSHOP, /* spr_workshop.png, 64 x 20 */
+ SPR_WORKSHOP_MAKEMACHINEPARTS, /* spr_workshop_makemachineparts.png, 20 x 20 */
+ SPR_WORKSHOP_PETPROJECTS, /* spr_workshop_petprojects.png, 20 x 20 */
+ SPR_COUNT
+};
+
+/* each sprite's width and height */
+#define SPR_9P_BUTTON_ACTIVE_W 22
+#define SPR_9P_BUTTON_ACTIVE_H 22
+#define SPR_9P_BUTTON_DISABLED_W 22
+#define SPR_9P_BUTTON_DISABLED_H 22
+#define SPR_9P_HINTINFO_W 60
+#define SPR_9P_HINTINFO_H 60
+#define SPR_9P_INFO_W 32
+#define SPR_9P_INFO_H 32
+#define SPR_9P_TOOLTIP_W 10
+#define SPR_9P_TOOLTIP_H 10
+#define SPR_9P_WINDOW_W 60
+#define SPR_9P_WINDOW_H 60
+#define SPR_9P_WINDOW_MOREOPAQUE_W 60
+#define SPR_9P_WINDOW_MOREOPAQUE_H 60
+#define SPR_9P_WINDOW_PURPLE_W 60
+#define SPR_9P_WINDOW_PURPLE_H 60
+#define SPR_ADVANCEDMEDICALCLINIC_W 64
+#define SPR_ADVANCEDMEDICALCLINIC_H 20
+#define SPR_AIMINING_W 20
+#define SPR_AIMINING_H 20
+#define SPR_ALIENDECRYPTOR_W 64
+#define SPR_ALIENDECRYPTOR_H 20
+#define SPR_ALIENHOUSE_W 64
+#define SPR_ALIENHOUSE_H 20
+#define SPR_ALIENHOUSE_LIVINGCOMPUTER_W 152
+#define SPR_ALIENHOUSE_LIVINGCOMPUTER_H 20
+#define SPR_ALIENRUINS_W 20
+#define SPR_ALIENRUINS_H 20
+#define SPR_ALIENRUINS_2_W 20
+#define SPR_ALIENRUINS_2_H 20
+#define SPR_ALIENRUINS_3_W 20
+#define SPR_ALIENRUINS_3_H 20
+#define SPR_ARCADE_W 64
+#define SPR_ARCADE_H 20
+#define SPR_ARROW_BACK_W 20
+#define SPR_ARROW_BACK_H 20
+#define SPR_ARROWDOWN_W 7
+#define SPR_ARROWDOWN_H 5
+#define SPR_ARROWDOWN_BIG_W 16
+#define SPR_ARROWDOWN_BIG_H 16
+#define SPR_ARROWUP_W 7
+#define SPR_ARROWUP_H 5
+#define SPR_ARROWUP_BIG_W 16
+#define SPR_ARROWUP_BIG_H 16
+#define SPR_ARTCOLONY_W 64
+#define SPR_ARTCOLONY_H 20
+#define SPR_ARTCOLONY_BUTTONBACK_W 20
+#define SPR_ARTCOLONY_BUTTONBACK_H 20
+#define SPR_ARTCOLONYWORK_W 306
+#define SPR_ARTCOLONYWORK_H 20
+#define SPR_BEACON_W 64
+#define SPR_BEACON_H 20
+#define SPR_BEACON_LIGHT_W 4
+#define SPR_BEACON_LIGHT_H 11
+#define SPR_BIGGERTV_W 20
+#define SPR_BIGGERTV_H 20
+#define SPR_BIRCHFOREST_W 20
+#define SPR_BIRCHFOREST_H 20
+#define SPR_BLOOMHOUSE_W 108
+#define SPR_BLOOMHOUSE_H 20
+#define SPR_BLOOMHUT_BUTTONBACK_W 20
+#define SPR_BLOOMHUT_BUTTONBACK_H 20
+#define SPR_BLOOMRESTAURANT_W 328
+#define SPR_BLOOMRESTAURANT_H 20
+#define SPR_BLOOMRESTAURANT_FOREGROUND_W 108
+#define SPR_BLOOMRESTAURANT_FOREGROUND_H 20
+#define SPR_BLOSSOMHIPPIEHQ_W 64
+#define SPR_BLOSSOMHIPPIEHQ_H 20
+#define SPR_BLUEWORLDGLOW_W 20
+#define SPR_BLUEWORLDGLOW_H 5
+#define SPR_BOARDGAMESTORE_W 64
+#define SPR_BOARDGAMESTORE_H 20
+#define SPR_BONUSRANGE_PLUS_W 9
+#define SPR_BONUSRANGE_PLUS_H 10
+#define SPR_BONUSRANGE_TOPBOTTOM_W 9
+#define SPR_BONUSRANGE_TOPBOTTOM_H 10
+#define SPR_BOTANICALGARDEN_DOME_BUTTONBACK_W 20
+#define SPR_BOTANICALGARDEN_DOME_BUTTONBACK_H 20
+#define SPR_BOTANICALGARDENS_W 328
+#define SPR_BOTANICALGARDENS_H 20
+#define SPR_BOTANICALGARDENS_BUTTONBACK_W 20
+#define SPR_BOTANICALGARDENS_BUTTONBACK_H 20
+#define SPR_BOTANICALGARDENS_PLANTS_W 300
+#define SPR_BOTANICALGARDENS_PLANTS_H 80
+#define SPR_BOULDER_W 164
+#define SPR_BOULDER_H 20
+#define SPR_BUILDHEREOUTLINE_W 20
+#define SPR_BUILDHEREOUTLINE_H 20
+#define SPR_BUILDINGBUTTON_W 70
+#define SPR_BUILDINGBUTTON_H 22
+#define SPR_BUTTON_W 70
+#define SPR_BUTTON_H 22
+#define SPR_BUTTON_ACTIVABLE_W 70
+#define SPR_BUTTON_ACTIVABLE_H 22
+#define SPR_BUTTON_CHECKED_W 70
+#define SPR_BUTTON_CHECKED_H 22
+#define SPR_BUTTON_GRAY_W 70
+#define SPR_BUTTON_GRAY_H 22
+#define SPR_BUTTON_MEDIUM_W 70
+#define SPR_BUTTON_MEDIUM_H 22
+#define SPR_BUTTON_SMALL_W 58
+#define SPR_BUTTON_SMALL_H 18
+#define SPR_BUTTON_SMALLER_W 49
+#define SPR_BUTTON_SMALLER_H 15
+#define SPR_BUTTON_SMALLER_MOBILE_W 61
+#define SPR_BUTTON_SMALLER_MOBILE_H 19
+#define SPR_BUTTON_WINDOWHEADER_W 73
+#define SPR_BUTTON_WINDOWHEADER_H 17
+#define SPR_BUTTON_WINDOWHEADER_MOBI_W 79
+#define SPR_BUTTON_WINDOWHEADER_MOBI_H 19
+#define SPR_BUTTONNOTIFICATION_W 22
+#define SPR_BUTTONNOTIFICATION_H 22
+#define SPR_CACAOFARM_W 64
+#define SPR_CACAOFARM_H 20
+#define SPR_CACAOFARM_TREES_W 152
+#define SPR_CACAOFARM_TREES_H 20
+#define SPR_CAMERA_W 14
+#define SPR_CAMERA_H 14
+#define SPR_CARROTJUICEBAR_W 64
+#define SPR_CARROTJUICEBAR_H 20
+#define SPR_CHECKBOX_W 18
+#define SPR_CHECKBOX_H 8
+#define SPR_CHILDREN_W 202
+#define SPR_CHILDREN_H 5
+#define SPR_CHOCOLATEFACTORY_W 64
+#define SPR_CHOCOLATEFACTORY_H 20
+#define SPR_CHOCOLATEFACTORY_FRAMES_W 240
+#define SPR_CHOCOLATEFACTORY_FRAMES_H 20
+#define SPR_CHOCOLATEFACTORY_IDLE_W 20
+#define SPR_CHOCOLATEFACTORY_IDLE_H 20
+#define SPR_CITIZEN_BALL_W 4
+#define SPR_CITIZEN_BALL_H 4
+#define SPR_CITYHALL_W 64
+#define SPR_CITYHALL_H 20
+#define SPR_CLOUDS_W 990
+#define SPR_CLOUDS_H 122
+#define SPR_COLORCIRCLE_W 200
+#define SPR_COLORCIRCLE_H 223
+#define SPR_COLOREDBLOCK_W 438
+#define SPR_COLOREDBLOCK_H 20
+#define SPR_COLOREDDOORS_W 130
+#define SPR_COLOREDDOORS_H 20
+#define SPR_COLORPICKER_CIRCLE_W 12
+#define SPR_COLORPICKER_CIRCLE_H 12
+#define SPR_COLORPICKER_COLORPICKED_W 10
+#define SPR_COLORPICKER_COLORPICKED_H 10
+#define SPR_COLORPICKER_TRIANGLE_W 12
+#define SPR_COLORPICKER_TRIANGLE_H 12
+#define SPR_COMFORTABLECOUCH_W 20
+#define SPR_COMFORTABLECOUCH_H 20
+#define SPR_COMFORTABLEHOUSE_W 64
+#define SPR_COMFORTABLEHOUSE_H 20
+#define SPR_COMMUNITYHOUSE_BUTTONBACK_W 20
+#define SPR_COMMUNITYHOUSE_BUTTONBACK_H 20
+#define SPR_COMMUNITYHOUSE_CROP_W 68
+#define SPR_COMMUNITYHOUSE_CROP_H 14
+#define SPR_COMMUNITYHOUSE_INDOORPOND_W 20
+#define SPR_COMMUNITYHOUSE_INDOORPOND_H 20
+#define SPR_COMMUNITYHOUSE_ROCK_W 61
+#define SPR_COMMUNITYHOUSE_ROCK_H 14
+#define SPR_COMMUNITYHOUSE_TREE_W 47
+#define SPR_COMMUNITYHOUSE_TREE_H 14
+#define SPR_COMMUNITYHOUSE_TREE_GROW_W 75
+#define SPR_COMMUNITYHOUSE_TREE_GROW_H 14
+#define SPR_COMPUTER_OBSERVATORY_W 20
+#define SPR_COMPUTER_OBSERVATORY_H 20
+#define SPR_COMPUTERCHIPFACTORY_W 64
+#define SPR_COMPUTERCHIPFACTORY_H 20
+#define SPR_COMPUTERCHIPFACTORY_FRAMES_W 526
+#define SPR_COMPUTERCHIPFACTORY_FRAMES_H 20
+#define SPR_COMPUTERCHIPFACTORY_IDLE_W 20
+#define SPR_COMPUTERCHIPFACTORY_IDLE_H 20
+#define SPR_COMPUTERRESEARCHCENTER_W 64
+#define SPR_COMPUTERRESEARCHCENTER_H 20
+#define SPR_COMPUTERRESEARCHCENTER_FRAMES_W 372
+#define SPR_COMPUTERRESEARCHCENTER_FRAMES_H 20
+#define SPR_COMPUTERRESEARCHCENTER_IDLE_W 20
+#define SPR_COMPUTERRESEARCHCENTER_IDLE_H 20
+#define SPR_CONTRAPTION_W 64
+#define SPR_CONTRAPTION_H 20
+#define SPR_CREDITS_W 14
+#define SPR_CREDITS_H 14
+#define SPR_CUTTINGEDGEHOME_W 64
+#define SPR_CUTTINGEDGEHOME_H 20
+#define SPR_DECORATION_KEYCITY_W 86
+#define SPR_DECORATION_KEYCITY_H 20
+#define SPR_DECORATION_ROCKS_W 64
+#define SPR_DECORATION_ROCKS_H 20
+#define SPR_DESTROYING_W 20
+#define SPR_DESTROYING_H 20
+#define SPR_DIESHRINK_W 20
+#define SPR_DIESHRINK_H 20
+#define SPR_DOME_BOTANICALGARDEN_W 130
+#define SPR_DOME_BOTANICALGARDEN_H 20
+#define SPR_DOME_BOTANICALGARDEN_ALT1_W 130
+#define SPR_DOME_BOTANICALGARDEN_ALT1_H 20
+#define SPR_DOME_BOTANICALGARDEN_ALT1B_W 130
+#define SPR_DOME_BOTANICALGARDEN_ALT1B_H 20
+#define SPR_DOME_BOTANICALGARDEN_ALT2_W 130
+#define SPR_DOME_BOTANICALGARDEN_ALT2_H 20
+#define SPR_DOME_BOTANICALGARDEN_ALT2B_W 130
+#define SPR_DOME_BOTANICALGARDEN_ALT2B_H 20
+#define SPR_DOME_BOTANICALGARDEN_B_W 130
+#define SPR_DOME_BOTANICALGARDEN_B_H 20
+#define SPR_DOME_BOTANICALGARDEN_PLANTS_W 300
+#define SPR_DOME_BOTANICALGARDEN_PLANTS_H 40
+#define SPR_DOMEROOF_W 460
+#define SPR_DOMEROOF_H 20
+#define SPR_DRACULA_ADULT_W 2
+#define SPR_DRACULA_ADULT_H 5
+#define SPR_DRACULA_CHILD_W 2
+#define SPR_DRACULA_CHILD_H 5
+#define SPR_ECOFARM_W 64
+#define SPR_ECOFARM_H 20
+#define SPR_ECOFARM_BUTTONBACK_W 20
+#define SPR_ECOFARM_BUTTONBACK_H 20
+#define SPR_ECOFARM_CROP1_W 94
+#define SPR_ECOFARM_CROP1_H 14
+#define SPR_ECOFARM_CROP2_W 68
+#define SPR_ECOFARM_CROP2_H 5
+#define SPR_ECOFARM_CROP2_ALT_W 58
+#define SPR_ECOFARM_CROP2_ALT_H 5
+#define SPR_ECOFARM_CROP2_ALT2_W 78
+#define SPR_ECOFARM_CROP2_ALT2_H 5
+#define SPR_ECOFARM_CROP3_W 78
+#define SPR_ECOFARM_CROP3_H 5
+#define SPR_ECOFARM_CROP3_ALT_W 58
+#define SPR_ECOFARM_CROP3_ALT_H 5
+#define SPR_EXPERIMENTALFARM_W 64
+#define SPR_EXPERIMENTALFARM_H 20
+#define SPR_EXPERIMENTALFARM_BUTTONBACK_W 20
+#define SPR_EXPERIMENTALFARM_BUTTONBACK_H 20
+#define SPR_EXPERIMENTALFARM_CROP1_W 75
+#define SPR_EXPERIMENTALFARM_CROP1_H 14
+#define SPR_EXPERIMENTALFARM_CROP2_W 61
+#define SPR_EXPERIMENTALFARM_CROP2_H 5
+#define SPR_EXPERIMENTALFARM_CROP3_W 33
+#define SPR_EXPERIMENTALFARM_CROP3_H 5
+#define SPR_EXPERIMENTATIONLAB_W 64
+#define SPR_EXPERIMENTATIONLAB_H 20
+#define SPR_EXPERIMENTATIONLAB_IDLE_W 42
+#define SPR_EXPERIMENTATIONLAB_IDLE_H 20
+#define SPR_EXPERIMENTATIONLAB_PIPE_BOTTOM_W 5
+#define SPR_EXPERIMENTATIONLAB_PIPE_BOTTOM_H 9
+#define SPR_EXPERIMENTATIONLAB_PIPE_TOP_W 5
+#define SPR_EXPERIMENTATIONLAB_PIPE_TOP_H 14
+#define SPR_EXPERIMENTATIONLAB_SCREWDRIVER_W 20
+#define SPR_EXPERIMENTATIONLAB_SCREWDRIVER_H 20
+#define SPR_EXPLORATIONCENTRE_W 64
+#define SPR_EXPLORATIONCENTRE_H 20
+#define SPR_EXPLORATIONSHIP_W 64
+#define SPR_EXPLORATIONSHIP_H 20
+#define SPR_FARMBYPRODUCTPROCESSOR_W 64
+#define SPR_FARMBYPRODUCTPROCESSOR_H 20
+#define SPR_FARMBYPRODUCTPROCESSOR_FRAMES_W 988
+#define SPR_FARMBYPRODUCTPROCESSOR_FRAMES_H 20
+#define SPR_FARMBYPRODUCTPROCESSOR_IDLE_W 20
+#define SPR_FARMBYPRODUCTPROCESSOR_IDLE_H 20
+#define SPR_FARMHOUSE_W 64
+#define SPR_FARMHOUSE_H 20
+#define SPR_FEATHERALLIANCE_W 64
+#define SPR_FEATHERALLIANCE_H 20
+#define SPR_FESTIVAL_PODIUM_SMALL_W 5
+#define SPR_FESTIVAL_PODIUM_SMALL_H 4
+#define SPR_FESTIVALHQ_W 64
+#define SPR_FESTIVALHQ_H 20
+#define SPR_FISH_W 18
+#define SPR_FISH_H 1
+#define SPR_FISH_BIG_W 16
+#define SPR_FISH_BIG_H 3
+#define SPR_FISH_BIG2_W 5
+#define SPR_FISH_BIG2_H 3
+#define SPR_FISH_JELLY_W 5
+#define SPR_FISH_JELLY_H 5
+#define SPR_FISH_SNAKE_W 8
+#define SPR_FISH_SNAKE_H 2
+#define SPR_FLOATINGPLATFORM_W 20
+#define SPR_FLOATINGPLATFORM_H 20
+#define SPR_FLOWER_UP_W 14
+#define SPR_FLOWER_UP_H 3
+#define SPR_FLOWERCRAFT_W 20
+#define SPR_FLOWERCRAFT_H 20
+#define SPR_FLOWERPENTHOUSE_W 64
+#define SPR_FLOWERPENTHOUSE_H 20
+#define SPR_FLOWERS_W 86
+#define SPR_FLOWERS_H 20
+#define SPR_FLOWERS_BLUE_W 64
+#define SPR_FLOWERS_BLUE_H 20
+#define SPR_FLOWERS_KEYCITY_W 86
+#define SPR_FLOWERS_KEYCITY_H 20
+#define SPR_FLYINGSAUCER_W 20
+#define SPR_FLYINGSAUCER_H 20
+#define SPR_FLYINGSAUCER_ALT_W 20
+#define SPR_FLYINGSAUCER_ALT_H 20
+#define SPR_FLYINGSAUCER_CUBE_W 20
+#define SPR_FLYINGSAUCER_CUBE_H 20
+#define SPR_FLYINGSAUCER_DEEPBLUE_W 20
+#define SPR_FLYINGSAUCER_DEEPBLUE_H 20
+#define SPR_FLYINGSAUCER_SHADE_W 20
+#define SPR_FLYINGSAUCER_SHADE_H 20
+#define SPR_FORCEDBUILDINGLOCATION_W 22
+#define SPR_FORCEDBUILDINGLOCATION_H 52
+#define SPR_FOREST_W 262
+#define SPR_FOREST_H 20
+#define SPR_FOREST_BRANCHES_W 262
+#define SPR_FOREST_BRANCHES_H 20
+#define SPR_FOREST_BRANCHES_GROW_W 284
+#define SPR_FOREST_BRANCHES_GROW_H 20
+#define SPR_FOREST_GROW_W 284
+#define SPR_FOREST_GROW_H 20
+#define SPR_FOSSILMUSEUM_W 64
+#define SPR_FOSSILMUSEUM_H 20
+#define SPR_FROG_W 16
+#define SPR_FROG_H 7
+#define SPR_FULLSCREEN_W 14
+#define SPR_FULLSCREEN_H 14
+#define SPR_GRASS_W 64
+#define SPR_GRASS_H 20
+#define SPR_GREENOUTLINE_W 22
+#define SPR_GREENOUTLINE_H 22
+#define SPR_HACKERHQ_W 64
+#define SPR_HACKERHQ_H 20
+#define SPR_HACKERS_BOLT_W 4
+#define SPR_HACKERS_BOLT_H 7
+#define SPR_HAPPINESS_W 10
+#define SPR_HAPPINESS_H 10
+#define SPR_HERBGARDEN_W 196
+#define SPR_HERBGARDEN_H 20
+#define SPR_HERBGARDEN_BUTTONBACK_W 20
+#define SPR_HERBGARDEN_BUTTONBACK_H 20
+#define SPR_HERBGARDEN_MEDIC_W 196
+#define SPR_HERBGARDEN_MEDIC_H 20
+#define SPR_HERBGARDEN_PLANTS_W 130
+#define SPR_HERBGARDEN_PLANTS_H 20
+#define SPR_HGH_BLOCK_W 4
+#define SPR_HGH_BLOCK_H 4
+#define SPR_HGH_BOOSTER_W 9
+#define SPR_HGH_BOOSTER_H 8
+#define SPR_HGH_CITIZENCLOTHES_1_W 2
+#define SPR_HGH_CITIZENCLOTHES_1_H 5
+#define SPR_HGH_MONSTER_1_W 14
+#define SPR_HGH_MONSTER_1_H 9
+#define SPR_HIDEUI_W 26
+#define SPR_HIDEUI_H 12
+#define SPR_HINTINFO_ARROW_W 10
+#define SPR_HINTINFO_ARROW_H 6
+#define SPR_HOLOGAMEHALL_W 130
+#define SPR_HOLOGAMEHALL_H 20
+#define SPR_HOUSEOFTHEKEYFRIENDS_W 64
+#define SPR_HOUSEOFTHEKEYFRIENDS_H 20
+#define SPR_HOUSING_W 10
+#define SPR_HOUSING_H 10
+#define SPR_HOVERHINT_W 70
+#define SPR_HOVERHINT_H 22
+#define SPR_HOVERHINTS_CITIZEN_W 94
+#define SPR_HOVERHINTS_CITIZEN_H 22
+#define SPR_HUMANS_W 202
+#define SPR_HUMANS_H 5
+#define SPR_HYPERELEVATOR_W 64
+#define SPR_HYPERELEVATOR_H 20
+#define SPR_HYPERELEVATOR_DOOR_W 46
+#define SPR_HYPERELEVATOR_DOOR_H 10
+#define SPR_ICON_BOOST_W 10
+#define SPR_ICON_BOOST_H 14
+#define SPR_ICON_BUILD_W 20
+#define SPR_ICON_BUILD_H 20
+#define SPR_ICON_BUILDINGMODE_DESTROY_W 20
+#define SPR_ICON_BUILDINGMODE_DESTROY_H 20
+#define SPR_ICON_BUILDINGMODE_DESTROYLEAVINGHOLE_W 20
+#define SPR_ICON_BUILDINGMODE_DESTROYLEAVINGHOLE_H 20
+#define SPR_ICON_BUILDINGMODE_DRAG_W 20
+#define SPR_ICON_BUILDINGMODE_DRAG_H 20
+#define SPR_ICON_BUILDINGMODE_DRAGREPLACE_W 20
+#define SPR_ICON_BUILDINGMODE_DRAGREPLACE_H 20
+#define SPR_ICON_BUILDINGMODE_INSERT_W 20
+#define SPR_ICON_BUILDINGMODE_INSERT_H 20
+#define SPR_ICON_BUILDINGMODE_ONTOP_W 20
+#define SPR_ICON_BUILDINGMODE_ONTOP_H 20
+#define SPR_ICON_BUILDINGMODE_REPLACE_W 20
+#define SPR_ICON_BUILDINGMODE_REPLACE_H 20
+#define SPR_ICON_CLOSE_W 21
+#define SPR_ICON_CLOSE_H 15
+#define SPR_ICON_ENTERTAINMENT_W 20
+#define SPR_ICON_ENTERTAINMENT_H 20
+#define SPR_ICON_FINDBUILDING_W 20
+#define SPR_ICON_FINDBUILDING_H 20
+#define SPR_ICON_FOLLOWCITIZEN_W 20
+#define SPR_ICON_FOLLOWCITIZEN_H 20
+#define SPR_ICON_HALFSPEED_W 12
+#define SPR_ICON_HALFSPEED_H 12
+#define SPR_ICON_HELP_W 12
+#define SPR_ICON_HELP_H 12
+#define SPR_ICON_HOUSES_W 20
+#define SPR_ICON_HOUSES_H 20
+#define SPR_ICON_INVITEPEOPLE_W 20
+#define SPR_ICON_INVITEPEOPLE_H 20
+#define SPR_ICON_MANAGEMENT_W 20
+#define SPR_ICON_MANAGEMENT_H 20
+#define SPR_ICON_MENU_W 12
+#define SPR_ICON_MENU_H 12
+#define SPR_ICON_PAUSE_W 12
+#define SPR_ICON_PAUSE_H 12
+#define SPR_ICON_PLAY_BIG_W 36
+#define SPR_ICON_PLAY_BIG_H 36
+#define SPR_ICON_PLAY_NORMALSPEED_W 12
+#define SPR_ICON_PLAY_NORMALSPEED_H 12
+#define SPR_ICON_ROCKET_W 12
+#define SPR_ICON_ROCKET_H 12
+#define SPR_ICON_SCHOOL_W 10
+#define SPR_ICON_SCHOOL_H 10
+#define SPR_ICON_SERVICES_W 20
+#define SPR_ICON_SERVICES_H 20
+#define SPR_ICON_SLIGHTLYSLOWERSPEED_W 12
+#define SPR_ICON_SLIGHTLYSLOWERSPEED_H 12
+#define SPR_ICON_SPECIALBUILDINGS_W 20
+#define SPR_ICON_SPECIALBUILDINGS_H 20
+#define SPR_ICON_SPEEDUP_W 12
+#define SPR_ICON_SPEEDUP_H 12
+#define SPR_ICON_TRANSPORT_W 20
+#define SPR_ICON_TRANSPORT_H 20
+#define SPR_ICON_UNLIMITED_W 13
+#define SPR_ICON_UNLIMITED_H 13
+#define SPR_ICON_UPGRADE_W 20
+#define SPR_ICON_UPGRADE_H 20
+#define SPR_ICON_WORK_W 20
+#define SPR_ICON_WORK_H 20
+#define SPR_IMPROVEDPICKAXES_W 20
+#define SPR_IMPROVEDPICKAXES_H 20
+#define SPR_INDOORFARM_W 64
+#define SPR_INDOORFARM_H 20
+#define SPR_INDOORFARM_BUTTONBACK_W 20
+#define SPR_INDOORFARM_BUTTONBACK_H 20
+#define SPR_INDOORFARM_CROPS_W 240
+#define SPR_INDOORFARM_CROPS_H 20
+#define SPR_INDOORPARK_W 328
+#define SPR_INDOORPARK_H 20
+#define SPR_INDOORPARK_ALT1_W 328
+#define SPR_INDOORPARK_ALT1_H 20
+#define SPR_INSERTBUILDINGHERE_W 20
+#define SPR_INSERTBUILDINGHERE_H 21
+#define SPR_INTERGALACTICLIBRARY_W 64
+#define SPR_INTERGALACTICLIBRARY_H 20
+#define SPR_LABESCAPEROOM_W 64
+#define SPR_LABESCAPEROOM_H 20
+#define SPR_LABORATORY_W 64
+#define SPR_LABORATORY_H 20
+#define SPR_LABORATORY_LIGHTSOFF_W 20
+#define SPR_LABORATORY_LIGHTSOFF_H 20
+#define SPR_LANDINGPLACE_W 64
+#define SPR_LANDINGPLACE_H 20
+#define SPR_LANDINGPLACE_ALT_W 64
+#define SPR_LANDINGPLACE_ALT_H 20
+#define SPR_LANDINGPLACE_DEEPBLUE_W 64
+#define SPR_LANDINGPLACE_DEEPBLUE_H 20
+#define SPR_LIBRARY_W 130
+#define SPR_LIBRARY_H 20
+#define SPR_LIVINGRESEARCHCENTER_W 64
+#define SPR_LIVINGRESEARCHCENTER_H 20
+#define SPR_LOCKEDBUILDING_W 42
+#define SPR_LOCKEDBUILDING_H 20
+#define SPR_LOFT_W 64
+#define SPR_LOFT_H 20
+#define SPR_LOFT_FURNISHINGS_W 130
+#define SPR_LOFT_FURNISHINGS_H 20
+#define SPR_LUXURYRESTAURANT_W 64
+#define SPR_LUXURYRESTAURANT_H 20
+#define SPR_MACHINEPARTSFACTORY_W 64
+#define SPR_MACHINEPARTSFACTORY_H 20
+#define SPR_MACHINEPARTSFACTORY_FRAMES_W 86
+#define SPR_MACHINEPARTSFACTORY_FRAMES_H 20
+#define SPR_MACHINEPARTSFACTORY_IDLE_W 42
+#define SPR_MACHINEPARTSFACTORY_IDLE_H 20
+#define SPR_MANSION_W 64
+#define SPR_MANSION_H 20
+#define SPR_MANSION_LEFT_W 64
+#define SPR_MANSION_LEFT_H 20
+#define SPR_MANSION_RIGHT_W 64
+#define SPR_MANSION_RIGHT_H 20
+#define SPR_MECHANICALHOUSE_W 64
+#define SPR_MECHANICALHOUSE_H 20
+#define SPR_MECHANICALHOUSE_BOTTOM_W 64
+#define SPR_MECHANICALHOUSE_BOTTOM_H 20
+#define SPR_MECHANICALHOUSE_BOTTOM_BGANIM_W 174
+#define SPR_MECHANICALHOUSE_BOTTOM_BGANIM_H 20
+#define SPR_MECHANICALHOUSE_HEATEDBED_W 20
+#define SPR_MECHANICALHOUSE_HEATEDBED_H 20
+#define SPR_MECHANICALHOUSE_LEFT_W 64
+#define SPR_MECHANICALHOUSE_LEFT_H 20
+#define SPR_MECHANICALHOUSE_LEFT_BGANIM_W 130
+#define SPR_MECHANICALHOUSE_LEFT_BGANIM_H 20
+#define SPR_MECHANICALHOUSE_LEFTRIGHT_W 64
+#define SPR_MECHANICALHOUSE_LEFTRIGHT_H 20
+#define SPR_MECHANICALHOUSE_LEFTRIGHT_BGANIM_W 130
+#define SPR_MECHANICALHOUSE_LEFTRIGHT_BGANIM_H 20
+#define SPR_MECHANICALHOUSE_PIPE_H_W 3
+#define SPR_MECHANICALHOUSE_PIPE_H_H 5
+#define SPR_MECHANICALHOUSE_PIPE_H2_W 3
+#define SPR_MECHANICALHOUSE_PIPE_H2_H 5
+#define SPR_MECHANICALHOUSE_PIPE_H2_BF_W 5
+#define SPR_MECHANICALHOUSE_PIPE_H2_BF_H 11
+#define SPR_MECHANICALHOUSE_PIPE_H3_W 26
+#define SPR_MECHANICALHOUSE_PIPE_H3_H 20
+#define SPR_MECHANICALHOUSE_PIPE_H3_BF_W 26
+#define SPR_MECHANICALHOUSE_PIPE_H3_BF_H 20
+#define SPR_MECHANICALHOUSE_PIPE_V1_W 5
+#define SPR_MECHANICALHOUSE_PIPE_V1_H 3
+#define SPR_MECHANICALHOUSE_PIPE_V2_W 5
+#define SPR_MECHANICALHOUSE_PIPE_V2_H 3
+#define SPR_MECHANICALHOUSE_PIPE_V3_W 7
+#define SPR_MECHANICALHOUSE_PIPE_V3_H 26
+#define SPR_MECHANICALHOUSE_RIGHT_W 64
+#define SPR_MECHANICALHOUSE_RIGHT_H 20
+#define SPR_MECHANICALHOUSE_RIGHT_BGANIM_W 130
+#define SPR_MECHANICALHOUSE_RIGHT_BGANIM_H 20
+#define SPR_MECHANICALHOUSE_TOP_W 64
+#define SPR_MECHANICALHOUSE_TOP_H 20
+#define SPR_MECHANICALHOUSE_TOP_BGANIM_W 42
+#define SPR_MECHANICALHOUSE_TOP_BGANIM_H 20
+#define SPR_MEDICALCLINIC_W 64
+#define SPR_MEDICALCLINIC_H 20
+#define SPR_MINIBUTTON_W 31
+#define SPR_MINIBUTTON_H 7
+#define SPR_MIRROR_W 20
+#define SPR_MIRROR_H 20
+#define SPR_MISDIRECTOR_W 64
+#define SPR_MISDIRECTOR_H 20
+#define SPR_MODERNART_W 218
+#define SPR_MODERNART_H 20
+#define SPR_MODERNARTMUSEUM_W 64
+#define SPR_MODERNARTMUSEUM_H 20
+#define SPR_MODERNARTMUSEUM_BUTTONBACK_W 20
+#define SPR_MODERNARTMUSEUM_BUTTONBACK_H 20
+#define SPR_MODERNCONVENIENCES_W 20
+#define SPR_MODERNCONVENIENCES_H 20
+#define SPR_MODERNHOMEPLANT_W 218
+#define SPR_MODERNHOMEPLANT_H 20
+#define SPR_MODERNRUSTICHOME_W 64
+#define SPR_MODERNRUSTICHOME_H 20
+#define SPR_MOREBUILDINGMODEBUTTONS_W 40
+#define SPR_MOREBUILDINGMODEBUTTONS_H 22
+#define SPR_MOREBUILDINGMODES_ARROWUP_W 10
+#define SPR_MOREBUILDINGMODES_ARROWUP_H 20
+#define SPR_MORESETTINGS_W 14
+#define SPR_MORESETTINGS_H 14
+#define SPR_NATURE_W 20
+#define SPR_NATURE_H 20
+#define SPR_NIGHTCLUB_W 130
+#define SPR_NIGHTCLUB_H 20
+#define SPR_NIGHTCLUB_LASER_W 358
+#define SPR_NIGHTCLUB_LASER_H 16
+#define SPR_NIGHTCLUB_LIGHT_W 5
+#define SPR_NIGHTCLUB_LIGHT_H 15
+#define SPR_NIGHTCLUB_LIGHT_RAINBOW_W 5
+#define SPR_NIGHTCLUB_LIGHT_RAINBOW_H 15
+#define SPR_NORMALHOUSE_W 64
+#define SPR_NORMALHOUSE_H 20
+#define SPR_OBSERVATORY_W 64
+#define SPR_OBSERVATORY_H 20
+#define SPR_ONEANDHALFSPEED_W 12
+#define SPR_ONEANDHALFSPEED_H 12
+#define SPR_PARK_BUTTONBG_W 20
+#define SPR_PARK_BUTTONBG_H 20
+#define SPR_PARK_PLANTS_W 284
+#define SPR_PARK_PLANTS_H 20
+#define SPR_PARKPOD_W 152
+#define SPR_PARKPOD_H 20
+#define SPR_PARKPOD_BUTTONBACK_W 20
+#define SPR_PARKPOD_BUTTONBACK_H 20
+#define SPR_PINEFOREST_W 262
+#define SPR_PINEFOREST_H 20
+#define SPR_PINEFOREST_GROW_W 240
+#define SPR_PINEFOREST_GROW_H 20
+#define SPR_PIXEL_W 1
+#define SPR_PIXEL_H 1
+#define SPR_PLANET_RING_BIG_W 835
+#define SPR_PLANET_RING_BIG_H 200
+#define SPR_PLANET_RING_SMALL_W 580
+#define SPR_PLANET_RING_SMALL_H 110
+#define SPR_PLANETS_BIG_W 1018
+#define SPR_PLANETS_BIG_H 100
+#define SPR_PLANETS_BIGGER_W 730
+#define SPR_PLANETS_BIGGER_H 120
+#define SPR_PLANETS_GIANT_W 566
+#define SPR_PLANETS_GIANT_H 140
+#define SPR_PLANETS_MEDIUM_W 654
+#define SPR_PLANETS_MEDIUM_H 80
+#define SPR_PLANETS_SMALL_W 250
+#define SPR_PLANETS_SMALL_H 40
+#define SPR_POPULATION_W 10
+#define SPR_POPULATION_H 10
+#define SPR_PROTESTSIGN_HAPPY_W 9
+#define SPR_PROTESTSIGN_HAPPY_H 14
+#define SPR_PROTESTSIGN_SAD_W 9
+#define SPR_PROTESTSIGN_SAD_H 14
+#define SPR_PUB_W 64
+#define SPR_PUB_H 20
+#define SPR_PUB_MARKING_KEY_W 9
+#define SPR_PUB_MARKING_KEY_H 9
+#define SPR_PURPLEFOREST_W 284
+#define SPR_PURPLEFOREST_H 20
+#define SPR_PURPLEFOREST_GROW_W 218
+#define SPR_PURPLEFOREST_GROW_H 20
+#define SPR_PURPLEGRASS_W 64
+#define SPR_PURPLEGRASS_H 20
+#define SPR_RECOLORABLE_W 22
+#define SPR_RECOLORABLE_H 22
+#define SPR_REDFOREST_W 262
+#define SPR_REDFOREST_H 20
+#define SPR_REDFOREST_GROW_W 284
+#define SPR_REDFOREST_GROW_H 20
+#define SPR_REDGRASS_W 64
+#define SPR_REDGRASS_H 20
+#define SPR_REDWOOD_W 262
+#define SPR_REDWOOD_H 20
+#define SPR_REDWOODTREEHOUSE_W 64
+#define SPR_REDWOODTREEHOUSE_H 20
+#define SPR_REFINEDMETALFACTORY_W 64
+#define SPR_REFINEDMETALFACTORY_H 20
+#define SPR_REFINEDMETALFACTORY_FRAMES_W 306
+#define SPR_REFINEDMETALFACTORY_FRAMES_H 20
+#define SPR_REFINEDMETALFACTORY_IDLE_W 42
+#define SPR_REFINEDMETALFACTORY_IDLE_H 20
+#define SPR_REFINEDMETALFACTORYPUB_W 130
+#define SPR_REFINEDMETALFACTORYPUB_H 20
+#define SPR_REFINEDMETALFACTORYPUB_FRAMES_W 482
+#define SPR_REFINEDMETALFACTORYPUB_FRAMES_H 20
+#define SPR_REFINEDMETALFACTORYPUB_IDLE_W 42
+#define SPR_REFINEDMETALFACTORYPUB_IDLE_H 20
+#define SPR_REMOVEDECORATION_W 20
+#define SPR_REMOVEDECORATION_H 20
+#define SPR_REPLACEBUILDINGHERE_W 20
+#define SPR_REPLACEBUILDINGHERE_H 21
+#define SPR_RESEARCHBOT_W 20
+#define SPR_RESEARCHBOT_H 20
+#define SPR_RESEARCHBOT_LANDINGPLACE_W 64
+#define SPR_RESEARCHBOT_LANDINGPLACE_H 20
+#define SPR_RESIDENTS_W 8
+#define SPR_RESIDENTS_H 10
+#define SPR_RESOURCE_COMPUTERCHIPS_W 10
+#define SPR_RESOURCE_COMPUTERCHIPS_H 10
+#define SPR_RESOURCE_DOWNTREND_W 10
+#define SPR_RESOURCE_DOWNTREND_H 10
+#define SPR_RESOURCE_FOOD_W 10
+#define SPR_RESOURCE_FOOD_H 10
+#define SPR_RESOURCE_GRAPHENE_W 10
+#define SPR_RESOURCE_GRAPHENE_H 10
+#define SPR_RESOURCE_KNOWLEDGE_W 10
+#define SPR_RESOURCE_KNOWLEDGE_H 10
+#define SPR_RESOURCE_MACHINEPARTS_W 10
+#define SPR_RESOURCE_MACHINEPARTS_H 10
+#define SPR_RESOURCE_REFINEDMETAL_W 10
+#define SPR_RESOURCE_REFINEDMETAL_H 10
+#define SPR_RESOURCE_ROCKETFUEL_W 10
+#define SPR_RESOURCE_ROCKETFUEL_H 10
+#define SPR_RESOURCE_STONE_W 10
+#define SPR_RESOURCE_STONE_H 10
+#define SPR_RESOURCE_WOOD_W 10
+#define SPR_RESOURCE_WOOD_H 10
+#define SPR_RESTAURANT_W 130
+#define SPR_RESTAURANT_H 20
+#define SPR_ROCK_W 152
+#define SPR_ROCK_H 20
+#define SPR_ROOFBOTTOM_W 438
+#define SPR_ROOFBOTTOM_H 20
+#define SPR_ROOFTOPPARK_W 130
+#define SPR_ROOFTOPPARK_H 20
+#define SPR_ROOFTOPPARK_BUTTONBG_W 20
+#define SPR_ROOFTOPPARK_BUTTONBG_H 20
+#define SPR_ROOFTOPPARK_ONBUILD_W 20
+#define SPR_ROOFTOPPARK_ONBUILD_H 20
+#define SPR_ROOFTOPPARK_PLANTS_W 130
+#define SPR_ROOFTOPPARK_PLANTS_H 20
+#define SPR_SCHOOL_W 64
+#define SPR_SCHOOL_H 20
+#define SPR_SCRAPYARDNIGHTCLUB_W 130
+#define SPR_SCRAPYARDNIGHTCLUB_H 20
+#define SPR_SECRETSOCIETYHOUSE_W 64
+#define SPR_SECRETSOCIETYHOUSE_H 20
+#define SPR_SECRETSOCIETYMACHINE_W 64
+#define SPR_SECRETSOCIETYMACHINE_H 20
+#define SPR_SECRETSOCIETYMACHINE_ANIM_W 548
+#define SPR_SECRETSOCIETYMACHINE_ANIM_H 20
+#define SPR_SELECTEDBUILDING_W 22
+#define SPR_SELECTEDBUILDING_H 22
+#define SPR_SELECTEDFISH_W 10
+#define SPR_SELECTEDFISH_H 10
+#define SPR_SELECTEDHUMAN_W 4
+#define SPR_SELECTEDHUMAN_H 7
+#define SPR_SHADYHOUSE_W 64
+#define SPR_SHADYHOUSE_H 20
+#define SPR_SLANTEDROOF_W 460
+#define SPR_SLANTEDROOF_H 20
+#define SPR_SLANTEDROOFTOP_W 438
+#define SPR_SLANTEDROOFTOP_H 20
+#define SPR_SLIDER_BG_W 22
+#define SPR_SLIDER_BG_H 22
+#define SPR_SLIDER_FILL_W 22
+#define SPR_SLIDER_FILL_H 22
+#define SPR_SMALLTELEPORTER_RAY_W 28
+#define SPR_SMALLTELEPORTER_RAY_H 5
+#define SPR_SMALLTELEPORTER_RAY_PENTHOUSE_W 33
+#define SPR_SMALLTELEPORTER_RAY_PENTHOUSE_H 5
+#define SPR_SMALLTELEPORTER_RAY_PENTHOUSE_MIRROR_W 33
+#define SPR_SMALLTELEPORTER_RAY_PENTHOUSE_MIRROR_H 5
+#define SPR_SMARTCHAIRS_W 20
+#define SPR_SMARTCHAIRS_H 20
+#define SPR_SMARTDIAGNOSE_W 20
+#define SPR_SMARTDIAGNOSE_H 20
+#define SPR_SMARTLIGHTS_W 20
+#define SPR_SMARTLIGHTS_H 20
+#define SPR_SMARTSPEAKER_W 20
+#define SPR_SMARTSPEAKER_H 20
+#define SPR_SOFTERBEDS_W 20
+#define SPR_SOFTERBEDS_H 20
+#define SPR_SPACIOUSHOUSE_W 64
+#define SPR_SPACIOUSHOUSE_H 20
+#define SPR_STATUEGARDEN_BUTTONBACK_W 20
+#define SPR_STATUEGARDEN_BUTTONBACK_H 20
+#define SPR_STATUEGARDEN_STATUES_W 174
+#define SPR_STATUEGARDEN_STATUES_H 20
+#define SPR_STATUEOFHAPPINESS_W 64
+#define SPR_STATUEOFHAPPINESS_H 20
+#define SPR_STATUEOFHAPPINESS_BG_W 20
+#define SPR_STATUEOFHAPPINESS_BG_H 20
+#define SPR_STATUEOFTHEKEY_W 64
+#define SPR_STATUEOFTHEKEY_H 20
+#define SPR_STATUEOFTHEKEY_BG_W 20
+#define SPR_STATUEOFTHEKEY_BG_H 20
+#define SPR_STONEMINE_W 64
+#define SPR_STONEMINE_H 20
+#define SPR_STONERESEARCHCENTRE_W 64
+#define SPR_STONERESEARCHCENTRE_H 20
+#define SPR_STONERESEARCHCENTRE_COMPUTER_W 20
+#define SPR_STONERESEARCHCENTRE_COMPUTER_H 20
+#define SPR_STONERESEARCHCENTRE_PICKAXETECH_W 20
+#define SPR_STONERESEARCHCENTRE_PICKAXETECH_H 20
+#define SPR_STONETELEPORTER_W 64
+#define SPR_STONETELEPORTER_H 20
+#define SPR_STONETELEPORTER_REMOTE_W 20
+#define SPR_STONETELEPORTER_REMOTE_H 20
+#define SPR_STONETELEPORTER_STONE_W 196
+#define SPR_STONETELEPORTER_STONE_H 20
+#define SPR_STONETELEPORTER_STONE_BIG_W 196
+#define SPR_STONETELEPORTER_STONE_BIG_H 20
+#define SPR_SUPERCOMPUTER_W 64
+#define SPR_SUPERCOMPUTER_H 20
+#define SPR_SYNIGHTCLUB_BG_W 20
+#define SPR_SYNIGHTCLUB_BG_H 20
+#define SPR_SYNIGHTCLUB_LEFTTEXTURES_W 64
+#define SPR_SYNIGHTCLUB_LEFTTEXTURES_H 19
+#define SPR_SYNIGHTCLUB_LIGHTS_W 1
+#define SPR_SYNIGHTCLUB_LIGHTS_H 10
+#define SPR_SYNIGHTCLUB_LIGHTS_H_W 10
+#define SPR_SYNIGHTCLUB_LIGHTS_H_H 1
+#define SPR_SYNIGHTCLUB_MAINTEXTURES_W 64
+#define SPR_SYNIGHTCLUB_MAINTEXTURES_H 19
+#define SPR_SYNIGHTCLUB_MINILIGHT_W 3
+#define SPR_SYNIGHTCLUB_MINILIGHT_H 3
+#define SPR_SYNIGHTCLUB_WATERFALLLIGHT_W 7
+#define SPR_SYNIGHTCLUB_WATERFALLLIGHT_H 2
+#define SPR_SYNIGHTCLUB_WATERFALLLIGHT_LAST_W 5
+#define SPR_SYNIGHTCLUB_WATERFALLLIGHT_LAST_H 6
+#define SPR_TECH_NIGHTCLUB_W 328
+#define SPR_TECH_NIGHTCLUB_H 20
+#define SPR_TECH_NIGHTCLUB_HOVERER_W 4
+#define SPR_TECH_NIGHTCLUB_HOVERER_H 4
+#define SPR_TELEPORTER_W 64
+#define SPR_TELEPORTER_H 20
+#define SPR_TELEPORTER_RAY_W 34
+#define SPR_TELEPORTER_RAY_H 15
+#define SPR_TELEPORTER_RAY_KEY_W 46
+#define SPR_TELEPORTER_RAY_KEY_H 15
+#define SPR_TELEPORTER_RAY_MISDIRECT_W 34
+#define SPR_TELEPORTER_RAY_MISDIRECT_H 15
+#define SPR_TELESCOPE_W 4
+#define SPR_TELESCOPE_H 5
+#define SPR_TINKERERSHOUSE_W 64
+#define SPR_TINKERERSHOUSE_H 20
+#define SPR_TINKERERSHOUSE_BACK_ALT_W 108
+#define SPR_TINKERERSHOUSE_BACK_ALT_H 20
+#define SPR_TINKERERSHOUSE_BETTERTOOLS_W 86
+#define SPR_TINKERERSHOUSE_BETTERTOOLS_H 20
+#define SPR_TINKERERSHOUSE_FRONT_ALT_W 196
+#define SPR_TINKERERSHOUSE_FRONT_ALT_H 20
+#define SPR_TITLE_W 261
+#define SPR_TITLE_H 55
+#define SPR_TRANSPARENTBUTTON_W 70
+#define SPR_TRANSPARENTBUTTON_H 22
+#define SPR_TRANSPARENTBUTTON_INFO_W 70
+#define SPR_TRANSPARENTBUTTON_INFO_H 22
+#define SPR_TRANSPARENTBUTTON_INFO_MINI_W 46
+#define SPR_TRANSPARENTBUTTON_INFO_MINI_H 14
+#define SPR_TRANSPARENTBUTTON_INFO_MINIPLUS_W 64
+#define SPR_TRANSPARENTBUTTON_INFO_MINIPLUS_H 20
+#define SPR_TREEGROWTHBOOST_W 20
+#define SPR_TREEGROWTHBOOST_H 20
+#define SPR_TREEHUGGERBASE_W 20
+#define SPR_TREEHUGGERBASE_H 20
+#define SPR_TREEPLANTATION_W 64
+#define SPR_TREEPLANTATION_H 20
+#define SPR_TREEPLANTATION_BUTTONBACK_W 20
+#define SPR_TREEPLANTATION_BUTTONBACK_H 20
+#define SPR_TREEPLANTATION_TREES_W 262
+#define SPR_TREEPLANTATION_TREES_H 20
+#define SPR_TREEPLANTATION_TREES_GROW_W 240
+#define SPR_TREEPLANTATION_TREES_GROW_H 20
+#define SPR_TUTORIALARROWDOWN_W 20
+#define SPR_TUTORIALARROWDOWN_H 30
+#define SPR_TUTORIALARROWLEFT_W 30
+#define SPR_TUTORIALARROWLEFT_H 20
+#define SPR_UNIQUEBUILDING_W 10
+#define SPR_UNIQUEBUILDING_H 10
+#define SPR_UNKNOWNBUILDING_W 64
+#define SPR_UNKNOWNBUILDING_H 20
+#define SPR_UPGRADE_FARMBOOST_W 20
+#define SPR_UPGRADE_FARMBOOST_H 20
+#define SPR_UPGRADE_FLOWERS_W 64
+#define SPR_UPGRADE_FLOWERS_H 20
+#define SPR_VILLA_W 64
+#define SPR_VILLA_H 20
+#define SPR_WALDO_ADULT_W 2
+#define SPR_WALDO_ADULT_H 5
+#define SPR_WALDO_CHILD_W 2
+#define SPR_WALDO_CHILD_H 5
+#define SPR_WHITEOUTLINE_W 22
+#define SPR_WHITEOUTLINE_H 22
+#define SPR_WINDOWPARTS_W 62
+#define SPR_WINDOWPARTS_H 24
+#define SPR_WINDOWPARTS_PURPLE_W 62
+#define SPR_WINDOWPARTS_PURPLE_H 24
+#define SPR_WOODCUTTINGCENTRE_W 64
+#define SPR_WOODCUTTINGCENTRE_H 20
+#define SPR_WORK_W 10
+#define SPR_WORK_H 10
+#define SPR_WORK_HOUSING_W 21
+#define SPR_WORK_HOUSING_H 10
+#define SPR_WORKSHOP_W 64
+#define SPR_WORKSHOP_H 20
+#define SPR_WORKSHOP_MAKEMACHINEPARTS_W 20
+#define SPR_WORKSHOP_MAKEMACHINEPARTS_H 20
+#define SPR_WORKSHOP_PETPROJECTS_W 20
+#define SPR_WORKSHOP_PETPROJECTS_H 20
+
+/* fonts (the original's BMFont fonts) */
+enum { FONT_STANDARD, FONT_10, FONT_15, FONT_16, FONT_18, FONT_COUNT };
+
+#endif
diff --git a/games/finalearth2/src/fe.h b/games/finalearth2/src/fe.h
new file mode 100644
index 00000000..2d977a2d
--- /dev/null
+++ b/games/finalearth2/src/fe.h
@@ -0,0 +1,159 @@
+/* The Final Earth 2 for the NumWorks calculator: the city and its simulation.
+ *
+ * Inspired by The Final Earth 2 by Florian van Strien, not affiliated with
+ * him. Made by Mason Chen as part of NumPlay.
+ *
+ * The simulation follows the original's code (its class and field names are
+ * kept, so each part can be checked against it): floating worlds with columns
+ * of 20x20 permanents (buildings, forests, rocks...) stacked on them, and
+ * citizens who walk the worlds' surfaces and through the buildings along paths
+ * the pathfinder gives them. The original runs at 60 frames a second with
+ * timeMod 1; here a tick is a 30th of a second, timeMod 2. */
+#ifndef FE_H
+#define FE_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+#include "plat.h"
+
+#define FPS 30
+#define TIMEMOD 2.0f
+
+/* ---------------------------------------------------------------- sizes */
+#define MAX_WORLDS 64
+#define MAX_COLS 512 /* columns of all the worlds together (a column is 20 pixels) */
+#define MAX_SHARDS 256
+#define MAX_PERMS 700 /* permanents (ids 1 to MAX_PERMS - 1, 0 is none) */
+#define MAX_CITS 800 /* citizens (ids 1 to MAX_CITS - 1) */
+#define NONE 0
+
+/* ---------------------------------------------------------------- materials */
+enum { M_FOOD, M_WOOD, M_STONE, M_MACHINEPARTS, M_REFINEDMETAL, M_COMPUTERCHIPS, M_CACAO, M_CHOCOLATE,
+ M_GRAPHENE, M_ROCKETFUEL, M_KNOWLEDGE, M_COUNT };
+/* stocks are doubles: production comes in tiny steps every tick, which a float of 100000 would lose */
+typedef struct { double m[M_COUNT]; } Materials;
+
+/* ---------------------------------------------------------------- worlds */
+typedef struct {
+ int16_t x, y, w, h; /* rect in city pixels; h 0: an invisible world (bridges, platforms) */
+ uint32_t seed;
+ uint8_t appearance; /* APPEAR_* */
+ uint8_t id; /* the original's world id (saves, stories) */
+ uint16_t col0; /* its first column in the column tables */
+ uint16_t ncols; /* w / 20 */
+ uint8_t flags; /* WF_* */
+ uint8_t group; /* worldGroup: worlds citizens can reach from each other */
+ uint16_t surfaceShard; /* surfaceShardId */
+} World;
+enum { WF_UNBUILDABLE_ALIENS = 1, WF_PROTECTED_KEY = 2, WF_HAS_TELEPORTER_ON_GROUP = 4 };
+
+/* ---------------------------------------------------------------- permanents
+ * A permanent is a building or a world resource (forest, rock, ruins), one
+ * 20x20 slot of a world's column. Its class (pcls[]) gives its data and what it
+ * does. */
+typedef struct {
+ uint8_t cls; /* index in pcls[] */
+ uint8_t world, col, row; /* worldPosition: column and height in the stack (0 on the ground) */
+ uint8_t flags; /* PF_* */
+ uint8_t upgrades; /* bits: the class's possible upgrades bought */
+ uint8_t mode; /* building mode */
+ int8_t bonusAttractiveness;
+ uint16_t left, right, top, bottom; /* neighbouring buildings (CityConnections) */
+ uint8_t nworkers, nresidents, nstudents, nvisitors; /* citizens who work, live, study or are here for fun */
+ int16_t bonusEntertainmentCapacity;
+ uint16_t shard; /* group of permanents citizens can walk between (CityConnections) */
+ uint8_t s[12]; /* the class's own state (see its bld file) */
+} Perm;
+enum {
+ PF_BUILDING = 1, PF_ROOFTOP = 2, PF_NO_BUILD_ON_TOP = 4, PF_DESTROYED = 8, PF_IS_ENTERTAINMENT = 16,
+ PF_IS_MEDICAL = 32
+};
+
+extern World worlds[MAX_WORLDS];
+extern int nworlds;
+extern Perm perms[MAX_PERMS];
+extern uint8_t col_height[MAX_COLS]; /* entries in each column's stack, holes included */
+
+static inline Perm *P(uint16_t id) { return id ? &perms[id] : NULL; }
+static inline uint16_t pid(const Perm *p) { return p ? (uint16_t)(p - perms) : 0; }
+static inline bool is_building(const Perm *p) { return p && (p->flags & PF_BUILDING); }
+uint16_t perm_at(int world, int col, int row); /* 0 if none (or a hole) */
+int perm_city_x(const Perm *p); /* position.x */
+int perm_city_y(const Perm *p); /* position.y: its top */
+
+/* ---------------------------------------------------------------- citizens */
+typedef struct {
+ float relativeX, relativeY;
+ float vpp; /* verticalPathProgress (cit_vpp) */
+ float timer; /* currentPathActionTimerXY (cit_timer) */
+ float bornOn; /* city time (minutes) of birth */
+ float educationLevel;
+ int16_t dieAgeModifier; /* years, x 100 */
+ uint16_t inBuildingSince; /* city time in half minutes (ticks), wrapping */
+ uint16_t pathStartTime; /* city time in minutes, wrapping */
+ int8_t workTimePref; /* actualWorkTimePreference, -1 to 1, x 127 */
+ uint8_t onWorld;
+ uint16_t inPermanent, home, job, school;
+ uint16_t pathDestination, requestingPathGoal, pathOnlyRelatedTo, pathActionPerm;
+ uint16_t nameIndex;
+ uint16_t pathOff; /* its path's steps in the path pool */
+ uint8_t pathLen, pathPos; /* steps in it, the next one */
+ uint8_t spriteIndex;
+ int8_t currentAction; /* 0 work, 1 school, 2 free, 3 controlled */
+ int8_t currentPathAction; /* -2 none, -1 about to start the next step, else the step's type */
+ uint8_t pathWalkSpeed; /* percent */
+ uint8_t then, onFail; /* what to do at the path's end, or if no path is found (THEN_*) */
+ uint16_t thenArg;
+ uint8_t wantsNightEntertainmentIn;
+ uint8_t hobby;
+ uint16_t flags; /* CF_* */
+ /* CitizenEntertainment, as city times that wrap: recentEntertainmentTypes in 2-hour units,
+ * tryForDayEntertainment, tryForEntertainment and entertainmentFinishedTime in 4-minute units */
+ uint8_t entRecent[6];
+ uint8_t entTryDay, entTry, entFinished;
+ uint8_t jobIndex; /* its place in its job's list of workers (workers.indexOf), kept by bld.c */
+} Cit;
+enum {
+ CF_ALIVE = 1, CF_CAN_VIEW_SELF = 2, CF_DELAY_CAN_VIEW_SELF = 4, CF_REQUESTING_PATH = 8,
+ CF_PATH_RECONSIDER = 16, CF_HAS_WORK_TOOLS = 32, CF_LIKES_NIGHTCLUBS = 64, CF_FORCED_HOME = 128,
+ CF_CONTROLLED = 256, CF_WITHOUT_JOB = 512, CF_BUILDING_INITED = 1024, CF_ENT_INITED = 2048,
+ CF_HAS_PATH = 4096
+};
+
+extern Cit cits[MAX_CITS];
+/* (kept as accessors: they may be packed later) */
+static inline float cit_vpp(const Cit *c) { return c->vpp; }
+static inline void cit_set_vpp(Cit *c, float v) { c->vpp = v; }
+static inline float cit_timer(const Cit *c) { return c->timer; }
+static inline void cit_set_timer(Cit *c, float v) { c->timer = v; }
+extern int ncits; /* living citizens */
+static inline Cit *C(uint16_t id) { return id ? &cits[id] : NULL; }
+static inline uint16_t cid(const Cit *c) { return c ? (uint16_t)(c - cits) : 0; }
+
+/* ---------------------------------------------------------------- the city */
+#define CITY_NAME_MAX 24 /* bytes of a city's name */
+typedef struct {
+ double timeSinceStart; /* minutes since the city began (CityTime) */
+ float minutesPerTick; /* 0.5 */
+ Materials materials;
+ float happiness;
+ float simulationSpeed; /* 1, 1.5, 2, 0.5 or 0.75 (gui.CityGUI.simulationSpeeds) */
+ bool paused;
+ uint8_t story; /* index of the story or free play map */
+ bool speedUpStartNights;
+ bool disableDying;
+ char cityName[CITY_NAME_MAX + 1]; /* the player's name for the city (CityHall), "" none (UTF-8) */
+} City;
+extern City city;
+
+static inline float city_hour(void) { return (float)(city.timeSinceStart / 60.0 - 24.0 * (int)(city.timeSinceStart / 1440.0)); }
+static inline int city_day(void) { return 1 + (int)city.timeSinceStart / 1440; }
+
+/* random numbers (the original's random.Random: getInt(a, b) is a to b - 1) */
+uint32_t rnd(void);
+float rnd_float(void); /* [0, 1) */
+float rnd_range(float a, float b); /* [a, b) */
+int rnd_int(int n); /* [0, n) */
+int rnd_between(int a, int b); /* [a, b) */
+#endif
diff --git a/games/finalearth2/src/game.c b/games/finalearth2/src/game.c
new file mode 100644
index 00000000..f47c90e8
--- /dev/null
+++ b/games/finalearth2/src/game.c
@@ -0,0 +1,138 @@
+/* The Final Earth 2 for the NumWorks calculator: the game's loop.
+ *
+ * Inspired by The Final Earth 2 by Florian van Strien, not affiliated with
+ * him. Made by Mason Chen as part of NumPlay. */
+#include "bld.h"
+#include "bg.h"
+#include "data.h"
+#include "game.h"
+#include "input.h"
+#include "save.h"
+#include "scratch.h"
+#include "story.h"
+#include "uii.h"
+#include "view.h"
+
+#ifndef HOST
+const char eadk_app_name[] __attribute__((section(".rodata.eadk_app_name"))) = "Final Earth 2";
+const uint32_t eadk_api_level __attribute__((section(".rodata.eadk_api_level"))) = 0;
+#endif
+
+bool game_running = true;
+uint32_t game_ticks;
+BgEdges city_edges;
+
+static void set_background(int s) {
+ BgPlanet p[BG_MAX_PLANETS];
+ int n = 0;
+ for (int i = 0; i < stories[s].nbackgrounds && n < BG_MAX_PLANETS; i++, n++) {
+ const StoryBackground *b = &stories[s].backgrounds[i];
+ p[n] = (BgPlanet){b->sprite, (uint16_t)b->width, (uint8_t)b->image, b->x, b->y, b->velocity};
+ }
+ bg_set_planets(p, n);
+}
+
+/* the view where the story wants it: centred on x 225 (or its viewStartX), its bottom at viewYFromBottom */
+static void camera_start(int s) {
+ view_edges(&city_edges);
+ float hw = SCREEN_W / 2.0f / camera.zoom, hh = SCREEN_H / 2.0f / camera.zoom;
+ float cx = stories[s].viewStartX ? stories[s].viewStartX : 225, cy = 150;
+ camera.x = cx - hw, camera.y = cy - hh;
+ camera_clamp_view();
+ if (stories[s].viewYFromBottom) camera.y = stories[s].viewYFromBottom - 2 * hh;
+}
+
+void game_start(int s, const NewCityOptions *opt) {
+ saved_view.valid = false;
+ story_new_city(s, opt);
+ set_background(s);
+ view_edges(&city_edges);
+ bg_clouds_start(&city_edges);
+ camera.zoom = 1;
+ camera_start(s);
+}
+
+void game_after_load(void) {
+ set_background(story.index);
+ view_edges(&city_edges);
+ bg_clouds_start(&city_edges);
+ camera.zoom = 1;
+ camera_start(story.index);
+ if (saved_view.valid) {
+ /* (City.load: its viewPos and zoomScale) */
+ camera.zoom = saved_view.zoom;
+ camera.x = saved_view.x, camera.y = saved_view.y;
+ camera_clamp_view();
+ }
+}
+
+void game_init(void) {
+ save_restore(); /* (after the app was installed again) */
+ bg_init(plat_millis() * 2654435761u + 1);
+ rnd_seed(plat_millis() * 2246822519u + 7);
+#ifdef START_STORY
+ ui_before_city();
+ game_start(START_STORY, NULL); /* test builds: make EXTRA=-DSTART_STORY=3 */
+ ui_after_load();
+#else
+ ui_init(); /* the title screen */
+#endif
+}
+
+/* how much longer than a tick (33.3 ms) the last frame took: the original's timeMod follows the real time
+ * (PIXI's ticker), so the city keeps its pace when frames are slow */
+float frame_time_mod = 1;
+
+void game_tick(void) {
+ input_update();
+ if (key_pressed(K_HOME)) { /* saves, then quits (a failed save says so, and the game goes on) */
+ if (ui_home()) game_running = false;
+ return;
+ }
+ ui_tick();
+ sim_tick(frame_time_mod);
+ if (game_ticks % 30 == 0) view_edges(&city_edges);
+ bg_clouds_update(2 * frame_time_mod * city.simulationSpeed * 0.6666667f * (city.paused ? 0 : 1), &city_edges);
+ game_ticks++;
+}
+
+void game_draw(void) {
+ /* the interface's primitives live on this stack until the frame is drawn (gfx_end) */
+ UiFrame f;
+ gfx_begin();
+ view_draw();
+ ui_draw(&f);
+ gfx_end();
+}
+
+#ifndef HOST
+uint32_t perf_frames __attribute__((used));
+uint32_t perf_ms __attribute__((used));
+uint32_t perf_max __attribute__((used));
+
+int main(void) {
+ /* memory only needed while a search or pass runs, on this stack: some calculator software gives apps less RAM */
+ Scratch scr;
+ scratch = &scr;
+ gfx_set_band_memory(scr.band);
+ plat_begin();
+ game_init();
+ uint32_t next = plat_millis(), last = next;
+ while (game_running) {
+ uint32_t t0 = plat_millis();
+ float tm = (float)(t0 - last) * (FPS / 1000.0f);
+ last = t0;
+ frame_time_mod = tm < 1.1f ? 1 : tm > 2 ? 2 : tm;
+ game_tick();
+ if (!game_running) break;
+ game_draw();
+ perf_frames++;
+ if (perf_frames > 30 && plat_millis() - t0 > perf_max) perf_max = plat_millis() - t0;
+ next += 1000 / FPS + (game_ticks % 3 == 0 ? 1 : 0); /* 33.3 ms */
+ uint32_t now = plat_millis();
+ if ((int32_t)(next - now) > 0) plat_sleep(next - now);
+ else next = now; /* late: the next tick's frame_time_mod makes up for it */
+ }
+ return plat_end();
+}
+#endif
diff --git a/games/finalearth2/src/game.h b/games/finalearth2/src/game.h
new file mode 100644
index 00000000..9112b2e5
--- /dev/null
+++ b/games/finalearth2/src/game.h
@@ -0,0 +1,18 @@
+/* The Final Earth 2: the game's loop (game.c). */
+#ifndef FE_GAME_H
+#define FE_GAME_H
+#include "fe.h"
+#include "story.h"
+
+#include "bg.h"
+
+extern bool game_running;
+extern uint32_t game_ticks;
+extern float frame_time_mod; /* the last frame's length in ticks, 1 to 2 */
+extern BgEdges city_edges; /* City.getCityEdges, kept up to date for the clouds and the camera */
+void game_init(void);
+void game_start(int story, const NewCityOptions *opt);
+void game_after_load(void); /* a save was read: its sky, clouds and view */
+void game_tick(void);
+void game_draw(void);
+#endif
diff --git a/games/finalearth2/src/gfx.c b/games/finalearth2/src/gfx.c
new file mode 100644
index 00000000..8e676c86
--- /dev/null
+++ b/games/finalearth2/src/gfx.c
@@ -0,0 +1,821 @@
+/* The renderer: a draw list rasterised in bands of GFX_BAND rows.
+ *
+ * Sprites are drawn straight from data.bin (tools/pack.py says how they are
+ * coded): each band walks the rows of the commands that cross it. Alpha has 33
+ * levels (the colour's own alpha times the command's), blended in RGB565. */
+#include "gfx.h"
+#include <string.h>
+#include "data.h"
+
+enum { K_RECT, K_SPRITE, K_TEXT, K_CALL };
+typedef struct {
+ int16_t x, y; /* top-left on screen */
+ int16_t sx, sy, w, h; /* sprite: its part; rect: w, h; text: font, top, width, height */
+ uint16_t ref; /* sprite, text (offset in the pool), band function (slot) */
+ uint16_t color; /* rect and text colour, sprite tint */
+ uint8_t kind; /* K_* | zoom << 4 */
+ uint8_t flags, alpha, clip;
+} Item;
+
+#define MAX_CLIPS 48
+#define MAX_CALLS 64
+typedef struct { int16_t x0, y0, x1, y1; } Clip;
+
+#ifdef HOST
+static uint16_t host_band[SCREEN_W * GFX_BAND];
+static uint16_t *band = host_band;
+#else
+static uint16_t *band;
+#endif
+void gfx_set_band_memory(uint16_t *px) {
+#ifdef HOST
+ band = px ? px : host_band;
+#else
+ band = px;
+#endif
+}
+static Item items[GFX_MAX_ITEMS];
+static char text_pool[GFX_TEXT_POOL];
+static Clip clips[MAX_CLIPS];
+static struct { GfxBandFn fn; void *ctx; } calls[MAX_CALLS];
+static int nitems, ntext, nclips, ncalls, zoom = 1, dropped, last_items, last_dropped;
+static bool clip_used; /* a command uses the last clip */
+static bool clips_full; /* no clip left: commands are dropped until the next frame */
+
+/* ---------------------------------------------------------------- data.bin */
+static inline uint32_t rd16(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8; }
+static inline uint32_t rd32(const uint8_t *p) { return rd16(p) | rd16(p + 2) << 16; }
+static inline uint32_t nsprites(void) { return rd16(fe_data + 4); }
+static inline const uint8_t *spr_rec(uint16_t spr) { return fe_data + rd32(fe_data + 8) + 8u * spr; }
+int spr_w(uint16_t spr) { return spr < nsprites() ? (int)rd16(spr_rec(spr) + 4) : 0; }
+int spr_h(uint16_t spr) { return spr < nsprites() ? (int)rd16(spr_rec(spr) + 6) : 0; }
+
+typedef struct {
+ const uint8_t *d; /* its data */
+ const uint16_t *pal; /* RGB565 of each colour */
+ const uint8_t *alpha; /* alpha (0..255) of each colour */
+ const uint8_t *slabs; /* per slab: u16 x0, u16 x1, u32 offset of its rows */
+ uint8_t mode; /* 0 4-bit, 1 8-bit, 2 direct */
+ bool big; /* u32 row offsets */
+ int ncol, nslab, w, h;
+} Spr;
+
+static void spr_open(uint16_t spr, Spr *s) {
+ const uint8_t *r = spr_rec(spr);
+ const uint8_t *d = fe_data + rd32(r);
+ s->d = d;
+ s->w = (int)rd16(r + 4);
+ s->h = (int)rd16(r + 6);
+ s->ncol = d[0];
+ s->mode = d[1] & 3;
+ s->big = d[1] & 4;
+ s->nslab = d[2];
+ s->pal = (const uint16_t *)(const void *)(d + 4);
+ s->alpha = d + 4 + 2 * s->ncol;
+ s->slabs = d + ((4 + 3 * (uint32_t)s->ncol + 3) & ~3u);
+}
+
+/* row r of slab k: its tokens, from *p to *end */
+static inline void slab_row(const Spr *s, int k, int r, const uint8_t **p, const uint8_t **end) {
+ const uint8_t *sl = s->d + rd32(s->slabs + 8 * k + 4);
+ uint32_t a, b;
+ if (s->big) {
+ a = ((const uint32_t *)(const void *)sl)[r];
+ b = ((const uint32_t *)(const void *)sl)[r + 1];
+ sl += 4 * (s->h + 1);
+ } else {
+ a = ((const uint16_t *)(const void *)sl)[r];
+ b = ((const uint16_t *)(const void *)sl)[r + 1];
+ sl += 2 * (s->h + 1);
+ }
+ *p = sl + a;
+ *end = sl + b;
+}
+
+/* ---------------------------------------------------------------- pixels */
+typedef uint32_t __attribute__((may_alias)) u32a;
+
+/* a colour times a tint, channel by channel (PIXI's tint) */
+static inline uint16_t tinted(uint16_t c, uint16_t t) {
+ uint32_t r = ((c >> 11) * (t >> 11) + 15) / 31, g = ((c >> 5 & 63) * (t >> 5 & 63) + 31) / 63,
+ b = ((c & 31) * (t & 31) + 15) / 31;
+ return (uint16_t)(r << 11 | g << 5 | b);
+}
+
+/* a colour's alpha (0..255) times the command's (ia: its alpha times 129) as 0..32 */
+static inline uint32_t mix_alpha(uint32_t a8, uint32_t ia) { return (a8 * ia + 131072) >> 18; }
+
+/* screen pixels [d0, d1) of a row in one colour */
+static inline void span(uint16_t *row, int d0, int d1, uint16_t c, uint32_t a5) {
+ uint16_t *p = row + d0, *e = row + d1;
+ if (a5 >= 32) {
+ if (((uintptr_t)p & 2) && p < e) *p++ = c;
+ uint32_t two = c | (uint32_t)c << 16;
+ u32a *w = (u32a *)(void *)p;
+ for (; p + 8 <= e; p += 8, w += 4) w[0] = w[1] = w[2] = w[3] = two;
+ for (; p + 2 <= e; p += 2) *w++ = two;
+ if (p < e) *p = c;
+ } else if (a5) {
+ uint32_t f = ((c | (uint32_t)c << 16) & 0x07E0F81Fu) * a5 + 0x02008010u, inv = 32 - a5;
+ for (; p < e; p++) {
+ uint32_t g = (*p | (uint32_t)*p << 16) & 0x07E0F81Fu;
+ uint32_t r = ((f + g * inv) >> 5) & 0x07E0F81Fu;
+ *p = (uint16_t)(r | r >> 16);
+ }
+ }
+}
+
+/* how the rows of a sprite's part are drawn */
+typedef struct {
+ uint16_t *row; /* the band row (indexed by screen x) */
+ int lo, hi; /* the source columns that show */
+ int base, step; /* screen x of source column p's left: base + p * step (step: the zoom, negative flipped) */
+ int z, cx0, cx1;
+ uint32_t ia; /* the command's alpha times 129 */
+ bool solid; /* the command's alpha is 255 */
+ bool plain; /* zoom 1, not flipped, opaque, not tinted: the fast way */
+ uint16_t tint;
+ const uint16_t *pal;
+ const uint8_t *alpha;
+ uint16_t col[16]; /* 4-bit sprites: each colour, tinted */
+ uint8_t a5[16]; /* and its alpha with the command's, 0..32 */
+} Blit;
+
+static inline void put_px(const Blit *c, uint16_t *d, uint16_t col, uint32_t a5) {
+ if (c->z == 1) {
+ *d = a5 >= 32 ? col : gfx_blend(col, *d, a5);
+ return;
+ }
+ for (int k = 0; k < 2; k++) { /* zoom 2: the pair can be half outside the clip */
+ int x = (int)(d + k - c->row);
+ if (x >= c->cx0 && x < c->cx1) d[k] = a5 >= 32 ? col : gfx_blend(col, d[k], a5);
+ }
+}
+
+/* source columns [a, b) in one colour */
+static inline void put_fill(const Blit *c, int a, int b, uint16_t col, uint32_t a5) {
+ if (a < c->lo) a = c->lo;
+ if (b > c->hi) b = c->hi;
+ if (a >= b || !a5) return;
+ int d0, d1;
+ if (c->step > 0) {
+ d0 = c->base + a * c->step;
+ d1 = c->base + b * c->step;
+ } else {
+ d0 = c->base + (b - 1) * c->step;
+ d1 = c->base + a * c->step + c->z;
+ }
+ if (d0 < c->cx0) d0 = c->cx0;
+ if (d1 > c->cx1) d1 = c->cx1;
+ if (d0 < d1) span(c->row, d0, d1, col, a5);
+}
+
+/* the length of a token (4-bit sprites) */
+static inline int tok4(const uint8_t *p, int *size) {
+ uint32_t t = *p;
+ if (t < 0x40) return *size = 1, (int)t + 1;
+ if (t < 0x80) return *size = 1 + (int)((t & 63) + 2) / 2, (int)(t & 63) + 1;
+ if (t < 0xF0) return *size = 1, (int)(t >> 4) - 7;
+ return *size = 2, (int)p[1] + 8;
+}
+
+/* one pixel of a plain command (zoom 1, not flipped, opaque, not tinted) */
+static inline void plain_px(uint16_t *d, uint16_t col, uint32_t a8) {
+ if (a8 == 255) *d = col;
+ else if (a8) *d = gfx_blend(col, *d, mix_alpha(a8, 255 * 129));
+}
+
+/* rows of a plain command (zoom 1, not flipped, opaque, not tinted), 4-bit, u16 row offsets:
+ * rows r to r + nrows - 1 of a slab starting at column x0; row[x] is source column x on the
+ * first screen row */
+__attribute__((noinline)) static void plain4(uint16_t *row, const uint16_t *pal, const uint8_t *al,
+ const uint16_t *offs, const uint8_t *data, int r, int nrows, int x0,
+ int lo, int hi) {
+ for (; nrows--; r++, row += SCREEN_W) {
+ const uint8_t *p = data + offs[r], *end = data + offs[r + 1];
+ int size, n, x = x0;
+ while (p < end && x + (n = tok4(p, &size)) <= lo) x += n, p += size; /* left of what shows */
+ while (p < end && x < hi) {
+ uint32_t t = *p++;
+ if (t < 0x40) {
+ x += (int)t + 1;
+ } else if (t < 0x80) {
+ n = (int)(t & 63) + 1;
+ const uint8_t *q = p;
+ p += (n + 1) >> 1;
+ int k = x < lo ? lo - x : 0, k1 = x + n > hi ? hi - x : n;
+ uint16_t *d = row + x + k;
+ if (k & 1) {
+ uint32_t i = q[k >> 1] >> 4;
+ plain_px(d++, pal[i], al[i]);
+ k++;
+ }
+ for (q += k >> 1; k + 1 < k1; k += 2, d += 2) {
+ uint32_t v = *q++, i0 = v & 15, i1 = v >> 4, a0 = al[i0], a1 = al[i1];
+ if (a0 == 255) d[0] = pal[i0];
+ else plain_px(d, pal[i0], a0);
+ if (a1 == 255) d[1] = pal[i1];
+ else plain_px(d + 1, pal[i1], a1);
+ }
+ if (k < k1) plain_px(d, pal[*q & 15], al[*q & 15]);
+ x += n;
+ } else {
+ uint32_t i = t & 15, a8 = al[i];
+ n = t < 0xF0 ? (int)(t >> 4) - 7 : *p++ + 8;
+ int a = x > lo ? x : lo, b = x + n < hi ? x + n : hi;
+ if (a8 == 255 && b - a <= 8) {
+ uint16_t col = pal[i], *d = row + a, *e = row + b;
+ while (d < e) *d++ = col;
+ } else {
+ span(row, a, b, pal[i], a8 == 255 ? 32 : mix_alpha(a8, 255 * 129));
+ }
+ x += n;
+ }
+ }
+ }
+}
+
+static void row4(const Blit *c, const uint8_t *p, const uint8_t *end, int x) {
+ int size, n;
+ while (p < end && x + (n = tok4(p, &size)) <= c->lo) x += n, p += size;
+ while (p < end && x < c->hi) {
+ uint32_t t = *p;
+ n = tok4(p, &size);
+ if (t >= 0x80) {
+ uint32_t i = t & 15;
+ put_fill(c, x, x + n, c->col[i], c->a5[i]);
+ } else if (t >= 0x40) {
+ const uint8_t *lit = p + 1;
+ int a = x > c->lo ? x : c->lo, b = x + n < c->hi ? x + n : c->hi;
+ uint16_t *d = c->row + c->base + a * c->step;
+ for (int k = a - x; k < b - x; k++, d += c->step) {
+ uint32_t i = lit[k >> 1] >> ((k & 1) << 2) & 15;
+ if (c->a5[i]) put_px(c, d, c->col[i], c->a5[i]);
+ }
+ }
+ x += n;
+ p += size;
+ }
+}
+
+static inline int tok8(const uint8_t *p, int *size) {
+ uint32_t t = *p;
+ if (t < 0x40) return *size = 1, (int)t + 1;
+ if (t < 0x80) return *size = 1 + (int)(t & 63) + 1, (int)(t & 63) + 1;
+ return *size = 2, (int)(t & 127) + 1;
+}
+
+static void row8(const Blit *c, const uint8_t *p, const uint8_t *end, int x) {
+ int size, n;
+ while (p < end && x + (n = tok8(p, &size)) <= c->lo) x += n, p += size;
+ while (p < end && x < c->hi) {
+ uint32_t t = *p;
+ n = tok8(p, &size);
+ if (t >= 0x80) {
+ uint32_t i = p[1], a8 = c->alpha[i];
+ uint16_t col = c->tint != GFX_NO_TINT ? tinted(c->pal[i], c->tint) : c->pal[i];
+ put_fill(c, x, x + n, col, c->solid && a8 == 255 ? 32 : mix_alpha(a8, c->ia));
+ } else if (t >= 0x40) {
+ const uint8_t *lit = p + 1;
+ int a = x > c->lo ? x : c->lo, b = x + n < c->hi ? x + n : c->hi;
+ uint16_t *d = c->row + c->base + a * c->step;
+ if (c->plain) {
+ for (int k = a - x; k < b - x; k++, d++) plain_px(d, c->pal[lit[k]], c->alpha[lit[k]]);
+ } else {
+ for (int k = a - x; k < b - x; k++, d += c->step) {
+ uint32_t i = lit[k], a8 = c->alpha[i], a5 = c->solid && a8 == 255 ? 32 : mix_alpha(a8, c->ia);
+ if (!a5) continue;
+ put_px(c, d, c->tint != GFX_NO_TINT ? tinted(c->pal[i], c->tint) : c->pal[i], a5);
+ }
+ }
+ }
+ x += n;
+ p += size;
+ }
+}
+
+/* direct colours (the colour picker's circle) */
+static void row16(const Blit *c, const uint8_t *p, const uint8_t *end, int x) {
+ while (p < end && x < c->hi) {
+ uint32_t t = *p++;
+ int n = (int)(t & 63) + 1;
+ if (t < 0x40) {
+ x += n;
+ } else if (t < 0x80 || t >= 0xC0) {
+ int step = t < 0x80 ? 2 : 3, a = x > c->lo ? x : c->lo, b = x + n < c->hi ? x + n : c->hi;
+ uint16_t *d = c->row + c->base + a * c->step;
+ for (int k = a - x; k < b - x; k++, d += c->step) {
+ uint32_t a8 = step == 2 ? 255 : p[step * k + 2], a5 = c->solid && a8 == 255 ? 32 : mix_alpha(a8, c->ia);
+ uint16_t col = (uint16_t)rd16(p + step * k);
+ if (a5) put_px(c, d, c->tint != GFX_NO_TINT ? tinted(col, c->tint) : col, a5);
+ }
+ p += step * n;
+ x += n;
+ } else {
+ uint16_t col = (uint16_t)rd16(p);
+ put_fill(c, x, x + n, c->tint != GFX_NO_TINT ? tinted(col, c->tint) : col, c->solid ? 32 : mix_alpha(255, c->ia));
+ p += 2;
+ x += n;
+ }
+ }
+}
+
+/* a sprite's part drawn into rows y0..y1 - 1 of the band (screen rows by0..), clipped to cx0..cx1 */
+static void draw_sprite(uint16_t *buf, int by0, int y0, int y1, int cx0, int cx1, uint16_t spr, int sx, int sy,
+ int w, int h, int x, int y, int z, uint8_t flags, uint8_t alpha, uint16_t tint) {
+ if (spr >= nsprites() || !alpha) return;
+ Spr s;
+ spr_open(spr, &s);
+ bool flip = flags & GFX_FLIPX;
+ /* the part, inside the sprite */
+ if (sx < 0) { x += flip ? 0 : -sx * z; w += sx; sx = 0; }
+ if (sy < 0) { y -= sy * z; h += sy; sy = 0; }
+ if (sx + w > s.w) { if (flip) x += (sx + w - s.w) * z; w = s.w - sx; }
+ if (sy + h > s.h) h = s.h - sy;
+ if (w <= 0 || h <= 0) return;
+ if (y0 < y) y0 = y;
+ if (y1 > y + h * z) y1 = y + h * z;
+ if (cx0 < x) cx0 = x;
+ if (cx1 > x + w * z) cx1 = x + w * z;
+ if (y0 >= y1 || cx0 >= cx1) return;
+ Blit c;
+ c.z = z;
+ c.cx0 = cx0;
+ c.cx1 = cx1;
+ c.ia = alpha * 129u;
+ c.solid = alpha == 255;
+ c.tint = tint;
+ c.pal = s.pal;
+ c.alpha = s.alpha;
+ int q0 = (cx0 - x) / z, q1 = (cx1 - x + z - 1) / z; /* the part's columns that show, from its left on screen */
+ if (flip) {
+ c.lo = sx + w - q1;
+ c.hi = sx + w - q0;
+ c.base = x + (sx + w - 1) * z;
+ c.step = -z;
+ } else {
+ c.lo = sx + q0;
+ c.hi = sx + q1;
+ c.base = x - sx * z;
+ c.step = z;
+ }
+ c.plain = z == 1 && !flip && c.solid && tint == GFX_NO_TINT;
+ if (s.mode == 0 && !c.plain) {
+ for (int i = 0; i < s.ncol; i++) {
+ uint32_t a8 = s.alpha[i];
+ c.a5[i] = (uint8_t)(c.solid && a8 == 255 ? 32 : mix_alpha(a8, c.ia));
+ c.col[i] = tint != GFX_NO_TINT ? tinted(s.pal[i], tint) : s.pal[i];
+ }
+ }
+ /* the slabs that show */
+ int k0 = 0, k1 = s.nslab;
+ for (int hi = k1; k0 < hi;) { /* the first that ends right of lo */
+ int m = (k0 + hi) >> 1;
+ if ((int)rd16(s.slabs + 8 * m + 2) <= c.lo) k0 = m + 1;
+ else hi = m;
+ }
+ while (k1 > k0 && (int)rd16(s.slabs + 8 * (k1 - 1)) >= c.hi) k1--;
+ if (c.plain && s.mode == 0 && !s.big) {
+ for (int k = k0; k < k1; k++) {
+ const uint8_t *sl = s.d + rd32(s.slabs + 8 * k + 4);
+ plain4(buf + (y0 - by0) * SCREEN_W + c.base, c.pal, c.alpha, (const uint16_t *)(const void *)sl,
+ sl + 2 * (s.h + 1), sy + (y0 - y), y1 - y0, (int)rd16(s.slabs + 8 * k), c.lo, c.hi);
+ }
+ return;
+ }
+ for (int yy = y0; yy < y1; yy++) {
+ c.row = buf + (yy - by0) * SCREEN_W;
+ int r = sy + (yy - y) / z;
+ for (int k = k0; k < k1; k++) {
+ const uint8_t *p, *end;
+ slab_row(&s, k, r, &p, &end);
+ int x0 = (int)rd16(s.slabs + 8 * k);
+ if (s.mode == 0) row4(&c, p, end, x0);
+ else if (s.mode == 1) row8(&c, p, end, x0);
+ else row16(&c, p, end, x0);
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- fonts */
+typedef struct {
+ uint8_t line_h, nglyphs;
+ uint16_t nkern;
+ const uint8_t *glyphs, *kern, *bits;
+} Font;
+
+static bool font_open(uint8_t f, Font *ft) {
+ if (f >= rd16(fe_data + 6)) return false;
+ const uint8_t *d = fe_data + rd32(fe_data + rd32(fe_data + 12) + 4u * f);
+ ft->line_h = d[0];
+ ft->nglyphs = d[1];
+ ft->nkern = (uint16_t)rd16(d + 2);
+ ft->glyphs = d + 8;
+ ft->kern = ft->glyphs + 8u * ft->nglyphs;
+ ft->bits = d + rd32(d + 4);
+ return true;
+}
+
+/* the next character of a UTF-8 string as a glyph index (-1: not in the fonts, -2: a new line) */
+static int next_glyph(const char **sp) {
+ const uint8_t *s = (const uint8_t *)*sp;
+ uint32_t c = *s++;
+ if (c >= 0xC0) {
+ int more = c >= 0xF0 ? 3 : c >= 0xE0 ? 2 : 1;
+ c &= 0x3F >> more;
+ while (more-- && (*s & 0xC0) == 0x80) c = c << 6 | (*s++ & 0x3F);
+ }
+ *sp = (const char *)s;
+ if (c == '\n') return -2;
+ if (c >= 32 && c < 127) return (int)c - 32;
+ switch (c) {
+ case 0xDF: return 95; /* the order of pack.py's EXTRA_CHARS */
+ case 0xE9: return 96;
+ case 0xEB: return 97;
+ case 0xFC: return 98;
+ }
+ return -1;
+}
+
+static int kerning(const Font *f, int prev, int g) {
+ int lo = 0, hi = f->nkern - 1;
+ while (lo <= hi) { /* pairs sorted by second, then first */
+ int m = (lo + hi) >> 1;
+ const uint8_t *k = f->kern + 4 * m;
+ int d = k[1] != g ? k[1] - g : k[0] - prev;
+ if (!d) return (int8_t)k[2];
+ if (d < 0) lo = m + 1;
+ else hi = m - 1;
+ }
+ return 0;
+}
+
+/* lays out a string; draw: also draws its glyphs that cross band rows y0..y1 - 1 */
+typedef struct {
+ uint16_t *buf;
+ int by0, y0, y1, cx0, cx1;
+ uint16_t color;
+ uint32_t a5;
+ bool rot; /* turned a quarter clockwise: text x goes down the screen, text y left */
+} TextDraw;
+
+/* one pixel of a glyph, at text position (tx, ty) from the origin (x, y) */
+static inline void text_px(const TextDraw *td, int x, int y, int tx, int ty) {
+ int sx = td->rot ? x - ty : x + tx, sy = td->rot ? y + tx : y + ty;
+ if (sy < td->y0 || sy >= td->y1 || sx < td->cx0 || sx >= td->cx1) return;
+ uint16_t *d = td->buf + (sy - td->by0) * SCREEN_W + sx;
+ *d = td->a5 >= 32 ? td->color : gfx_blend(td->color, *d, td->a5);
+}
+
+/* end: where the string stops (NULL: at its 0) */
+static int text_layout(const Font *f, int x, int y, int z, const char *s, const char *end, const TextDraw *td, int *top,
+ int *bottom) {
+ int pen = 0, line = 0, widest = 0, prev = -1, t = 1 << 30, b = -(1 << 30);
+ while (*s && (!end || s < end)) {
+ int g = next_glyph(&s);
+ if (g == -2) {
+ if (pen > widest) widest = pen;
+ pen = 0;
+ line++;
+ prev = -1;
+ continue;
+ }
+ if (g < 0 || g >= f->nglyphs) continue;
+ const uint8_t *gl = f->glyphs + 8 * g;
+ if (prev >= 0 && f->nkern) pen += kerning(f, prev, g);
+ int gx = pen + (int8_t)gl[2], gy = line * f->line_h + (int8_t)gl[3], gw = gl[4], gh = gl[5];
+ if (gw && gh) {
+ if (gy < t) t = gy;
+ if (gy + gh > b) b = gy + gh;
+ }
+ if (td && td->rot && gw && gh) {
+ int first = (int)rd16(gl);
+ for (int r = 0; r < gh; r++)
+ for (int k = 0, bit = first + r * gw; k < gw; k++, bit++)
+ if (f->bits[bit >> 3] >> (bit & 7) & 1) text_px(td, x, y, gx + k, gy + r);
+ } else if (td && gw && gh) {
+ int sy0 = y + gy * z, first = (int)rd16(gl);
+ int r0 = td->y0 > sy0 ? (td->y0 - sy0) / z : 0, r1 = (td->y1 - sy0 + z - 1) / z;
+ if (r1 > gh) r1 = gh;
+ for (int r = r0; r < r1; r++) {
+ int bit = first + r * gw;
+ for (int k = 0; k < gw; k++, bit++) {
+ if (!(f->bits[bit >> 3] >> (bit & 7) & 1)) continue;
+ for (int dy = 0; dy < z; dy++) {
+ int sy = sy0 + r * z + dy;
+ if (sy < td->y0 || sy >= td->y1) continue;
+ uint16_t *row = td->buf + (sy - td->by0) * SCREEN_W;
+ for (int dx = 0; dx < z; dx++) {
+ int sx = x + (gx + k) * z + dx;
+ if (sx < td->cx0 || sx >= td->cx1) continue;
+ row[sx] = td->a5 >= 32 ? td->color : gfx_blend(td->color, row[sx], td->a5);
+ }
+ }
+ }
+ }
+ }
+ pen += gl[6];
+ prev = g;
+ }
+ if (pen > widest) widest = pen;
+ if (top) *top = t > b ? 0 : t;
+ if (bottom) *bottom = t > b ? 0 : b;
+ return widest;
+}
+
+int gfx_font_height(uint8_t font) {
+ Font f;
+ return font_open(font, &f) ? f.line_h : 0;
+}
+
+int gfx_text_width(uint8_t font, const char *s) {
+ Font f;
+ return font_open(font, &f) && s ? text_layout(&f, 0, 0, 1, s, NULL, NULL, NULL, NULL) : 0;
+}
+
+int gfx_text_width_n(uint8_t font, const char *s, int n) {
+ Font f;
+ return font_open(font, &f) && s ? text_layout(&f, 0, 0, 1, s, s + n, NULL, NULL, NULL) : 0;
+}
+
+/* PIXI's BitmapText wrapping (maxWidth): a line breaks at its last white space once the pen passes
+ * max_w; a word longer than max_w stays whole */
+int gfx_text_wrap(uint8_t font, const char *s, int max_w, int *line_w, const char **next) {
+ Font f;
+ const char *p = s;
+ int pen = 0, prev = -1, brk = -1, brk_w = 0;
+ if (!font_open(font, &f)) {
+ *line_w = 0;
+ *next = s + strlen(s);
+ return (int)(*next - s);
+ }
+ while (*p) {
+ const char *c = p;
+ if (*c == ' ' || *c == '\t') brk = (int)(c - s), brk_w = pen;
+ int g = next_glyph(&p);
+ if (g == -2) {
+ *line_w = pen;
+ *next = p;
+ return (int)(c - s);
+ }
+ if (g < 0 || g >= f.nglyphs) continue;
+ if (prev >= 0 && f.nkern) pen += kerning(&f, prev, g);
+ pen += f.glyphs[8 * g + 6];
+ prev = g;
+ if (brk >= 0 && max_w > 0 && pen > max_w) {
+ *line_w = brk_w;
+ *next = s + brk + 1;
+ return brk;
+ }
+ }
+ *line_w = p > s && (p[-1] == ' ' || p[-1] == '\t') ? brk_w : pen;
+ *next = p;
+ return (int)(p - s);
+}
+
+void gfx_band_text(const GfxBand *b, uint8_t font, int x, int y, const char *s, int n, uint16_t color, uint8_t alpha,
+ bool rot) {
+ Font f;
+ if (!s || !alpha || b->cy0 >= b->cy1 || !font_open(font, &f)) return;
+ TextDraw td = {b->px, b->y0, b->cy0, b->cy1, b->cx0, b->cx1, color, gfx_alpha32(alpha), rot};
+ text_layout(&f, x, y, rot ? 1 : b->zoom, s, s + n, &td, NULL, NULL);
+}
+
+/* ---------------------------------------------------------------- the list */
+static Item *add(uint8_t kind) {
+ if (nitems >= GFX_MAX_ITEMS || clips_full) {
+ dropped++;
+ return NULL;
+ }
+ Item *it = &items[nitems++];
+ memset(it, 0, sizeof *it);
+ it->kind = (uint8_t)(kind | zoom << 4);
+ it->clip = (uint8_t)(nclips - 1);
+ it->alpha = 255;
+ it->color = GFX_NO_TINT;
+ clip_used = true;
+ return it;
+}
+
+void gfx_begin(void) {
+ last_items = nitems;
+ last_dropped = dropped;
+ nitems = ntext = ncalls = dropped = 0;
+ zoom = 1;
+ nclips = 1;
+ clips[0] = (Clip){0, 0, SCREEN_W, SCREEN_H};
+ clip_used = clips_full = false;
+}
+
+int gfx_items(void) { return last_items; }
+int gfx_dropped(void) { return last_dropped; }
+
+void gfx_zoom(int z) { zoom = z == 2 ? 2 : 1; }
+
+void gfx_clip(int x, int y, int w, int h) {
+ int x1 = x + w, y1 = y + h;
+ if (x < 0) x = 0;
+ if (y < 0) y = 0;
+ if (x1 > SCREEN_W) x1 = SCREEN_W;
+ if (y1 > SCREEN_H) y1 = SCREEN_H;
+ if (x1 < x) x1 = x;
+ if (y1 < y) y1 = y;
+ Clip c = {(int16_t)x, (int16_t)y, (int16_t)x1, (int16_t)y1};
+ if (!clip_used) {
+ clips[nclips - 1] = c; /* no command uses the last one yet */
+ return;
+ }
+ if (nclips >= MAX_CLIPS) {
+ clips_full = true;
+ return;
+ }
+ clips[nclips++] = c;
+ clip_used = false;
+}
+
+void gfx_fill(uint16_t color) {
+ const Clip *c = &clips[nclips - 1];
+ gfx_rect(c->x0, c->y0, c->x1 - c->x0, c->y1 - c->y0, color, 255);
+}
+
+void gfx_rect(int x, int y, int w, int h, uint16_t color, uint8_t alpha) {
+ if (w <= 0 || h <= 0 || !alpha) return;
+ Item *it = add(K_RECT);
+ if (!it) return;
+ it->kind = K_RECT; /* (rects are in screen pixels: no zoom) */
+ it->x = (int16_t)x;
+ it->y = (int16_t)y;
+ it->w = (int16_t)w;
+ it->h = (int16_t)h;
+ it->color = color;
+ it->alpha = alpha;
+}
+
+void gfx_sprite_ex(uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags, uint8_t alpha,
+ uint16_t tint) {
+ if (spr >= nsprites() || !alpha || w <= 0 || h <= 0) return;
+ if (x >= SCREEN_W || y >= SCREEN_H || x + w * zoom <= 0 || y + h * zoom <= 0) return;
+ Item *it = add(K_SPRITE);
+ if (!it) return;
+ it->ref = spr;
+ it->x = (int16_t)x;
+ it->y = (int16_t)y;
+ it->sx = (int16_t)sx;
+ it->sy = (int16_t)sy;
+ it->w = (int16_t)w;
+ it->h = (int16_t)h;
+ it->flags = flags;
+ it->alpha = alpha;
+ it->color = tint;
+}
+
+void gfx_sprite(uint16_t spr, int x, int y, uint8_t flags, uint8_t alpha) {
+ gfx_sprite_ex(spr, 0, 0, spr_w(spr), spr_h(spr), x, y, flags, alpha, GFX_NO_TINT);
+}
+
+void gfx_sprite_part(uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags, uint8_t alpha) {
+ gfx_sprite_ex(spr, sx, sy, w, h, x, y, flags, alpha, GFX_NO_TINT);
+}
+
+void gfx_sprite_tint(uint16_t spr, int x, int y, uint8_t flags, uint16_t tint) {
+ gfx_sprite_ex(spr, 0, 0, spr_w(spr), spr_h(spr), x, y, flags, 255, tint);
+}
+
+void gfx_frame(uint16_t spr, int fw, int i, int x, int y, uint8_t flags, uint8_t alpha) {
+ gfx_sprite_ex(spr, (fw + 2) * i, 0, fw, spr_h(spr), x, y, flags, alpha, GFX_NO_TINT);
+}
+
+int gfx_text_ex(uint8_t font, int x, int y, const char *s, uint16_t color, uint8_t alpha) {
+ Font f;
+ if (!s || !font_open(font, &f)) return 0;
+ int top, bottom;
+ int w = text_layout(&f, 0, 0, 1, s, NULL, NULL, &top, &bottom);
+ size_t n = strlen(s) + 1;
+ if (!alpha || bottom <= top) return w;
+ if (ntext + n > GFX_TEXT_POOL) {
+ dropped++;
+ return w;
+ }
+ Item *it = add(K_TEXT);
+ if (!it) return w;
+ memcpy(text_pool + ntext, s, n);
+ it->ref = (uint16_t)ntext;
+ ntext += (int)n;
+ it->x = (int16_t)x;
+ it->y = (int16_t)y;
+ it->sx = font;
+ it->sy = (int16_t)top;
+ it->w = (int16_t)w;
+ it->h = (int16_t)(bottom - top);
+ it->color = color;
+ it->alpha = alpha;
+ return w;
+}
+
+int gfx_text(uint8_t font, int x, int y, const char *s, uint16_t color) { return gfx_text_ex(font, x, y, s, color, 255); }
+
+void gfx_call(GfxBandFn fn, void *ctx, int y, int h) {
+ if (!fn || h <= 0) return;
+ if (ncalls >= MAX_CALLS) {
+ dropped++;
+ return;
+ }
+ Item *it = add(K_CALL);
+ if (!it) return;
+ calls[ncalls].fn = fn;
+ calls[ncalls].ctx = ctx;
+ it->ref = (uint16_t)ncalls++;
+ it->y = (int16_t)y;
+ it->h = (int16_t)h;
+}
+
+/* ---------------------------------------------------------------- band functions' helpers */
+void gfx_band_sprite(const GfxBand *b, uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags,
+ uint8_t alpha, uint16_t tint) {
+ int y0 = b->cy0, y1 = b->cy1;
+ if (y0 >= y1) return;
+ draw_sprite(b->px, b->y0, y0, y1, b->cx0, b->cx1, spr, sx, sy, w, h, x, y, b->zoom, flags, alpha, tint);
+}
+
+void gfx_band_span(const GfxBand *b, int y, int x0, int x1, uint16_t color, uint8_t alpha) {
+ if (y < b->cy0 || y >= b->cy1 || !alpha) return;
+ if (x0 < b->cx0) x0 = b->cx0;
+ if (x1 > b->cx1) x1 = b->cx1;
+ if (x0 < x1) span(b->px + (y - b->y0) * SCREEN_W, x0, x1, color, gfx_alpha32(alpha));
+}
+
+/* ---------------------------------------------------------------- rasterising */
+static void draw_item(const Item *it, int by0, int by1) {
+ const Clip *c = &clips[it->clip];
+ int z = it->kind >> 4, kind = it->kind & 15;
+ int y0 = by0 > c->y0 ? by0 : c->y0, y1 = by1 < c->y1 ? by1 : c->y1;
+ if (y0 >= y1 || c->x0 >= c->x1) return;
+ switch (kind) {
+ case K_RECT: {
+ int ry0 = it->y > y0 ? it->y : y0, ry1 = it->y + it->h < y1 ? it->y + it->h : y1;
+ int x0 = it->x > c->x0 ? it->x : c->x0, x1 = it->x + it->w < c->x1 ? it->x + it->w : c->x1;
+ if (x0 >= x1) return;
+ uint32_t a5 = gfx_alpha32(it->alpha);
+ for (int y = ry0; y < ry1; y++) span(band + (y - by0) * SCREEN_W, x0, x1, it->color, a5);
+ break;
+ }
+ case K_SPRITE:
+ draw_sprite(band, by0, y0, y1, c->x0, c->x1, it->ref, it->sx, it->sy, it->w, it->h, it->x, it->y, z, it->flags,
+ it->alpha, it->color);
+ break;
+ case K_TEXT: {
+ Font f;
+ if (!font_open((uint8_t)it->sx, &f)) return;
+ TextDraw td = {band, by0, y0, y1, c->x0, c->x1, it->color, gfx_alpha32(it->alpha), false};
+ text_layout(&f, it->x, it->y, z, text_pool + it->ref, NULL, &td, NULL, NULL);
+ break;
+ }
+ case K_CALL: {
+ int ry0 = it->y > y0 ? it->y : y0, ry1 = it->y + it->h < y1 ? it->y + it->h : y1;
+ if (ry0 >= ry1) return;
+ GfxBand b = {band, by0, by1, c->x0, ry0, c->x1, ry1, z};
+ calls[it->ref].fn(&b, calls[it->ref].ctx);
+ break;
+ }
+ }
+}
+
+/* the screen rows an item may touch */
+static void item_rows(const Item *it, int *y0, int *y1) {
+ int z = it->kind >> 4;
+ switch (it->kind & 15) {
+ case K_SPRITE:
+ *y0 = it->y;
+ *y1 = it->y + it->h * z;
+ break;
+ case K_TEXT: {
+ /* (each line's own top and bottom are inside the first's and the last's) */
+ *y0 = it->y + it->sy * z;
+ *y1 = it->y + (it->sy + it->h) * z;
+ break;
+ }
+ default:
+ *y0 = it->y;
+ *y1 = it->y + it->h;
+ }
+}
+
+void gfx_end(void) {
+ if (!band) return;
+ /* a first command that covers the whole screen needs no clearing first */
+ bool covered = nitems && (items[0].kind & 15) == K_RECT && items[0].alpha == 255 && items[0].x <= 0 &&
+ items[0].y <= 0 && items[0].x + items[0].w >= SCREEN_W && items[0].y + items[0].h >= SCREEN_H &&
+ clips[items[0].clip].x0 == 0 && clips[items[0].clip].y0 == 0 &&
+ clips[items[0].clip].x1 == SCREEN_W && clips[items[0].clip].y1 == SCREEN_H;
+ for (int by0 = 0; by0 < SCREEN_H; by0 += GFX_BAND) {
+ int by1 = by0 + GFX_BAND < SCREEN_H ? by0 + GFX_BAND : SCREEN_H;
+ if (!covered) memset(band, 0, sizeof(uint16_t) * SCREEN_W * GFX_BAND);
+ for (int i = 0; i < nitems; i++) {
+ int y0, y1;
+ item_rows(&items[i], &y0, &y1);
+ if (y1 <= by0 || y0 >= by1) continue;
+ draw_item(&items[i], by0, by1);
+ }
+ plat_push(0, by0, SCREEN_W, by1 - by0, band);
+ }
+}
diff --git a/games/finalearth2/src/gfx.h b/games/finalearth2/src/gfx.h
new file mode 100644
index 00000000..94151cb2
--- /dev/null
+++ b/games/finalearth2/src/gfx.h
@@ -0,0 +1,104 @@
+/* The Final Earth 2: drawing.
+ *
+ * A frame is a draw list, rasterised band by band (the calculator has no
+ * frame buffer) and pushed to the screen. Commands are in screen pixels and
+ * painted in the order given. */
+#ifndef FE_GFX_H
+#define FE_GFX_H
+#include <stdbool.h>
+#include <stdint.h>
+#include "plat.h"
+
+static inline uint16_t rgb565(uint32_t rgb) { /* 0xRRGGBB */
+ return (uint16_t)(((rgb >> 8) & 0xF800) | ((rgb >> 5) & 0x07E0) | ((rgb >> 3) & 0x001F));
+}
+/* the nearest RGB565 colour (the sprites' colours are packed this way) */
+static inline uint16_t rgb565_near(uint32_t rgb) {
+ uint32_t r = rgb >> 16 & 255, g = rgb >> 8 & 255, b = rgb & 255;
+ return (uint16_t)(((r * 31 + 127) / 255) << 11 | ((g * 63 + 127) / 255) << 5 | ((b * 31 + 127) / 255));
+}
+
+enum { GFX_FLIPX = 1 };
+#define GFX_NO_TINT 0xFFFF
+
+/* the memory the renderer keeps (gfx.c): the draw list, its text, clips and band functions
+ * (7.1 KB on the calculator); the band is the caller's (gfx_set_band_memory) */
+#define GFX_BAND 16 /* screen rows rasterised at a time */
+#define GFX_MAX_ITEMS 256 /* commands in a frame (more are dropped and counted) */
+#define GFX_TEXT_POOL 1024 /* bytes of text in a frame */
+
+/* where gfx_end rasterises: SCREEN_W * GFX_BAND pixels, only used while gfx_end runs (on the
+ * calculator gfx_end draws nothing until it is given; the computer's build has its own) */
+void gfx_set_band_memory(uint16_t *px);
+void gfx_begin(void); /* a new frame */
+void gfx_end(void); /* rasterise it and push it */
+/* the zoom of the commands that follow (1 or 2): a sprite pixel becomes z x z screen pixels;
+ * positions stay in screen pixels */
+void gfx_zoom(int z);
+/* later commands draw only inside this screen rectangle (gfx_clip(0, 0, SCREEN_W, SCREEN_H): all) */
+void gfx_clip(int x, int y, int w, int h);
+
+void gfx_fill(uint16_t color); /* the whole clip rectangle */
+void gfx_rect(int x, int y, int w, int h, uint16_t color, uint8_t alpha); /* alpha 0 (none) to 255 */
+/* a sprite of the atlas (SPR_* in data.h) with its top-left at (x, y) */
+void gfx_sprite(uint16_t spr, int x, int y, uint8_t flags, uint8_t alpha);
+/* the part (sx, sy, w, h) of a sprite (a strip of frames, a building's variant...) */
+void gfx_sprite_part(uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags, uint8_t alpha);
+/* the same sprite at many places, tinted (citizens, grass, stars...) */
+void gfx_sprite_tint(uint16_t spr, int x, int y, uint8_t flags, uint16_t tint);
+/* all of it at once: a part, flipped, see-through and tinted (GFX_NO_TINT: none); the tint
+ * multiplies each colour channel, as PIXI's tint does */
+void gfx_sprite_ex(uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags, uint8_t alpha,
+ uint16_t tint);
+/* frame i of a strip of frames fw pixels wide and 2 pixels apart (the original's
+ * Resources.getTexturesByWidth(name, fw)), full height */
+void gfx_frame(uint16_t spr, int fw, int i, int x, int y, uint8_t flags, uint8_t alpha);
+int spr_w(uint16_t spr);
+int spr_h(uint16_t spr);
+
+/* text in one of the original's fonts (FONT_* in data.h), its top-left at (x, y); returns its width.
+ * UTF-8; '\n' starts a new line. Letters are laid out as PIXI's BitmapText does (offsets,
+ * advances, kerning), and scaled by the zoom. */
+int gfx_text(uint8_t font, int x, int y, const char *s, uint16_t color);
+int gfx_text_ex(uint8_t font, int x, int y, const char *s, uint16_t color, uint8_t alpha);
+int gfx_text_width(uint8_t font, const char *s); /* of its widest line, at zoom 1 */
+int gfx_text_width_n(uint8_t font, const char *s, int n); /* of its first n bytes (one line) */
+/* the first line of s wrapped as PIXI's BitmapText wraps at max_w (0: no wrapping): returns its bytes,
+ * sets its width and where the next line starts */
+int gfx_text_wrap(uint8_t font, const char *s, int max_w, int *line_w, const char **next);
+int gfx_font_height(uint8_t font); /* the line height */
+
+/* Drawing of one's own (the sky's stars, the islands, the clouds): fn is called
+ * for each band that rows y to y + h - 1 cross, in its place in the list, and
+ * draws into the band. px[(sy - y0) * SCREEN_W + sx] is screen pixel (sx, sy),
+ * for rows y0 to y1 - 1; draw only inside cx0..cx1 - 1, cy0..cy1 - 1 (the
+ * clip rectangle in the band). zoom: gfx_zoom's when fn was added. Up to 64 a frame. */
+typedef struct {
+ uint16_t *px;
+ int y0, y1;
+ int cx0, cy0, cx1, cy1;
+ int zoom;
+} GfxBand;
+typedef void (*GfxBandFn)(const GfxBand *b, void *ctx);
+void gfx_call(GfxBandFn fn, void *ctx, int y, int h);
+/* for band functions: a sprite (at b's zoom) or a row's span, drawn into the band now */
+void gfx_band_sprite(const GfxBand *b, uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags,
+ uint8_t alpha, uint16_t tint);
+void gfx_band_span(const GfxBand *b, int y, int x0, int x1, uint16_t color, uint8_t alpha);
+/* n bytes of text drawn into the band now (rot: turned a quarter clockwise, its top-left at (x, y)) */
+void gfx_band_text(const GfxBand *b, uint8_t font, int x, int y, const char *s, int n, uint16_t color, uint8_t alpha,
+ bool rot);
+
+/* fg over bg with alpha a (0 to 32) */
+static inline uint16_t gfx_blend(uint16_t fg, uint16_t bg, uint32_t a) {
+ uint32_t f = (fg | (uint32_t)fg << 16) & 0x07E0F81Fu, g = (bg | (uint32_t)bg << 16) & 0x07E0F81Fu;
+ uint32_t r = ((f * a + g * (32 - a) + 0x02008010u) >> 5) & 0x07E0F81Fu;
+ return (uint16_t)(r | r >> 16);
+}
+/* alpha 0..255 as gfx_blend's 0..32 */
+static inline uint32_t gfx_alpha32(uint32_t a) { return (a * 32 + 127) / 255; }
+
+/* the last frame: commands drawn, and commands lost because the list or the text pool was full */
+int gfx_items(void);
+int gfx_dropped(void);
+#endif
diff --git a/games/finalearth2/src/icon.png b/games/finalearth2/src/icon.png
new file mode 100644
index 00000000..98d9f8ed
Binary files /dev/null and b/games/finalearth2/src/icon.png differ
diff --git a/games/finalearth2/src/input.c b/games/finalearth2/src/input.c
new file mode 100644
index 00000000..dc282421
--- /dev/null
+++ b/games/finalearth2/src/input.c
@@ -0,0 +1,32 @@
+/* The Final Earth 2: keys, as pressed this tick or held, with repeats. */
+#include "input.h"
+
+Input input;
+
+void input_update(void) {
+ uint32_t now = plat_keys();
+ int tk = plat_text_key();
+ input.text_key = (int8_t)(tk >= 0 && tk != input.text_held ? tk : -1);
+ input.text_held = (int8_t)tk;
+ if (input.typing) {
+ /* 4, 6, 8, 2 and 5 type digits (or letters), + and - their signs, not the arrows, OK and the zoom */
+ static const struct { int8_t tk; uint16_t k; } alias[] = {
+ {TK_FOUR, K_LEFT}, {TK_SIX, K_RIGHT}, {TK_EIGHT, K_UP}, {TK_TWO, K_DOWN}, {TK_FIVE, K_OK}, {TK_PLUS, K_PLUS},
+ {TK_MINUS, K_MINUS}};
+ for (unsigned i = 0; i < sizeof alias / sizeof alias[0]; i++)
+ if (tk == alias[i].tk) now &= ~(uint32_t)alias[i].k;
+ }
+ input.pressed = now & ~input.held;
+ input.released = input.held & ~now;
+ input.held = now;
+ input.repeat = input.pressed;
+ for (int i = 0; i < 16; i++) {
+ if (now & (1u << i)) {
+ input.held_ticks[i]++;
+ /* a held key repeats after 12 ticks, then every 3 */
+ if (input.held_ticks[i] > 12 && (input.held_ticks[i] - 12) % 3 == 0) input.repeat |= 1u << i;
+ } else {
+ input.held_ticks[i] = 0;
+ }
+ }
+}
diff --git a/games/finalearth2/src/input.h b/games/finalearth2/src/input.h
new file mode 100644
index 00000000..eca77ead
--- /dev/null
+++ b/games/finalearth2/src/input.h
@@ -0,0 +1,21 @@
+/* The Final Earth 2: keys, as pressed this tick or held, with repeats. */
+#ifndef FE_INPUT_H
+#define FE_INPUT_H
+#include "plat.h"
+
+typedef struct {
+ uint32_t held; /* K_* held now */
+ uint32_t pressed; /* went down this tick */
+ uint32_t repeat; /* pressed, or held long enough to repeat (arrows, + and -) */
+ uint32_t released;
+ uint16_t held_ticks[16];
+ int8_t text_key; /* a typing key that went down this tick (TK_*), -1 none */
+ int8_t text_held; /* the typing key held, -1 none */
+ bool typing; /* a text is being typed: the typing keys don't also act as the arrows, OK, + and - */
+} Input;
+extern Input input;
+void input_update(void);
+static inline bool key_pressed(uint32_t k) { return (input.pressed & k) != 0; }
+static inline bool key_repeat(uint32_t k) { return (input.repeat & k) != 0; }
+static inline bool key_held(uint32_t k) { return (input.held & k) != 0; }
+#endif
diff --git a/games/finalearth2/src/lang_data.c b/games/finalearth2/src/lang_data.c
new file mode 100644
index 00000000..753e19ac
--- /dev/null
+++ b/games/finalearth2/src/lang_data.c
@@ -0,0 +1,533 @@
+/* The Final Earth 2: the user interface's texts and build menu tables (made by tools/gen_lang.py
+ * from the original's lang_en.csv and data). Don't edit: edit the generator. */
+#include "lang_data.h"
+#include "classes.h"
+#include "data.h"
+
+const char L_age_and_education[] = "Age: [0]\nEducation: [1]";
+const char L_alien_ruins_description_1a[] = "Your explorers chopped some roots for 20 wood.";
+const char L_alien_ruins_description_1b[] = "Your explorers found a big rock containing 25 stone.";
+const char L_alien_ruins_description_1c[] = "Your explorers almost tripped over a huge heap of small pebbles. They gathered them for 22 stone.";
+const char L_alien_ruins_description_1d[] = "Your explorers found an alien refrigerator with 12 food in it. They then dismantled it for 5 machine parts.";
+const char L_alien_ruins_description_1e[] = "Your explorers laid eye on some orange rocks. They are good for 35 stone.";
+const char L_alien_ruins_description_2a[] = "Your explorers found a hidden supply of 40 strange purple wood.";
+const char L_alien_ruins_description_2b[] = "Your explorers cut down a huge pillar that stood in their way. It contained 35 stone.";
+const char L_alien_ruins_description_2c[] = "Your explorers dismantled a weird beeping device and gained 20 machine parts.";
+const char L_alien_ruins_description_2d[] = "Your explorers found a pile of cans with sweet-tasting luminous plants in it. The plants turned out to be quite nutritious, so your citizens can eat them for 42 food.";
+const char L_alien_ruins_description_2e[] = "Your explorers found some suspicious mushrooms. Very carefully, they tasted a bit. To everyone's surprise, they actually taste pretty good and you got 55 food.";
+const char L_alien_ruins_description_3a[] = "Your explorers found a wooden box filled with wires. The box was made of 10 wood and the wires work as 5 machine parts.";
+const char L_alien_ruins_description_3b[] = "Your explorers found a large pile with 17 wood.";
+const char L_alien_ruins_description_3c[] = "Your explorers cut down a large stone door and gained 15 stone.";
+const char L_alien_ruins_description_3d[] = "Your explorers found some berry bushes containing 22 food.";
+const char L_alien_ruins_description_3e[] = "Your explorers found a pile of gears. They work as seven machine parts.";
+const char L_alien_ruins_description_4a[] = "Your explorers found some paintings on a rock of a better way to farm. Farmers now get 5 more food from each harvest.";
+const char L_alien_ruins_description_4b[] = "Your explorers found a blueprint to build an alien house.";
+const char L_alien_ruins_description_4c[] = "Your explorers found a book containing information about alien factories. With this knowledge, machine parts factories now work 10% faster.";
+const char L_alien_ruins_description_4d[] = "Your explorers found a perfectly preserved alien brain in a jar. With knowledge about its structure, researchers in labs understand the human brain better and can gather knowledge 5% faster.";
+const char L_alien_ruins_description_4e[] = "Your explorers found a small device, that may have something to do with the inaccessible worlds.";
+const char L_alien_ruins_find_1a[] = "Overgrown";
+const char L_alien_ruins_find_1b[] = "Big Rock";
+const char L_alien_ruins_find_1c[] = "Small Pebbles";
+const char L_alien_ruins_find_1d[] = "Alien Refrigerator";
+const char L_alien_ruins_find_1e[] = "Orange Rocks";
+const char L_alien_ruins_find_2a[] = "Purple Wood";
+const char L_alien_ruins_find_2b[] = "Huge Pillar";
+const char L_alien_ruins_find_2c[] = "Beeping Device";
+const char L_alien_ruins_find_2d[] = "Canned Food";
+const char L_alien_ruins_find_2e[] = "Mushrooms";
+const char L_alien_ruins_find_3a[] = "Box with Wires";
+const char L_alien_ruins_find_3b[] = "Pile of Wood";
+const char L_alien_ruins_find_3c[] = "Large Stone Door";
+const char L_alien_ruins_find_3d[] = "Berry Bushes";
+const char L_alien_ruins_find_3e[] = "Gears";
+const char L_alien_ruins_find_4a[] = "Farming Rock Paintings";
+const char L_alien_ruins_find_4b[] = "Alien Housing Blueprint";
+const char L_alien_ruins_find_4c[] = "Alien Factories Information";
+const char L_alien_ruins_find_4d[] = "Alien Brain";
+const char L_alien_ruins_find_4e[] = "Strange Device";
+const char L_all[] = "All";
+const char L_all_building_modes[] = "All Building Modes";
+const char L_also_unlocks_new[] = "Also unlocks new buildings.";
+const char L_and[] = "and";
+const char L_are_n_children[] = "There are [0] children.";
+const char L_art[] = "Art";
+const char L_assign_more_to_speed_up[] = "Assign more workers to speed this up!";
+const char L_assign_workers[] = "Assign Workers";
+const char L_assign_workers_to_prepare[] = "Assign workers to prepare for a new festival!";
+const char L_auto_upgrade[] = "Auto-Upgrade";
+const char L_babies_born_normal[] = "Babies will be born at the normal rate.";
+const char L_back[] = "Back";
+const char L_back_to_title[] = "Back to Title";
+const char L_best_time[] = "Best time: [0]d [1]h [2]m";
+const char L_birth_control[] = "Birth Control";
+const char L_build_anywhere[] = "Build anywhere in a tower.";
+const char L_build_mode_destroy[] = "Destroy Mode";
+const char L_build_mode_destroy_explanation[] = "Quickly destroy buildings.";
+const char L_build_mode_destroyleavinghole[] = "Destroy, Leaving a Hole";
+const char L_build_mode_destroyleavinghole_explanation[] = "Destroy a building, then leave a hole instead of moving the buildings above downwards.";
+const char L_build_mode_insert[] = "Building mode: Insert";
+const char L_build_mode_multi[] = "Building mode: Multi";
+const char L_build_mode_multi_explanation[] = "Hold OK and move the cursor to quickly build multiple buildings of the same type.";
+const char L_build_mode_multi_replace[] = "Building mode: Multi Replace";
+const char L_build_mode_multi_replace_explanation[] = "Hold OK and move the cursor to quickly build or replace buildings.";
+const char L_build_mode_normal[] = "Building mode: Normal";
+const char L_build_mode_normal_explanation[] = "Build only on the ground and on top of buildings, or just below rooftop buildings. Press OK on a building for information and options.";
+const char L_build_mode_replace[] = "Building mode: Replace";
+const char L_build_mode_replace_explanation[] = "Easily replace existing buildings.";
+const char L_building_a_building[] = "Building [0]";
+const char L_building_mode_afford[] = "Set the building mode of as many buildings of this type as you can afford. There are [0].";
+const char L_building_mode_all_explain[] = "Set the building mode of all buildings of this type. There are [0].";
+const char L_building_mode_only_this[] = "Set the building mode of only this building.";
+const char L_building_modes[] = "Building Modes";
+const char L_building_prevented_strange_force[] = "A strange force prevents you from building there.";
+const char L_cant_afford[] = "You can't afford that!";
+const char L_cant_organize[] = "You can't organize a Music Festival right now!";
+const char L_center_on_house[] = "Center view on home";
+const char L_center_on_school[] = "Center view on school";
+const char L_center_on_work[] = "Center view on work";
+const char L_change_appearance_upgrade[] = "Change the appearance of this upgrade.";
+const char L_change_building_color[] = "Change Building Color";
+const char L_change_city_name[] = "Change City Name";
+const char L_change_door_color[] = "Change Door Color";
+const char L_change_game_speed_pc[] = "Press OK to change the game speed.\nPress shift and OK to select an advanced speed.";
+const char L_change_home_job[] = "Change Home/Job";
+const char L_change_home_school[] = "Change Home/School";
+const char L_change_variant[] = "Change Variant";
+const char L_choose_color[] = "Choose Color";
+const char L_citizen_gratefulness_bonus[] = "Citizen Gratefulness";
+const char L_citizen_passed_away[] = "Unfortunately, [0] passed away. :(";
+const char L_citizen_production_cost[] = "Your citizens produced [0] [1] yesterday and [2] today so far.";
+const char L_citizens_and_children[] = "There are [0] citizens, of whom [1] children.";
+const char L_citizens_by_age_explain[] = "The amount of citizens of each age is shown below.";
+const char L_citizens_unhappy[] = "Your citizens are very unhappy! They work much slower while they're unhappy, so it's a good idea to solve their problems.";
+const char L_citizens_unhappy_food[] = "Your citizens don't have enough food! This makes them very unhappy and they'll work slower. Try building more farms, assigning more workers to farms, or building farms closer to homes to reduce travel time. ";
+const char L_citizens_unhappy_key[] = "The Key needs your citizens to be at least moderately happy, otherwise they are slow and useless. You are advised to fix their problems, however ordinary.";
+const char L_citizens_unhappy_title[] = "Your citizens are unhappy!";
+const char L_citizens_work_at_speed[] = "With the current happiness, citizens work at [0]x their normal speed.";
+const char L_city_name[] = "City name";
+const char L_city_policies[] = "City Policies";
+const char L_city_upgrades[] = "City Upgrades";
+const char L_click_here_to_play[] = "Press OK to Play";
+const char L_close[] = "Close";
+const char L_color_code[] = "Color Code...";
+const char L_color_code_enter[] = "Enter a color code, like #FF00FF.";
+const char L_color_not_parsed[] = "We couldn't parse that color.";
+const char L_computer_chips[] = "Computer Chips";
+const char L_computer_chips_use[] = "Used to create smart machines.";
+const char L_confirm[] = "Confirm";
+const char L_continue[] = "Continue";
+const char L_credits[] = "Credits";
+const char L_credits_additional_sprites[] = "Additional Sprites: LukXD99";
+const char L_current_festival[] = "Current Festival";
+const char L_current_task[] = "Current Task";
+const char L_current_tasks[] = "Current Tasks";
+const char L_customize_free_play[] = "Customize Free Play";
+const char L_destroy[] = "Destroy";
+const char L_destroy_this_building[] = "Destroy This Building";
+const char L_double_speed[] = "Double Speed";
+const char L_duplicate_building[] = "Duplicate Building";
+const char L_education_happiness[] = "Education happiness:";
+const char L_education_level_0[] = "None";
+const char L_education_level_1[] = "Poor";
+const char L_education_level_2[] = "Weak";
+const char L_education_level_3[] = "Limited";
+const char L_education_level_4[] = "Moderate";
+const char L_education_level_5[] = "Fair";
+const char L_education_level_6[] = "Good";
+const char L_education_level_7[] = "Very Good";
+const char L_education_level_8[] = "Great";
+const char L_encourage_contraception[] = "Encourage Contraception";
+const char L_encourage_parenthood[] = "Encourage Parenthood";
+const char L_entertainment_happiness[] = "Entertainment happiness:";
+const char L_entertainment_information_multiple_wg_with_citizens[] = "Not all citizens can reach all entertainment buildings at the moment! This may affect your entertainment happiness.";
+const char L_exploration_nothing_found[] = "Your explorers haven't found anything here yet!";
+const char L_extra_resources[] = "Extra Resources";
+const char L_factory_operating_cost[] = "Your factories used [0] [1] yesterday and [2] today so far.";
+const char L_find_homeless[] = "Find Homeless Person";
+const char L_findings[] = "Findings";
+const char L_first_house_cheaper[] = "The first house is cheaper as you can use some scrap material from your ship.";
+const char L_follow_citizen[] = "Follow Citizen";
+const char L_following[] = "Following [0]";
+const char L_food[] = "food";
+const char L_food_description_1[] = "Your citizens need to eat!";
+const char L_food_description_2[] = "Adults eat about one food per day, children eat 1/2 food.";
+const char L_food_description_3[] = "Herbs reduce this by [0]/[1]%.";
+const char L_food_description_4[] = "Currently, [0] food is being consumed each day.";
+const char L_food_rationing_unhappiness[] = "Food rationing unhappiness:";
+const char L_food_shortage_unhappiness[] = "Food shortage unhappiness:";
+const char L_for_all_buildings[] = "for all buildings";
+const char L_for_citizen[] = "for [0]";
+const char L_for_n_buildings[] = "for [0] buildings";
+const char L_for_one_building[] = "for one building";
+const char L_for_this_building[] = "for this building";
+const char L_forest_instant_uproot[] = "Uproot";
+const char L_forest_instant_uproot_description[] = "Instantly destroy this forest.";
+const char L_forest_management[] = "Forest Management";
+const char L_forest_management_all[] = "Set the management mode for all forests";
+const char L_forest_management_only_this[] = "Only set the management mode for this forest.";
+const char L_forest_management_question_1[] = "What should woodcutters do with all forests?";
+const char L_forest_management_question_2[] = "What should woodcutters do with this forest?";
+const char L_forest_protect[] = "Protect";
+const char L_forest_protect_description_1[] = "Don't cut them down.";
+const char L_forest_protect_description_2[] = "Don't cut it down.";
+const char L_forest_regrow[] = "Cut Down and Regrow";
+const char L_forest_regrow_description_1[] = "Cut them down, then let them regrow.";
+const char L_forest_regrow_description_2[] = "Cut it down, then let it regrow.";
+const char L_forest_uproot[] = "Cut Down and Uproot";
+const char L_forest_uproot_description_1[] = "Cut them down to make room for other things.";
+const char L_forest_uproot_description_2[] = "Cut it down to make room for other things.";
+const char L_free_play[] = "Free Play";
+const char L_game_menu[] = "Game Menu";
+const char L_game_paused[] = "Game Paused";
+const char L_game_running[] = "Game Running";
+const char L_gaming[] = "Gaming";
+const char L_give_city_name[] = "Give your city a name!";
+const char L_glory_of_the_key[] = "Glory of the Key";
+const char L_graphene[] = "Graphene";
+const char L_graphene_use[] = "Extremely thin, yet among the strongest materials ever tested.";
+const char L_great_gather_stone[] = "Great! Now, let's gather 6 wood and 4 stone.";
+const char L_greatly_discourage_children[] = "Greatly Discourage Getting Children";
+const char L_half_speed[] = "Half Speed";
+const char L_happiness[] = "Happiness";
+const char L_happiness_explainer[] = "Happy citizens work faster. They also get more children.";
+const char L_hide_extra_info[] = "Hide extra city info & options.";
+const char L_high_end_restaurants[] = "Upscale Restaurants";
+const char L_highlight_buildings[] = "Highlight Buildings";
+const char L_highlighting[] = "Highlighting [0]";
+const char L_hint_hint[] = "Tip! If you ever forget what to do, just press OK on the ? here (press var to reach it).";
+const char L_home_happiness[] = "Home happiness:";
+const char L_homeless_n[] = "There are [0] homeless people.";
+const char L_homeless_one[] = "There's one homeless person.";
+const char L_house_n_cap_remaining[] = "There's [0] house capacity remaining.";
+const char L_houses_exactly_enough[] = "There are exactly enough homes for your citizens.";
+const char L_housing[] = "Housing";
+const char L_housing_information[] = "Housing Information";
+const char L_ignore_unhappy_citizens[] = "Ignore unhappy citizen warnings";
+const char L_increase_woodcutting_priority[] = "Increase the priority of woodcutting!";
+const char L_invalid_structure[] = "You can't destroy this building as that would result in an invalid structure.";
+const char L_invalid_structure_2[] = "You can't destroy this building and leave a hole as that would result in an invalid structure.";
+const char L_invite_not_enough_houses[] = "There are not enough houses to invite more people.";
+const char L_invite_people[] = "Invite Citizens";
+const char L_invite_people_description[] = "To invite [0] more people to your city, you must have enough houses for them and pay:";
+const char L_invite_people_done[] = "You can't find anyone who wants to be invited to your city anymore.";
+const char L_invite_people_success[] = "You invited [0] people! They'll arrive soon.";
+const char L_is_one_child[] = "There is one child";
+const char L_keypad_builder_hint[] = "Arrows move, OK builds here, Back picks another building.";
+const char L_keypad_caps[] = "Caps";
+const char L_keypad_credits_1[] = "Inspired by The Final Earth 2 by Florian van Strien.";
+const char L_keypad_credits_2[] = "Not affiliated with him.";
+const char L_keypad_credits_3[] = "The sprites, fonts and texts are his, from the original game.";
+const char L_keypad_credits_4[] = "Made by Mason Chen as part of NumPlay.";
+const char L_keypad_delete[] = "Delete";
+const char L_keypad_home_quit[] = "Press Home again to quit without saving.";
+const char L_keypad_load_failed[] = "The saved city could not be loaded.";
+const char L_keypad_menu_hint[] = "Left and right: buildings. Up and down: categories. OK: pick.";
+const char L_keypad_save_failed[] = "The city could not be saved: there is not enough room on the calculator.";
+const char L_keypad_save_failed_title[] = "Not Saved";
+const char L_keypad_saved[] = "The city was saved.";
+const char L_keypad_space[] = "Space";
+const char L_keypad_toolbox_hint[] = "Press toolbox to open the build menu.";
+const char L_keypad_typing_hint[] = "Type with alpha and the keys' letters (shift, alpha: capitals), or pick them here:";
+const char L_keypad_var_hint[] = "Press var to reach these buttons.";
+const char L_knowledge[] = "knowledge";
+const char L_knowledge_use[] = "Used for research.";
+const char L_last_saved[] = "Last saved [0] seconds ago.";
+const char L_libraries[] = "Libraries";
+const char L_limitedBuilding[] = "Limit: [0]";
+const char L_limited_per_citizens[] = "Limit: 1 per [0] citizens";
+const char L_luxury_housing[] = "Luxury Housing";
+const char L_machine_parts[] = "Machine Parts";
+const char L_machine_parts_use[] = "Used to build machines and advanced buildings.";
+const char L_main_goal[] = "Main Goal";
+const char L_malfunctioned_haunted_labs[] = "Malfunctioned Haunted Laboratories";
+const char L_management[] = "Management";
+const char L_mandatory_overtime_unhappiness[] = "Mandatory overtime unhappiness:";
+const char L_max[] = "Max";
+const char L_medical_happiness[] = "Medical happiness:";
+const char L_mines_warning[] = "Warning! You seem to have far more rock teleporters than stone mines. Rock teleporters only teleport rocks. They don't normally produce stone. You need stone mines to actually mine the meteroids.";
+const char L_mirror[] = "Mirror";
+const char L_more_babies_born[] = "More babies will be born, as long as the happiness is high enough.";
+const char L_more_happiness_info[] = "Press OK on the Happiness button near the bottom right for more information.";
+const char L_move[] = "Move";
+const char L_move_ruins_howto[] = "Press OK on an empty space on a world to move these alien ruins.";
+const char L_music_festival[] = "Music Festival";
+const char L_music_festival_boost[] = "Music Festival Boost";
+const char L_music_festival_doing[] = "Now entertaining your citizens with a great Music Festival!";
+const char L_music_festival_help[] = "A huge, awesome party that lasts for one day. Boosts the happiness of your citizens for a week. This can even make it go over 100.";
+const char L_music_festival_planned[] = "You planned an awesome Music Festival!";
+const char L_n_days[] = "[0] days";
+const char L_n_days_ago[] = "[0] days ago";
+const char L_n_hours[] = "[0] hours";
+const char L_n_minutes[] = "[0] minutes";
+const char L_n_pct_explored[] = "[0]% explored.";
+const char L_nature[] = "Nature";
+const char L_new_city[] = "New City";
+const char L_new_city_enthousiasm[] = "New city enthusiasm bonus:";
+const char L_next_scenario[] = "Next Scenario";
+const char L_night_clubs[] = "Night Clubs";
+const char L_no_basic_houses[] = "There are no basic Houses.";
+const char L_no_destroy_allowed[] = "Your citizens don't want to destroy buildings right now!";
+const char L_no_residents[] = "No Residents";
+const char L_no_special_policy[] = "No Special Policy";
+const char L_no_undo[] = "Please note this cannot be undone.";
+const char L_no_upgrades[] = "No upgrades available.";
+const char L_no_work_buildings[] = "There are no buildings with work yet!";
+const char L_no_workers[] = "No workers";
+const char L_normal_resources[] = "Normal Resources";
+const char L_normal_speed[] = "Normal Speed";
+const char L_not_enough_food[] = "You don't have enough food! The next [0] food you produce will be eaten instantly by hungry citizens.";
+const char L_ok_or_alpha[] = "Press OK (or alpha)";
+const char L_one[] = "One";
+const char L_one_day[] = "one day";
+const char L_one_hour[] = "one hour";
+const char L_one_minute[] = "one minute";
+const char L_onepointfive_speed[] = "1.5x Speed";
+const char L_only_show_unupgraded[] = "Hide Completed Upgrades";
+const char L_operating_cost[] = "Operating buildings cost [0] [1] yesterday and [2] today so far.";
+const char L_operating_cost_pd[] = "Operating cost/day:";
+const char L_organize_a_festival[] = "Organize a Festival";
+const char L_pct_grown[] = "[0]% grown.";
+const char L_pct_left[] = "[0]/[1] [2] left.";
+const char L_per_building[] = "per building";
+const char L_placing_a_decoration[] = "Placing [0]";
+const char L_planned_festival[] = "Planned Festival";
+const char L_planting_a_forest[] = "Planting [0]";
+const char L_played_before[] = "Played Before?";
+const char L_pop_by_age[] = "Population by Age";
+const char L_pop_limit[] = "Population Limit:";
+const char L_pop_limit_hint[] = "Your population will no longer grow once you reach this limit. Please note that increasing this may result in a low frame rate and/or severe lag!";
+const char L_pop_stabilize[] = "The population will roughly stabilize.";
+const char L_population[] = "Population";
+const char L_preparing[] = "Preparing...";
+const char L_prioritize[] = "Prioritize";
+const char L_prioritize_description_1[] = "Woodcutters will cut this forest first. Press OK to disable.";
+const char L_prioritize_description_2[] = "When prioritized, woodcutters will cut this forest first.";
+const char L_prioritized[] = "Prioritized";
+const char L_priority_text[] = " priority.";
+const char L_production[] = "Production";
+const char L_pubs_restaurants[] = "Pubs & Restaurants";
+const char L_quality[] = "Quality: [0]";
+const char L_rationing_halves_this[] = "Rationing halves this.";
+const char L_really_destroy[] = "Really Destroy?";
+const char L_really_uproot[] = "Really Uproot?";
+const char L_reduce_stone_mining_priority[] = "Reduce the priority of stone mining.";
+const char L_refined_metals[] = "Refined Metals";
+const char L_refined_metals_use[] = "Used to create advanced buildings and computer chips.";
+const char L_residents[] = "[0]/[1] residents";
+const char L_residents_of[] = "Residents of [0]";
+const char L_restart[] = "Restart";
+const char L_restart_scenario[] = "Restart Scenario";
+const char L_restart_scenario_question[] = "Restart Scenario?";
+const char L_rock_management_mine[] = "Mine";
+const char L_rock_management_mine_description_1[] = "Mine them.";
+const char L_rock_management_mine_description_2[] = "Mine the rock.";
+const char L_rock_management_protect_description_1[] = "Don't mine rocks; keep them as decoration.";
+const char L_rock_management_protect_description_2[] = "Don't mine the rock; keep it as decoration.";
+const char L_rock_management_question_1[] = "What should miners do with all rocks?";
+const char L_rock_management_question_2[] = "What should miners do with this rock?";
+const char L_rock_mining[] = "Rock Mining";
+const char L_rock_prioritized_description[] = "Stone miners will mine this rock first. Press OK to disable.";
+const char L_rock_prioritized_description_2[] = "When prioritized, stone miners will mine this rock first.";
+const char L_rocketFuel[] = "Rocket Fuel";
+const char L_rocketFuel_use[] = "Used for rocket missions.";
+const char L_save[] = "Save";
+const char L_sculptures[] = "Sculptures";
+const char L_secret_society_forbidden[] = "The Key wouldn't want that.";
+const char L_see_wood_here[] = "See your wood here.";
+const char L_select_any[] = "Select Any";
+const char L_sense_of_purpose[] = "Sense of purpose (job/school):";
+const char L_set_management_all_rocks[] = "Set the management mode for all rocks";
+const char L_set_management_rock[] = "Only set the management mode for this rock.";
+const char L_show_extra_info[] = "Show extra city info & options.";
+const char L_slow_pop_growth[] = "The population will grow slowly.";
+const char L_speedup_hint[] = "Tip! If you ever think the game is going a bit too slowly, you can speed it up with the button here.";
+const char L_start_scenario[] = "Start Scenario";
+const char L_starting_citizens[] = "Starting Citizens";
+const char L_starting_resources[] = "Starting Resources";
+const char L_stone[] = "stone";
+const char L_stone_use[] = "Used to build and to create machine parts. Can also be purified to refined metals.";
+const char L_stone_warning[] = "Warning! There are no more rocks on a reachable world! Try building a rock teleporter. If needed, gather some machine chips with the Workshop first.";
+const char L_students[] = "[0]/[1] students";
+const char L_sure_restart[] = "Are you sure you'd like to restart the scenario from the beginning?";
+const char L_tap_for_age_distribution[] = "Press OK for the age distribution.";
+const char L_tap_for_age_distribution_or_pop_limit[] = "Press OK for the age distribution or to change the population limit.";
+const char L_tap_near_citizen_to_follow[] = "Press OK near a citizen to follow them.";
+const char L_thanks_for_playing[] = "Thanks a lot for playing!";
+const char L_there_are_no_houses[] = "There are no houses!";
+const char L_this_citizen[] = "this citizen";
+const char L_threequarter_speed[] = "0.75x Speed";
+const char L_to_pause[] = "to pause the game.";
+const char L_to_research[] = "to research";
+const char L_to_unpause[] = "to unpause the game.";
+const char L_today[] = "Today";
+const char L_total[] = "Total";
+const char L_total_amount_of_citizens[] = "The total amount of citizens in your city.";
+const char L_total_happiness[] = "Total Happiness:";
+const char L_unique[] = "Unique";
+const char L_unlock_all[] = "Unlock All";
+const char L_unnamed_city[] = "Unnamed City";
+const char L_upgrade_afford[] = "Upgrade as many buildings of this type as you can afford. There are [0].";
+const char L_upgrade_all_explain[] = "Upgrade all buildings of this type. There are [0].";
+const char L_upgrade_all_labs[] = "Upgrade all labs with the relevant upgrade(s) for their adjacent buildings.";
+const char L_upgrade_basic_for[] = "Upgrade [0] of [1] basic Houses for:";
+const char L_upgrade_basic_houses[] = "Upgrade Basic Houses";
+const char L_upgrade_basic_houses_hint[] = "Basic Houses can't be upgraded to 100 quality. Instead, you can quickly upgrade them all to another type here.\n\nFirst, select a type to upgrade to:";
+const char L_upgrade_only_this[] = "Upgrade only this building.";
+const char L_upgrade_to_x[] = "Upgrade to [0]";
+const char L_upgraded_houses[] = "Success! Upgraded [0] houses.";
+const char L_upgrades[] = "Upgrades";
+const char L_upgrades_and_policies[] = "Upgrades and Policies";
+const char L_usage[] = "Usage";
+const char L_wood[] = "wood";
+const char L_wood_use[] = "Used to build.";
+const char L_work[] = "Work";
+const char L_work_speed_modifier[] = "Work Speed Modifier:";
+const char L_work_tooltip[] = "People with a job / total labor force.\nThere are [0] jobs.\nPress OK to assign workers.";
+const char L_workers[] = "[0]/[1] workers";
+const char L_workers_of[] = "Workers of [0]";
+const char L_yesterday[] = "yesterday";
+const char L_you_have_enough_stone[] = "You have enough stone for now! Let's get some workers back on cutting wood.";
+const char L_you_have_enough_wood[] = "You have enough wood. Let's build the stone mine!";
+const ClsText cls_text[] = {
+ {"Forest", "Plant young trees which will grow to a forest.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Pine Forest", "Plant young trees which will grow to a pine forest.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Branchy Forest", "Plant young trees which will grow to a branchy forest.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Forest", "Plant young trees which will grow to a red forest.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Forest", "Plant young trees which will grow to a otherworldly purple forest.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Pine Forest", "", NULL, 0, 0, 0, 0, 0, 0},
+ {"Rock", "Place a rock on a world for decoration. It can be mined, unless you protect it.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Boulder", "Place a boulder on a world for decoration. It can be mined, unless you protect it.", NULL, 0, 0, 0, 0, 0, 0},
+ {"Alien Ruins", "", NULL, 0, 0, 0, 0, 0, 0},
+ {"Alien Ruins", "", NULL, 0, 0, 0, 0, 0, 0},
+ {"House", "Your citizens will certainly appreciate a roof above their heads.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Alien House", "Five people can live in this strange home full of otherworldly technology.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Modern Rustic Home", "This rustic-looking house makes people think of Earth. The housing quality is increased by 15 if there are at least three other modern rustic homes or parks next to it.", NULL, BACK_OWN, 0, SPR_BONUSRANGE_PLUS, 0, 0, 0},
+ {"Wooden House", "It's not exactly luxurious, but still quite comfortable.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Mechanical House", "The mechanics and heating of this house need a Machine Parts Factory to function. The housing quality is increased by 50 if there is one next to it.", "Build at least three Machine Parts Factories to unlock!", BACK_OWN, 0, SPR_BONUSRANGE_PLUS, 0, 0, 0},
+ {"Spacious House", "A modern house with lots of space.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Cutting-Edge House", "A hypermodern home filled with technology.", "Build the Living Research Center to unlock!", BACK_OWN, 0, 0, 0, 0, 0},
+ {"Park Pod", "A home in the middle of a park.", NULL, SPR_PARKPOD_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Loft Apartment", "A rooftop apartment with a high ceiling and lots of light, perfect for artists. Generates a small amount of art happiness.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Tinkerers' House", "This house is designed for makers and inventors. Residents earn extra education.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Community House", "This house gives a strong sense of community. Produces a small amount of food, wood or stone for each resident. Most upgrades don't apply to this production.", NULL, SPR_COMMUNITYHOUSE_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Blossum Hut", "Residents of this hut will really flourish!", "Build ten blossom restaurants to unlock!", SPR_BLOOMHUT_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Villa", "A luxurious, modern villa complete with a private teleporter.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Mansion", "A large, luxurious house with a private teleporter. It improves education of residents, and makes them live slightly longer. The housing quality is increased by 25 if connected to another mansion.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Flower Penthouse", "A lavish rooftop house. It makes residents live longer. It also comes with a private teleporter.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Landing Pad", "The landing pad works like a bus stop in space. People can take a space ship from here to other landing pads. Can only be placed on the ground or on a rooftop.", NULL, SPR_FLYINGSAUCER, 0, 0, 0, 0, 0},
+ {"Landed Exploration Ship", "Living in this exploration ship may not be very comfortable, but it's certainly very adventurous! Can only be placed on the ground or on a rooftop.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Hyper Elevator", "Allows citizens to quickly go to elevators above and below in the same contiguous building. There may be other buildings in between the elevators.", "Have at least 200 citizens to unlock!", BACK_OWN, 0, 0, 0, 0, 0},
+ {"Teleporter", "The very fastest form of transportation. Allows citizens to instantly go to other teleporters.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Woodcutting Center", "Woodcutters retrieve their materials here, then go to the nearest forest to cut wood.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Stone Mine", "Stone miners retrieve their materials here, then go to the nearest rock to mine stone.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Indoor Farm", "Crops can be grown here to produce food.", NULL, SPR_INDOORFARM_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Exploration Center", "Explore alien ruins to gain knowledge, resources and special bonuses. When all ruins have been explored, workers will investigate their findings to gain more knowledge.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Machine Parts Factory", "Produces machine parts from stone. Three stone is needed to make one machine part.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Lab", "Scientists gather knowledge here. Also has upgrades boosting adjacent farms and tree plantations.", NULL, BACK_OWN, 0, SPR_BONUSRANGE_PLUS, 0, 0, 0},
+ {"Tree Plantation", "These trees are kept in an optimal environment and regrow faster than trees on the world surface. Woodcutters from a Woodcutting Center can help cut them down.", NULL, SPR_TREEPLANTATION_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Rock Teleporter", "Teleports meteoroids to your city. Doesn't produce stone by itself; miners from Stone Mines can gather stone from the meteroids.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Refined Metals Factory", "Produces refined metals from stone. Five stone is needed to make one unit of refined metal.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Computer Chip Factory", "Produces computer chips from refined metals. Seven units of refined metals are needed to make one computer chip.!unlocks", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Eco Farm", "Produces food sustainably. Also generates a small amount of nature entertainment happiness.", "Build an Experimental Farm and ten Botanical Gardens to unlock!", SPR_ECOFARM_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Farm By-Product Processor", "Produces wood for each adjacent farm. Each farm only produces enough by-products for one By-Product Processor.", NULL, BACK_OWN, 0, SPR_BONUSRANGE_PLUS, 0, 0, 0},
+ {"Experimentation Lab", "Scientists experiment with machine parts here. You earn five knowledge for every machine part used. This knowledge production is faster than with normal labs.\nRefined Metal Factories above and below this building work faster and use 10% less stone per unit of refined metal.", "Build twelve mechanical houses, ten refined metal factories and three computer chip factories to unlock!", BACK_OWN, 0, SPR_BONUSRANGE_TOPBOTTOM, 0, 0, 0},
+ {"School", "Educates children, improving how effective they'll be at some jobs later.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Library", "Improves the education of visitors of all ages.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Herb Garden", "Herbs and spices are grown here. They make food taste better, reducing the amount of food people need. Also has an extra effect depending on the herb type.", "Build two restaurants to unlock!", SPR_HERBGARDEN_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Medical Clinic", "Helps people live longer and better.", "Build a Refined Metals Factory to unlock!", BACK_OWN, 0, 0, 0, 0, 0},
+ {"Specialized Medical Clinic", "Specialized in treating complicated diseases. It improves medical happiness and makes citizens live longer.", NULL, BACK_OWN, 0, 0, CT_LIMITED, 0, 1000},
+ {"Pub", "A great place for people to get together.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Carrot Juice Bar", "", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Restaurant", "A cozy place with nice food.", "Build at least five Pubs to unlock!", BACK_OWN, 0, 0, 0, 0, 0},
+ {"Upscale Restaurant", "A highly rated restaurant with exclusive meals and a stylish atmosphere.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Factory Pub", "A charming little pub that doubles up as a refined metals factory.\nIt can't be boosted by Experimentation Labs, though.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Blossom Restaurant", "Dine under the beautiful tree blossom! If you build multiple restaurants on top of each other, people can sit on tree branches.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Park", "A nice place to relax.", NULL, SPR_PARK_BUTTONBG, 0, 0, 0, 0, 0},
+ {"Botanical Gardens", "A nice garden full of exotic plants.", "Build at least ten Parks and five Labs to unlock!", SPR_BOTANICALGARDENS_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Dome Botanical Gardens", "A stylish roof for your botanical gardens.", NULL, SPR_BOTANICALGARDEN_DOME_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Rooftop Park", "Green roofs can look really nice and give your citizens more space to experience nature.", NULL, SPR_ROOFTOPPARK_BUTTONBG, SPR_ROOFTOPPARK_ONBUILD, 0, 0, 0, 0},
+ {"Redwood Tree", "A tree that can grow really tall. It can only be built on the ground. You can make it grow once every 24 hours.", "Build 40 Community Houses to unlock!", 0, 0, 0, 0, 0, 0},
+ {"Redwood Tree House", "", NULL, 0, 0, 0, 0, 0, 0},
+ {"Nightclub", "Some people will have a lot of fun in this nightclub.", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Scrapyard Nightclub", "A nightclub full of strange luminous machines.", NULL, SPR_SYNIGHTCLUB_BG, 0, 0, 0, 0, 0},
+ {"Modern Art Museum", "Abstract art by upcoming artists.", "Build a Refined Metals Factory to unlock!", SPR_MODERNARTMUSEUM_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Sculpture Garden", "A garden filled with art.", NULL, SPR_STATUEGARDEN_BUTTONBACK, 0, 0, 0, 0, 0},
+ {"Arcade", "Fun games for the whole family.", "Build a Computer Chip Factory to unlock!", BACK_OWN, 0, 0, 0, 0, 0},
+ {"Holo Game Hall", "Bring gaming into the future!", NULL, BACK_OWN, 0, 0, 0, 0, 0},
+ {"Workshop", "Makes all machine parts factories in your city work faster. Also, workers can gather knowledge or produce machine parts from wood.", NULL, BACK_OWN, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Research Craft", "A researcher can gather knowledge from this little spacecraft. There can be no building or world directly above this.", NULL, SPR_RESEARCHBOT, 0, 0, CT_UNIQUE, 0, 0},
+ {"Experimental Farm", "Food is produced here. Also slightly increases the growth speed of crops in indoor farms.", NULL, SPR_EXPERIMENTALFARM_BUTTONBACK, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Observatory", "Produces knowledge. Can only be placed on the ground or on a rooftop.", NULL, BACK_OWN, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Art Colony", "A house full of creativity. Generates art entertainment happiness.", "Build at least three Modern Art Museums to unlock!", SPR_ARTCOLONY_BUTTONBACK, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"City Hall", "Allows you to implement city policies and to change the name of your city.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Mining Research Center", "Boosts stone production based on your knowledge production and the number of workers.", "Build at least 15 Stone Mines and three Rock Teleporters to unlock!", BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Computing Research Center", "Produces knowledge and allows you to research and build Computer Chip Factories.", "Build at least five Labs and a Refined Metal Factory to unlock!", BACK_OWN, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Living Research Center", "Upgrades for homes can be researched here. Also houses two people and produces knowledge.", "Have at least 200 citizens with homes to unlock!", BACK_OWN, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Hackers of the Bolt HQ", "These hardware hackers are actually really nice and helpful.\nThey spend most of their days tinkering around with computers and electronics. Some of their inventions are more useful than others.", "Build at least three Arcades to unlock!", BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Alien Decryptor", "A specialized computer built to decrypt alien secrets.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Lab Escape Room", "A challenging lab-themed escape room, which generates gaming entertainment happiness. It also has lasers!", NULL, BACK_OWN, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Misdirector", "Whenever someone uses a teleporter, there is a small chance they will be brought here instead. This will confuse them for a short while. This invention is not completely useless though: you will gain some knowledge each time. Also, the Misdirector halves the operating cost of teleporters.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Secret Society of the Key", "The Secret Society of the Key requests a place of residence. It can then give you tasks that you would be honored to complete.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"The Machine", "Makes Secret Society of the Key members live forever. Also produces random resources every day.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Friends of the Key", "A house for friends of the Secret Society of the Key. As long as The Machine exists, people in this house live forever.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Blossom Hippies Center", "These hippies love flowers, peace and music. They have a few tasks for you, if you don't mind.", "Build a stack of Botanical Gardens at least twenty buildings high to unlock!", BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Festival HQ", "Organize awesome festivals to entertain your citizens!", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Feather Alliance Outpost", "The Feather Alliance has one simple goal: discover everything they can about the universe. They'd appreciate your help.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Intergalactic Library", "This grand library greatly educates visitors. Workers produce knowledge based on the total number of citizens in associated cities. Also allows you to research city upgrades.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Supercomputer", "Produces knowledge based on the amount of lab employees in your city. Also allows you to research some city upgrades.", NULL, BACK_OWN, 0, 0, CT_NOT_UNIQUE_GL | CT_UNIQUE, 0, 0},
+ {"Tree Hugger Base", "Who wouldn't hug this tree?", NULL, SPR_TREEHUGGERBASE, 0, 0, CT_UNIQUE, 0, 0},
+ {"Museum of Space Fossils", "Fossils found by the Fossil Detector are displayed here. Improves the education of visitors. Workers produce knowledge based on the number of fossils you found.", NULL, BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Statue of Happiness", "Your citizens' reward for reaching 100 happiness!", NULL, SPR_STATUEOFHAPPINESS_BG, 0, 0, CT_UNIQUE, 0, 0},
+ {"Statue of the Key", "The birthday gift of a Secret Society of the Key member who reached the respectable age of 500!", NULL, SPR_STATUEOFTHEKEY_BG, 0, 0, CT_UNIQUE, 0, 0},
+ {"The Beacon", "Your citizens' reward for keeping them really happy for a while!", "Maintain :D or better happiness for at least fourteen days to unlock!", BACK_OWN, 0, 0, CT_UNIQUE, 0, 0},
+ {"Painted Block", "A building painted in a single color for decoration purposes, or as a placeholder.", NULL, BACK_OWN, 0, 0, CT_MULTI_DECOR | CT_ANYCOLOR, 1, 0},
+ {"Decorative Window", "A window for decorative purposes, or as a placeholder.", NULL, BACK_OWN, 0, 0, CT_MULTI_DECOR | CT_MULTI_SPEC, 1, 0},
+ {"Slanted Roof", "A nice slanted roof for decoration purposes.", NULL, BACK_OWN, 0, 0, CT_MULTI_DECOR | CT_ANYCOLOR | CT_MIRRORABLE, 2, 0},
+ {"Slanted Rooftop", "The top of a slanted roof.", NULL, BACK_OWN, 0, 0, CT_MULTI_DECOR | CT_ANYCOLOR, 3, 0},
+ {"Dome Roof", "A dome that can be placed on a roof.", NULL, BACK_OWN, 0, 0, CT_MULTI_DECOR | CT_ANYCOLOR, 5, 0},
+ {"Slanted Roof Base", "A bottom piece for two slanted roofs.", NULL, BACK_OWN, 0, 0, CT_MULTI_DECOR | CT_ANYCOLOR, 4, 0}};
+const uint8_t build_order[] = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96};
+const int nbuild_order = 87;
+const CatText cat_text[NCATEGORIES] = {{"Houses", "Build houses for your citizens to live in.", SPR_ICON_HOUSES}, {"Production", "Build production buildings to get more resources.", SPR_ICON_WORK}, {"Services", "Services help people, improving their lives.", SPR_ICON_SERVICES}, {"Entertainment", "Build entertainment to keep your citizens happy.", SPR_ICON_ENTERTAINMENT}, {"Transportation", "Build transportation to let citizens move on and between worlds quickly.", SPR_ICON_TRANSPORT}, {"Unique Buildings", "Only one of each of these special buildings can be built.", SPR_ICON_SPECIALBUILDINGS}, {"Decoration & Nature", "Place decoration on the ground, and plant forests.", SPR_NATURE}};
+const CatText sub_text[NSUBCATEGORIES] = {{"Painted Blocks", NULL, SPR_COLOREDBLOCK}, {"Slanted Roofs", NULL, SPR_SLANTEDROOF}, {"Slanted Rooftops", NULL, SPR_SLANTEDROOFTOP}, {"Slanted Roof Bases", NULL, SPR_ROOFBOTTOM}, {"Dome Roofs", NULL, SPR_DOMEROOF}};
+const DecoText deco_text[] = {
+ {SPR_GRASS, 0, 0, 1, 0, "High Grass", NULL},
+ {SPR_FLOWERS, 0, 0, 1, 0, "High Grass with Flowers", NULL},
+ {SPR_FLOWERS_BLUE, DT_GENE_EDITING, 0, 1, 0, "High Grass with Blue Flowers", NULL},
+ {SPR_DECORATION_ROCKS, 0, 0, 0, 1, "Small Rocks", NULL},
+ {SPR_DECORATION_KEYCITY, 0, 0, 1, 0, "Dry Grass", NULL},
+ {SPR_FLOWERS_KEYCITY, 0, 0, 1, 0, "Dry Grass with Flowers", NULL},
+ {SPR_PURPLEGRASS, DT_GENE_EDITING, 0, 1, 0, "Purple Grass", NULL},
+ {SPR_REDGRASS, DT_GENE_EDITING, 0, 1, 0, "Red Grass", NULL},
+ {SPR_REMOVEDECORATION, DT_REMOVE, 0, 0, 0, "Remove Decoration", "Clear any decoration from a world surface."}};
+const int ndeco_text = 9;
+const ResText res_text[] = {
+ {CLS_Forest, 10, -1, 20, 0, "Forest", "Plant young trees which will grow to a forest."},
+ {CLS_PineForest, 10, -1, 20, 0, "Pine Forest", "Plant young trees which will grow to a pine forest."},
+ {CLS_BranchyForest, 10, -1, 20, 0, "Branchy Forest", "Plant young trees which will grow to a branchy forest."},
+ {CLS_RedForest, 10, -1, 20, 0, "Red Forest", "Plant young trees which will grow to a red forest."},
+ {CLS_PurpleForest, 10, -1, 20, 0, "Purple Forest", "Plant young trees which will grow to a otherworldly purple forest."},
+ {CLS_Rock, -1, 250, 0, 250, "Rock", "Place a rock on a world for decoration. It can be mined, unless you protect it."},
+ {CLS_Boulder, -1, 200, 0, 200, "Boulder", "Place a boulder on a world for decoration. It can be mined, unless you protect it."}};
+const int nres_text = 7;
+const int ncitizen_names = 8910;
+static const uint8_t names_blob[] = {0,45,0,0,65,97,114,111,110,0,1,98,0,2,98,97,0,3,101,0,4,121,0,3,105,101,0,3,111,116,0,5,116,0,3,121,0,2,100,101,108,0,3,117,108,0,2,101,0,3,108,0,4,97,114,100,0,3,117,0,3,121,0,2,105,101,0,2,110,101,114,0,2,114,97,104,97,109,0,6,110,0,4,109,0,5,111,0,4,110,0,1,100,0,2,97,105,114,0,3,109,0,4,111,0,4,115,0,3,110,0,2,100,105,101,0,4,115,111,110,0,0,65,100,100,121,0,2,101,0,3,108,98,101,114,116,0,2,104,97,109,0,2,108,97,105,0,3,101,114,0,2,111,0,3,108,102,0,4,112,104,0,6,101,0,6,111,0,6,117,115,0,2,114,105,97,110,0,6,111,0,4,101,110,0,1,103,111,115,116,111,0,2,117,105,101,0,4,115,116,105,110,0,3,115,116,101,0,5,105,110,0,1,104,97,114,111,110,0,2,109,97,100,0,3,101,100,0,1,105,108,98,101,114,116,0,1,107,105,109,0,2,115,101,108,0,1,108,0,2,97,105,110,0,4,114,0,3,110,0,4,100,0,4,111,0,0,65,108,97,110,115,111,110,0,3,114,100,0,4,105,99,0,3,115,100,97,105,114,0,4,116,97,105,114,0,5,101,105,114,0,6,114,0,2,98,101,114,105,107,0,5,116,0,6,111,0,3,105,101,0,3,114,101,99,104,116,0,2,100,101,110,0,3,105,110,0,4,115,0,3,111,0,4,110,0,4,117,115,0,3,114,105,99,0,6,104,0,5,100,103,101,0,3,117,115,0,3,119,105,110,0,2,101,99,0,3,106,97,110,100,114,111,0,4,111,97,0,3,107,115,97,110,100,114,0,3,115,115,97,110,100,114,111,0,3,120,0,4,97,110,100,101,114,0,7,114,0,8,101,0,0,65,108,101,120,97,110,100,114,111,0,9,115,0,4,101,105,0,4,105,111,0,5,115,0,2,102,0,3,105,101,0,3,111,110,115,0,6,101,0,6,111,0,4,114,100,0,3,114,101,100,0,6,111,0,3,121,0,2,103,101,114,110,111,110,0,2,105,0,3,99,0,4,107,0,3,115,97,110,100,101,114,0,4,116,97,105,114,0,5,101,114,0,3,120,0,2,108,97,110,0,4,114,100,0,4,121,110,101,0,3,101,110,0,4,121,0,5,110,0,3,105,101,0,4,110,0,4,115,116,101,114,0,6,105,114,0,0,65,108,108,121,110,0,2,111,105,110,0,3,110,0,4,115,111,0,4,122,111,0,3,121,115,105,117,115,0,2,112,104,97,114,100,0,4,111,110,115,101,0,7,111,0,2,114,105,99,0,2,117,105,110,0,5,111,0,2,118,97,0,4,110,0,3,105,101,0,4,110,0,4,115,0,3,121,0,2,119,105,110,0,3,121,110,0,2,121,111,115,104,97,0,1,109,98,108,101,0,3,114,111,115,0,6,101,0,6,105,0,7,111,0,7,117,115,0,3,121,0,2,101,114,105,103,111,0,4,121,0,2,111,114,121,0,3,115,0,0,65,110,97,116,111,108,0,6,101,0,6,108,111,0,2,99,101,108,108,0,2,100,101,114,115,0,6,111,110,0,3,105,101,0,3,111,110,105,115,0,3,114,97,115,0,4,101,0,5,97,0,6,115,0,5,106,0,5,115,0,5,119,0,5,121,0,4,105,115,0,4,111,115,0,4,117,115,0,3,121,0,2,103,101,0,4,108,0,5,105,0,6,99,111,0,5,111,0,3,105,101,0,3,117,115,0,2,115,101,108,0,5,108,0,5,109,0,3,111,110,0,2,116,104,111,110,121,0,0,65,110,116,105,110,0,3,111,105,110,101,0,4,110,0,5,101,0,5,105,0,6,110,0,7,111,0,6,111,0,6,117,115,0,5,115,0,5,121,0,2,121,0,1,114,97,0,3,108,100,111,0,2,99,104,0,4,97,105,109,98,97,117,100,0,5,109,98,97,117,108,116,0,4,101,114,0,4,105,98,97,108,100,0,9,111,0,6,111,108,100,0,5,101,0,4,121,0,2,101,108,0,2,105,0,3,101,0,4,108,0,3,110,0,3,111,0,3,115,116,111,116,108,101,0,2,108,97,110,0,3,101,110,0,0,65,114,108,101,121,0,3,105,110,0,2,109,97,110,0,5,100,0,6,111,0,3,105,110,0,3,115,116,114,111,110,103,0,2,110,97,108,100,111,0,3,101,0,4,121,0,3,105,0,4,101,0,3,111,108,100,0,6,111,0,3,117,97,100,0,3,121,0,2,111,110,0,2,114,105,0,3,111,110,0,2,116,0,3,97,105,114,0,3,101,0,4,109,97,115,0,5,105,115,0,5,117,115,0,3,104,101,114,0,4,117,114,0,3,105,101,0,3,117,114,0,5,111,0,4,115,0,3,121,0,0,65,114,118,0,3,105,101,0,4,110,0,3,121,0,1,115,97,0,2,101,0,2,104,0,3,98,101,121,0,4,121,0,3,101,114,0,3,108,101,121,0,4,105,110,0,3,116,111,110,0,1,117,98,101,0,4,114,111,110,0,5,116,0,3,114,101,121,0,2,103,105,101,0,3,117,115,116,0,6,105,110,0,8,101,0,6,111,0,6,117,115,0,3,121,0,2,114,116,104,117,114,0,2,115,116,101,110,0,4,105,110,0,1,118,101,0,3,114,101,108,108,0,4,105,108,0,6,108,0,4,121,0,0,65,118,105,99,116,111,114,0,3,103,100,111,114,0,2,114,97,109,0,3,111,109,0,1,120,0,2,101,0,3,108,0,1,121,108,109,97,114,0,4,101,114,0,0,87,101,105,195,159,0,0,65,121,109,101,114,0,0,66,97,105,108,0,4,101,121,0,4,105,101,0,4,108,105,101,0,4,121,0,3,114,100,0,2,108,100,0,4,117,105,110,0,4,119,105,110,0,3,101,0,2,110,0,3,99,114,111,102,116,0,3,107,0,4,121,0,2,114,0,3,98,97,98,97,115,0,3,99,108,97,121,0,3,100,0,4,101,0,3,110,0,4,97,98,97,115,0,0,66,97,114,110,97,98,101,0,6,121,0,5,114,100,0,4,101,98,97,115,0,5,116,116,0,5,121,0,4,105,101,0,4,121,0,3,111,110,0,3,114,0,4,101,116,0,6,116,0,4,105,0,5,101,0,5,115,0,4,111,110,0,4,121,0,3,116,0,4,101,108,0,4,104,0,5,101,108,0,5,111,108,101,109,121,0,7,111,109,101,111,0,10,117,115,0,10,119,0,4,105,101,0,4,108,101,116,0,7,116,0,4,111,108,101,109,111,0,6,111,109,101,111,0,5,110,0,4,114,97,109,0,0,66,97,114,116,121,0,3,121,0,4,114,97,109,0,2,115,101,0,3,105,108,0,5,101,0,5,105,111,0,6,117,115,0,3,116,105,97,110,0,5,101,110,0,2,116,0,3,104,111,108,111,109,101,119,0,2,117,100,111,105,110,0,2,120,0,3,105,101,0,3,116,101,114,0,3,121,0,2,121,0,3,97,114,100,0,1,101,97,108,101,0,4,108,101,0,3,114,0,4,110,97,114,100,0,3,117,0,4,102,111,114,116,0,4,114,101,103,97,114,100,0,2,99,107,0,2,108,116,114,97,110,0,2,110,0,3,100,105,99,107,0,6,116,121,0,5,120,0,0,66,101,110,101,100,101,116,116,111,0,5,105,99,107,0,7,116,0,8,111,0,6,107,116,0,3,103,116,0,3,105,97,109,105,110,111,0,4,116,111,0,3,106,97,109,101,110,0,6,105,110,0,4,105,0,5,101,0,4,121,0,3,110,0,4,111,0,4,101,116,116,0,4,105,101,0,4,121,0,3,111,105,116,0,3,115,111,110,0,3,116,0,4,108,101,101,0,6,121,0,4,111,110,0,3,121,97,109,105,110,0,2,114,0,3,107,0,4,101,0,5,108,101,121,0,4,105,101,0,4,108,101,121,0,5,121,0,0,66,101,114,107,121,0,3,110,0,4,97,114,100,0,7,111,0,6,114,0,4,101,0,4,104,97,114,100,0,4,105,101,0,4,121,0,3,116,0,4,105,0,5,101,0,4,111,110,0,4,114,97,109,0,6,110,100,0,8,111,0,4,121,0,2,118,0,3,97,110,0,3,105,110,0,3,111,110,0,1,105,108,0,3,108,0,4,105,101,0,4,121,0,2,110,103,0,3,107,0,4,121,0,2,114,99,104,0,3,107,0,3,111,110,0,1,106,111,114,110,0,0,66,108,97,105,110,101,0,4,114,0,3,107,101,0,3,110,101,0,3,121,110,101,0,1,111,0,2,98,0,3,98,105,101,0,4,121,0,2,103,97,114,116,0,3,101,121,0,2,105,103,105,101,0,2,110,100,0,4,105,101,0,4,111,110,0,4,121,0,3,101,0,3,105,102,97,99,101,0,2,111,110,101,0,4,105,101,0,4,121,0,3,116,0,4,101,0,4,104,0,5,101,0,2,114,100,0,4,101,110,0,4,105,101,0,4,121,0,3,103,0,3,105,115,0,2,117,114,107,101,0,0,66,111,119,105,101,0,2,121,0,3,99,101,0,5,121,0,4,105,101,0,3,100,0,1,114,97,100,0,4,97,110,0,4,101,0,5,110,0,4,102,111,114,100,0,4,108,101,121,0,5,121,0,4,110,101,121,0,4,121,0,3,109,0,3,110,0,4,100,0,5,101,110,0,6,114,0,5,111,110,0,5,116,114,0,5,121,0,6,110,0,4,110,111,110,0,4,116,0,5,108,101,121,0,2,101,110,0,4,100,97,110,0,5,101,110,0,5,105,110,0,6,115,0,0,66,114,101,110,100,111,110,0,4,110,97,110,0,5,101,110,0,4,116,0,3,116,0,4,116,0,3,119,0,4,101,114,0,4,115,116,101,114,0,2,105,97,110,0,5,111,0,5,116,0,3,99,101,0,3,101,110,0,3,103,0,4,103,0,5,115,0,4,104,97,109,0,3,111,110,0,3,116,0,4,116,0,2,110,97,98,97,0,5,121,0,2,111,99,107,0,5,105,101,0,5,121,0,3,100,0,4,100,105,101,0,5,121,0,4,101,114,105,99,0,8,107,0,4,105,101,0,0,66,114,111,100,121,0,3,107,0,3,110,0,4,110,105,101,0,5,121,0,4,115,111,110,0,3,111,107,0,5,101,0,5,115,0,3,115,101,0,2,117,99,101,0,4,105,101,0,3,105,115,0,3,110,111,0,2,121,97,110,0,5,116,0,6,121,0,3,99,101,0,3,110,0,3,111,110,0,1,117,99,107,0,4,105,101,0,4,121,0,2,100,0,3,100,0,4,105,101,0,4,121,0,2,105,114,111,110,0,2,114,99,104,0,3,103,0,4,101,115,115,0,3,107,0,0,66,117,114,107,101,0,3,108,0,4,105,101,0,3,110,97,98,121,0,5,114,100,0,3,114,0,3,116,0,4,105,101,0,4,111,110,0,4,121,0,2,116,99,104,0,1,121,114,97,109,0,4,110,0,5,110,0,3,108,101,0,3,111,109,0,4,110,0,0,67,97,100,0,3,100,114,105,99,0,2,101,115,97,114,0,2,108,0,3,100,119,101,108,108,0,3,101,0,4,98,0,3,104,111,117,110,0,3,108,101,97,110,0,3,118,0,4,105,110,0,2,109,0,3,101,114,111,110,0,4,121,0,3,109,121,0,0,67,97,114,0,3,99,101,0,3,101,0,4,121,0,3,108,0,4,101,116,111,110,0,4,105,101,0,5,110,0,6,103,0,4,111,0,5,115,0,4,121,0,5,108,101,0,3,109,105,110,101,0,3,110,101,121,0,4,121,0,3,111,108,117,115,0,3,114,0,4,111,108,0,6,108,0,3,115,111,110,0,3,116,0,4,101,114,0,3,118,101,114,0,3,121,0,4,108,0,2,115,97,114,0,3,101,0,4,121,0,3,104,0,3,112,97,114,0,4,101,114,0,0,67,97,115,115,0,4,105,101,0,5,117,115,0,2,122,0,3,122,105,101,0,1,99,104,97,100,100,105,101,0,1,101,99,101,0,3,105,108,0,5,105,111,0,6,117,115,0,2,100,0,3,114,105,99,0,2,108,108,111,0,2,115,97,114,0,5,101,0,5,111,0,1,104,97,100,0,4,100,0,5,105,101,0,5,121,0,4,119,105,99,107,0,3,105,109,0,3,108,109,101,114,115,0,3,110,0,4,99,101,0,6,121,0,4,100,108,101,114,0,4,101,0,3,114,105,111,116,0,4,108,101,115,0,6,121,0,5,105,101,0,0,67,104,97,114,108,116,111,110,0,3,115,0,4,101,0,3,117,110,99,101,0,7,121,0,2,101,0,3,110,0,3,115,0,4,116,101,114,0,5,111,110,0,3,116,0,3,118,0,4,97,108,105,101,114,0,4,121,0,2,105,99,0,4,107,0,5,105,101,0,5,121,0,4,111,0,3,108,116,111,110,0,3,112,0,2,114,105,115,0,5,115,101,0,6,105,101,0,6,121,0,5,116,105,97,110,0,9,111,0,7,101,0,6,111,102,102,101,114,0,8,111,114,111,0,7,112,101,114,0,8,104,0,0,67,104,114,105,115,116,111,112,104,101,0,10,114,0,9,111,114,117,115,0,7,115,0,6,121,0,5,121,0,3,111,116,111,101,109,0,2,117,99,104,111,0,4,107,0,1,105,114,105,108,108,111,0,5,111,0,3,111,0,1,108,97,105,98,111,114,110,0,8,101,0,4,114,0,5,101,0,3,114,97,110,99,101,0,4,101,0,5,110,99,101,0,4,107,0,5,101,0,3,117,100,101,108,108,0,5,105,97,110,0,8,117,115,0,6,111,0,6,117,115,0,4,115,0,3,121,0,4,98,111,114,110,0,8,101,0,6,117,114,110,101,0,4,115,111,110,0,0,67,108,97,121,116,111,110,0,2,101,97,118,108,97,110,100,0,3,109,0,4,101,110,115,0,6,116,0,7,101,0,7,105,117,115,0,4,109,105,101,0,5,121,0,3,111,110,0,3,114,99,0,3,116,105,115,0,4,117,115,0,3,118,101,0,5,108,97,110,100,0,5,121,0,4,105,101,0,2,105,102,102,0,5,111,114,100,0,3,109,0,3,110,116,0,3,118,101,0,2,121,0,3,100,101,0,3,118,101,0,3,119,100,0,1,111,98,0,3,98,0,4,105,101,0,4,121,0,2,100,105,0,4,101,0,0,67,111,100,121,0,2,105,110,116,111,110,0,2,108,97,110,0,4,115,0,3,98,121,0,3,101,0,4,109,97,110,0,4,116,0,3,105,110,0,3,108,105,110,0,3,109,97,110,0,3,118,101,114,0,2,110,0,3,97,110,0,5,116,0,3,110,0,4,101,121,0,4,105,101,0,4,111,114,0,4,121,0,3,114,97,100,0,6,101,0,6,111,0,4,111,121,0,3,115,97,108,118,101,0,4,116,97,110,116,105,110,0,10,101,0,10,111,0,3,119,97,121,0,2,111,112,0,4,101,114,0,2,114,98,101,116,0,0,67,111,114,98,101,116,116,0,4,105,101,0,5,110,0,4,121,0,3,100,0,4,101,108,108,0,4,105,101,0,4,121,0,3,101,121,0,3,105,0,3,110,97,108,108,0,4,101,108,105,117,115,0,6,108,0,5,121,0,4,105,101,0,4,121,0,3,114,101,121,0,4,105,101,0,3,116,0,4,105,101,0,4,121,0,3,121,0,2,115,0,3,105,109,111,0,3,109,101,0,4,111,0,3,116,97,0,2,117,114,116,0,5,110,97,121,0,6,101,121,0,2,122,109,111,0,1,114,97,103,103,105,101,0,0,67,114,97,103,103,121,0,3,105,103,0,3,119,102,111,114,100,0,2,101,105,103,104,0,6,116,0,7,111,110,0,2,105,99,104,116,111,110,0,3,115,0,4,116,105,97,110,0,8,111,0,5,111,98,97,108,0,2,111,115,98,121,0,4,115,0,1,117,108,108,0,4,97,110,0,4,101,110,0,5,121,0,4,105,101,0,5,110,0,4,121,0,3,118,101,114,0,2,114,99,105,111,0,3,114,0,4,97,110,0,4,101,121,0,4,105,101,0,4,121,0,3,116,0,4,105,99,101,0,5,115,0,1,121,0,2,114,105,108,0,0,67,121,114,105,108,108,0,6,101,0,6,117,115,0,3,117,115,0,0,68,39,65,114,99,121,0,1,97,101,108,0,2,103,0,3,110,121,0,2,108,0,3,101,0,3,105,115,0,3,108,0,4,97,115,0,4,105,0,5,115,0,4,111,110,0,3,115,116,111,110,0,3,116,0,4,111,110,0,2,109,101,0,3,105,97,110,0,6,111,0,4,101,110,0,3,111,110,0,2,110,0,3,97,0,3,101,0,3,105,0,4,101,0,5,108,0,3,110,101,108,0,4,105,101,0,0,68,97,110,110,121,0,3,116,101,0,3,121,97,0,2,114,0,3,98,0,4,101,101,0,4,121,0,3,99,121,0,3,101,0,4,110,0,3,105,108,108,0,4,110,0,4,111,0,4,117,115,0,3,110,0,4,97,108,108,0,4,101,108,108,0,3,111,110,0,3,114,101,108,0,6,108,0,5,110,0,4,105,99,107,0,5,110,0,4,121,108,0,3,119,105,110,0,3,121,108,0,5,101,0,2,118,0,3,101,0,4,110,0,4,121,0,3,105,100,0,0,68,97,118,105,100,100,101,0,5,101,0,5,115,111,110,0,4,101,0,4,110,0,4,115,0,3,111,110,0,3,121,0,1,101,32,87,105,116,116,0,2,97,110,0,4,101,0,2,99,99,97,0,3,107,0,2,108,0,3,97,105,110,101,121,0,4,110,101,121,0,5,111,0,3,98,101,114,116,0,3,108,0,3,109,97,114,0,4,101,114,0,4,111,114,0,6,101,0,2,109,101,116,114,101,0,6,105,0,7,115,0,7,117,115,0,3,111,116,116,0,2,110,0,3,101,0,3,105,115,0,3,110,101,116,0,0,68,101,110,110,101,121,0,4,105,101,0,5,115,0,6,111,110,0,4,121,0,3,118,101,114,0,3,121,115,0,2,114,0,3,98,121,0,3,101,107,0,3,105,99,107,0,3,107,0,3,109,111,116,0,3,114,101,107,0,4,105,99,107,0,5,107,0,5,108,0,4,111,110,0,4,121,0,3,119,97,114,100,0,4,105,110,0,2,115,0,3,105,0,3,109,111,110,100,0,4,117,110,100,0,2,118,0,3,105,110,0,3,108,97,110,100,0,4,101,110,0,4,105,110,0,3,121,0,2,119,0,0,68,101,119,97,105,110,0,3,101,121,0,3,105,101,0,4,116,116,0,2,120,0,3,116,101,114,0,1,105,97,114,109,105,100,0,2,99,107,0,4,105,101,0,4,121,0,2,101,103,111,0,3,116,101,114,0,4,114,105,99,104,0,2,108,97,110,0,3,108,0,4,105,101,0,4,111,110,0,4,121,0,2,109,105,116,114,105,0,6,121,0,2,110,111,0,2,111,110,0,4,105,115,105,111,0,4,121,115,117,115,0,2,114,107,0,1,109,105,116,114,105,0,1,111,108,102,0,3,112,104,0,2,109,0,3,101,110,105,99,0,7,111,0,3,105,110,103,111,0,0,68,111,109,105,110,105,99,0,7,107,0,6,107,0,6,113,117,101,0,2,110,0,3,97,108,0,5,108,0,5,116,0,4,117,103,104,0,4,118,111,110,0,3,110,0,4,101,108,108,0,4,105,101,0,4,121,0,3,111,118,97,110,0,2,114,101,0,4,121,0,3,105,97,110,0,4,101,0,3,121,0,2,117,103,0,4,105,101,0,4,108,97,115,0,7,115,0,4,121,0,2,118,0,2,121,0,3,108,101,0,1,114,97,107,101,0,2,101,119,0,2,117,0,3,100,0,0,68,114,117,103,105,0,1,117,97,110,101,0,2,100,0,3,108,101,121,0,2,102,102,0,4,105,101,0,4,121,0,2,103,97,108,100,0,2,107,101,0,4,121,0,3,105,101,0,3,121,0,2,110,0,3,99,0,4,97,110,0,3,110,0,3,115,116,97,110,0,2,114,0,3,97,110,100,0,5,116,0,6,101,0,3,119,97,114,100,0,1,119,97,105,110,0,3,121,110,101,0,2,105,103,104,116,0,1,121,108,97,110,0,0,69,97,100,109,117,110,100,0,2,108,0,2,109,111,110,0,2,114,108,0,4,101,0,4,105,101,0,0,69,97,114,108,121,0,0,65,114,118,105,100,0,0,69,97,114,118,105,110,0,1,98,0,2,101,110,0,4,101,115,101,114,0,5,122,101,114,0,3,114,104,97,114,100,0,4,116,111,0,1,100,0,2,97,110,0,2,100,0,3,105,101,0,3,121,0,2,103,97,114,0,5,100,0,6,111,0,2,105,107,0,2,108,105,110,0,2,109,111,110,0,3,117,110,100,0,2,111,117,97,114,100,0,2,115,101,108,0,2,117,97,114,100,0,6,111,0,3,105,110,111,0,2,118,97,114,100,0,2,119,97,114,100,0,3,105,110,0,1,102,114,101,109,0,4,110,0,1,103,97,110,0,0,69,103,98,101,114,116,0,2,111,110,0,3,114,0,1,108,0,2,98,101,114,116,0,2,100,101,110,0,3,105,110,0,3,111,110,0,3,114,101,100,103,101,0,4,105,100,103,101,0,2,105,0,3,97,0,4,115,0,3,104,117,0,3,106,97,104,0,3,111,116,0,3,115,104,97,0,2,108,97,114,121,0,3,101,114,101,121,0,5,121,0,3,105,111,116,0,6,116,0,4,115,0,3,115,119,101,114,116,104,0,5,111,114,116,104,0,3,119,111,111,100,0,2,109,101,114,0,3,111,0,4,114,101,0,2,110,97,114,0,2,114,111,121,0,2,115,116,111,110,0,0,69,108,115,119,111,114,116,104,0,2,116,111,110,0,2,118,105,110,0,4,115,0,3,121,110,0,2,119,105,110,0,3,111,111,100,0,3,121,110,0,2,121,0,1,109,0,2,97,110,117,101,108,0,7,101,0,2,101,108,101,110,0,3,114,115,111,110,0,4,121,0,2,105,108,101,0,4,105,111,0,2,108,101,110,0,3,121,110,0,2,109,97,110,117,101,108,0,3,101,114,105,99,104,0,5,121,0,4,116,0,5,116,0,3,105,116,0,3,111,116,116,0,3,121,0,2,111,114,121,0,1,110,103,101,108,98,101,114,116,0,3,108,101,98,101,114,116,0,2,110,105,115,0,2,111,99,104,0,0,69,110,111,115,0,2,114,105,99,111,0,4,113,117,101,0,1,112,104,114,97,105,109,0,5,121,105,109,0,4,101,109,0,1,114,97,115,109,117,115,0,4,116,117,115,0,2,101,107,0,2,104,97,114,100,0,5,116,0,2,105,99,0,4,104,0,4,107,0,3,101,0,3,107,0,3,110,0,2,108,0,2,109,97,110,110,111,0,3,105,110,0,2,110,101,115,116,0,6,111,0,6,117,115,0,3,105,101,0,3,115,116,0,3,121,0,2,114,105,99,107,0,3,111,108,0,5,108,0,2,115,107,105,110,101,0,2,118,0,3,73,110,0,0,69,114,119,105,110,0,1,115,100,114,97,115,0,2,109,101,0,2,114,97,0,2,116,101,98,97,110,0,4,118,97,110,0,1,116,97,110,0,2,104,97,110,0,3,101,0,4,108,98,101,114,116,0,5,114,101,100,0,2,105,101,110,110,101,0,2,116,111,114,101,0,1,117,101,108,108,0,2,103,101,110,0,5,101,0,5,105,111,0,6,117,115,0,2,115,116,97,99,101,0,1,118,0,2,97,110,0,2,101,108,105,110,0,4,121,110,0,3,110,0,3,114,97,114,100,0,4,101,100,0,5,116,116,0,2,105,110,0,2,121,110,0,1,119,97,110,0,3,114,100,0,4,116,0,0,69,119,101,108,108,0,3,110,0,1,122,101,99,104,105,101,108,0,3,107,105,101,108,0,3,113,117,105,101,108,0,2,105,101,99,104,105,101,108,101,0,2,114,97,0,3,105,0,0,70,97,98,101,0,4,114,0,3,105,97,110,0,6,111,0,4,101,110,0,4,111,0,2,105,114,0,4,102,97,120,0,4,108,101,105,103,104,0,5,105,101,0,2,108,105,116,111,0,3,107,110,101,114,0,2,114,0,3,108,97,121,0,4,101,101,0,5,105,103,104,0,5,121,0,4,105,101,0,4,121,0,3,114,0,4,101,108,0,6,108,0,4,105,115,0,2,117,108,107,110,101,114,0,0,70,97,120,0,1,101,100,101,114,105,99,111,0,2,101,0,2,108,105,99,0,5,101,0,5,105,111,0,4,107,101,0,5,115,0,4,112,101,0,4,120,0,4,122,105,111,0,2,111,100,111,114,0,2,114,100,0,4,105,101,0,5,110,97,110,100,0,4,121,0,3,103,117,115,0,6,111,110,0,3,110,97,110,100,111,0,3,114,101,108,0,6,108,0,4,105,115,0,1,105,100,101,108,0,5,105,111,0,3,111,108,101,0,2,101,108,100,0,5,105,110,103,0,5,115,0,2,108,98,101,114,116,0,7,101,0,7,111,0,3,105,112,0,0,70,105,108,105,112,112,111,0,3,109,101,114,0,4,111,114,101,0,2,110,0,3,100,108,97,121,0,5,101,121,0,3,108,97,121,0,4,101,121,0,3,110,0,2,116,122,0,4,103,101,114,97,108,100,0,1,108,101,109,0,4,105,110,103,0,4,109,105,110,103,0,3,116,99,104,0,6,101,114,0,2,105,110,0,4,110,0,4,116,0,2,111,114,105,97,110,0,4,121,0,3,121,100,0,2,121,110,110,0,1,111,110,115,0,4,105,101,0,3,122,0,4,105,101,0,2,114,98,101,115,0,3,100,0,3,101,115,116,0,6,101,114,0,3,114,101,115,116,0,0,70,111,114,114,101,115,116,101,114,0,3,115,116,101,114,0,2,115,115,0,3,116,101,114,0,2,119,108,101,114,0,1,114,97,110,0,4,99,101,115,99,111,0,5,104,111,116,0,5,105,115,0,7,99,111,0,7,107,117,115,0,5,107,108,105,110,0,7,121,110,0,5,111,105,115,0,4,107,0,5,105,101,0,5,108,105,110,0,6,121,110,0,5,121,0,4,110,105,101,0,5,121,0,4,115,0,5,105,115,99,111,0,4,116,115,0,4,122,0,5,101,110,0,3,115,99,111,0,4,101,114,0,4,105,101,114,0,4,113,117,105,116,111,0,3,122,101,0,5,114,0,0,70,114,97,122,105,101,114,0,2,101,100,0,4,100,105,101,0,5,121,0,4,101,107,0,5,114,105,99,0,8,104,0,8,107,0,8,111,0,7,103,111,0,7,107,0,4,114,105,99,0,7,107,0,3,101,0,4,100,109,97,110,0,4,108,97,110,100,0,4,109,97,110,0,5,111,110,0,3,109,111,110,116,0,2,105,101,100,114,105,99,104,0,8,107,0,3,116,122,0,1,117,108,116,111,110,0,0,71,97,98,98,105,101,0,4,121,0,3,101,0,3,105,0,4,101,0,3,114,105,101,108,0,7,101,0,7,108,111,0,3,121,0,0,71,97,101,108,0,4,97,110,0,2,103,101,0,2,105,108,0,4,101,0,2,108,0,3,101,0,4,110,0,3,108,97,103,104,101,114,0,5,114,100,0,3,118,97,110,0,4,101,110,0,4,105,110,0,2,109,97,108,105,101,108,0,2,110,0,3,110,105,101,0,4,111,110,0,4,121,0,2,114,0,3,97,108,100,0,3,100,0,4,101,110,101,114,0,4,105,101,0,5,110,101,114,0,4,110,101,114,0,4,121,0,3,101,0,4,107,0,4,116,104,0,4,121,0,3,102,105,101,108,100,0,3,105,107,0,0,71,97,114,110,101,114,0,3,111,108,100,0,3,114,97,114,100,0,4,101,107,0,5,116,0,6,104,0,6,116,0,4,105,99,107,0,5,107,0,4,111,116,0,6,116,0,4,121,0,3,116,104,0,3,118,0,4,101,121,0,4,105,110,0,4,121,0,3,119,105,110,0,4,111,111,100,0,3,121,0,2,115,112,97,114,0,6,100,0,6,111,0,4,101,114,0,3,116,111,110,0,2,117,108,116,105,101,114,111,0,3,116,104,105,101,114,0,2,118,0,3,97,110,0,3,101,110,0,3,105,110,0,2,119,97,105,110,0,0,71,97,119,101,110,0,2,121,0,3,101,108,111,114,100,0,3,108,101,0,5,114,0,4,111,114,0,6,100,0,1,101,97,114,97,108,116,0,5,114,100,0,2,110,101,0,3,111,0,2,111,102,102,0,5,114,101,121,0,6,121,0,3,114,97,115,0,4,100,105,101,0,4,103,0,5,101,0,6,115,0,5,105,0,6,101,0,5,121,0,2,114,97,108,100,0,4,114,100,0,6,111,0,3,101,107,0,3,104,97,114,100,0,7,116,0,3,105,0,4,99,107,0,4,107,0,3,109,97,105,110,0,0,71,101,114,109,97,105,110,101,0,5,121,110,101,0,3,111,109,101,0,3,114,97,114,100,0,4,105,0,5,101,0,4,121,0,3,121,0,1,104,101,114,97,114,100,111,0,1,105,97,99,111,98,111,0,5,109,111,0,5,112,111,0,3,110,0,4,110,105,0,3,118,97,110,105,0,2,98,0,3,98,0,4,105,101,0,4,121,0,2,100,101,111,110,0,2,102,102,0,4,97,114,100,0,4,101,114,0,4,105,101,0,4,111,114,100,0,4,121,0,2,108,0,3,98,101,114,116,0,7,111,0,4,117,114,116,0,3,101,115,0,3,108,0,0,71,105,108,108,101,115,0,2,110,103,101,114,0,3,111,0,2,111,114,100,97,110,111,0,4,103,105,0,6,111,0,3,118,97,110,110,105,0,2,114,97,108,100,111,0,4,117,100,0,2,115,101,108,98,101,114,116,0,2,117,108,105,111,0,3,115,101,112,112,101,0,4,116,105,110,111,0,5,111,0,1,108,101,110,0,4,100,101,110,0,5,111,110,0,4,110,0,2,121,110,0,4,110,0,1,111,100,97,114,100,0,5,116,0,3,100,97,114,100,0,6,116,0,3,102,114,101,101,0,6,121,0,5,121,0,3,119,105,110,0,2,110,122,97,108,101,115,0,6,111,0,2,111,98,101,114,0,2,114,97,110,0,0,71,111,114,97,117,100,0,3,100,97,110,0,4,101,110,0,4,105,101,0,4,111,110,0,4,121,0,2,116,104,97,114,116,0,3,116,102,114,105,101,100,0,1,114,97,99,101,0,3,100,101,105,103,104,0,5,121,0,4,121,0,3,101,104,109,101,0,4,109,101,0,3,104,97,109,0,3,105,103,0,3,109,0,3,110,0,4,103,101,0,6,114,0,4,110,105,101,0,5,121,0,4,116,0,5,104,97,109,0,6,101,109,0,5,108,101,121,0,4,118,105,108,108,101,0,3,121,0,2,101,103,0,4,103,0,5,111,114,121,0,4,111,105,114,101,0,0,71,114,101,103,111,111,114,0,5,114,0,6,105,111,0,7,117,115,0,6,121,0,3,110,118,105,108,108,101,0,2,105,102,102,0,5,105,101,0,6,110,0,6,116,104,0,5,121,0,3,115,0,4,119,111,108,100,0,3,122,0,2,111,118,101,0,5,114,0,1,117,97,108,116,101,114,105,111,0,2,103,108,105,101,108,109,111,0,2,105,100,111,0,3,108,98,101,114,116,0,4,108,97,117,109,101,0,5,101,114,109,111,0,2,110,0,3,97,114,0,3,110,101,114,0,3,116,97,114,0,4,101,114,0,4,104,101,114,0,2,115,0,3,115,0,3,116,97,102,0,5,118,0,0,71,117,115,116,97,118,101,0,6,111,0,6,117,115,0,2,116,104,114,101,121,0,5,105,101,0,5,121,0,2,121,0,0,72,97,100,0,3,108,101,101,0,5,105,103,104,0,5,121,0,3,114,105,97,110,0,2,103,97,110,0,3,101,110,0,2,105,108,101,121,0,4,121,0,2,107,101,101,109,0,3,105,109,0,2,108,0,3,101,0,4,105,103,104,0,4,121,0,3,108,0,4,115,121,0,3,115,101,121,0,4,121,0,2,109,0,3,101,108,0,3,105,100,0,4,108,0,5,116,111,110,0,4,115,104,0,0,72,97,109,108,101,110,0,4,105,110,0,3,109,97,100,0,3,110,101,116,0,2,110,97,110,0,3,107,0,3,115,0,4,105,97,105,110,0,4,111,110,0,2,114,97,108,100,0,3,98,101,114,116,0,3,99,111,117,114,116,0,3,100,121,0,3,108,97,110,0,6,100,0,4,101,110,0,5,121,0,4,105,110,0,3,109,97,110,0,4,111,110,0,3,111,108,100,0,4,117,110,0,3,112,0,4,101,114,0,3,114,105,115,0,6,111,110,0,4,121,0,3,116,0,4,108,101,121,0,4,119,101,108,108,0,3,118,0,4,101,121,0,0,72,97,114,119,101,108,108,0,4,105,108,108,108,0,2,115,104,101,101,109,0,4,105,109,0,3,107,101,108,0,6,108,0,3,108,101,116,116,0,3,116,105,101,0,5,110,103,115,0,4,121,0,2,118,101,110,0,2,121,100,101,110,0,4,111,110,0,3,101,115,0,3,119,97,114,100,0,4,111,111,100,0,3,121,105,109,0,2,122,101,0,4,108,0,3,108,101,116,116,0,1,101,97,108,108,0,3,116,104,0,2,98,101,114,116,0,2,99,116,111,114,0,2,105,110,100,114,105,99,107,0,4,114,105,99,107,0,6,107,0,2,110,100,101,114,115,111,110,0,4,114,105,99,107,0,6,107,0,3,114,105,0,5,107,0,0,72,101,110,114,121,0,2,114,98,0,4,101,114,116,0,4,105,101,0,4,121,0,3,99,0,4,117,108,101,0,7,115,0,6,105,101,0,3,105,98,101,114,116,111,0,3,109,97,110,0,6,110,0,4,105,101,0,4,111,110,0,4,121,0,3,110,97,110,100,111,0,3,111,108,100,0,3,114,105,99,107,0,3,115,99,104,0,6,101,108,0,4,104,0,5,101,108,0,3,118,101,0,5,121,0,2,119,0,3,101,0,4,116,0,5,116,0,3,105,101,0,4,116,116,0,2,121,119,111,111,100,0,1,105,0,0,72,105,101,114,111,110,121,109,117,115,0,2,108,97,114,105,111,0,6,117,115,0,5,121,0,3,108,0,4,97,114,100,0,6,121,0,4,101,108,0,5,114,121,0,4,105,97,114,100,0,5,101,0,6,114,0,4,121,0,5,101,114,0,3,116,111,110,0,2,110,122,101,0,2,114,97,109,0,3,115,99,104,0,1,111,98,97,114,100,0,5,116,0,3,101,121,0,3,105,101,0,2,100,103,101,0,2,101,98,97,114,116,0,2,103,97,110,0,2,108,100,101,110,0,3,108,105,115,0,4,121,0,3,109,101,115,0,3,116,0,2,109,101,114,0,5,101,0,0,72,111,109,101,114,117,115,0,2,114,97,99,101,0,5,105,111,0,4,116,105,111,0,6,117,115,0,3,115,116,0,3,116,0,4,101,110,0,4,111,110,0,2,119,97,114,100,0,3,101,121,0,3,105,101,0,2,121,116,0,1,117,98,101,0,4,114,116,0,6,111,0,4,121,0,3,105,101,0,2,101,121,0,2,103,104,0,4,105,101,0,3,105,98,101,114,116,0,3,111,0,3,117,101,115,0,2,109,98,101,114,116,0,7,111,0,3,102,114,101,121,0,5,105,100,0,6,101,100,0,3,112,104,114,101,121,0,2,110,102,114,101,100,111,0,3,116,0,0,72,117,110,116,101,114,0,4,105,110,103,116,111,110,0,4,108,101,101,0,6,121,0,2,114,108,101,101,0,5,105,103,104,0,5,121,0,2,115,97,105,110,0,3,101,105,110,0,3,115,101,105,110,0,1,121,0,2,97,116,116,0,2,109,97,110,0,3,105,101,0,0,73,97,103,111,0,2,105,110,0,2,110,0,1,98,114,97,104,105,109,0,1,99,104,97,98,111,100,0,1,103,103,105,101,0,3,121,0,2,110,97,99,101,0,5,105,111,0,6,117,115,0,4,116,105,117,115,0,4,122,0,5,105,111,0,2,111,114,0,1,107,101,0,3,121,0,1,108,97,105,114,101,0,3,114,105,111,0,0,73,109,109,97,110,117,101,108,0,1,110,103,97,109,97,114,0,4,114,0,3,101,108,98,101,114,116,0,4,109,97,114,0,4,114,0,3,108,101,98,101,114,116,0,4,105,115,0,3,109,97,114,0,3,114,97,0,5,109,0,4,105,109,0,2,105,103,111,0,2,110,101,115,115,0,3,105,115,0,1,111,114,103,111,0,5,115,0,2,115,101,112,0,1,114,97,0,2,118,0,3,105,110,0,5,101,0,5,103,0,2,119,105,110,0,5,110,0,1,115,97,0,3,97,99,0,4,107,0,3,99,0,4,99,111,0,3,100,111,114,0,6,101,0,0,73,115,97,105,97,104,0,3,107,0,2,105,97,104,105,0,3,100,111,114,0,6,101,0,6,111,0,4,114,111,0,2,114,97,101,108,0,2,115,105,97,104,0,1,116,99,104,0,1,118,97,110,0,3,114,0,2,101,0,3,114,0,3,115,0,2,111,114,0,1,122,97,97,107,0,3,107,0,2,122,121,0,0,74,97,98,101,122,0,2,99,107,0,4,105,101,0,4,115,111,110,0,4,121,0,3,111,98,0,5,111,0,3,113,117,101,115,0,2,101,0,2,105,109,101,0,4,105,101,0,2,107,101,0,3,105,101,0,0,74,97,107,111,98,0,2,109,97,97,108,0,4,108,0,3,101,115,0,5,111,110,0,5,121,0,4,121,0,3,105,101,0,4,108,0,5,108,0,4,115,111,110,0,3,109,97,108,0,2,110,0,3,101,107,0,3,111,115,0,2,114,97,100,0,3,100,0,3,101,98,0,4,100,0,3,105,98,0,4,100,0,3,114,97,100,0,4,101,100,0,5,116,0,6,116,0,4,105,100,0,4,111,100,0,3,118,105,115,0,2,115,101,0,4,110,0,3,111,110,0,3,112,101,114,0,0,74,97,115,117,110,0,2,118,105,101,114,0,2,121,0,3,101,0,3,109,101,0,4,105,101,0,3,115,111,110,0,1,100,97,118,105,101,0,1,101,97,110,0,2,99,104,111,0,2,100,0,3,100,0,4,121,0,3,101,100,105,97,104,0,3,105,100,105,97,104,0,2,102,102,0,4,101,114,101,121,0,6,115,111,110,0,4,105,101,0,4,114,101,121,0,5,121,0,4,121,0,2,104,117,0,2,110,111,0,3,115,0,2,112,104,116,104,97,104,0,2,114,97,100,0,4,108,100,0,4,109,101,121,0,5,105,101,0,3,101,0,4,109,101,0,0,74,101,114,101,109,105,97,104,0,7,115,0,6,101,0,5,121,0,3,109,97,105,110,0,7,101,0,5,121,110,101,0,3,111,109,101,0,5,121,0,3,114,105,0,5,101,0,4,111,108,100,0,5,109,101,0,4,121,0,3,118,105,115,0,2,115,115,0,4,101,0,5,101,0,5,121,0,4,105,101,0,3,117,115,0,2,116,104,0,4,114,111,0,1,105,109,0,3,109,105,101,0,4,121,0,1,111,0,2,97,99,104,105,109,0,3,113,117,105,110,0,2,98,0,2,99,107,0,4,111,0,0,74,111,100,105,0,4,101,0,3,121,0,2,101,0,3,108,0,3,121,0,2,104,97,110,0,5,110,0,6,101,115,0,3,110,0,4,97,116,104,97,110,0,7,111,110,0,4,110,105,101,0,5,121,0,4,121,0,2,110,0,3,97,104,0,4,115,0,4,116,104,97,110,0,6,111,110,0,3,101,0,2,114,100,97,110,0,4,111,110,0,3,103,97,110,0,4,101,0,3,121,0,2,115,101,0,4,105,116,111,0,4,112,104,0,3,104,0,4,105,97,0,4,117,97,0,0,74,111,115,104,117,97,104,0,3,105,97,104,0,5,115,0,2,117,114,100,97,105,110,0,2,122,101,102,0,1,117,97,110,0,2,100,0,3,97,104,0,4,115,0,3,100,0,3,101,0,3,111,110,0,2,108,101,0,4,115,0,3,105,97,110,0,4,101,0,4,111,0,4,117,115,0,2,115,116,101,110,0,4,105,110,0,6,105,97,110,0,6,111,0,5,115,0,4,117,115,0,0,75,97,104,97,108,101,101,108,0,3,108,105,108,0,2,105,110,0,4,101,0,3,115,101,114,0,2,108,101,0,4,98,0,3,105,108,0,0,75,97,108,108,101,0,3,118,105,110,0,2,110,101,0,2,114,101,101,109,0,4,108,0,3,105,109,0,3,108,0,4,97,110,0,4,101,110,115,0,4,105,107,0,5,115,0,3,110,101,121,0,3,111,108,121,0,2,115,112,97,114,0,4,101,114,0,2,121,110,101,0,1,101,97,110,0,4,101,0,3,114,110,101,121,0,4,121,0,2,101,102,101,0,5,114,0,3,108,98,121,0,3,110,0,4,97,110,0,4,101,0,2,105,114,0,3,116,104,0,2,108,98,101,101,0,4,121,0,3,101,0,3,108,98,121,0,0,75,101,108,108,101,110,0,5,121,0,4,121,0,3,115,101,121,0,3,118,105,110,0,3,119,105,110,0,2,110,0,3,100,97,108,0,6,108,0,4,101,108,108,0,4,114,105,99,107,0,8,115,0,3,110,0,4,97,110,0,4,101,100,121,0,5,116,104,0,6,116,0,4,105,101,0,5,116,104,0,4,121,0,3,111,110,0,3,116,0,4,111,110,0,3,121,111,110,0,2,114,0,3,98,121,0,3,107,0,3,109,105,101,0,5,116,0,4,121,0,3,114,0,4,121,0,0,75,101,114,119,105,110,0,6,110,0,2,118,0,3,97,110,0,3,101,110,0,3,105,110,0,3,111,110,0,1,104,97,108,105,108,0,1,105,101,108,0,3,110,97,110,0,2,108,101,0,4,121,0,3,105,97,110,0,3,108,105,97,110,0,5,101,0,4,121,0,2,109,0,3,98,97,108,108,0,4,101,108,108,0,4,108,101,0,2,110,0,3,99,97,105,100,0,3,103,0,4,115,108,101,121,0,6,121,0,5,116,111,110,0,3,110,105,101,0,4,121,0,3,115,108,101,121,0,2,112,0,0,84,111,107,0,0,75,105,112,112,0,0,75,105,112,112,97,114,0,4,101,114,0,4,105,101,0,4,121,0,2,114,98,121,0,3,107,0,2,116,0,1,108,97,117,115,0,2,101,109,101,110,115,0,6,116,0,3,111,110,0,2,105,109,101,110,116,0,1,110,111,120,0,1,111,101,110,114,97,97,100,0,2,110,114,97,100,0,3,115,116,97,110,116,105,110,0,10,101,0,2,114,101,121,0,3,116,0,3,121,0,1,114,105,115,0,4,104,97,0,5,110,97,0,7,104,0,4,112,105,110,0,4,116,105,97,110,0,5,111,0,6,102,101,114,0,7,102,101,114,0,7,111,114,0,9,111,0,6,112,104,101,114,0,0,75,114,105,115,116,111,115,0,1,117,114,116,0,4,105,115,0,1,121,0,2,108,101,0,3,105,101,0,0,76,97,105,114,100,0,2,108,111,0,2,109,97,114,0,3,98,101,114,116,0,3,109,111,110,100,0,3,111,110,100,0,5,116,0,2,110,99,101,0,5,108,111,116,0,3,100,0,3,101,0,4,121,0,3,103,115,100,111,110,0,5,116,111,110,0,3,105,101,0,3,110,105,101,0,4,121,0,2,114,114,121,0,3,115,0,2,117,103,104,116,111,110,0,3,110,99,101,0,3,114,101,110,0,6,99,101,0,6,115,0,6,116,0,4,105,101,0,0,76,97,117,114,105,116,122,0,2,119,0,3,114,101,110,99,101,0,4,121,0,3,116,111,110,0,2,121,0,3,116,111,110,0,2,122,97,114,0,5,101,0,5,111,0,5,117,115,0,1,101,101,0,3,108,97,110,100,0,2,102,116,121,0,2,105,99,101,115,116,101,114,0,3,102,0,3,103,104,0,5,116,111,110,0,2,107,0,2,108,97,110,100,0,2,109,0,3,97,114,0,3,109,105,101,0,4,121,0,3,117,101,108,0,2,110,97,114,100,0,3,99,105,0,3,110,97,114,100,0,4,105,101,0,2,111,0,3,110,0,4,97,114,100,0,0,76,101,111,110,97,114,100,111,0,4,101,114,100,0,4,104,97,114,100,0,4,105,100,0,6,97,115,0,3,112,111,108,100,0,2,114,111,105,0,4,121,0,2,115,0,3,108,101,121,0,4,105,101,0,3,116,101,114,0,2,117,112,111,108,100,0,2,118,0,3,101,121,0,3,105,0,4,110,0,3,111,110,0,3,121,0,2,119,0,3,101,115,0,3,105,101,0,4,115,115,0,2,122,108,101,121,0,1,105,97,109,0,2,101,102,0,2,110,0,3,99,0,4,111,108,110,0,3,100,0,4,111,110,0,4,115,97,121,0,0,76,105,110,100,115,101,121,0,4,121,0,3,107,0,3,110,0,3,111,101,108,0,3,117,115,0,2,111,110,0,4,101,108,0,6,108,111,0,2,115,108,101,0,1,108,101,119,101,108,108,121,110,0,2,111,121,100,0,2,121,119,101,108,108,121,110,0,1,121,110,120,0,1,111,99,107,0,4,101,0,4,119,111,111,100,0,2,100,111,118,105,99,111,0,2,103,97,110,0,2,109,98,97,114,100,0,2,110,0,3,110,97,114,100,0,4,105,101,0,4,121,0,2,114,97,110,116,0,3,101,110,0,5,115,0,5,122,111,0,3,105,110,0,3,110,101,0,3,114,105,101,0,4,121,0,0,76,111,116,104,97,105,114,101,0,5,114,105,111,0,2,117,0,3,105,101,0,4,115,0,2,118,101,108,108,0,2,119,101,0,4,108,108,0,3,114,97,110,99,101,0,2,121,0,3,100,105,101,0,1,117,99,97,0,4,105,115,0,4,115,0,3,101,0,3,104,111,0,3,105,97,110,0,6,111,0,5,115,0,4,101,110,0,4,111,0,4,117,115,0,2,100,111,118,105,99,111,0,3,118,105,103,0,3,119,105,103,0,2,105,103,105,0,3,115,0,2,107,97,115,0,3,101,0,2,116,101,114,111,0,3,104,101,114,0,1,121,0,0,76,121,100,111,110,0,2,101,108,108,0,2,108,101,0,2,109,97,110,0,2,110,0,3,110,0,2,111,110,0,0,77,97,99,0,3,101,0,3,107,0,4,101,110,122,105,101,0,2,100,100,105,101,0,4,121,0,3,105,115,111,110,0,2,103,110,117,109,0,2,104,109,111,117,100,0,4,117,100,0,2,105,115,111,110,0,2,106,101,0,3,111,114,0,2,108,0,3,97,99,104,105,0,3,99,104,121,0,4,111,108,109,0,3,108,111,114,121,0,3,118,105,110,0,2,110,0,3,100,101,108,0,3,102,114,101,100,0,3,110,105,101,0,4,121,0,3,111,0,0,77,97,110,111,108,111,0,3,117,101,108,0,2,114,0,3,99,0,4,101,108,0,6,108,111,0,7,117,115,0,6,111,0,4,104,97,108,108,0,4,111,0,5,115,0,4,117,115,0,3,105,106,110,0,4,111,0,5,110,0,4,117,115,0,3,107,0,4,111,115,0,4,117,115,0,3,108,105,110,0,4,111,0,5,110,0,5,119,0,6,101,0,3,109,97,100,117,107,101,0,3,115,104,0,5,97,108,0,7,108,0,3,116,0,4,97,105,110,110,0,4,101,110,0,4,105,101,0,0,77,97,114,116,105,110,0,6,111,0,4,121,0,5,110,0,3,118,0,4,101,0,5,110,0,4,105,110,0,3,119,105,110,0,2,115,111,110,0,3,115,105,109,105,108,105,97,110,111,0,6,111,0,2,116,97,0,3,101,111,0,3,104,101,0,5,119,0,4,105,97,110,0,6,115,0,3,105,97,115,0,3,116,0,4,101,111,0,4,104,97,101,117,115,0,5,101,117,115,0,6,119,0,5,105,97,115,0,6,101,117,0,7,119,0,5,117,115,0,4,105,97,115,0,5,101,0,4,121,0,2,117,114,105,99,101,0,0,77,97,117,114,105,99,105,111,0,5,101,0,5,115,101,0,5,116,115,0,5,122,105,111,0,4,121,0,2,120,0,3,105,101,0,4,109,0,5,105,108,105,97,110,0,10,117,115,0,8,101,110,0,5,111,0,3,119,101,108,108,0,3,121,0,2,121,101,114,0,3,110,97,114,100,0,4,101,0,4,111,114,100,0,3,111,114,0,1,101,97,100,0,4,101,0,2,105,101,114,0,3,114,0,2,108,0,3,118,105,110,0,4,121,110,0,2,110,97,114,100,0,3,100,101,108,0,4,105,101,0,4,121,0,2,114,101,100,101,116,104,0,0,77,101,114,101,100,105,116,104,0,4,108,108,0,3,105,108,108,0,3,108,101,0,3,114,101,108,0,4,105,99,107,0,5,108,108,0,4,121,0,3,118,0,4,105,110,0,3,119,105,110,0,4,121,110,0,3,121,108,0,2,121,101,114,0,1,105,99,0,3,97,104,0,3,104,97,101,108,0,5,105,108,0,5,108,0,6,101,0,4,101,97,108,0,5,105,108,0,5,108,0,6,101,0,3,107,0,4,101,121,0,4,105,101,0,4,121,0,2,103,117,101,108,0,2,107,97,101,108,0,3,101,0,4,108,0,0,77,105,107,101,121,0,3,107,101,108,0,3,111,108,0,2,108,101,0,4,115,0,3,108,0,4,97,114,100,0,4,101,114,0,3,111,0,3,116,0,4,105,101,0,4,111,110,0,4,121,0,2,110,101,114,0,3,111,114,0,2,115,99,104,97,0,2,116,99,104,0,5,97,101,108,0,5,101,108,0,7,108,0,1,111,101,0,2,104,97,109,109,101,100,0,4,110,100,97,115,0,6,105,115,0,2,105,115,101,0,5,115,0,4,104,101,0,2,110,114,111,0,5,101,0,3,116,97,103,117,101,0,4,101,0,4,103,111,109,101,114,121,0,0,77,111,110,116,105,0,4,121,0,2,111,114,101,0,2,114,100,0,4,101,99,97,105,0,4,121,0,3,101,121,0,3,103,97,110,0,4,101,110,0,4,117,110,0,3,105,101,0,4,116,122,0,3,108,101,101,0,5,121,0,4,121,0,3,114,105,101,0,5,115,0,4,121,0,3,115,101,0,3,116,0,4,101,110,0,4,105,101,0,5,109,101,114,0,4,111,110,0,4,121,0,2,115,101,0,4,115,0,3,104,101,0,3,115,0,2,122,101,115,0,1,117,102,102,105,110,0,2,104,97,109,109,97,100,0,0,77,117,110,109,114,111,0,3,114,111,101,0,2,114,100,111,99,104,0,6,107,0,3,114,97,121,0,4,121,0,3,118,121,110,0,1,121,0,2,99,97,0,4,104,0,3,104,97,108,0,2,101,114,0,2,108,101,115,0,3,111,0,2,114,111,110,0,3,118,121,110,0,3,119,121,110,0,0,78,97,104,117,109,0,2,112,0,3,111,108,101,111,110,0,3,112,105,101,0,4,121,0,2,116,0,3,97,108,0,5,101,0,4,110,105,101,108,0,3,101,0,3,104,97,110,0,6,97,101,108,0,6,105,97,108,0,7,101,108,0,7,108,0,0,78,97,116,116,121,0,1,101,97,108,0,4,101,0,4,108,0,4,111,110,0,4,115,111,110,0,4,121,0,2,100,0,3,100,105,101,0,4,121,0,2,101,108,0,2,102,101,110,0,2,104,101,109,105,97,104,0,2,105,108,0,4,108,0,4,115,0,2,108,115,0,4,111,110,0,2,114,111,0,4,110,0,2,115,116,101,114,0,4,111,114,0,2,118,0,0,66,105,110,103,111,0,2,108,98,111,0,0,78,101,118,105,108,0,5,101,0,5,108,101,0,4,110,0,5,115,0,2,119,116,111,110,0,1,105,97,108,0,0,78,105,97,108,108,0,2,99,99,111,108,111,0,3,104,111,108,97,115,0,6,101,0,6,115,0,3,107,0,4,101,121,0,4,105,101,0,4,111,0,5,108,97,0,7,105,0,7,115,0,7,117,115,0,4,121,0,3,111,0,4,108,0,5,97,0,6,105,0,7,115,0,6,115,0,5,105,115,0,2,101,108,0,4,115,0,2,103,101,108,0,2,107,105,0,4,116,97,0,3,107,105,0,3,111,0,4,108,97,0,6,105,0,6,111,115,0,6,115,0,0,78,105,107,111,108,97,117,115,0,5,111,115,0,4,115,0,2,108,0,3,101,115,0,3,115,0,4,111,110,0,2,118,101,110,0,1,111,97,99,104,0,3,104,0,3,107,0,0,74,111,195,171,108,0,0,78,111,97,109,0,2,98,101,0,3,105,101,0,3,108,101,0,3,121,0,2,101,0,3,108,0,2,108,97,110,0,5,100,0,3,108,0,4,105,101,0,4,121,0,2,114,98,101,114,116,0,4,105,101,0,4,121,0,3,109,97,110,0,6,100,0,4,105,101,0,4,121,0,3,114,105,101,0,0,78,111,114,114,105,115,0,4,121,0,3,116,104,0,5,114,111,112,0,6,117,112,0,4,111,110,0,2,119,101,108,108,0,1,121,101,0,0,79,97,116,101,115,0,1,98,97,100,105,97,104,0,6,115,0,2,101,100,0,4,105,97,104,0,3,114,111,110,0,2,105,100,105,97,104,0,3,101,0,2,121,0,1,99,116,97,118,105,117,115,0,1,100,101,0,3,108,108,0,3,121,0,2,105,101,0,2,111,0,2,121,0,1,103,100,97,110,0,3,101,110,0,3,111,110,0,1,108,97,103,0,3,118,0,2,101,0,3,110,111,108,105,110,0,2,105,110,0,0,79,108,105,118,101,114,0,6,111,0,4,105,101,114,0,7,111,0,2,108,105,101,0,3,121,0,2,118,97,110,0,1,109,97,114,0,2,101,114,111,0,1,110,102,114,101,0,4,111,105,0,2,111,102,114,101,100,111,0,1,114,97,110,0,3,122,105,111,0,2,98,97,100,105,97,104,0,2,101,110,0,2,105,110,0,3,111,110,0,2,108,97,110,0,5,100,0,6,111,0,2,114,97,110,0,3,101,110,0,3,105,110,0,2,115,111,110,0,2,116,111,110,0,2,118,0,3,105,108,108,101,0,1,115,98,101,114,116,0,3,111,114,110,0,6,101,0,4,117,114,110,0,0,79,115,98,111,117,114,110,101,0,2,103,111,111,100,0,2,109,111,110,100,0,3,117,110,100,0,2,115,105,101,0,2,119,97,108,100,0,3,101,108,108,0,1,116,101,115,0,2,104,101,108,108,111,0,3,111,0,2,105,115,0,2,116,111,0,1,119,101,110,0,1,122,122,105,101,0,3,121,0,0,80,97,98,108,111,0,2,99,101,0,3,107,115,116,111,110,0,3,111,0,4,114,114,111,0,2,100,100,105,101,0,4,121,0,3,103,101,116,0,6,116,0,3,114,97,105,99,0,6,103,0,4,105,97,99,0,2,103,101,0,2,105,103,101,0,3,108,0,2,108,108,0,3,109,0,0,80,97,108,109,101,114,0,2,110,99,104,105,116,111,0,5,111,0,2,111,108,111,0,2,112,97,103,101,110,111,0,2,113,117,105,116,111,0,2,114,107,0,4,101,0,5,114,0,3,110,101,108,108,0,3,114,110,101,108,108,0,4,121,0,3,115,105,102,97,108,0,2,115,99,97,108,0,6,101,0,3,113,117,97,108,101,0,2,116,0,3,101,0,4,110,0,3,105,110,0,3,111,110,0,3,114,105,99,0,6,101,0,6,105,111,0,6,107,0,5,122,105,111,0,7,117,115,0,3,115,121,0,3,116,101,110,0,4,105,101,0,5,110,0,4,111,110,0,0,80,97,116,116,121,0,2,117,108,0,4,105,101,0,4,111,0,4,121,0,2,118,101,108,0,3,108,111,118,0,2,120,111,110,0,3,116,111,110,0,2,121,116,111,110,0,1,101,97,100,97,114,0,3,114,99,101,0,2,98,114,111,111,107,0,2,100,101,114,0,3,114,111,0,2,105,114,99,101,0,2,109,98,114,111,107,101,0,2,110,0,3,110,0,4,105,101,0,4,121,0,3,114,111,100,0,2,112,101,0,3,105,108,108,111,0,4,116,111,0,2,114,99,101,118,97,108,0,4,105,118,97,108,0,4,121,0,3,105,99,101,0,3,107,105,110,0,3,110,101,108,108,0,3,114,101,110,0,0,80,101,114,114,121,0,2,116,101,0,4,114,0,5,117,115,0,4,121,0,3,114,0,2,121,116,101,114,0,4,111,110,0,1,104,105,108,0,4,98,101,114,116,0,4,105,112,0,4,108,105,112,0,7,101,0,7,112,0,3,110,101,97,115,0,3,112,0,1,105,101,114,99,101,0,4,114,101,0,4,115,111,110,0,3,116,101,114,0,4,114,101,107,0,5,111,0,2,103,103,121,0,2,110,99,97,115,0,4,104,97,115,0,4,117,115,0,3,101,97,112,112,108,101,0,2,111,116,114,0,2,112,0,3,112,111,0,1,111,111,104,0,2,114,116,0,0,80,111,114,116,101,114,0,4,105,101,0,4,121,0,2,117,108,0,2,119,101,108,108,0,1,114,101,110,0,4,116,0,5,105,99,101,0,6,115,115,0,3,115,99,111,116,116,0,4,116,111,110,0,2,105,99,101,0,3,110,99,101,0,4,122,0,2,121,99,101,0,1,117,102,102,0,2,114,99,101,108,108,0,2,116,110,97,109,0,4,101,109,0,1,121,111,116,114,0,0,81,117,101,110,116,0,5,105,110,0,2,105,108,108,0,5,97,110,0,3,110,99,101,121,0,5,121,0,4,108,97,110,0,4,110,0,4,116,0,5,105,110,0,5,111,110,0,5,117,115,0,0,82,97,98,0,3,98,105,0,3,105,0,2,100,0,3,99,108,105,102,102,101,0,3,100,105,101,0,4,121,0,2,102,97,101,108,0,6,108,108,101,0,7,111,0,3,101,0,3,102,0,4,97,101,108,108,111,0,5,114,116,121,0,4,101,114,116,121,0,3,105,0,2,103,110,97,114,0,2,105,109,111,110,100,111,0,4,117,110,100,0,7,111,0,3,110,101,114,0,2,108,101,105,103,104,0,3,102,0,3,112,104,0,2,109,0,3,111,110,0,3,115,97,121,0,4,101,121,0,2,110,99,101,0,5,108,108,0,3,100,0,4,97,108,0,0,82,97,110,100,97,108,108,0,4,101,108,108,0,4,105,0,5,101,0,4,111,108,102,0,6,112,104,0,4,121,0,3,115,101,108,108,0,4,111,109,0,2,111,117,108,0,2,112,104,97,101,108,0,2,117,108,0,2,118,105,0,4,100,0,4,118,0,2,119,108,101,121,0,2,121,0,3,109,111,110,100,0,4,117,110,100,0,3,110,97,114,100,0,4,101,114,0,4,111,114,0,1,101,97,100,0,4,101,0,3,103,97,110,0,4,101,110,0,3,109,111,110,110,0,2,100,0,3,100,0,3,102,111,114,100,0,2,101,99,101,0,3,100,0,0,82,101,101,115,0,4,101,0,2,103,0,3,97,110,0,3,101,110,0,3,103,105,101,0,5,115,0,4,121,0,3,105,110,97,108,100,0,6,117,108,100,0,2,105,100,0,4,97,114,0,4,101,114,0,3,108,108,121,0,3,110,97,108,100,0,7,111,0,8,115,0,4,104,97,114,100,0,5,111,108,100,0,4,111,108,100,0,4,119,97,108,100,0,2,109,0,3,105,110,103,116,111,110,0,3,117,115,0,2,110,97,100,111,0,4,108,100,111,0,4,114,100,0,4,116,111,0,4,117,100,0,5,108,116,0,3,101,0,2,117,98,101,0,0,82,101,117,98,101,110,0,3,118,101,110,0,2,120,0,2,121,0,3,110,97,114,100,0,4,111,108,100,0,7,115,0,1,104,101,116,116,0,2,121,115,0,1,105,99,0,3,97,114,100,0,6,111,0,3,99,97,114,100,111,0,3,101,0,0,66,97,103,97,103,101,0,0,80,101,104,117,195,169,110,0,0,82,105,99,104,0,4,97,114,100,0,7,111,0,6,116,0,4,105,101,0,4,109,111,110,100,0,6,117,110,100,0,4,121,0,3,107,0,0,77,97,114,105,101,110,0,0,82,105,99,107,97,114,100,0,4,101,114,116,0,5,121,0,4,105,0,5,101,0,4,121,0,0,82,105,99,111,114,105,107,105,0,2,107,0,3,107,105,0,2,108,101,121,0,2,110,97,108,100,111,0,3,103,0,4,111,0,2,111,98,97,114,100,0,3,114,100,97,110,0,2,112,0,3,108,101,121,0,2,116,99,104,105,101,0,1,111,97,114,107,101,0,2,98,0,3,98,0,4,101,114,116,0,4,105,101,0,4,121,0,3,101,114,115,0,5,116,0,6,111,0,3,105,110,0,5,101,116,0,5,115,111,110,0,2,99,104,101,115,116,101,114,0,3,107,0,4,101,121,0,4,105,101,0,4,119,101,108,108,0,4,121,0,2,100,0,3,100,0,0,82,111,100,100,105,101,0,4,121,0,3,101,114,105,99,0,7,104,0,7,107,0,6,103,111,0,3,103,101,0,5,114,0,3,110,101,121,0,3,111,108,102,111,0,5,112,104,0,7,101,0,3,114,105,99,107,0,5,103,111,0,5,113,117,101,0,2,103,0,3,101,114,0,5,105,111,0,5,115,0,2,105,0,2,108,97,110,100,0,6,111,0,3,100,97,110,0,3,101,121,0,3,102,0,4,101,0,3,108,97,110,100,0,4,105,101,0,5,110,0,6,115,0,4,111,0,3,112,104,0,0,82,111,109,97,0,4,105,110,0,4,110,0,3,101,111,0,2,110,0,3,97,108,100,0,3,110,105,101,0,4,121,0,2,111,110,101,121,0,3,115,101,118,101,108,116,0,2,114,107,101,0,3,121,0,2,115,99,111,0,5,101,0,3,115,0,4,105,101,0,4,121,0,2,116,104,0,2,117,114,107,101,0,3,118,105,110,0,2,119,97,110,0,3,101,110,0,3,108,97,110,100,0,3,110,101,121,0,2,121,0,3,97,108,0,5,108,0,3,99,101,0,1,114,105,111,99,97,114,100,0,1,117,98,101,0,4,110,0,3,105,110,0,0,82,117,98,121,0,2,100,100,0,4,105,101,0,4,121,0,3,105,101,0,4,103,101,114,0,3,111,108,102,0,6,111,0,5,112,104,0,3,121,0,4,97,114,100,0,2,102,101,0,3,117,115,0,2,103,103,105,101,114,111,0,2,112,101,114,116,0,6,111,0,3,114,101,99,104,116,0,2,114,105,107,0,2,115,115,0,4,101,108,108,0,3,116,105,101,0,5,110,0,4,121,0,2,116,103,101,114,0,3,104,101,114,102,111,114,100,0,3,108,101,100,103,101,0,3,116,101,114,0,4,103,101,114,0,2,121,0,1,121,97,110,0,2,108,101,121,0,2,111,110,0,0,82,121,117,110,0,0,83,97,108,0,3,101,101,109,0,4,109,0,3,105,109,0,3,109,111,110,0,3,111,109,111,0,6,110,0,7,101,0,3,118,97,100,111,114,0,5,116,111,114,101,0,4,105,100,111,114,0,2,109,0,3,109,105,101,0,4,121,0,3,112,115,111,110,0,3,115,111,110,0,3,117,101,108,0,6,101,0,2,110,99,104,111,0,3,100,101,114,0,6,115,0,7,111,110,0,4,111,114,0,4,114,111,0,4,121,0,3,102,111,114,100,0,3,115,111,110,0,6,101,0,2,114,103,101,0,5,110,116,0,2,115,99,104,97,0,0,83,97,115,104,97,0,2,117,108,0,3,110,99,104,111,0,4,100,101,114,0,7,115,0,8,111,110,0,5,114,97,0,3,118,101,117,114,0,2,119,0,3,121,101,114,0,6,101,0,2,120,0,3,101,0,3,111,110,0,2,121,0,3,101,114,0,5,115,0,3,114,101,0,5,115,0,1,99,97,114,102,97,99,101,0,2,104,117,121,108,101,114,0,2,111,116,0,4,116,0,5,105,0,6,101,0,5,121,0,1,101,97,109,117,115,0,3,110,0,2,98,97,115,116,105,97,110,0,9,111,0,7,101,110,0,2,101,0,0,83,101,108,98,121,0,3,105,103,0,2,114,103,101,0,5,97,110,116,0,5,105,0,5,110,116,0,4,105,111,0,2,116,104,0,2,117,109,97,115,0,2,119,97,114,100,0,2,121,109,111,117,114,0,1,104,97,100,111,119,0,3,101,0,3,105,110,101,0,3,108,111,109,0,3,109,117,115,0,3,110,97,110,0,4,101,0,4,110,97,110,0,5,111,110,0,3,117,103,104,110,0,4,110,0,3,119,0,4,110,0,3,121,0,4,110,101,0,2,101,97,0,3,102,102,0,5,105,101,0,7,108,100,0,5,121,0,3,108,98,121,0,0,83,104,101,108,100,101,110,0,4,108,0,5,101,121,0,4,116,111,110,0,3,109,0,3,112,0,4,97,114,100,0,4,104,101,114,100,0,4,112,97,114,100,0,5,101,114,100,0,3,114,105,100,97,110,0,4,108,111,99,107,0,8,101,0,4,109,0,5,97,110,0,5,105,101,0,5,121,0,4,119,105,110,0,5,111,111,100,0,5,121,110,100,0,2,111,108,111,109,0,2,117,114,108,111,99,107,0,8,101,0,4,119,111,111,100,0,1,105,0,2,98,121,108,0,2,100,0,3,110,101,101,0,5,121,0,2,101,103,102,114,105,101,100,0,2,102,102,114,101,0,2,103,0,0,83,105,103,102,114,105,100,0,6,101,100,0,3,105,115,109,111,110,100,0,9,111,0,6,117,110,100,0,9,111,0,3,109,117,110,100,0,3,118,97,114,100,0,2,108,97,115,0,3,118,97,105,110,0,5,110,0,6,111,0,6,117,115,0,4,101,115,116,101,114,0,4,105,111,0,2,109,0,3,101,111,110,0,3,109,111,110,100,115,0,3,111,110,0,5,101,0,2,110,99,108,97,105,114,0,6,114,101,0,2,119,97,114,100,0,1,107,101,108,108,0,5,121,0,2,105,112,0,4,112,0,5,101,114,0,5,105,101,0,5,121,0,4,116,111,110,0,2,121,0,0,83,107,121,101,0,3,108,97,114,0,4,101,114,0,1,108,97,100,101,0,2,111,97,110,0,5,101,0,2,121,0,1,109,105,116,104,0,4,116,121,0,1,111,108,0,3,108,105,101,0,4,121,0,3,111,109,111,110,0,2,109,101,114,115,101,116,0,2,110,0,3,110,105,101,0,4,121,0,1,112,101,110,99,101,0,6,114,0,4,115,101,0,6,114,0,2,105,107,101,0,1,116,97,99,101,101,0,4,121,0,3,102,102,97,114,100,0,5,111,114,100,0,4,111,114,100,0,3,110,0,4,100,102,111,114,100,0,4,102,105,101,108,100,0,5,111,114,100,0,4,105,115,108,97,115,0,0,83,116,97,110,105,115,108,97,117,115,0,8,119,0,4,108,101,105,103,104,0,6,121,0,5,121,0,4,116,111,110,0,4,119,111,111,100,0,3,118,114,111,0,6,115,0,2,101,97,114,110,0,6,101,0,3,102,97,110,0,6,111,0,4,102,101,110,0,3,112,104,97,110,0,7,117,115,0,5,101,110,0,3,114,108,105,110,103,0,4,110,0,5,101,0,3,118,101,0,5,110,0,4,105,101,0,4,121,0,3,119,97,114,100,0,6,116,0,2,105,108,108,109,97,110,0,8,110,0,3,110,107,121,0,3,114,108,105,110,103,0,2,117,0,3,97,114,116,0,0,83,117,108,108,105,118,97,110,0,4,121,0,2,109,110,101,114,0,2,110,110,121,0,2,116,104,101,114,108,97,110,0,9,100,0,3,116,111,110,0,1,118,101,110,0,4,100,0,1,119,101,110,0,1,121,100,0,3,110,101,121,0,2,108,97,115,0,3,118,97,110,0,4,101,115,116,101,114,0,2,109,97,110,0,3,111,110,0,0,84,97,98,0,3,98,0,4,105,101,0,4,121,0,3,101,114,0,3,111,114,0,2,100,0,3,100,0,4,101,111,0,5,117,115,122,0,3,101,97,115,0,4,111,0,4,115,0,3,105,111,0,2,105,108,111,114,0,0,84,97,105,116,0,4,101,0,2,108,98,101,114,116,0,4,111,116,0,3,108,105,101,0,4,121,0,2,109,0,3,97,115,0,3,109,105,101,0,4,121,0,2,110,0,3,110,0,4,101,114,0,5,121,0,4,105,101,0,4,121,0,2,114,114,97,110,99,101,0,2,116,101,0,2,121,108,111,114,0,1,101,97,100,111,114,0,2,100,0,3,100,0,4,105,101,0,4,121,0,3,105,101,0,3,109,97,110,0,4,117,110,100,0,2,109,112,0,4,108,101,0,6,116,111,110,0,2,111,100,111,111,114,0,5,114,0,0,84,101,111,100,111,114,105,99,111,0,6,111,0,2,114,101,110,99,101,0,6,105,111,0,3,114,97,110,99,101,0,4,101,108,0,6,108,0,5,110,99,101,0,4,105,0,5,108,108,0,4,121,0,1,104,97,99,104,101,114,0,3,100,100,101,117,115,0,5,117,115,0,4,101,117,115,0,3,105,110,0,5,101,0,3,110,101,0,3,116,99,104,0,6,101,114,0,3,120,116,101,114,0,3,121,110,101,0,2,101,98,97,117,108,116,0,3,100,114,105,99,0,7,107,0,3,111,0,4,98,97,108,100,0,4,100,111,114,0,7,101,0,7,105,99,0,2,105,98,97,117,100,0,6,116,0,0,84,104,111,109,0,4,97,0,5,115,0,3,114,0,4,105,110,0,4,110,0,5,100,105,107,101,0,5,105,101,0,5,116,111,110,0,5,121,0,4,112,101,0,4,115,116,101,105,110,0,7,110,0,4,118,97,108,100,0,2,117,114,115,116,97,110,0,6,111,110,0,1,105,98,111,108,100,0,2,101,98,111,108,100,0,5,117,116,0,2,108,101,114,0,2,109,0,3,109,105,101,0,4,121,0,3,111,102,101,105,0,4,116,101,111,0,5,104,101,101,0,7,117,115,0,6,121,0,2,114,114,101,108,108,0,2,116,111,0,4,115,0,3,117,115,0,0,84,111,98,101,0,3,105,97,104,0,5,115,0,4,101,0,4,110,0,4,116,0,3,121,0,2,100,0,3,100,0,4,105,101,0,4,121,0,2,105,98,111,105,100,0,2,109,0,3,97,115,0,5,111,0,3,101,0,3,107,105,110,0,3,108,105,110,0,3,109,105,101,0,4,121,0,2,110,110,105,101,0,3,121,0,2,114,101,0,4,121,0,3,105,110,0,3,114,0,4,97,110,99,101,0,4,101,0,5,110,99,101,0,5,121,0,4,105,110,0,4,121,0,0,84,111,119,110,0,4,101,121,0,4,105,101,0,4,115,101,110,100,0,4,121,0,1,114,97,99,101,0,5,121,0,4,105,101,0,4,121,0,3,118,101,114,0,6,115,0,4,105,115,0,4,117,115,0,2,101,102,111,114,0,3,109,97,105,110,0,7,101,0,5,121,110,101,0,3,110,116,0,5,111,110,0,3,118,0,4,97,114,0,4,101,114,0,4,111,114,0,3,121,0,2,105,112,0,4,112,0,3,115,0,4,116,97,109,0,6,110,0,2,111,121,0,2,115,116,114,97,109,0,2,117,101,109,97,110,0,0,84,114,117,109,97,105,110,101,0,5,110,0,6,110,0,1,117,99,107,0,4,101,114,0,4,105,101,0,4,121,0,2,100,111,114,0,2,108,108,0,4,101,121,0,4,121,0,2,114,110,101,114,0,1,121,0,2,98,97,108,116,0,2,101,0,2,108,101,114,0,2,109,111,110,0,4,116,104,121,0,2,110,97,110,0,2,114,111,110,101,0,3,117,115,0,2,115,111,110,0,0,85,100,97,108,101,0,4,108,0,2,101,108,108,0,1,103,111,0,1,108,98,101,114,116,111,0,2,105,99,107,0,3,115,101,115,0,2,114,105,99,0,5,104,0,5,107,0,0,85,108,121,115,115,101,115,0,1,109,98,101,114,116,111,0,1,112,116,111,110,0,1,114,98,97,105,110,0,4,110,0,5,111,0,5,117,115,0,2,105,0,3,97,104,0,3,101,108,0,2,115,111,110,0,0,86,97,99,104,101,108,0,3,108,97,118,0,2,105,108,0,2,108,0,3,100,101,109,97,114,0,3,101,0,4,110,116,105,106,110,0,7,110,0,8,101,0,8,111,0,3,108,101,0,2,110,0,3,99,101,0,3,121,97,0,2,115,105,108,105,0,6,115,0,5,121,0,3,115,105,108,105,0,6,121,0,2,117,103,104,97,110,0,5,110,0,0,86,101,114,103,101,0,4,105,108,0,3,110,0,4,101,0,5,110,0,5,121,0,4,111,110,0,5,114,0,1,105,99,0,3,107,0,3,116,111,105,114,0,5,114,0,2,100,111,118,105,99,0,6,107,0,2,110,0,3,99,101,0,5,110,116,0,7,115,0,7,121,0,6,122,0,3,110,105,101,0,4,121,0,3,115,111,110,0,2,114,103,101,0,4,105,101,0,5,108,0,6,105,111,0,2,116,101,0,3,111,0,3,116,111,114,105,111,0,1,108,97,100,0,4,97,109,105,114,0,0,86,108,97,100,105,109,105,114,0,1,111,110,0,0,87,97,100,101,0,3,115,119,111,114,116,104,0,2,105,110,0,4,119,114,105,103,104,116,0,3,116,0,4,101,0,5,114,0,2,107,101,0,4,102,105,101,108,100,0,2,108,100,0,4,101,109,97,114,0,5,110,0,4,111,0,5,110,0,3,107,101,114,0,3,108,97,99,101,0,6,104,101,0,5,115,0,4,105,101,0,5,115,0,4,121,0,3,115,104,0,3,116,0,4,104,101,114,0,4,111,110,0,2,110,103,0,2,114,100,0,4,101,0,5,110,0,3,101,0,0,87,97,114,105,110,103,0,3,110,101,114,0,3,114,101,110,0,2,115,104,0,4,105,110,103,116,111,110,0,2,116,0,2,118,101,114,108,101,121,0,6,121,0,2,121,0,3,108,97,110,0,6,100,0,4,101,110,0,4,105,110,0,4,111,110,0,3,110,101,0,1,101,98,0,3,98,0,3,101,114,0,3,115,116,101,114,0,2,105,100,97,114,0,4,101,114,0,2,108,98,105,101,0,4,121,0,3,99,104,0,3,108,115,0,3,115,104,0,2,110,100,97,108,108,0,4,101,108,0,6,108,0,2,114,110,101,114,0,4,104,101,114,0,2,115,0,0,87,101,115,108,101,121,0,3,116,0,4,98,114,111,111,107,0,9,101,0,4,108,101,105,103,104,0,6,121,0,4,111,110,0,2,121,108,105,110,0,1,104,101,101,108,101,114,0,2,105,116,0,4,97,107,101,114,0,4,98,121,0,4,109,97,110,0,4,110,101,121,0,4,116,97,107,101,114,0,1,105,97,116,116,0,2,108,98,101,114,116,0,4,117,114,0,6,116,0,3,100,101,110,0,4,111,110,0,3,101,107,0,4,121,0,3,102,114,101,100,0,5,105,100,0,3,104,101,108,109,0,3,108,0,4,97,114,100,0,4,100,111,110,0,4,101,109,0,5,121,0,4,105,0,0,87,105,108,108,105,97,109,0,5,101,0,5,115,0,4,121,0,3,109,97,114,0,4,101,114,0,3,116,0,4,111,110,0,2,110,0,3,100,104,97,109,0,3,102,105,101,108,100,0,4,114,101,100,0,3,105,102,105,101,108,100,0,3,110,0,4,105,101,0,4,121,0,3,115,108,111,119,0,4,116,111,110,0,3,116,104,114,111,112,0,2,116,0,3,116,105,101,0,4,121,0,1,111,108,102,0,4,103,97,110,103,0,4,105,101,0,4,121,0,2,111,100,0,4,105,101,0,4,109,97,110,0,4,114,111,119,0,4,121,0,2,114,100,101,110,0,0,87,111,114,116,104,0,5,105,110,103,116,111,110,0,5,121,0,1,114,105,103,104,116,0,1,121,97,116,97,110,0,4,116,0,2,101,0,2,108,105,101,0,2,110,0,3,100,104,97,109,0,3,110,0,0,88,97,118,105,101,114,0,1,101,110,111,115,0,2,114,120,101,115,0,2,118,101,114,0,1,105,109,101,110,101,115,0,6,122,0,1,121,109,101,110,101,115,0,0,89,97,108,101,0,2,110,97,116,111,110,0,3,99,101,0,5,121,0,4,121,0,3,107,0,4,101,101,0,2,114,100,0,4,108,101,121,0,1,101,104,117,100,105,0,6,116,0,1,111,114,103,111,0,5,115,0,3,107,0,0,89,111,114,107,101,0,5,114,0,1,117,108,0,3,101,0,3,109,97,0,2,109,97,0,2,114,105,0,4,107,0,1,118,101,115,0,2,111,110,0,3,114,0,0,90,97,99,99,97,114,105,97,0,3,104,0,4,97,114,105,97,0,8,104,0,8,115,0,7,101,0,6,121,0,4,101,114,105,101,0,6,121,0,3,107,0,4,97,114,105,97,104,0,2,107,0,2,110,101,0,2,114,101,100,0,1,101,98,0,3,97,100,105,97,104,0,3,101,100,101,101,0,3,117,108,101,110,0,5,111,110,0,2,99,104,97,114,105,97,104,0,2,100,0,0,90,101,100,101,107,105,97,104,0,2,107,101,0,2,108,105,103,0,2,114,107,0,1,111,108,108,105,101,0,4,121,0,0,65,97,114,101,110,0,3,105,107,97,0,1,98,97,103,97,101,108,0,5,105,108,0,2,98,101,0,4,121,0,3,105,0,4,101,0,3,121,0,4,101,0,2,105,103,97,101,108,0,5,105,108,0,5,108,101,0,2,114,97,0,1,100,97,0,3,104,0,3,108,105,110,101,0,3,110,0,3,114,97,0,2,100,97,0,3,105,0,4,97,0,4,101,0,3,121,0,2,101,108,0,4,97,0,0,65,100,101,108,97,105,100,97,0,7,101,0,4,101,0,4,104,101,105,100,0,4,105,99,101,0,5,110,97,0,6,100,0,6,101,0,4,108,97,0,5,101,0,3,110,97,0,3,121,0,2,105,0,3,97,110,97,0,3,110,97,0,2,111,114,97,0,4,101,0,5,101,0,4,110,101,0,2,114,101,97,0,3,105,97,0,5,101,110,115,0,5,110,0,6,97,0,6,101,0,6,110,97,0,7,101,0,4,101,110,97,0,6,110,101,0,1,101,114,105,101,108,0,6,97,0,6,108,0,0,65,102,116,111,110,0,1,103,0,2,97,99,101,0,3,116,97,0,4,104,97,0,5,101,0,2,103,105,0,4,101,0,3,121,0,2,110,97,0,3,101,108,108,97,0,4,115,0,5,101,0,5,115,101,0,4,116,97,0,3,111,108,97,0,2,114,101,116,104,97,0,1,105,100,97,0,4,110,0,2,103,110,101,105,115,0,2,108,97,0,3,101,0,4,101,0,5,110,0,4,110,101,0,4,121,0,3,105,0,4,110,97,0,4,115,0,3,115,117,110,0,3,121,110,0,2,109,101,0,0,65,105,109,101,101,0,3,105,108,0,2,110,100,114,101,97,0,3,115,108,101,101,0,6,121,0,5,105,101,0,1,106,97,121,0,1,108,97,105,110,101,0,3,109,101,100,97,0,3,110,97,0,5,104,0,4,101,0,4,110,97,0,3,121,110,101,0,2,98,101,114,116,97,0,6,105,110,97,0,8,101,0,3,105,110,97,0,2,101,99,105,97,0,3,100,97,0,3,101,99,101,0,4,110,0,3,106,97,110,100,114,97,0,8,105,110,97,0,3,110,97,0,4,101,0,3,115,115,97,110,100,114,97,0,3,116,97,0,4,104,101,97,0,3,120,0,4,97,0,5,110,100,114,97,0,0,65,108,101,120,97,110,100,114,105,110,97,0,4,105,0,5,97,0,5,110,97,0,6,101,0,5,115,0,2,102,105,0,4,101,0,3,114,101,100,97,0,3,121,0,2,105,0,3,97,0,3,99,97,0,4,101,0,5,97,0,4,105,97,0,3,100,97,0,4,105,97,0,3,101,0,3,107,97,0,4,101,101,0,3,110,97,0,4,101,0,3,115,0,4,97,0,4,104,97,0,4,111,110,0,4,115,97,0,4,117,110,0,3,120,0,3,122,97,0,2,108,97,0,0,65,108,108,101,101,110,0,4,103,114,97,0,4,110,101,0,3,105,0,4,97,110,111,114,97,0,4,101,0,4,110,97,0,4,115,0,5,111,110,0,5,115,97,0,4,120,0,3,115,117,110,0,3,120,0,3,121,0,4,99,101,0,4,110,0,4,115,0,5,111,110,0,2,109,97,0,3,101,100,97,0,4,114,105,97,0,4,116,97,0,3,105,114,97,0,5,101,0,2,111,105,115,101,0,5,105,97,0,3,121,115,105,97,0,2,116,97,0,3,104,101,97,0,2,118,101,114,97,0,5,116,97,0,3,105,110,97,0,0,65,108,118,105,110,105,97,0,4,114,97,0,2,121,99,101,0,3,100,97,0,3,115,0,4,97,0,4,101,0,4,105,97,0,4,111,110,0,4,115,0,5,97,0,1,109,97,98,101,108,0,6,108,101,0,3,108,101,97,0,5,101,0,5,116,97,0,4,105,97,0,5,101,0,5,116,97,0,4,108,101,0,3,110,100,97,0,5,105,0,6,101,0,5,121,0,3,114,97,0,4,103,111,0,3,116,97,0,2,98,101,114,0,5,108,121,0,3,117,114,0,2,101,0,3,108,105,97,0,0,65,109,101,108,105,101,0,5,110,97,0,6,101,0,5,116,97,0,2,105,0,3,101,0,3,105,0,3,108,0,3,116,105,101,0,4,121,0,2,109,97,109,97,114,105,97,0,2,121,0,3,101,0,1,110,97,0,3,98,97,108,0,4,101,108,0,6,108,97,0,7,101,0,3,108,105,101,115,101,0,5,115,101,0,4,108,101,115,101,0,5,105,115,101,0,3,115,116,97,115,105,97,0,8,101,0,7,115,105,97,0,3,116,111,108,97,0,2,100,101,101,0,5,101,0,4,114,101,97,0,3,105,0,4,101,0,3,114,97,0,0,65,110,100,114,101,97,0,6,110,97,0,5,101,0,5,105,0,4,105,97,0,6,110,97,0,5,101,116,116,101,0,4,111,109,97,99,104,101,0,3,121,0,2,101,115,116,97,115,115,105,97,0,3,116,0,4,116,0,5,97,0,5,101,0,2,103,101,0,4,108,0,5,97,0,5,101,0,5,105,97,0,6,99,97,0,6,107,97,0,6,110,97,0,7,101,0,6,113,117,101,0,6,116,97,0,5,108,101,0,3,105,101,0,4,108,0,3,121,0,2,105,97,0,3,99,97,0,3,115,115,97,0,0,65,110,105,116,97,0,4,114,97,0,2,106,97,110,101,116,116,101,0,3,101,108,97,0,2,110,0,3,45,77,97,114,105,101,0,3,97,0,4,45,68,105,97,110,97,0,9,101,0,5,77,97,114,105,97,0,4,98,97,108,0,5,101,108,0,7,97,0,7,108,0,8,97,0,8,101,0,4,100,105,97,110,97,0,8,101,0,4,108,101,101,0,5,105,101,115,101,0,6,115,101,0,4,109,97,114,105,97,0,8,101,0,3,101,0,4,45,67,111,114,105,110,110,101,0,5,77,97,114,105,101,0,4,99,111,114,105,110,110,101,0,4,108,105,101,115,101,0,6,115,101,0,4,109,97,114,105,101,0,4,116,116,97,0,6,101,0,0,65,110,110,105,0,4,99,101,0,4,101,0,4,115,0,5,115,97,0,3,109,97,114,105,97,0,7,101,0,3,110,111,114,97,0,3,111,114,97,0,3,121,0,2,115,101,108,109,97,0,3,108,101,121,0,3,116,105,99,101,0,2,116,104,101,0,5,97,0,4,105,97,0,6,116,104,105,97,0,3,111,105,110,101,116,116,101,0,4,110,101,108,108,97,0,6,116,116,97,0,5,105,97,0,6,101,0,7,116,116,97,0,6,110,97,0,2,121,97,0,1,112,112,111,108,111,110,105,97,0,2,114,105,108,0,5,101,116,116,101,0,1,114,97,0,3,98,101,108,0,6,97,0,6,101,0,0,65,114,97,98,101,108,108,97,0,7,101,0,2,100,97,0,4,116,104,0,3,101,101,110,0,4,108,105,97,0,6,115,0,5,108,97,0,6,101,0,4,110,0,5,101,0,5,105,97,0,3,105,110,101,0,4,115,0,5,106,0,4,116,104,0,3,114,97,0,3,121,99,101,0,4,115,0,4,116,104,0,2,101,116,104,97,0,2,105,97,100,110,101,0,4,110,97,0,3,100,97,116,104,97,0,3,101,108,0,5,97,0,5,108,97,0,6,101,0,2,108,97,110,97,0,3,101,101,0,5,110,0,4,110,0,0,65,114,108,101,110,97,0,5,101,0,4,116,97,0,5,116,101,0,4,121,110,101,0,3,105,101,0,5,110,101,0,4,110,97,0,5,100,97,0,5,101,0,3,117,101,110,101,0,3,121,0,4,110,0,5,101,0,2,121,110,0,1,115,104,101,108,121,0,3,105,97,0,4,101,110,0,4,108,0,3,108,97,0,5,110,0,4,101,101,0,5,105,103,104,0,5,110,0,5,121,0,4,105,0,5,101,0,4,121,0,2,105,97,0,2,116,114,97,0,4,105,100,0,5,120,0,0,65,116,97,108,97,110,116,97,0,2,104,101,110,97,0,5,101,0,2,108,97,110,116,97,0,6,101,0,1,117,98,101,114,116,97,0,3,105,110,101,0,3,114,101,101,0,5,116,116,101,0,5,121,0,4,105,101,0,4,121,0,2,100,105,0,4,101,0,3,114,97,0,4,101,0,5,121,0,4,105,101,0,4,121,0,5,101,0,3,121,0,2,103,117,115,116,97,0,6,101,0,6,105,110,97,0,8,101,0,2,110,100,114,101,97,0,2,114,97,0,3,101,97,0,4,108,0,5,101,97,0,5,105,97,0,6,101,0,0,65,117,114,105,97,0,4,101,0,4,108,105,97,0,3,108,105,101,0,3,111,111,114,97,0,4,114,97,0,5,101,0,2,115,116,105,110,0,6,97,0,6,101,0,1,118,97,0,2,101,108,105,110,101,0,3,114,105,108,0,4,121,108,0,2,105,101,0,3,115,0,3,118,97,0,5,104,0,2,114,105,108,0,4,116,0,1,121,110,0,0,66,97,98,0,3,97,114,97,0,3,98,0,4,101,116,116,101,0,4,105,101,0,3,101,116,116,101,0,3,105,116,97,0,3,115,0,2,109,98,105,0,5,101,0,4,121,0,0,66,97,114,98,0,4,97,98,114,97,0,5,114,97,0,7,45,65,110,110,101,0,7,97,110,110,101,0,4,101,0,5,101,0,5,116,116,101,0,5,121,0,4,105,0,5,101,0,4,114,97,0,4,121,0,3,105,0,3,114,105,101,0,4,121,0,2,115,105,97,0,2,116,104,115,104,101,98,97,0,3,115,104,101,118,97,0,1,101,97,0,3,116,114,105,99,101,0,6,115,97,0,6,120,0,6,122,0,2,98,101,0,2,99,99,97,0,3,107,97,0,4,105,0,5,101,0,4,121,0,2,101,0,2,105,108,117,108,0,0,66,101,105,116,114,105,115,0,2,107,107,105,0,2,108,0,3,105,97,0,4,99,105,97,0,4,110,100,97,0,4,116,97,0,3,108,0,4,97,0,5,110,99,97,0,4,101,0,4,105,110,97,0,3,118,97,0,4,105,97,0,2,110,100,105,116,101,0,3,101,100,101,116,116,97,0,5,105,99,116,97,0,6,107,116,97,0,4,116,116,97,0,3,105,116,97,0,3,110,105,0,5,101,0,4,121,0,3,111,105,116,101,0,2,114,101,110,105,99,101,0,4,116,0,3,103,101,116,0,3,110,97,0,5,100,101,110,101,0,7,116,116,101,0,6,105,110,97,0,8,101,0,0,66,101,114,110,97,114,100,105,110,97,0,9,101,0,4,101,108,108,101,0,5,116,101,0,6,116,97,0,7,101,0,4,105,0,5,99,101,0,5,101,0,5,116,97,0,4,121,0,3,114,105,0,5,101,0,4,121,0,3,116,0,4,97,0,4,101,0,4,104,97,0,5,101,0,4,105,0,5,101,0,5,110,97,0,6,101,0,4,121,0,3,121,108,0,5,101,0,2,115,115,0,4,105,101,0,4,121,0,2,116,104,0,4,97,110,110,101,0,6,121,0,0,66,101,116,104,101,110,97,0,4,105,110,97,0,3,115,101,121,0,4,121,0,3,116,97,0,4,101,0,5,45,65,110,110,0,5,97,110,110,0,8,101,0,4,105,0,5,110,97,0,6,101,0,4,121,0,5,101,0,2,117,108,97,104,0,2,118,0,3,101,114,105,101,0,5,108,101,101,0,7,121,0,6,105,101,0,6,121,0,3,118,121,0,1,105,97,110,99,97,0,4,107,97,0,2,98,98,105,101,0,4,121,0,5,101,0,3,105,0,2,100,100,105,101,0,4,121,0,3,103,101,116,0,2,108,105,0,0,66,105,108,108,0,4,105,0,5,101,0,4,121,0,5,101,0,2,110,110,105,0,5,101,0,4,121,0,2,114,100,0,4,105,101,0,3,103,105,116,0,6,116,97,0,1,108,97,105,114,0,5,101,0,3,107,101,0,5,108,101,101,0,7,121,0,3,110,99,97,0,5,104,0,6,97,0,6,101,0,2,105,110,110,105,0,6,101,0,5,121,0,3,115,115,0,5,101,0,3,116,104,101,0,2,111,110,100,101,108,108,0,8,101,0,5,105,101,0,5,121,0,2,121,116,104,101,0,0,66,111,98,98,101,0,5,101,0,5,116,116,101,0,4,105,0,5,101,0,4,121,0,5,101,0,3,101,116,116,101,0,3,105,110,97,0,5,101,0,6,116,116,101,0,2,110,105,116,97,0,3,110,101,101,0,4,105,0,5,98,101,108,108,101,0,5,101,0,4,121,0,1,114,97,110,97,0,4,100,97,105,115,0,5,101,0,6,97,0,5,105,0,6,99,101,0,6,101,0,6,115,101,0,5,121,0,2,101,97,110,110,101,0,4,114,0,3,101,0,4,110,97,0,3,110,0,4,97,0,0,66,114,101,110,100,97,0,4,110,0,5,97,0,3,116,116,0,2,105,97,0,4,110,97,0,5,110,97,0,6,101,0,3,100,101,0,4,103,101,116,0,7,116,101,0,4,105,101,0,3,101,114,0,4,116,116,97,0,3,103,105,100,0,6,97,0,5,116,0,6,116,97,0,7,101,0,3,110,97,0,4,101,121,0,4,110,0,5,97,0,4,121,0,3,116,0,4,97,0,4,110,101,121,0,5,105,0,4,116,0,5,97,0,6,110,0,7,101,121,0,0,66,114,105,116,116,97,110,105,0,7,121,0,5,101,0,6,110,121,0,5,110,101,0,7,121,0,6,105,0,2,111,111,107,0,5,101,0,5,115,0,2,117,110,104,105,108,100,97,0,8,101,0,2,121,97,110,97,0,3,110,0,4,97,0,4,110,0,5,97,0,5,101,0,1,117,102,102,121,0,2,110,110,105,0,5,101,0,4,121,0,0,67,97,99,105,108,105,97,0,6,101,0,2,104,114,97,0,2,105,114,105,115,116,105,111,110,97,0,3,116,108,105,110,0,4,114,105,110,0,2,108,0,3,105,100,97,0,3,108,97,0,4,101,121,0,0,67,97,108,108,105,0,5,100,97,0,5,101,0,4,121,0,3,121,112,115,111,0,2,109,0,3,97,108,97,0,3,101,108,0,5,108,97,0,6,105,97,0,3,105,0,4,108,97,0,5,101,0,5,108,97,0,6,101,0,3,109,105,0,5,101,0,4,121,0,2,110,100,97,99,101,0,4,105,0,5,99,101,0,5,100,97,0,6,101,0,5,101,0,5,115,0,4,114,97,0,4,121,0,2,112,114,105,99,101,0,2,114,97,0,4,108,105,101,0,3,101,110,0,5,97,0,0,67,97,114,101,115,97,0,5,115,97,0,6,101,0,4,121,0,3,105,0,4,97,0,4,101,0,4,108,0,5,121,110,0,4,110,0,5,97,0,5,101,0,4,111,116,116,97,0,4,115,115,97,0,4,116,97,0,5,116,97,0,3,108,97,0,4,101,101,0,6,110,0,5,110,0,6,101,0,5,121,0,4,105,101,0,5,110,0,6,97,0,6,101,0,5,116,97,0,4,111,116,97,0,6,116,97,0,4,121,0,5,101,0,5,110,0,0,67,97,114,108,121,110,110,0,7,101,0,3,109,97,0,4,101,108,0,6,97,0,6,105,97,0,7,110,97,0,7,116,97,0,6,108,97,0,7,101,0,5,110,0,6,99,105,116,97,0,4,105,110,97,0,6,101,0,5,116,97,0,4,111,110,0,3,111,0,4,108,0,5,45,74,101,97,110,0,5,97,0,6,110,0,7,110,0,5,101,0,6,101,0,5,105,110,0,7,97,0,7,101,0,5,106,101,97,110,0,5,121,110,0,7,101,0,7,110,0,4,110,0,0,67,97,114,114,101,101,0,4,105,0,5,101,0,5,115,115,97,0,4,111,108,108,0,4,121,0,3,121,0,4,108,0,4,110,0,2,115,97,110,100,114,97,0,3,101,121,0,3,105,0,4,101,0,3,115,0,4,97,110,100,114,97,0,8,101,0,8,121,0,5,117,110,100,114,97,0,4,101,121,0,4,105,0,5,101,0,4,111,110,100,114,97,0,4,121,0,2,116,97,114,105,110,97,0,3,101,0,4,114,105,110,97,0,3,104,97,0,5,114,105,110,97,0,8,101,0,4,101,0,5,101,0,5,114,105,110,0,0,67,97,116,104,101,114,105,110,97,0,8,101,0,4,105,0,5,101,0,4,108,101,101,110,0,6,110,101,0,4,114,105,110,0,7,101,0,5,121,110,0,4,121,0,5,108,101,101,110,0,3,105,0,4,101,0,4,110,97,0,3,108,97,105,110,97,0,4,101,101,0,4,105,110,0,3,114,105,110,97,0,5,111,110,97,0,3,121,0,2,121,101,0,3,108,97,0,1,101,99,101,108,105,97,0,3,105,108,0,5,101,0,6,121,0,5,105,97,0,5,108,97,0,5,121,0,2,105,108,0,2,108,101,0,4,110,101,0,0,67,101,108,101,115,116,97,0,6,101,0,6,105,97,0,7,110,97,0,8,101,0,6,121,110,0,8,97,0,3,105,97,0,4,101,0,4,110,97,0,5,100,97,0,5,101,0,5,107,97,0,4,115,115,101,0,3,107,97,0,3,108,101,0,2,115,121,97,0,1,104,97,100,0,3,110,100,97,0,6,108,0,5,114,97,0,4,110,97,0,4,116,97,108,0,7,108,101,0,3,114,105,108,0,5,110,0,5,115,0,6,115,97,0,7,101,0,5,116,97,0,6,121,0,4,108,97,0,0,67,104,97,114,108,101,97,110,0,6,101,110,0,6,110,97,0,7,101,0,5,105,110,101,0,5,111,116,0,7,116,97,0,8,101,0,4,109,97,105,110,0,8,101,0,6,110,101,0,5,105,97,110,0,6,110,101,0,6,111,110,0,4,111,0,4,121,108,0,3,115,116,105,116,121,0,2,101,108,115,97,101,0,5,101,97,0,6,121,0,5,105,101,0,5,121,0,3,114,0,4,101,0,5,121,0,4,105,0,5,97,110,110,101,0,5,99,101,0,5,100,97,0,5,101,0,5,108,121,110,0,8,110,0,0,67,104,101,114,105,110,0,5,115,101,0,6,104,0,4,108,121,110,0,4,114,105,0,6,116,97,0,5,121,0,4,121,0,5,101,0,5,108,0,3,115,108,105,101,0,2,105,97,114,114,97,0,3,99,107,105,101,0,5,121,0,3,113,117,105,97,0,6,116,97,0,2,108,111,0,4,101,0,5,116,116,101,0,4,114,105,115,0,2,114,105,115,0,5,115,105,101,0,6,121,0,5,116,97,0,7,98,101,108,0,10,108,97,0,7,108,0,8,108,101,0,7,110,0,6,101,97,110,0,7,108,0,7,110,0,0,67,104,114,105,115,116,105,0,7,97,110,0,9,97,0,9,101,0,7,101,0,7,110,0,8,97,0,8,101,0,6,121,0,7,101,0,7,110,97,0,3,121,115,97,0,5,108,101,114,0,5,116,97,108,0,6,101,0,7,108,0,1,105,99,101,108,121,0,3,105,108,121,0,2,101,108,0,2,108,107,97,0,2,110,100,97,0,4,101,101,0,5,108,121,110,0,5,114,101,108,108,97,0,4,105,0,5,101,0,4,114,97,0,4,121,0,3,110,97,109,111,110,0,2,115,115,105,101,101,0,4,121,0,1,108,97,105,114,0,0,67,108,97,105,114,101,0,3,114,97,0,5,98,101,108,108,101,0,4,101,0,5,115,116,97,0,5,116,97,0,6,116,97,0,7,101,0,5,121,0,4,105,0,5,98,101,108,0,5,99,101,0,5,101,0,5,110,100,97,0,6,101,0,5,115,115,97,0,7,101,0,5,116,97,0,4,121,0,3,117,100,101,0,6,108,108,101,0,6,116,116,97,0,8,101,0,5,105,97,0,6,101,0,6,110,97,0,7,101,0,2,101,97,0,3,109,0,4,101,110,99,101,0,6,116,105,97,0,8,110,97,0,0,67,108,101,109,101,110,116,105,110,101,0,4,109,105,101,0,5,121,0,3,111,0,4,112,97,116,114,97,0,3,114,105,115,115,97,0,2,105,111,0,2,111,0,3,101,0,3,114,105,115,0,3,116,105,108,100,97,0,3,118,105,115,0,1,111,100,101,101,0,3,105,0,4,101,0,3,121,0,2,108,101,101,110,0,4,110,101,0,4,116,116,97,0,6,101,0,3,108,101,101,110,0,5,110,0,5,116,101,0,6,116,101,0,4,105,101,0,5,110,101,0,4,121,0,2,110,0,3,99,101,116,116,105,110,97,0,4,104,105,116,97,0,4,111,114,100,105,97,0,3,110,105,0,0,67,111,110,110,105,101,0,4,121,0,3,115,111,108,97,116,97,0,4,116,97,110,99,101,0,8,105,97,0,8,121,0,7,116,97,0,8,105,97,0,9,110,97,0,10,101,0,4,117,101,108,97,0,7,111,0,2,111,107,105,101,0,2,114,97,0,4,98,101,108,0,7,108,97,0,8,101,0,4,108,0,5,105,101,0,6,110,101,0,5,121,110,0,3,100,101,108,105,97,0,7,101,0,5,121,0,4,105,0,5,101,0,4,117,108,97,0,4,121,0,3,101,101,110,0,4,108,108,97,0,4,110,100,97,0,5,101,0,0,67,111,114,101,116,116,97,0,6,101,0,4,121,0,3,105,0,4,101,0,4,108,108,97,0,4,110,97,0,5,101,0,5,110,97,0,6,101,0,4,115,115,0,6,97,0,3,108,105,115,115,0,4,121,0,3,110,101,108,97,0,6,105,97,0,6,108,101,0,4,105,101,0,4,121,0,3,114,101,110,97,0,5,121,0,4,105,0,5,97,110,110,101,0,5,101,0,5,110,97,0,6,101,0,6,110,101,0,4,121,0,3,116,110,101,121,0,3,121,0,2,115,101,116,116,97,0,6,101,0,0,67,111,115,116,97,110,122,97,0,2,117,114,116,101,110,97,121,0,5,110,97,121,0,6,101,121,0,1,114,105,110,0,3,115,0,4,115,105,101,0,5,121,0,4,116,97,0,6,98,101,108,0,6,108,0,5,101,110,0,5,105,0,6,101,0,6,110,0,7,97,0,7,101,0,6,111,110,110,97,0,5,121,0,2,121,115,116,97,0,6,108,0,5,105,101,0,1,116,104,114,105,110,101,0,1,121,98,0,3,105,108,0,5,108,0,2,109,98,114,101,0,2,110,100,101,0,4,105,0,5,97,0,5,101,0,4,121,0,0,67,121,110,116,104,101,97,0,5,105,97,0,6,101,0,5,121,0,0,68,97,99,101,121,0,3,105,97,0,4,101,0,3,121,0,2,101,108,0,2,102,102,105,0,5,101,0,4,121,0,2,103,109,97,114,0,2,104,108,105,97,0,2,105,108,101,0,3,115,101,121,0,4,105,0,5,101,0,4,121,0,2,108,101,0,4,110,110,97,0,3,105,97,0,4,108,97,0,3,108,97,115,0,3,111,114,105,115,0,2,109,97,114,97,0,5,105,115,0,3,105,116,97,0,2,110,97,0,3,101,108,108,0,6,97,0,4,116,116,101,0,0,68,97,110,105,0,4,97,0,4,99,97,0,5,101,0,4,101,108,97,0,6,101,0,6,108,97,0,7,101,0,4,107,97,0,4,108,97,0,4,116,0,5,97,0,3,110,97,0,4,105,0,5,101,0,4,121,0,5,101,0,3,121,97,0,4,101,108,108,101,0,5,116,116,101,0,2,112,104,101,110,101,0,4,110,97,0,5,101,0,2,114,97,0,3,98,0,4,105,101,0,4,121,0,3,99,101,101,0,5,121,0,4,105,0,5,101,0,4,121,0,0,68,97,114,100,97,0,3,101,101,110,0,4,108,108,0,6,101,0,3,105,0,4,97,0,4,99,101,0,3,108,97,0,4,101,101,110,0,5,110,101,0,4,105,110,101,0,4,108,101,101,110,0,3,111,110,0,3,114,101,108,108,101,0,4,121,108,0,3,115,101,121,0,4,105,101,0,3,121,97,0,4,108,0,4,110,0,2,115,104,97,0,3,105,0,4,101,0,3,121,97,0,2,116,104,97,0,2,117,110,101,0,2,118,101,101,110,0,4,116,97,0,3,105,100,97,0,4,110,97,0,5,101,0,4,116,97,0,0,68,97,119,110,0,4,97,0,2,121,108,101,0,3,110,97,0,1,100,101,110,101,0,1,101,0,2,97,110,97,0,4,101,0,4,110,97,0,5,101,0,2,98,0,3,98,105,0,5,101,0,4,121,0,3,101,101,0,4,114,97,0,3,105,0,3,111,114,0,5,97,0,6,104,0,3,114,97,0,2,100,101,0,3,105,101,0,3,114,97,0,2,101,0,3,32,68,101,101,0,3,97,110,110,0,6,101,0,3,100,101,101,0,3,110,97,0,3,114,100,114,101,0,3,121,110,0,0,68,101,104,108,105,97,0,2,105,100,114,101,0,3,110,97,0,3,114,100,114,101,0,2,108,0,3,97,0,3,99,105,110,97,0,6,101,0,3,105,97,0,4,108,97,0,6,104,0,4,110,100,97,0,3,108,0,4,97,0,4,121,0,3,111,114,97,0,5,101,115,0,5,105,97,0,6,115,0,3,112,104,105,110,101,0,7,105,97,0,2,109,101,116,101,114,0,5,114,97,0,6,105,97,0,7,115,0,2,110,97,0,3,105,0,4,99,101,0,4,115,101,0,3,110,97,0,4,105,0,5,101,0,0,68,101,110,110,121,0,3,121,0,4,115,0,5,101,0,2,111,110,110,101,0,2,115,100,101,109,111,110,97,0,3,105,114,97,101,0,5,101,101,0,5,105,0,2,118,97,0,4,110,0,3,105,0,4,110,0,5,97,0,5,110,101,0,3,111,110,0,5,100,114,97,0,5,110,97,0,6,101,0,4,114,97,0,1,105,0,2,97,104,97,110,110,0,3,110,0,4,97,0,4,100,114,97,0,4,101,0,5,45,77,97,114,105,101,0,5,109,97,114,105,101,0,4,110,0,5,97,0,5,101,0,5,110,101,0,0,68,105,100,105,0,3,111,0,2,101,110,97,0,3,114,100,114,101,0,2,110,97,0,4,104,0,3,110,105,101,0,4,121,0,2,111,110,0,4,101,0,4,105,115,0,4,110,101,0,2,116,97,0,2,120,0,3,105,101,0,1,110,105,114,101,110,0,1,111,100,101,0,3,105,0,4,101,0,3,121,0,2,101,0,2,108,108,0,4,101,121,0,4,105,0,5,101,0,4,121,0,3,111,114,101,115,0,5,105,116,97,0,8,115,0,2,109,101,110,105,103,97,0,3,105,110,103,97,0,5,105,0,0,68,111,109,105,110,105,99,97,0,6,113,117,101,0,2,110,97,0,3,101,108,108,97,0,6,101,0,4,116,116,97,0,3,105,97,0,4,99,97,0,4,101,108,108,101,0,3,110,97,0,5,109,97,114,105,101,0,4,105,0,5,101,0,4,121,0,2,114,97,0,4,108,105,97,0,6,110,0,5,121,110,0,7,110,0,8,101,0,3,101,0,4,101,110,0,4,108,105,97,0,5,108,97,0,6,101,0,4,110,97,0,5,101,0,4,116,116,97,0,6,101,0,4,121,0,3,105,0,4,97,0,0,68,111,114,105,97,110,0,4,99,101,0,4,101,0,4,110,101,0,4,115,0,5,97,0,5,101,0,4,116,97,0,3,111,0,4,108,105,99,101,0,6,115,97,0,4,116,101,97,0,6,121,97,0,5,104,101,97,0,7,101,0,6,121,0,3,114,101,101,0,4,105,0,5,101,0,5,115,0,4,121,0,3,116,104,101,97,0,5,121,0,3,121,0,2,115,105,0,2,116,0,3,105,0,3,116,105,0,5,101,0,4,121,0,1,114,101,0,3,100,100,121,0,0,68,114,101,100,105,0,2,111,110,97,0,2,117,0,3,99,105,0,5,101,0,5,108,108,0,4,121,0,3,115,105,0,5,101,0,5,108,108,97,0,4,121,0,1,117,108,99,101,0,5,97,0,4,105,0,5,97,0,6,110,97,0,5,101,0,5,110,101,0,7,97,0,4,121,0,3,115,101,97,0,2,115,116,121,0,1,121,97,110,0,4,97,0,4,101,0,4,110,0,5,97,0,5,101,0,2,110,97,0,4,104,0,0,69,97,99,104,101,108,108,101,0,2,100,97,0,0,69,97,100,105,101,0,4,116,104,0,2,108,97,115,97,105,100,0,2,114,116,104,97,0,2,115,116,101,114,0,1,98,97,0,2,98,97,0,2,111,110,101,101,0,4,121,0,1,100,97,0,2,100,105,0,4,101,0,3,121,0,2,101,0,3,101,0,3,108,105,110,101,0,3,110,0,2,105,0,3,101,0,3,110,0,3,116,97,0,4,104,0,5,97,0,5,101,0,3,118,97,0,2,110,97,0,2,119,105,110,97,0,2,121,0,3,116,104,0,5,101,0,1,102,102,105,101,0,1,105,108,101,101,110,0,0,69,105,108,105,115,0,2,109,105,108,101,0,2,114,101,110,97,0,1,107,97,116,101,114,105,110,97,0,1,108,97,105,110,97,0,5,101,0,3,110,97,0,4,101,0,3,121,110,101,0,2,98,101,114,116,97,0,6,105,110,97,0,8,101,0,2,101,97,110,111,114,0,7,97,0,7,101,0,3,99,116,114,97,0,3,101,110,0,3,110,97,0,4,101,0,4,105,0,4,111,114,101,0,3,111,110,111,114,97,0,7,101,0,2,102,105,101,0,3,114,101,100,97,0,4,105,100,97,0,5,101,100,97,0,2,103,97,0,2,105,97,110,111,114,97,0,7,101,0,3,99,105,97,0,3,101,0,0,69,108,105,110,111,114,0,6,101,0,3,115,97,0,5,98,101,116,0,8,104,0,8,116,97,0,4,101,0,4,104,97,0,4,115,97,0,3,116,97,0,3,122,97,0,5,98,101,116,0,8,104,0,2,107,97,0,3,101,0,2,108,97,0,4,100,105,110,101,0,3,101,0,4,110,0,5,101,0,4,116,116,101,0,3,105,0,4,101,0,4,115,115,97,0,3,121,0,4,110,0,5,110,0,2,109,105,114,97,0,2,110,97,0,3,111,114,97,0,5,101,0,2,111,105,115,97,0,0,69,108,111,105,115,101,0,3,110,111,114,101,0,3,114,97,0,2,115,97,0,3,98,101,116,104,0,3,101,0,4,116,0,4,121,0,3,105,0,4,101,0,4,110,111,114,101,0,3,112,101,116,104,0,3,121,0,2,118,97,0,3,101,114,97,0,3,105,110,97,0,4,114,97,0,2,119,105,114,97,0,2,121,110,0,3,115,101,0,5,101,0,4,104,97,0,4,105,97,0,4,115,97,0,1,109,0,0,68,105,101,100,101,100,97,107,0,5,114,105,107,0,0,69,109,97,0,3,108,101,101,0,4,105,97,0,2,101,108,100,97,0,4,105,97,0,0,69,109,101,108,105,110,97,0,6,101,0,5,116,97,0,4,121,110,101,0,3,114,97,0,2,105,108,101,101,0,4,105,0,5,97,0,5,101,0,5,110,101,0,4,121,0,2,108,121,110,0,5,110,0,6,101,0,2,109,97,0,4,108,101,101,0,0,68,101,32,75,97,112,105,116,101,105,110,0,0,84,104,101,32,67,97,112,116,97,105,110,0,0,69,109,109,97,108,105,110,101,0,5,121,110,0,7,110,0,8,101,0,3,101,108,105,110,101,0,4,121,0,3,105,0,4,101,0,3,121,0,4,101,0,2,111,103,101,110,101,0,2,121,108,101,0,5,101,0,1,110,103,114,97,99,105,97,0,0,69,110,105,100,0,2,114,105,99,97,0,5,104,101,116,116,97,0,4,107,97,0,4,113,117,101,116,97,0,1,111,108,97,110,100,97,0,6,101,0,1,114,97,110,0,2,100,97,0,2,101,110,97,0,2,105,99,97,0,4,104,97,0,4,107,97,0,3,107,97,0,3,110,0,4,97,0,4,110,0,5,97,0,2,109,97,0,3,101,110,103,97,114,100,101,0,5,116,114,117,100,101,0,3,105,110,97,0,5,105,97,0,6,101,0,2,110,97,0,4,108,105,110,101,0,3,101,115,116,97,0,6,105,110,101,0,2,116,104,97,0,2,121,110,0,1,115,109,97,0,0,83,116,105,106,110,0,0,69,115,109,97,114,105,97,0,3,101,0,4,114,97,108,100,97,0,2,115,97,0,3,105,101,0,3,121,0,2,116,97,0,3,101,108,0,5,101,0,5,108,0,6,97,0,6,101,0,4,114,0,3,104,101,114,0,3,114,101,108,108,97,0,7,105,116,97,0,1,116,104,101,108,0,5,100,97,0,5,105,110,0,7,100,0,7,101,0,5,121,110,0,3,121,108,0,2,116,97,0,3,105,0,4,101,0,3,121,0,1,117,100,111,114,97,0,2,103,101,110,105,97,0,6,101,0,3,105,110,101,0,2,108,97,0,0,69,117,108,97,108,105,101,0,2,110,105,99,101,0,2,112,104,101,109,105,97,0,2,115,116,97,99,105,97,0,1,118,97,0,3,108,101,101,110,0,3,110,103,101,108,105,97,0,8,110,0,9,97,0,9,101,0,4,105,97,0,4,110,101,0,2,101,0,3,108,101,101,110,0,4,105,110,97,0,6,101,0,4,121,110,0,3,121,0,2,105,101,0,3,116,97,0,2,111,110,110,101,0,2,118,105,101,0,3,121,0,2,121,0,1,121,100,101,0,3,105,101,0,1,122,109,101,114,97,108,100,97,0,0,70,97,101,0,2,105,110,97,0,3,116,104,0,2,108,108,111,110,0,2,110,0,0,70,97,110,99,104,101,116,116,101,0,5,111,110,0,4,105,101,0,4,121,0,3,101,99,104,107,97,0,3,105,97,0,3,110,105,0,5,101,0,4,121,0,3,121,97,0,2,114,97,0,4,104,0,4,110,100,0,3,105,99,97,0,3,114,97,0,5,104,0,5,110,100,0,2,117,110,0,4,105,101,0,3,115,116,105,110,97,0,7,101,0,2,119,110,0,4,101,0,4,105,97,0,2,121,0,3,100,114,97,0,3,101,0,4,116,116,101,0,3,105,110,97,0,3,114,101,0,3,116,104,0,5,101,0,0,70,101,100,101,114,105,99,97,0,3,111,114,97,0,2,108,101,99,105,97,0,3,105,99,100,97,100,0,5,101,0,5,105,97,0,6,116,121,0,5,108,101,0,4,112,97,0,4,115,104,97,0,4,116,97,0,4,122,97,0,2,110,101,108,105,97,0,2,111,100,111,114,97,0,2,114,100,105,110,97,110,100,97,0,9,101,0,3,110,0,4,97,110,100,97,0,7,101,0,7,105,110,97,0,4,101,0,2,121,0,1,105,97,110,110,0,5,97,0,2,100,101,108,97,0,0,77,97,114,105,108,108,0,0,70,105,100,101,108,105,97,0,6,116,121,0,2,102,105,0,4,110,101,0,2,108,105,97,0,4,100,101,0,0,70,105,108,105,112,112,97,0,2,110,97,0,2,111,110,97,0,4,110,97,0,5,117,108,97,0,3,114,101,110,122,101,0,1,108,101,117,114,0,5,101,116,116,101,0,2,111,0,3,114,0,4,97,0,5,110,99,101,0,4,101,0,5,108,108,97,0,5,110,99,101,0,7,105,97,0,6,116,105,97,0,6,122,97,0,5,116,116,101,0,4,105,0,5,97,0,5,100,97,0,5,101,0,5,110,97,0,6,100,97,0,5,115,0,4,114,105,0,6,101,0,5,121,0,4,121,0,3,115,115,105,0,6,101,0,0,70,108,111,115,115,121,0,2,115,115,0,1,114,97,110,0,4,99,101,110,101,0,6,115,0,7,99,97,0,5,105,110,101,0,6,115,99,97,0,7,107,97,0,5,111,105,115,101,0,5,121,110,101,0,4,107,0,5,105,101,0,5,121,0,4,110,105,0,6,101,0,5,121,0,3,121,100,97,0,2,101,100,0,4,97,0,4,100,105,0,0,84,105,109,109,101,114,109,97,110,0,0,70,114,101,100,100,105,101,0,5,121,0,4,101,108,105,97,0,5,114,105,99,97,0,8,107,97,0,7,113,117,101,0,4,105,0,5,97,0,4,114,97,0,5,105,107,97,0,0,70,114,101,105,100,97,0,2,105,101,100,97,0,5,101,114,105,107,101,0,1,117,108,118,105,97,0,0,71,97,98,98,101,121,0,4,105,0,5,101,0,3,101,121,0,3,105,0,4,101,0,3,114,105,101,108,0,7,97,0,7,108,0,8,97,0,8,101,0,8,105,97,0,5,108,97,0,3,121,0,2,101,0,3,108,0,2,105,108,0,2,108,101,0,4,0,3,105,110,97,0,2,114,108,97,110,100,0,3,110,101,116,0,6,116,101,0,2,116,101,115,0,2,118,114,97,0,4,105,101,108,108,101,0,2,121,0,3,101,0,0,71,97,121,101,108,0,3,108,97,0,4,101,0,5,101,110,0,5,110,101,0,3,110,111,114,0,1,101,108,121,97,0,2,110,97,0,3,101,0,4,118,97,0,5,105,101,118,101,0,5,114,97,0,3,105,97,0,3,110,97,0,4,105,0,5,101,0,5,102,101,114,0,4,121,0,3,111,118,101,114,97,0,3,118,105,101,118,101,0,2,111,114,103,101,0,6,97,110,110,97,0,9,101,0,6,110,97,0,6,116,97,0,7,116,97,0,8,101,0,5,105,97,0,7,110,97,0,8,110,97,0,9,101,0,6,101,0,0,71,101,111,114,103,105,110,97,0,7,101,0,2,114,97,108,100,97,0,6,105,110,101,0,3,100,97,0,3,104,97,114,100,105,110,101,0,3,105,0,4,97,110,110,97,0,7,101,0,3,108,97,100,105,110,97,0,3,109,97,105,110,0,7,101,0,5,110,97,0,3,114,105,0,5,101,0,5,108,101,101,0,4,121,0,3,116,0,4,97,0,4,105,0,5,101,0,4,114,117,100,0,7,97,0,7,101,0,7,105,115,0,4,121,0,1,105,97,99,105,110,116,97,0,3,110,97,0,4,105,110,97,0,4,110,97,0,2,103,105,0,2,108,98,101,114,116,97,0,0,71,105,108,98,101,114,116,101,0,7,105,110,97,0,9,101,0,3,100,97,0,3,101,109,101,116,116,101,0,3,108,0,4,97,110,0,4,105,0,5,97,110,0,5,101,0,5,103,97,110,0,4,121,0,2,110,97,0,3,101,108,108,101,0,4,118,114,97,0,3,103,101,114,0,3,110,105,0,5,101,0,5,102,101,114,0,4,121,0,2,111,114,103,105,97,0,3,118,97,110,110,97,0,2,112,115,121,0,2,114,97,108,100,97,0,2,115,101,108,97,0,5,101,0,5,108,97,0,6,101,0,2,117,100,105,116,116,97,0,3,108,105,97,0,5,101,116,116,97,0,3,115,116,105,110,97,0,0,71,105,122,101,108,97,0,1,108,97,100,0,4,105,0,4,121,115,0,2,101,100,97,0,3,110,0,4,100,97,0,4,105,110,101,0,4,110,0,5,97,0,5,105,101,0,6,115,0,2,111,114,105,0,5,97,0,6,110,97,0,7,101,0,4,121,0,2,121,110,0,4,100,97,0,4,105,115,0,4,110,105,115,0,1,110,110,105,0,1,111,100,105,118,97,0,2,108,100,97,0,5,114,105,110,97,0,4,105,0,5,97,0,5,101,0,5,110,97,0,4,121,0,1,114,97,99,101,0,4,105,97,0,0,71,114,97,99,105,101,0,3,116,97,0,4,105,97,0,6,110,97,0,3,121,0,4,99,101,0,3,122,105,97,0,2,101,101,114,0,3,116,97,0,5,108,0,4,99,104,101,110,0,4,101,0,5,108,0,4,104,101,108,0,4,110,97,0,4,116,97,0,2,105,101,114,0,3,115,101,108,100,97,0,4,115,101,108,0,1,117,101,110,100,111,108,101,110,0,4,101,118,101,114,101,0,4,110,97,0,2,103,108,105,101,108,109,97,0,2,105,0,3,108,108,101,109,97,0,7,101,116,116,101,0,3,110,101,118,101,114,101,0,4,110,97,0,2,110,105,108,108,97,0,2,115,0,3,101,108,108,97,0,3,115,105,0,0,71,117,115,115,105,101,0,4,121,0,3,116,97,0,4,105,0,5,101,0,4,121,0,1,119,101,110,0,4,100,111,108,101,110,0,7,105,110,0,7,121,110,0,4,101,116,104,0,6,116,101,0,4,110,101,116,104,0,5,105,0,0,80,105,107,97,99,104,117,0,0,71,119,101,110,110,105,101,0,5,121,0,4,111,114,97,0,6,101,0,2,121,110,0,4,101,116,104,0,4,110,101,0,1,121,112,115,121,0,0,72,97,100,114,105,97,0,2,105,108,101,101,0,4,121,0,2,108,101,105,103,104,0,4,116,116,101,0,4,121,0,3,105,0,4,101,0,4,109,101,100,97,0,0,72,97,108,108,101,121,0,4,105,0,5,101,0,4,121,0,2,110,97,0,3,110,97,0,5,104,0,4,105,0,5,101,0,5,115,0,4,121,0,2,112,112,121,0,2,114,108,101,110,101,0,5,121,0,4,105,0,5,101,0,3,109,111,110,105,97,0,7,101,0,6,121,0,3,114,105,0,5,101,0,6,116,0,7,116,0,0,77,97,103,101,110,116,97,0,0,72,97,114,114,105,101,116,116,97,0,8,101,0,5,111,116,0,7,116,0,2,116,116,105,0,5,101,0,4,121,0,2,121,108,101,121,0,0,72,97,122,101,108,0,1,101,97,116,104,0,5,101,114,0,2,100,97,0,0,79,114,97,109,101,110,0,0,72,101,100,100,97,0,4,105,0,5,101,0,3,105,0,3,118,105,103,0,6,101,0,3,119,105,103,0,6,97,0,3,121,0,2,105,100,97,0,4,105,0,5,101,0,2,108,97,105,110,97,0,6,101,0,3,101,110,0,5,45,69,108,105,122,97,98,101,116,104,0,5,97,0,5,101,0,5,107,97,0,3,103,97,0,4,101,0,3,108,105,0,3,111,105,115,101,0,3,115,97,0,3,121,110,0,2,110,100,114,105,107,97,0,3,107,97,0,0,72,101,110,114,105,101,0,6,116,97,0,7,116,97,0,8,101,0,4,121,101,116,116,97,0,2,112,104,122,105,98,97,104,0,2,114,109,105,97,0,0,70,101,110,103,0,0,72,101,114,109,105,110,97,0,6,101,0,6,105,97,0,5,111,110,101,0,3,116,97,0,4,104,97,0,2,115,116,101,114,0,4,104,101,114,0,4,105,97,0,2,116,116,105,0,5,101,0,4,121,0,1,105,108,97,114,121,0,3,100,97,0,5,103,97,114,100,0,9,101,0,4,101,0,5,103,97,97,114,100,0,7,114,100,101,0,0,69,108,100,117,105,110,0,0,72,105,108,100,121,0,3,108,97,114,121,0,4,105,97,114,121,0,2,110,100,97,0,0,72,111,108,108,105,0,5,101,0,4,121,0,5,45,65,110,110,101,0,5,97,110,110,101,0,2,110,101,121,0,3,111,114,0,5,105,97,0,2,112,101,0,2,114,97,116,105,97,0,3,116,101,110,115,101,0,7,105,97,0,1,117,108,100,97,0,1,121,97,99,105,110,116,104,0,8,97,0,8,101,0,8,105,97,0,9,101,0,2,110,100,97,0,0,73,97,110,116,104,101,0,1,98,98,105,101,0,3,121,0,1,100,97,0,3,108,105,97,0,5,110,97,0,6,101,0,2,101,108,108,0,5,101,0,3,116,116,101,0,1,108,101,97,110,97,0,5,101,0,3,110,101,0,0,73,108,105,115,101,0,2,107,97,0,2,108,97,0,2,115,97,0,3,101,0,2,121,115,97,0,4,101,0,4,115,97,0,1,109,101,108,100,97,0,2,111,103,101,110,0,6,101,0,3,106,101,97,110,0,1,110,97,0,2,100,105,114,97,0,2,101,115,0,4,105,116,97,0,4,115,97,0,3,122,0,2,103,97,0,4,98,101,114,103,0,5,111,114,103,0,3,101,0,4,98,101,114,103,0,5,111,114,103,0,4,114,0,3,114,105,100,0,3,117,110,110,97,0,2,110,97,0,1,111,108,97,110,100,101,0,5,116,104,101,0,2,110,97,0,2,114,109,105,110,97,0,0,73,114,97,0,2,101,110,97,0,4,101,0,2,105,110,97,0,3,115,0,3,116,97,0,2,109,97,0,1,115,97,0,3,98,101,108,0,6,105,116,97,0,6,108,97,0,7,101,0,3,100,111,114,97,0,3,104,101,108,108,97,0,2,101,97,98,97,108,0,2,105,100,111,114,97,0,3,115,0,2,111,98,101,108,0,2,115,105,0,4,101,0,3,121,0,1,118,101,116,116,0,5,101,0,2,105,101,0,2,111,110,110,101,0,3,114,121,0,2,121,0,1,122,97,98,101,108,0,0,74,97,99,101,110,116,97,0,3,105,110,100,97,0,5,116,97,0,6,104,97,0,0,74,97,99,105,110,116,104,101,0,3,107,101,108,121,110,0,4,105,0,5,101,0,4,108,105,110,0,5,121,110,0,4,113,117,101,108,105,110,0,10,101,0,4,121,0,3,108,105,110,0,4,121,110,0,3,113,117,101,108,105,110,0,9,101,0,7,121,110,0,9,110,0,6,110,101,116,116,97,0,10,101,0,6,116,116,97,0,8,101,0,5,105,0,6,101,0,3,121,110,116,104,0,2,100,97,0,3,101,0,2,105,109,101,0,4,105,101,0,3,110,101,0,2,109,105,0,4,101,0,4,109,97,0,3,109,105,101,0,2,110,0,0,74,97,110,97,0,4,121,97,0,5,101,0,3,100,121,0,3,101,0,4,97,110,0,4,99,122,107,97,0,4,101,110,0,4,108,0,5,97,0,5,108,97,0,6,101,0,4,110,101,0,5,110,97,0,4,115,115,97,0,4,116,0,5,97,0,5,116,97,0,0,78,105,101,107,0,0,74,97,110,101,116,116,101,0,4,118,97,0,4,121,0,3,105,97,0,4,99,101,0,4,101,0,4,102,101,114,0,4,110,97,0,5,101,0,4,115,0,4,116,104,0,3,107,97,0,3,110,97,0,0,74,97,110,110,101,108,0,6,108,101,0,3,111,116,0,3,121,0,2,113,117,101,108,105,110,0,6,121,110,0,5,110,101,116,116,97,0,9,101,0,4,105,116,104,0,2,115,109,105,110,0,6,97,0,6,101,0,2,121,109,101,0,5,101,0,3,110,101,0,5,108,108,0,2,122,109,105,110,0,1,101,97,110,0,4,97,0,4,101,0,5,108,108,101,0,5,116,116,101,0,2,108,108,101,0,0,78,101,120,0,3,117,115,0,0,74,101,97,110,105,101,0,5,110,101,0,4,110,97,0,5,101,0,6,116,116,101,0,5,105,101,0,6,110,101,0,0,74,101,104,97,110,110,97,0,2,108,101,110,101,0,2,109,105,101,0,4,109,97,0,6,104,0,3,109,105,101,0,4,121,0,2,110,0,3,97,0,3,100,97,0,3,101,108,108,101,0,3,105,0,4,99,97,0,4,101,99,101,0,4,102,101,114,0,5,102,101,114,0,4,108,101,101,0,4,110,101,0,3,110,0,4,97,0,4,101,101,0,5,116,116,101,0,4,105,0,5,99,97,0,5,101,0,5,102,101,114,0,5,108,101,101,0,5,110,101,0,4,121,0,2,114,97,108,101,101,0,3,101,0,3,105,0,0,74,101,114,109,97,105,110,101,0,3,114,105,101,0,5,108,101,101,0,6,121,110,0,5,110,101,0,4,121,0,5,108,101,101,0,2,115,115,0,4,97,0,5,108,105,110,0,6,121,110,0,5,109,105,110,101,0,6,121,110,0,4,101,0,5,108,121,110,0,4,105,0,5,99,97,0,5,101,0,5,107,97,0,4,121,0,2,119,101,108,0,5,108,0,6,101,0,1,105,108,108,0,4,97,110,97,0,6,101,0,5,121,110,101,0,4,101,101,110,0,5,110,101,0,4,105,0,5,97,110,0,5,101,0,0,74,105,108,108,121,0,2,110,110,121,0,1,111,0,2,32,65,110,110,0,2,45,65,110,110,0,6,101,0,2,97,110,0,4,97,0,4,101,0,4,105,101,0,4,110,0,5,97,0,5,101,0,6,115,0,2,98,101,121,0,3,105,0,4,101,0,4,110,97,0,3,121,0,4,101,0,4,110,97,0,2,99,101,108,105,110,0,7,101,0,5,121,110,0,7,101,0,2,100,101,101,0,3,105,0,4,101,0,3,121,0,2,101,97,110,110,0,3,108,97,0,4,105,101,0,0,74,111,101,108,108,0,5,97,0,5,101,0,6,110,0,5,121,0,6,110,0,4,121,110,110,0,3,116,101,0,3,121,0,2,104,97,110,110,97,0,7,104,0,3,110,97,0,5,116,104,0,4,101,116,116,101,0,4,110,97,0,2,105,99,101,0,2,106,111,0,2,108,101,101,0,5,110,0,4,110,101,0,4,116,116,97,0,3,105,0,4,101,0,4,110,101,0,3,121,0,4,110,0,5,110,0,2,110,101,108,108,0,3,105,0,4,101,0,4,115,0,2,114,100,97,105,110,0,0,74,111,114,100,97,110,0,6,97,0,6,110,97,0,3,101,121,0,3,105,0,4,101,0,3,114,105,101,0,4,121,0,2,115,99,101,108,105,110,0,3,101,101,0,4,102,97,0,5,105,110,97,0,4,112,104,97,0,6,105,110,97,0,8,101,0,4,121,0,3,105,0,4,101,0,3,115,101,108,121,110,0,3,121,0,2,117,114,100,97,110,0,2,121,0,3,97,0,4,110,0,5,110,0,3,99,101,0,5,108,105,110,0,3,101,0,1,115,97,110,100,121,101,0,1,117,97,110,97,0,4,105,116,97,0,2,100,105,0,0,74,117,100,105,101,0,4,116,104,0,6,97,0,3,121,0,4,101,0,2,105,101,116,97,0,2,108,101,101,0,3,105,0,4,97,0,5,110,97,0,6,101,0,6,110,0,7,97,0,7,101,0,4,101,0,5,110,110,101,0,5,116,0,6,97,0,6,116,97,0,7,101,0,4,110,97,0,5,101,0,4,115,115,97,0,4,116,97,0,2,110,101,0,4,116,116,101,0,3,105,97,0,4,101,0,4,110,97,0,2,115,116,105,110,97,0,6,101,0,6,110,0,0,74,121,111,116,105,0,0,75,97,99,101,121,0,3,105,101,0,3,121,0,2,101,108,97,0,2,105,0,3,97,0,3,108,97,0,4,101,0,5,121,0,3,116,108,105,110,0,5,121,110,0,7,110,0,2,106,97,0,2,107,97,108,105,110,97,0,2,108,97,0,3,101,101,110,97,0,3,105,0,4,101,0,4,108,97,0,4,110,97,0,5,100,97,0,6,105,0,3,108,105,0,4,121,0,2,109,101,107,111,0,3,105,108,97,0,6,104,0,5,108,97,104,0,2,110,100,97,99,101,0,4,121,0,3,105,97,0,0,75,97,110,121,97,0,2,114,97,0,4,45,76,121,110,110,0,4,108,101,101,0,5,121,110,110,0,3,101,0,4,101,0,4,108,0,4,110,0,5,97,0,3,105,0,4,97,0,4,101,0,4,108,0,5,121,110,110,0,4,110,0,5,97,0,5,101,0,4,111,116,116,97,0,4,115,97,0,5,115,97,0,4,116,97,0,3,108,97,0,4,101,101,0,6,110,0,5,110,0,6,101,0,4,105,101,0,4,111,116,116,97,0,7,101,0,4,121,0,5,110,0,0,75,97,114,109,101,110,0,3,110,97,0,3,111,108,0,5,97,0,5,101,0,5,105,110,97,0,7,101,0,5,121,0,4,110,0,3,114,97,104,0,4,105,101,0,4,121,0,3,121,0,4,108,0,5,105,110,0,4,110,0,2,115,101,121,0,3,115,0,4,97,110,100,114,97,0,4,101,121,0,4,105,0,5,97,0,5,101,0,2,116,0,3,97,0,4,108,105,110,0,3,101,0,4,101,0,4,114,105,110,97,0,7,101,0,4,121,0,3,104,0,0,75,97,116,104,97,0,5,114,105,110,97,0,8,101,0,6,121,110,0,4,101,0,5,114,105,110,97,0,8,101,0,6,121,110,0,4,105,0,5,101,0,4,108,101,101,110,0,5,105,110,0,4,114,105,110,101,0,5,121,110,0,7,101,0,4,121,0,5,101,0,3,105,0,4,101,0,4,110,97,0,5,101,0,5,107,97,0,3,108,101,101,110,0,4,105,110,0,3,114,105,110,97,0,6,101,0,6,107,97,0,3,116,105,0,5,101,0,3,117,115,99,104,97,0,5,104,97,0,3,121,0,0,75,97,116,121,97,0,2,121,0,3,99,101,101,0,3,101,0,3,108,97,0,4,101,0,5,101,0,5,121,0,4,105,108,0,4,121,110,0,1,101,101,108,101,121,0,4,105,97,0,4,121,0,2,108,99,101,121,0,4,105,0,5,101,0,4,121,0,3,105,108,97,0,3,108,101,110,0,5,121,0,4,105,0,5,97,0,5,101,0,5,110,97,0,4,115,105,101,0,4,121,0,5,97,110,110,0,3,115,101,121,0,4,105,0,4,121,0,2,110,100,114,97,0,5,101,0,0,75,101,110,110,97,0,2,114,105,0,4,97,110,110,0,7,101,0,3,114,105,0,5,101,0,5,108,108,0,5,110,0,4,121,0,3,115,116,105,110,0,2,115,108,101,121,0,4,105,101,0,3,115,105,97,0,6,104,0,2,116,116,105,0,5,101,0,4,121,0,2,118,105,110,97,0,3,121,110,0,1,105,0,2,97,104,0,3,108,0,2,101,108,101,0,3,114,115,116,101,110,0,2,107,101,108,105,97,0,2,108,101,121,0,2,109,0,3,98,101,114,108,101,101,0,8,121,0,7,105,0,7,121,0,1,111,114,110,0,0,75,105,109,98,101,114,108,121,110,0,4,114,97,0,3,109,105,0,5,101,0,4,121,0,2,110,110,97,0,2,112,0,3,112,0,4,105,101,0,4,121,0,2,114,97,0,3,98,101,101,0,4,105,101,0,4,121,0,3,105,0,3,115,116,101,110,0,7,105,0,5,105,0,6,110,0,5,121,110,0,2,115,115,101,101,0,4,105,97,104,0,5,101,0,2,116,0,3,116,105,0,5,101,0,4,121,0,2,122,122,101,101,0,4,105,101,0,1,108,97,114,97,0,4,105,107,97,0,4,114,105,115,97,0,0,75,111,110,115,116,97,110,99,101,0,7,122,101,0,2,111,0,2,114,97,0,4,108,0,5,108,101,0,3,100,117,108,97,0,3,101,0,4,108,108,97,0,4,110,0,4,115,115,97,0,3,105,0,4,101,0,3,110,101,121,0,3,114,105,101,0,4,121,0,1,114,105,115,0,4,115,105,101,0,5,121,0,4,116,97,0,6,108,0,6,110,0,5,101,0,6,108,0,6,110,0,5,105,0,6,101,110,0,6,110,0,7,97,0,7,101,0,5,121,0,6,110,0,0,75,114,121,115,116,97,0,6,108,0,7,108,101,0,5,108,101,0,5,121,110,97,0,1,121,108,97,0,3,101,0,4,110,0,3,105,101,0,4,108,97,0,3,121,110,110,0,2,109,0,2,110,116,104,105,97,0,2,114,115,116,105,110,0,0,76,97,32,86,101,114,110,101,0,2,99,101,101,0,4,121,0,3,105,101,0,3,121,0,2,100,111,110,110,97,0,2,101,116,105,116,105,97,0,2,105,110,97,0,4,101,121,0,2,110,97,0,4,101,0,3,101,0,4,116,116,101,0,4,121,0,3,105,0,4,101,0,4,116,97,0,3,110,97,0,0,76,97,110,110,105,0,4,121,0,2,114,97,0,4,105,110,101,0,3,105,0,4,110,97,0,5,101,0,4,115,97,0,5,115,97,0,3,107,0,3,121,115,115,97,0,2,116,97,115,104,105,97,0,3,105,97,0,4,115,104,97,0,3,114,101,110,97,0,4,105,110,97,0,2,117,114,97,0,5,105,110,101,0,5,108,0,6,101,101,0,4,101,0,5,101,0,6,110,0,5,108,0,6,108,97,0,5,110,0,6,97,0,6,101,0,5,116,116,97,0,7,101,0,4,105,0,5,97,110,110,101,0,0,76,97,117,114,105,99,101,0,5,101,0,4,121,110,0,2,118,101,110,97,0,4,114,110,97,0,6,101,0,3,105,110,97,0,5,105,97,0,6,101,0,2,121,108,97,0,3,110,101,0,5,121,0,1,101,97,0,3,104,0,3,110,100,114,97,0,4,110,0,5,97,0,4,111,114,0,6,97,0,2,98,98,105,101,0,2,100,97,0,2,101,0,3,97,110,110,0,6,101,0,3,108,97,0,5,104,0,3,110,97,0,3,115,97,0,4,101,0,2,103,114,97,0,2,105,97,0,3,103,104,0,0,76,101,105,103,104,97,0,3,108,97,0,5,104,0,3,115,104,97,0,2,108,97,0,4,104,0,4,110,100,0,3,105,97,0,2,110,97,0,3,101,101,0,4,116,116,101,0,3,107,97,0,3,110,97,0,3,111,114,97,0,5,101,0,2,111,100,111,114,97,0,3,105,110,101,0,3,108,97,0,4,105,110,101,0,3,110,97,0,5,110,105,101,0,4,101,0,5,108,108,101,0,4,105,101,0,4,111,114,97,0,6,101,0,4,116,105,110,101,0,5,121,110,101,0,3,114,97,0,2,115,104,105,97,0,3,108,101,121,0,4,105,0,0,76,101,115,108,105,101,0,4,121,0,3,121,97,0,2,116,97,0,3,104,105,97,0,3,105,99,105,97,0,4,115,104,97,0,4,116,105,97,0,4,122,105,97,0,3,116,97,0,4,105,0,5,101,0,4,121,0,2,120,0,3,105,0,4,101,0,4,110,101,0,4,115,0,3,121,0,2,121,108,97,0,2,122,108,105,101,0,1,105,97,0,3,110,0,4,97,0,4,101,0,4,110,97,0,5,101,0,2,98,0,3,98,101,121,0,4,105,0,5,101,0,4,121,0,0,76,105,99,104,97,0,2,100,97,0,3,105,97,0,2,101,115,97,0,2,108,0,3,97,0,4,104,0,4,115,0,3,105,97,0,5,110,0,6,101,0,5,115,0,4,116,104,0,3,108,97,0,4,105,0,5,97,110,0,5,115,0,4,108,105,101,0,4,121,0,3,121,0,4,97,110,0,2,110,0,3,97,0,3,100,0,4,97,0,4,105,0,5,101,0,4,115,97,121,0,5,101,121,0,5,121,0,4,121,0,3,101,97,0,0,76,105,110,101,108,108,0,4,116,0,5,116,101,0,3,110,0,4,101,97,0,5,108,108,0,5,116,0,4,105,101,0,3,122,121,0,2,114,97,0,2,115,97,0,4,98,101,116,104,0,3,98,101,116,104,0,3,101,0,4,116,116,97,0,6,101,0,3,104,97,0,4,101,0,3,115,97,0,4,105,0,5,101,0,4,121,0,2,116,97,0,2,117,107,97,0,2,118,0,3,97,0,3,105,97,0,3,118,105,101,0,4,121,0,5,121,0,3,121,0,2,122,0,0,76,105,122,97,0,4,98,101,116,104,0,3,98,101,116,104,0,3,101,116,116,101,0,3,122,105,101,0,4,121,0,1,111,101,108,108,97,0,2,105,115,0,4,101,0,2,108,97,0,3,101,116,97,0,3,105,116,97,0,3,108,121,0,2,110,97,0,3,101,101,0,3,105,0,3,110,97,0,4,105,0,5,101,0,2,114,97,0,4,105,110,0,6,101,0,4,108,101,101,0,5,105,101,0,5,121,110,0,3,101,101,0,5,110,0,4,108,101,105,0,5,108,101,0,4,110,0,5,97,0,5,101,0,0,76,111,114,101,110,122,97,0,4,116,116,97,0,6,101,0,3,105,0,4,97,0,5,110,110,97,0,7,101,0,4,101,0,4,108,101,101,0,5,121,110,0,4,110,100,97,0,5,101,0,4,116,97,0,3,110,97,0,4,101,0,3,114,97,105,110,101,0,5,121,110,101,0,4,105,0,5,101,0,5,110,0,4,121,0,3,121,0,2,116,116,97,0,4,101,0,4,105,0,5,101,0,4,121,0,2,117,0,3,101,108,108,97,0,3,105,115,97,0,5,101,0,6,116,116,101,0,0,76,111,117,116,105,116,105,97,0,1,117,0,2,99,101,0,3,105,0,4,97,0,5,110,97,0,4,101,0,5,110,110,101,0,4,108,97,0,5,105,97,0,5,108,101,0,4,110,97,0,5,100,97,0,5,101,0,4,116,97,0,3,107,121,0,3,114,101,116,105,97,0,3,121,0,2,100,111,118,105,107,97,0,2,101,108,108,97,0,5,101,0,2,105,115,97,0,4,101,0,2,108,97,0,3,105,116,97,0,3,117,0,2,114,97,0,3,101,116,116,101,0,3,108,101,101,110,0,5,110,101,0,4,105,110,101,0,2,115,97,0,0,76,117,122,0,1,121,100,97,0,3,105,97,0,4,101,0,2,110,0,3,100,97,0,4,101,0,5,108,0,6,108,0,4,115,97,121,0,5,101,121,0,5,105,101,0,4,121,0,3,101,97,0,4,108,108,101,0,4,116,116,0,6,101,0,3,110,0,4,97,0,4,101,0,5,97,0,5,108,108,0,7,101,0,5,116,0,6,116,0,7,101,0,3,115,101,121,0,2,115,115,97,0,0,77,97,98,0,3,101,108,0,5,108,101,0,3,108,101,0,0,77,97,100,97,0,4,108,101,110,97,0,5,121,110,0,3,100,97,108,101,110,97,0,4,105,0,5,101,0,4,121,0,3,101,108,0,5,97,105,110,101,0,5,101,105,110,101,0,6,110,97,0,7,101,0,5,105,110,0,7,97,0,7,101,0,5,108,97,0,6,101,0,5,111,110,0,5,121,110,0,3,103,101,0,3,108,101,110,0,4,105,110,0,3,111,110,110,97,0,3,121,0,2,101,0,3,103,97,110,0,2,103,0,3,100,97,0,5,105,97,0,5,108,101,110,0,8,97,0,8,101,0,0,77,97,103,103,101,101,0,4,105,0,5,101,0,4,121,0,2,104,97,108,97,0,5,105,97,0,2,105,97,0,3,98,108,101,0,3,103,97,0,4,104,100,105,108,110,0,3,114,0,4,101,0,3,115,101,121,0,4,105,101,0,3,116,105,108,100,101,0,2,108,97,0,4,110,105,101,0,3,101,110,97,0,3,105,97,0,4,110,97,0,5,100,97,0,6,101,0,4,115,115,97,0,6,105,97,0,3,108,105,115,115,97,0,4,111,114,105,101,0,6,121,0,3,111,114,105,101,0,5,121,0,3,118,97,0,4,105,110,97,0,3,121,110,100,97,0,0,77,97,109,101,0,3,105,101,0,2,110,100,97,0,4,105,0,5,101,0,4,121,0,3,111,110,0,3,121,97,0,2,114,97,0,4,98,101,108,0,3,99,101,108,97,0,6,105,97,0,6,108,97,0,7,101,0,7,105,110,97,0,9,101,0,4,104,101,108,108,101,0,4,105,0,5,97,0,5,101,0,5,108,101,0,6,108,101,0,4,121,0,3,101,97,104,0,4,110,0,5,97,0,4,115,115,97,0,3,103,97,0,5,108,105,116,0,6,111,0,5,114,101,116,0,8,97,0,0,77,97,114,103,97,114,101,116,101,0,8,104,97,0,9,101,0,8,116,97,0,9,101,0,6,105,116,97,0,5,117,120,0,4,101,0,5,97,117,120,0,5,114,121,0,5,116,0,6,116,101,0,4,105,0,5,101,0,5,116,0,4,111,0,5,116,0,4,114,101,116,0,4,117,101,114,105,116,101,0,4,121,0,3,105,0,4,97,0,5,109,0,5,110,0,6,97,0,6,110,0,7,97,0,7,101,0,4,98,101,108,0,7,108,101,0,6,116,104,0,4,99,101,0,0,77,97,114,105,100,101,108,0,4,101,0,5,45,65,110,110,0,6,74,101,97,110,110,101,0,5,97,110,110,0,5,106,101,97,110,110,101,0,5,108,0,6,101,0,6,108,101,0,8,110,0,5,116,116,97,0,7,101,0,4,103,111,108,100,0,4,106,111,0,4,107,97,0,4,108,101,101,0,5,105,110,0,5,108,105,110,0,5,121,110,0,4,110,0,5,97,0,5,110,97,0,4,111,110,0,4,113,117,105,108,108,97,0,4,115,0,5,97,0,5,107,97,0,5,115,97,0,4,116,97,0,5,115,97,0,4,121,97,0,3,106,0,0,77,97,114,106,97,0,4,101,0,4,105,0,5,101,0,4,111,114,105,101,0,6,121,0,4,121,0,3,107,101,116,97,0,3,108,97,0,5,110,101,0,4,101,97,104,0,5,101,0,6,110,0,5,110,97,0,6,101,0,5,121,0,4,105,101,0,5,110,101,0,4,111,0,4,121,110,0,3,110,97,0,4,101,0,5,121,0,4,105,0,5,97,0,5,101,0,3,113,117,105,116,97,0,3,114,105,108,101,101,0,5,115,0,6,115,97,0,3,115,104,97,0,4,105,101,108,108,97,0,0,77,97,114,116,97,0,4,101,108,108,101,0,4,103,117,101,114,105,116,97,0,4,104,97,0,5,101,0,6,110,97,0,4,105,0,5,99,97,0,5,101,0,5,110,97,0,5,116,97,0,4,121,0,5,110,110,101,0,3,121,0,4,97,0,5,110,110,0,7,97,0,7,101,0,4,98,101,108,108,101,0,6,116,104,0,4,101,108,108,101,110,0,4,106,97,110,101,0,5,111,0,4,108,0,5,101,101,0,5,105,110,0,7,100,97,0,5,111,117,0,5,121,110,110,101,0,4,114,111,115,101,0,4,115,0,5,97,0,0,77,97,115,104,97,0,2,116,101,108,100,97,0,3,104,105,108,100,97,0,7,101,0,3,105,108,100,97,0,6,101,0,3,116,105,0,5,101,0,4,121,0,2,117,100,0,4,101,0,4,105,101,0,3,114,97,0,4,101,0,5,101,110,0,7,101,0,5,110,101,0,4,105,110,101,0,5,115,101,0,5,116,97,0,5,122,105,97,0,2,118,105,115,0,3,114,97,0,2,120,0,3,105,0,4,101,0,4,110,101,0,3,121,0,2,121,0,3,98,101,108,108,101,0,3,101,0,1,101,97,100,0,0,77,101,97,100,101,0,3,103,97,110,0,4,104,97,110,0,3,114,97,0,2,99,104,101,108,108,101,0,2,103,0,3,97,110,0,3,101,110,0,3,103,105,0,5,101,0,4,121,0,3,104,97,110,0,6,110,0,2,104,101,116,97,98,101,108,0,2,105,0,2,108,0,3,97,0,4,109,105,101,0,4,110,105,97,0,6,101,0,5,116,104,97,0,5,121,0,3,98,97,0,3,101,115,97,0,5,115,97,0,3,105,99,101,110,116,0,4,110,97,0,5,100,97,0,6,101,0,4,115,97,0,6,110,100,101,0,8,114,97,0,0,77,101,108,105,115,101,110,100,97,0,7,116,0,5,115,97,0,6,101,0,4,116,97,0,5,116,97,0,3,108,97,0,4,105,0,5,99,101,110,116,0,5,101,0,5,115,97,0,6,101,110,116,0,4,111,110,101,121,0,4,121,0,3,111,100,101,101,0,5,105,101,0,5,121,0,4,110,105,101,0,5,121,0,4,115,97,0,3,118,97,0,2,114,99,101,100,101,115,0,4,105,0,5,101,0,4,121,0,3,101,100,105,116,104,0,8,101,0,3,105,100,101,108,0,5,105,116,104,0,4,101,108,0,4,108,101,101,0,5,121,110,0,0,77,101,114,105,115,0,5,115,97,0,3,108,0,4,97,0,4,101,0,4,105,110,97,0,6,101,0,3,110,97,0,3,111,108,97,0,3,114,97,108,101,101,0,4,105,100,105,101,0,5,101,0,6,108,108,101,0,5,108,101,0,7,101,0,6,105,0,6,108,0,6,121,0,4,121,0,3,115,101,121,0,3,121,108,0,2,116,97,0,1,105,97,0,2,99,97,101,108,97,0,3,104,97,101,108,97,0,7,105,110,97,0,9,101,0,7,108,97,0,5,108,0,4,101,108,0,6,101,0,6,105,110,97,0,0,77,105,99,104,101,108,105,110,101,0,6,108,0,7,101,0,3,107,105,0,5,101,0,4,121,0,2,100,103,101,0,2,103,110,111,110,0,6,110,101,0,3,117,101,108,97,0,6,105,116,97,0,2,107,97,101,108,97,0,2,108,0,3,100,114,101,100,0,5,105,100,0,3,101,110,97,0,3,105,99,101,110,116,0,4,115,115,101,110,116,0,3,107,97,0,3,108,105,0,5,99,101,110,116,0,5,101,0,5,115,101,110,116,0,4,121,0,3,122,105,101,0,2,109,105,0,2,110,0,3,97,0,3,100,97,0,4,121,0,3,101,114,118,97,0,4,116,116,97,0,0,77,105,110,101,116,116,101,0,3,110,97,0,5,109,105,110,110,105,101,0,4,101,0,4,105,0,5,101,0,4,110,105,101,0,4,121,0,3,116,97,0,2,111,102,32,77,101,108,97,0,2,113,117,101,108,97,0,2,114,97,0,4,98,101,108,0,7,108,97,0,8,101,0,4,110,0,5,100,97,0,3,101,105,101,108,108,101,0,5,108,108,101,0,4,108,108,97,0,6,101,0,3,105,97,109,0,4,108,108,97,0,3,110,97,0,2,115,104,97,0,3,115,105,101,0,4,121,0,3,116,105,0,4,121,0,2,116,122,105,0,1,111,100,101,115,116,97,0,6,105,97,0,0,77,111,100,101,115,116,105,110,101,0,6,121,0,2,105,110,97,0,3,114,97,0,2,108,108,0,4,101,101,0,4,105,0,5,101,0,4,121,0,2,109,109,121,0,2,110,97,0,4,104,0,3,105,99,97,0,4,107,97,0,4,113,117,101,0,2,114,97,0,3,101,101,110,0,4,110,97,0,3,103,97,110,0,6,97,0,6,105,99,97,0,6,110,101,0,4,101,110,0,3,105,97,0,4,115,115,97,0,3,110,97,0,2,115,101,108,108,101,0,2,121,110,97,0,3,114,97,0,2,122,101,108,108,101,0,1,117,102,102,105,110,0,3,105,0,0,77,117,102,105,110,101,108,108,97,0,2,105,114,101,0,2,114,101,105,108,0,3,105,97,108,0,4,101,108,0,6,108,101,0,1,121,114,97,0,4,104,0,4,110,100,97,0,3,105,97,109,0,4,108,108,97,0,3,108,101,0,5,110,101,0,3,110,97,0,3,116,97,0,4,105,97,0,5,99,101,0,5,101,0,4,108,101,0,0,78,97,100,97,0,3,101,97,110,0,4,101,110,0,3,105,97,0,4,110,101,0,4,121,97,0,3,121,0,4,97,0,2,108,97,110,105,0,2,110,0,3,97,0,4,110,110,101,0,3,99,101,0,0,78,97,110,99,101,101,0,5,121,0,4,105,0,5,101,0,4,121,0,3,101,116,101,0,5,116,101,0,3,105,0,4,99,101,0,4,110,101,0,3,110,101,116,116,101,0,4,105,0,5,101,0,4,121,0,3,111,110,0,2,111,109,97,0,4,105,0,2,114,97,0,3,105,0,4,107,111,0,2,116,0,3,97,0,4,108,97,0,5,101,101,0,5,105,101,0,6,110,97,0,7,101,0,5,121,97,0,4,115,104,97,0,5,115,105,97,0,3,104,97,108,105,97,0,7,101,0,0,78,97,116,105,118,105,100,97,100,0,3,107,97,0,3,116,121,0,1,101,97,108,97,0,2,100,97,0,3,100,97,0,3,105,0,2,101,108,121,0,2,105,108,97,0,4,101,0,4,108,97,0,5,101,0,2,108,105,97,0,4,101,0,3,108,0,4,101,0,4,105,0,5,101,0,4,121,0,2,114,105,115,115,97,0,4,116,97,0,3,116,0,4,97,0,4,101,0,4,105,0,5,101,0,4,121,0,2,115,115,97,0,4,105,0,5,101,0,4,121,0,3,116,97,0,0,78,101,116,116,97,0,4,105,0,5,101,0,4,108,101,0,4,121,0,2,118,115,97,0,2,121,115,97,0,1,105,99,104,111,108,0,6,101,0,6,108,101,0,3,107,105,0,5,101,0,4,121,0,3,111,108,0,5,97,0,5,101,0,6,97,0,6,116,116,101,0,5,105,0,6,110,97,0,7,101,0,5,108,101,0,2,107,97,110,105,107,105,0,3,101,0,3,105,0,3,107,105,0,5,101,0,3,111,108,101,116,116,97,0,5,105,97,0,2,110,97,0,3,101,116,116,97,0,6,101,0,0,78,105,110,110,101,116,116,97,0,7,101,0,3,111,110,0,2,115,115,97,0,4,101,0,4,105,101,0,4,121,0,2,116,97,0,2,120,105,101,0,1,111,97,109,105,0,2,101,108,0,4,97,110,105,0,4,108,0,5,97,0,5,101,0,5,121,110,0,4,121,110,0,3,109,105,0,2,108,97,0,4,110,97,0,3,105,101,0,3,108,105,101,0,2,109,105,0,2,110,97,0,4,104,0,3,105,0,4,101,0,3,110,97,0,5,104,0,2,114,97,0,4,104,0,3,101,97,110,0,0,78,111,114,101,101,110,0,4,110,101,0,3,105,110,97,0,5,101,0,3,109,97,0,3,114,105,0,5,101,0,4,121,0,2,118,101,108,105,97,0,1,121,100,105,97,0,2,115,115,97,0,0,79,99,116,97,118,105,97,0,1,100,101,108,101,0,4,105,97,0,5,110,100,97,0,4,108,97,0,5,101,0,3,115,115,97,0,3,116,116,97,0,5,101,0,2,105,108,105,97,0,4,108,101,0,1,102,101,108,105,97,0,4,108,97,0,2,105,108,105,97,0,1,108,97,0,2,101,110,107,97,0,2,103,97,0,2,105,97,0,3,109,112,105,97,0,3,118,101,0,5,116,116,101,0,0,79,108,105,118,105,97,0,5,101,0,3,121,0,2,108,105,101,0,3,121,0,2,118,97,0,2,119,101,110,0,2,121,109,112,101,0,5,105,97,0,6,101,0,1,110,100,114,101,97,0,2,101,105,100,97,0,2,105,100,97,0,1,111,110,97,0,1,112,97,108,0,4,105,110,97,0,6,101,0,2,104,101,108,105,97,0,6,101,0,1,114,97,0,3,108,101,101,0,4,105,97,0,5,101,0,4,108,97,0,5,101,0,2,101,108,0,4,101,101,0,4,105,97,0,5,101,0,4,108,97,0,5,101,0,2,105,97,110,97,0,0,79,114,108,121,0,2,115,97,0,3,111,108,97,0,2,116,101,110,115,105,97,0,1,116,104,97,0,3,101,108,105,97,0,5,108,97,0,3,105,108,105,97,0,6,101,0,2,116,105,108,105,101,0,0,80,97,103,101,0,2,105,103,101,0,2,108,111,109,97,0,2,109,0,3,101,108,97,0,5,105,110,97,0,5,108,97,0,3,109,105,0,5,101,0,4,121,0,2,110,100,111,114,97,0,3,115,105,101,0,4,121,0,2,111,108,97,0,4,105,110,97,0,2,112,97,103,101,110,97,0,2,116,0,3,105,101,110,99,101,0,3,114,105,99,97,0,6,101,0,6,105,97,0,5,122,105,97,0,0,80,97,116,115,121,0,3,116,105,0,5,101,0,4,121,0,2,117,108,97,0,4,101,0,5,116,116,97,0,7,101,0,4,105,0,5,101,0,5,110,97,0,6,101,0,5,116,97,0,4,121,0,2,118,105,97,0,3,108,97,0,1,101,97,114,108,0,5,97,0,5,101,0,5,105,110,101,0,2,103,0,3,101,101,110,0,3,103,105,0,5,101,0,4,121,0,2,110,0,3,101,108,111,112,97,0,7,101,0,3,110,105,0,5,101,0,4,121,0,2,112,105,0,0,80,101,112,105,116,97,0,2,114,105,0,4,97,0,3,108,0,4,97,0,4,101,0,3,114,105,0,5,110,101,0,4,121,0,3,115,105,115,0,2,116,0,3,97,0,3,114,97,0,4,105,110,97,0,4,111,110,101,108,108,97,0,6,105,97,0,7,108,108,97,0,9,101,0,3,117,110,105,97,0,1,104,97,101,100,114,97,0,3,105,100,114,97,0,2,101,98,101,0,3,100,114,97,0,3,108,105,97,0,2,105,108,0,4,105,112,97,0,6,112,97,0,7,101,0,7,105,110,101,0,5,115,0,4,108,105,100,97,0,6,101,0,0,80,104,105,108,108,105,115,0,5,121,0,4,111,109,101,110,97,0,2,111,101,98,101,0,2,121,108,105,115,0,4,108,105,100,97,0,6,115,0,5,121,115,0,4,121,115,0,1,105,97,0,2,101,114,0,4,101,116,116,101,0,4,114,101,116,116,101,0,3,116,114,97,0,2,112,101,114,0,3,112,97,0,4,121,0,1,111,108,108,121,0,5,97,110,110,97,0,2,111,104,0,2,112,112,121,0,2,114,116,105,97,0,1,114,105,115,0,4,99,97,0,5,101,108,108,97,0,5,105,108,108,97,0,4,115,105,101,0,2,117,0,3,100,101,110,99,101,0,4,105,0,4,121,0,3,101,0,0,81,117,101,101,110,105,101,0,3,110,116,105,110,0,3,114,105,100,97,0,2,105,110,110,0,4,116,97,0,6,110,97,0,5,105,108,108,97,0,6,110,97,0,0,82,97,99,104,97,101,108,0,4,101,108,0,6,101,0,6,108,101,0,2,101,0,3,97,110,110,0,2,102,0,3,97,0,4,101,108,97,0,6,105,97,0,7,116,97,0,2,104,97,108,0,3,101,108,0,2,105,110,97,0,4,101,0,2,107,101,108,0,2,108,105,110,97,0,2,109,111,110,97,0,5,100,97,0,2,110,97,0,3,100,97,0,4,101,101,0,5,110,101,0,4,105,0,0,82,97,110,100,105,101,0,4,121,0,3,101,101,0,3,105,0,4,97,0,4,99,101,0,4,113,117,101,0,3,110,97,0,2,112,104,97,101,108,97,0,2,113,117,101,108,0,6,97,0,2,115,105,97,0,3,108,97,0,2,118,101,110,0,2,121,0,3,99,104,101,108,0,3,101,0,3,110,97,0,4,101,108,108,0,3,115,104,101,108,108,0,1,101,97,0,2,98,97,0,3,98,101,99,99,97,0,3,101,0,4,99,97,0,5,99,97,0,5,107,97,0,4,107,97,0,6,104,0,5,107,97,104,0,2,101,0,3,98,97,0,0,82,101,101,110,97,0,3,116,97,0,3,118,97,0,2,103,97,110,0,3,103,105,0,5,101,0,3,105,110,97,0,5,101,0,2,105,107,111,0,3,110,97,0,4,101,0,2,109,121,0,2,110,97,0,4,101,0,4,116,97,0,5,101,0,3,101,0,4,101,0,4,108,108,0,6,101,0,3,105,101,0,3,110,105,101,0,2,116,97,0,3,104,97,0,2,118,107,97,104,0,2,121,0,3,110,97,0,1,104,101,97,0,3,98,97,0,3,116,97,0,4,116,97,0,2,105,97,109,111,110,0,0,82,104,105,97,110,110,97,0,5,111,110,0,2,111,100,97,0,4,105,97,0,5,101,0,4,121,0,3,110,97,0,4,100,97,0,1,105,97,110,101,0,4,110,111,110,0,4,111,110,0,2,99,97,0,3,99,97,0,3,105,0,3,107,105,0,5,101,0,4,121,0,2,107,105,0,3,107,105,0,2,110,97,0,2,115,97,0,2,116,97,0,2,118,97,0,4,108,101,101,0,3,105,0,3,107,97,104,0,3,121,0,1,111,97,110,97,0,4,110,97,0,5,101,0,2,98,98,105,0,5,101,0,0,82,111,98,98,105,110,0,4,121,0,5,110,0,3,101,110,97,0,5,105,97,0,4,114,116,97,0,3,105,110,0,5,97,0,5,101,116,0,7,116,0,8,97,0,8,101,0,5,105,97,0,3,121,0,4,110,0,2,99,104,0,4,101,108,108,0,7,97,0,7,101,0,5,116,116,101,0,2,100,97,0,3,105,0,4,101,0,4,110,97,0,2,105,115,0,2,109,111,108,97,0,4,110,97,0,5,100,97,0,3,121,0,2,110,97,0,4,108,100,97,0,3,100,97,0,0,82,111,110,105,99,97,0,3,110,97,0,4,105,0,5,99,97,0,5,101,0,4,121,0,2,111,98,98,105,101,0,2,114,97,0,3,105,0,4,101,0,3,121,0,2,115,0,3,97,0,4,98,101,108,0,7,108,97,0,8,101,0,4,108,101,101,110,0,5,105,97,0,6,101,0,6,110,100,0,8,97,0,8,101,0,7,101,0,5,121,110,0,7,100,0,4,109,111,110,100,0,5,117,110,100,0,0,68,114,111,103,111,110,0,0,82,111,115,97,110,97,0,5,110,97,0,6,101,0,3,101,0,0,82,111,115,101,97,110,110,0,7,97,0,7,101,0,4,108,105,97,0,6,110,0,7,101,0,5,108,97,0,6,101,0,4,109,97,114,105,97,0,8,101,0,7,121,0,5,111,110,100,101,0,4,110,101,0,4,116,116,97,0,6,101,0,3,104,101,108,108,101,0,3,105,101,0,4,110,97,0,4,116,97,0,3,108,121,110,0,3,109,117,110,100,97,0,3,121,0,2,119,0,3,101,0,4,110,97,0,2,120,97,110,97,0,5,101,0,5,110,97,0,6,101,0,3,105,0,4,101,0,4,110,101,0,0,82,111,120,121,0,2,122,0,3,97,108,105,101,0,6,110,0,4,109,111,110,100,0,4,110,110,97,0,6,101,0,3,101,0,4,108,101,0,5,108,97,0,6,101,0,3,105,110,97,0,1,117,98,101,116,116,97,0,3,105,0,4,97,0,4,101,0,4,110,97,0,3,121,0,2,112,101,114,116,97,0,2,116,104,0,4,97,110,110,0,7,101,0,4,101,0,4,105,0,5,101,0,4,121,0,1,121,97,110,110,0,2,99,99,97,0,0,83,97,98,97,0,3,105,110,97,0,5,101,0,3,114,97,0,0,83,97,98,114,105,110,97,0,2,99,104,97,0,2,100,97,0,3,101,108,108,97,0,3,105,101,0,3,121,101,0,2,105,100,101,101,0,2,108,0,3,97,105,100,104,0,3,108,101,101,0,4,105,0,5,101,0,4,121,0,5,97,110,110,0,8,101,0,3,111,109,97,0,5,101,0,5,105,0,2,109,0,3,97,110,116,104,97,0,4,114,97,0,5,105,97,0,3,109,121,0,2,110,100,101,0,4,105,0,5,101,0,4,114,97,0,4,121,0,5,101,0,2,112,112,104,105,114,97,0,7,101,0,2,114,97,0,0,83,97,114,97,45,65,110,110,0,4,97,110,110,0,4,104,0,4,106,97,110,101,0,3,101,101,0,4,110,97,0,5,101,0,4,116,116,101,0,3,105,0,4,110,97,0,5,101,0,4,116,97,0,2,115,99,104,97,0,3,104,97,0,4,101,110,107,97,0,2,117,100,114,97,0,3,110,100,114,97,0,2,118,105,110,97,0,2,121,114,101,0,1,99,97,114,108,101,116,0,7,116,0,1,101,97,110,0,4,97,0,2,107,97,0,2,108,97,0,3,101,110,97,0,5,101,0,4,115,116,105,110,97,0,3,105,97,0,4,101,0,4,110,97,0,5,100,97,0,0,83,101,108,105,110,101,0,3,108,97,0,4,101,0,3,109,97,0,2,110,97,0,2,112,104,105,114,97,0,2,114,101,110,97,0,5,101,0,1,104,97,101,0,3,105,110,97,0,5,101,0,3,108,110,97,0,5,101,0,3,110,97,0,4,100,97,0,5,101,101,0,6,105,103,104,0,5,105,101,0,5,114,97,0,5,121,0,4,101,0,4,105,0,5,101,0,4,110,97,0,6,104,0,5,101,110,0,5,111,110,0,4,111,110,0,4,116,97,0,5,101,101,0,3,114,97,0,5,105,0,0,83,104,97,114,105,0,5,97,0,5,116,121,0,4,108,0,5,97,0,5,101,101,110,0,6,110,101,0,5,105,110,101,0,4,111,110,0,6,97,0,4,114,111,110,0,4,121,108,0,3,117,110,0,5,97,0,3,119,110,0,5,97,0,5,101,101,0,3,121,0,4,108,97,0,6,104,0,5,121,110,0,7,110,0,4,110,97,0,5,101,0,2,101,97,0,3,98,97,0,3,101,108,97,0,6,103,104,0,6,104,0,4,110,97,0,4,114,101,101,0,3,105,108,97,0,0,83,104,101,105,108,97,45,75,97,116,104,114,121,110,0,6,104,0,3,108,0,4,97,0,5,103,104,0,4,98,97,0,5,105,0,5,121,0,4,105,97,0,4,108,0,5,101,121,0,5,105,0,6,101,0,5,121,0,3,110,97,0,3,114,0,4,101,101,0,4,105,0,5,101,0,5,108,108,0,6,121,110,0,4,108,105,110,101,0,4,114,105,0,6,101,0,5,121,0,4,121,101,0,5,108,0,2,105,110,97,0,3,114,0,4,108,0,5,101,101,0,7,110,0,0,83,104,105,114,108,101,110,101,0,6,121,0,5,105,110,101,0,2,111,115,104,97,110,97,0,7,110,97,0,1,105,97,110,97,0,4,110,97,0,2,98,0,3,98,105,101,0,4,121,0,3,101,97,108,0,4,108,0,5,108,97,0,6,101,0,3,105,108,108,97,0,3,108,101,121,0,3,121,108,0,5,108,97,0,6,101,0,2,100,111,110,101,121,0,5,105,97,0,5,110,105,101,0,2,103,114,105,100,0,2,108,101,0,4,97,115,0,3,118,97,0,5,110,97,0,4,105,97,0,5,101,0,2,109,111,110,97,0,5,101,0,6,116,116,101,0,0,83,105,109,111,110,110,101,0,2,110,100,101,101,0,2,111,98,104,97,110,0,3,117,120,0,5,105,101,0,2,115,101,108,121,0,3,105,108,101,0,3,115,105,101,0,4,121,0,2,117,115,97,110,0,1,111,102,105,97,0,4,101,0,2,110,100,114,97,0,3,105,97,0,3,106,97,0,3,110,105,0,5,101,0,4,110,105,101,0,4,121,0,3,121,97,0,2,112,104,101,121,0,4,105,0,5,97,0,5,101,0,4,114,111,110,105,97,0,2,114,99,104,97,0,2,115,97,110,110,97,0,1,116,97,99,101,0,5,101,0,5,121,0,4,105,0,5,97,0,0,83,116,97,99,105,101,0,4,121,0,3,102,97,110,105,0,3,114,0,4,108,97,0,5,101,110,101,0,5,105,110,0,4,114,0,2,101,102,97,0,5,110,105,97,0,7,101,0,4,102,97,110,101,0,5,105,0,6,101,0,3,108,108,97,0,3,112,104,97,0,6,110,97,0,7,105,0,8,101,0,7,110,105,101,0,5,101,110,105,101,0,5,105,0,6,101,0,6,110,101,0,3,115,104,97,0,3,118,97,110,97,0,4,101,110,97,0,2,111,100,100,97,114,100,0,3,114,109,0,5,105,0,6,101,0,5,121,0,0,83,117,101,0,3,108,108,101,110,0,2,107,101,121,0,3,105,0,2,108,97,0,2,110,110,121,0,3,115,104,105,110,101,0,2,115,97,110,0,5,97,0,5,101,116,116,97,0,5,110,0,6,97,0,7,104,0,6,101,0,3,101,116,116,101,0,3,105,0,4,101,0,3,121,0,2,122,97,110,110,0,6,97,0,6,101,0,3,101,116,116,101,0,3,105,0,4,101,0,3,121,0,1,121,98,105,108,0,5,97,0,5,108,97,0,6,101,0,3,121,108,0,2,100,101,108,0,5,108,101,0,0,83,121,100,110,101,121,0,2,108,118,105,97,0,0,84,97,98,97,116,104,97,0,3,98,97,116,104,97,0,4,105,0,5,101,0,5,116,104,97,0,4,121,0,3,105,110,97,0,4,116,104,97,0,2,102,102,121,0,2,108,105,97,0,3,108,105,97,0,5,101,0,4,111,117,0,4,117,108,97,104,0,4,121,0,3,121,97,0,5,104,0,2,109,97,114,0,5,97,0,6,104,0,5,114,97,0,3,101,114,97,0,3,105,0,4,107,111,0,3,109,97,0,5,114,97,0,4,105,0,5,101,0,4,121,0,3,113,114,97,104,0,0,84,97,109,114,97,0,2,110,97,0,3,100,105,0,5,101,0,4,121,0,3,104,121,97,0,3,105,0,4,97,0,4,116,97,110,115,121,0,3,115,121,0,3,121,97,0,2,114,97,0,4,104,0,3,114,97,0,5,104,0,3,121,110,0,2,115,104,97,0,3,105,97,0,2,116,101,0,3,105,97,110,97,0,6,105,97,0,3,117,109,0,2,119,110,121,97,0,3,115,104,97,0,1,101,100,0,3,100,97,0,4,105,0,5,101,0,4,121,0,3,105,0,3,114,97,0,2,101,110,97,0,0,84,101,105,114,116,122,97,0,2,111,100,111,114,97,0,2,114,97,0,0,78,97,115,116,106,97,0,0,84,111,110,0,1,101,114,101,115,97,0,5,101,0,5,105,110,97,0,6,116,97,0,5,115,97,0,3,105,0,4,97,110,110,0,3,114,97,0,4,105,0,5,101,0,5,106,111,0,4,121,0,5,101,0,3,115,105,110,97,0,3,122,97,0,2,115,115,0,4,97,0,4,105,0,5,101,0,4,121,0,1,104,97,108,105,97,0,2,101,97,0,4,100,111,114,97,0,3,100,97,0,3,107,108,97,0,3,108,109,97,0,3,111,0,0,84,104,101,111,100,111,114,97,0,6,115,105,97,0,3,114,101,115,97,0,6,101,0,6,105,110,97,0,7,116,97,0,6,115,97,0,4,105,110,101,0,2,105,97,0,2,111,109,97,115,97,0,6,105,110,0,8,97,0,8,101,0,1,97,107,105,115,0,0,67,101,100,101,114,0,0,68,114,97,103,111,110,0,0,84,105,101,110,97,0,3,114,110,101,121,0,4,116,122,97,0,2,102,102,0,4,97,110,105,0,7,101,0,6,121,0,4,105,0,5,101,0,4,121,0,2,108,100,97,0,4,105,0,5,101,0,4,121,0,3,108,105,101,0,4,121,0,0,84,105,109,0,3,105,0,3,109,105,0,5,101,0,4,121,0,3,111,116,104,101,97,0,2,110,97,0,3,101,0,2,112,104,97,110,105,0,7,101,0,6,121,0,2,115,104,0,4,97,0,1,111,98,101,0,4,121,0,3,105,0,3,121,0,4,101,0,2,105,110,101,116,116,101,0,2,109,97,0,4,115,105,110,97,0,7,101,0,3,105,0,3,109,105,0,5,101,0,4,121,0,2,110,105,0,4,97,0,4,101,0,3,121,0,4,97,0,4,101,0,0,84,111,111,116,115,105,101,0,2,114,101,121,0,3,105,0,4,101,0,3,114,105,101,0,3,121,0,2,118,97,0,3,101,0,1,114,97,99,101,101,0,5,121,0,4,105,0,5,101,0,4,121,0,2,101,110,110,97,0,3,115,97,0,4,99,104,97,0,4,115,97,0,2,105,99,105,97,0,3,110,97,0,3,115,104,0,5,97,0,4,116,97,0,3,120,0,4,105,0,5,101,0,4,121,0,2,117,100,97,0,4,101,0,5,121,0,4,105,0,5,101,0,4,121,0,0,84,114,117,108,97,0,1,117,101,115,100,97,121,0,1,119,105,108,97,0,2,121,108,97,0,1,121,98,105,0,4,101,0,2,110,101,0,0,85,108,97,0,2,108,97,0,2,114,105,99,97,0,4,107,97,0,6,117,109,101,107,111,0,5,101,0,1,109,101,107,111,0,1,110,97,0,1,114,115,97,0,4,108,97,0,3,111,108,97,0,3,117,108,97,0,5,105,110,97,0,7,101,0,1,116,97,0,0,86,97,108,0,3,97,114,101,101,0,5,105,97,0,3,101,0,4,100,97,0,4,110,99,105,97,0,5,101,0,5,107,97,0,5,116,105,97,0,7,110,97,0,0,86,97,108,101,110,116,105,110,101,0,4,114,97,0,5,105,97,0,6,101,0,5,121,0,6,101,0,3,105,100,97,0,4,110,97,0,3,108,105,0,5,101,0,4,121,0,3,109,97,0,3,114,121,0,2,110,0,3,100,97,0,3,101,115,115,97,0,3,105,97,0,3,110,97,0,4,105,0,5,101,0,4,121,0,3,121,97,0,1,101,100,97,0,2,108,109,97,0,3,118,101,116,0,2,110,105,116,97,0,3,117,115,0,2,114,97,0,4,100,105,115,0,3,101,0,4,110,97,0,5,101,0,0,86,101,114,105,101,101,0,4,108,101,0,4,110,97,0,5,101,0,3,108,97,0,3,110,97,0,4,105,99,101,0,3,111,110,105,99,97,0,6,107,97,0,7,101,0,6,113,117,101,0,2,118,97,121,0,1,105,0,2,99,107,105,0,5,101,0,4,121,0,3,116,111,114,105,97,0,2,100,97,0,2,107,105,0,3,107,105,0,4,121,0,2,108,104,101,108,109,105,110,97,0,3,109,97,0,2,110,0,3,97,0,3,105,116,97,0,3,110,105,0,5,101,0,4,121,0,2,111,108,97,0,5,110,116,101,0,4,101,0,0,86,105,111,108,101,116,0,6,116,97,0,7,101,0,2,114,103,105,101,0,5,110,97,0,6,105,97,0,7,101,0,2,116,97,0,3,105,97,0,3,111,114,105,97,0,3,116,111,114,105,97,0,2,118,0,3,97,0,3,105,0,4,97,0,5,110,0,6,97,0,6,110,97,0,7,101,0,4,101,0,5,110,0,6,101,0,6,110,101,0,4,121,97,110,0,3,121,97,110,0,6,110,101,0,1,111,110,110,105,0,5,101,0,4,121,0,1,121,107,121,0,0,87,97,108,108,105,101,0,5,115,0,0,87,97,108,108,105,119,0,4,121,0,3,121,0,2,110,100,97,0,4,105,101,0,5,115,0,3,101,116,97,0,3,105,100,115,0,1,101,110,100,97,0,4,101,108,105,110,101,0,4,105,0,5,101,0,4,121,0,5,101,0,3,111,110,97,0,6,104,0,1,104,105,116,110,101,121,0,1,105,108,101,101,110,0,3,104,101,108,109,105,110,97,0,9,101,0,3,105,101,0,3,108,97,0,5,98,101,108,108,97,0,5,109,105,110,97,0,4,101,116,116,97,0,7,101,0,4,105,0,5,101,0,4,111,119,0,4,121,0,5,116,0,3,109,97,0,0,87,105,108,109,101,116,116,101,0,3,111,110,97,0,5,101,0,4,119,0,2,110,100,121,0,3,105,0,4,102,114,101,100,0,3,110,97,0,5,104,0,4,101,0,4,105,0,5,101,0,5,102,114,101,100,0,4,121,0,3,111,110,97,0,6,104,0,1,114,101,110,0,4,110,105,101,0,1,121,108,109,97,0,2,110,110,0,4,101,0,4,105,101,0,4,121,0,0,88,97,118,105,101,114,97,0,1,101,110,97,0,3,105,97,0,1,121,108,105,97,0,4,110,97,0,0,89,97,108,111,110,100,97,0,2,115,109,101,101,110,0,4,105,110,0,1,101,108,101,110,97,0,0,89,101,116,116,97,0,4,105,101,0,4,121,0,2,118,101,116,116,101,0,1,110,101,115,0,3,122,0,1,111,107,111,0,2,108,97,110,100,97,0,6,101,0,5,101,0,5,116,104,101,0,2,115,104,105,0,5,107,111,0,2,118,111,110,110,100,97,0,1,115,97,98,101,108,0,1,118,101,116,116,101,0,2,111,110,110,101,0,0,90,97,98,114,105,110,97,0,2,104,97,114,97,0,2,110,100,114,97,0,3,101,116,97,0,2,114,97,0,4,104,0,3,105,97,0,3,108,97,0,1,101,97,0,2,108,100,97,0,3,109,97,0,2,110,97,0,3,105,97,0,1,105,97,0,2,108,118,105,97,0,0,90,105,116,97,0,3,101,108,108,97,0,1,111,101,0,2,108,97,0,2,110,100,97,0,4,114,97,0,3,110,121,97,0,2,114,97,0,4,104,0,4,110,97,0,3,105,110,97,0,5,101,0,1,115,97,32,90,115,97,0,3,122,115,97,0,1,117,108,101,109,97,0,2,122,97,110,97,0,0,78,111,100,100,121,0,0,67,97,114,114,111,116,0,0,77,111,105,115,116,0,0,72,121,100,114,97,0,0,68,121,108,97,110,97,116,116,111,0,0,83,119,97,110,0,0,87,97,114,108,105,116,97,0,0,77,97,104,97,114,108,105,107,97,0,0,65,109,105,104,97,110,0,0,72,97,98,97,103,97,116,0,0,71,97,121,97,110,101,0,0,72,97,121,107,117,104,105,0,4,0,0,83,114,98,117,104,105,0,0,73,115,107,111,117,104,105,0,0,77,97,114,105,110,101,0,0,77,97,114,101,108,0,0,65,110,106,97,110,101,121,117,108,117,0,0,71,105,114,114,97,106,0,0,75,114,105,115,104,110,97,109,117,114,116,105,0,0,86,105,115,119,97,110,97,116,104,97,110,0,0,78,97,114,101,115,104,0,0,80,97,114,100,101,101,112,0,0,65,97,115,104,117,0,0,82,97,116,110,97,107,97,114,0,0,77,101,114,105,116,120,101,108,108,0,0,76,97,107,115,104,109,105,0,0,68,101,101,112,116,105,0,0,84,97,110,118,105,0,0,68,114,97,99,117,108,97,0};
+static const uint32_t names_index[] = {0,121,266,421,558,698,827,962,1093,1226,1374,1507,1656,1794,1916,2047,2171,2299,2425,2562,2685,2826,2959,3107,3243,3381,3516,3657,3783,3904,4040,4172,4322,4449,4591,4745,4896,5055,5199,5354,5508,5652,5802,5954,6097,6233,6372,6505,6649,6812,6959,7113,7250,7393,7559,7695,7844,7993,8153,8298,8437,8564,8710,8842,8968,9108,9246,9373,9516,9669,9817,9963,10103,10259,10402,10552,10681,10819,10962,11098,11242,11378,11522,11661,11782,11916,12065,12218,12374,12523,12682,12829,12981,13126,13271,13415,13569,13716,13847,13990,14142,14288,14427,14570,14724,14875,15032,15182,15330,15468,15625,15772,15896,16033,16182,16330,16460,16600,16747,16902,17049,17209,17354,17492,17622,17752,17908,18032,18171,18301,18442,18575,18743,18900,19036,19163,19302,19441,19581,19734,19856,19993,20122,20253,20374,20520,20647,20764,20888,21026,21165,21294,21429,21565,21705,21838,21992,22131,22262,22401,22543,22664,22802,22930,23064,23200,23333,23465,23588,23715,23851,24009,24138,24285,24444,24602,24739,24896,25031,25195,25331,25481,25622,25760,25910,26068,26202,26366,26520,26654,26802,26971,27125,27278,27430,27572,27702,27849,27986,28121,28247,28376,28516,28639,28777,28900,29021,29153,29280,29420,29555,29679,29825,29958,30090,30233,30358,30473,30597,30731,30859,31001,31121,31254,31401,31530,31655,31798,31928,32067,32200,32341,32484,32619,32770,32923,33069,33212,33340,33466,33598,33728,33884,34025,34184,34308,34451,34609,34757,34899,35031,35164,35290,35423,35557,35692,35830,35980,36111,36237,36362,36509,36659,36798,36930,37072,37204,37348,37496,37618,37744,37896,38029,38169,38302,38448,38601,38762,38968};
+const char *citizen_name(int i, char *buf, int size) {
+ buf[0] = 0;
+ if (i < 0 || i >= ncitizen_names || size < 2) return buf;
+ const uint8_t *p = names_blob + names_index[i / 32];
+ int len = 0;
+ for (int k = i - i % 32; k <= i; k++) {
+ int shared = *p++;
+ if (shared > len) shared = len;
+ len = shared;
+ while (*p) {
+ if (len < size - 1) buf[len++] = (char)*p;
+ p++;
+ }
+ p++;
+ buf[len] = 0;
+ }
+ return buf;
+}
diff --git a/games/finalearth2/src/lang_data.h b/games/finalearth2/src/lang_data.h
new file mode 100644
index 00000000..f33170e6
--- /dev/null
+++ b/games/finalearth2/src/lang_data.h
@@ -0,0 +1,430 @@
+/* The Final Earth 2: the user interface's texts and build menu tables (made by tools/gen_lang.py
+ * from the original's lang_en.csv and data). Don't edit: edit the generator. */
+#ifndef FE_LANG_DATA_H
+#define FE_LANG_DATA_H
+#include <stdint.h>
+
+extern const char L_age_and_education[];
+extern const char L_alien_ruins_description_1a[];
+extern const char L_alien_ruins_description_1b[];
+extern const char L_alien_ruins_description_1c[];
+extern const char L_alien_ruins_description_1d[];
+extern const char L_alien_ruins_description_1e[];
+extern const char L_alien_ruins_description_2a[];
+extern const char L_alien_ruins_description_2b[];
+extern const char L_alien_ruins_description_2c[];
+extern const char L_alien_ruins_description_2d[];
+extern const char L_alien_ruins_description_2e[];
+extern const char L_alien_ruins_description_3a[];
+extern const char L_alien_ruins_description_3b[];
+extern const char L_alien_ruins_description_3c[];
+extern const char L_alien_ruins_description_3d[];
+extern const char L_alien_ruins_description_3e[];
+extern const char L_alien_ruins_description_4a[];
+extern const char L_alien_ruins_description_4b[];
+extern const char L_alien_ruins_description_4c[];
+extern const char L_alien_ruins_description_4d[];
+extern const char L_alien_ruins_description_4e[];
+extern const char L_alien_ruins_find_1a[];
+extern const char L_alien_ruins_find_1b[];
+extern const char L_alien_ruins_find_1c[];
+extern const char L_alien_ruins_find_1d[];
+extern const char L_alien_ruins_find_1e[];
+extern const char L_alien_ruins_find_2a[];
+extern const char L_alien_ruins_find_2b[];
+extern const char L_alien_ruins_find_2c[];
+extern const char L_alien_ruins_find_2d[];
+extern const char L_alien_ruins_find_2e[];
+extern const char L_alien_ruins_find_3a[];
+extern const char L_alien_ruins_find_3b[];
+extern const char L_alien_ruins_find_3c[];
+extern const char L_alien_ruins_find_3d[];
+extern const char L_alien_ruins_find_3e[];
+extern const char L_alien_ruins_find_4a[];
+extern const char L_alien_ruins_find_4b[];
+extern const char L_alien_ruins_find_4c[];
+extern const char L_alien_ruins_find_4d[];
+extern const char L_alien_ruins_find_4e[];
+extern const char L_all[];
+extern const char L_all_building_modes[];
+extern const char L_also_unlocks_new[];
+extern const char L_and[];
+extern const char L_are_n_children[];
+extern const char L_art[];
+extern const char L_assign_more_to_speed_up[];
+extern const char L_assign_workers[];
+extern const char L_assign_workers_to_prepare[];
+extern const char L_auto_upgrade[];
+extern const char L_babies_born_normal[];
+extern const char L_back[];
+extern const char L_back_to_title[];
+extern const char L_best_time[];
+extern const char L_birth_control[];
+extern const char L_build_anywhere[];
+extern const char L_build_mode_destroy[];
+extern const char L_build_mode_destroy_explanation[];
+extern const char L_build_mode_destroyleavinghole[];
+extern const char L_build_mode_destroyleavinghole_explanation[];
+extern const char L_build_mode_insert[];
+extern const char L_build_mode_multi[];
+extern const char L_build_mode_multi_explanation[];
+extern const char L_build_mode_multi_replace[];
+extern const char L_build_mode_multi_replace_explanation[];
+extern const char L_build_mode_normal[];
+extern const char L_build_mode_normal_explanation[];
+extern const char L_build_mode_replace[];
+extern const char L_build_mode_replace_explanation[];
+extern const char L_building_a_building[];
+extern const char L_building_mode_afford[];
+extern const char L_building_mode_all_explain[];
+extern const char L_building_mode_only_this[];
+extern const char L_building_modes[];
+extern const char L_building_prevented_strange_force[];
+extern const char L_cant_afford[];
+extern const char L_cant_organize[];
+extern const char L_center_on_house[];
+extern const char L_center_on_school[];
+extern const char L_center_on_work[];
+extern const char L_change_appearance_upgrade[];
+extern const char L_change_building_color[];
+extern const char L_change_city_name[];
+extern const char L_change_door_color[];
+extern const char L_change_game_speed_pc[];
+extern const char L_change_home_job[];
+extern const char L_change_home_school[];
+extern const char L_change_variant[];
+extern const char L_choose_color[];
+extern const char L_citizen_gratefulness_bonus[];
+extern const char L_citizen_passed_away[];
+extern const char L_citizen_production_cost[];
+extern const char L_citizens_and_children[];
+extern const char L_citizens_by_age_explain[];
+extern const char L_citizens_unhappy[];
+extern const char L_citizens_unhappy_food[];
+extern const char L_citizens_unhappy_key[];
+extern const char L_citizens_unhappy_title[];
+extern const char L_citizens_work_at_speed[];
+extern const char L_city_name[];
+extern const char L_city_policies[];
+extern const char L_city_upgrades[];
+extern const char L_click_here_to_play[];
+extern const char L_close[];
+extern const char L_color_code[];
+extern const char L_color_code_enter[];
+extern const char L_color_not_parsed[];
+extern const char L_computer_chips[];
+extern const char L_computer_chips_use[];
+extern const char L_confirm[];
+extern const char L_continue[];
+extern const char L_credits[];
+extern const char L_credits_additional_sprites[];
+extern const char L_current_festival[];
+extern const char L_current_task[];
+extern const char L_current_tasks[];
+extern const char L_customize_free_play[];
+extern const char L_destroy[];
+extern const char L_destroy_this_building[];
+extern const char L_double_speed[];
+extern const char L_duplicate_building[];
+extern const char L_education_happiness[];
+extern const char L_education_level_0[];
+extern const char L_education_level_1[];
+extern const char L_education_level_2[];
+extern const char L_education_level_3[];
+extern const char L_education_level_4[];
+extern const char L_education_level_5[];
+extern const char L_education_level_6[];
+extern const char L_education_level_7[];
+extern const char L_education_level_8[];
+extern const char L_encourage_contraception[];
+extern const char L_encourage_parenthood[];
+extern const char L_entertainment_happiness[];
+extern const char L_entertainment_information_multiple_wg_with_citizens[];
+extern const char L_exploration_nothing_found[];
+extern const char L_extra_resources[];
+extern const char L_factory_operating_cost[];
+extern const char L_find_homeless[];
+extern const char L_findings[];
+extern const char L_first_house_cheaper[];
+extern const char L_follow_citizen[];
+extern const char L_following[];
+extern const char L_food[];
+extern const char L_food_description_1[];
+extern const char L_food_description_2[];
+extern const char L_food_description_3[];
+extern const char L_food_description_4[];
+extern const char L_food_rationing_unhappiness[];
+extern const char L_food_shortage_unhappiness[];
+extern const char L_for_all_buildings[];
+extern const char L_for_citizen[];
+extern const char L_for_n_buildings[];
+extern const char L_for_one_building[];
+extern const char L_for_this_building[];
+extern const char L_forest_instant_uproot[];
+extern const char L_forest_instant_uproot_description[];
+extern const char L_forest_management[];
+extern const char L_forest_management_all[];
+extern const char L_forest_management_only_this[];
+extern const char L_forest_management_question_1[];
+extern const char L_forest_management_question_2[];
+extern const char L_forest_protect[];
+extern const char L_forest_protect_description_1[];
+extern const char L_forest_protect_description_2[];
+extern const char L_forest_regrow[];
+extern const char L_forest_regrow_description_1[];
+extern const char L_forest_regrow_description_2[];
+extern const char L_forest_uproot[];
+extern const char L_forest_uproot_description_1[];
+extern const char L_forest_uproot_description_2[];
+extern const char L_free_play[];
+extern const char L_game_menu[];
+extern const char L_game_paused[];
+extern const char L_game_running[];
+extern const char L_gaming[];
+extern const char L_give_city_name[];
+extern const char L_glory_of_the_key[];
+extern const char L_graphene[];
+extern const char L_graphene_use[];
+extern const char L_great_gather_stone[];
+extern const char L_greatly_discourage_children[];
+extern const char L_half_speed[];
+extern const char L_happiness[];
+extern const char L_happiness_explainer[];
+extern const char L_hide_extra_info[];
+extern const char L_high_end_restaurants[];
+extern const char L_highlight_buildings[];
+extern const char L_highlighting[];
+extern const char L_hint_hint[];
+extern const char L_home_happiness[];
+extern const char L_homeless_n[];
+extern const char L_homeless_one[];
+extern const char L_house_n_cap_remaining[];
+extern const char L_houses_exactly_enough[];
+extern const char L_housing[];
+extern const char L_housing_information[];
+extern const char L_ignore_unhappy_citizens[];
+extern const char L_increase_woodcutting_priority[];
+extern const char L_invalid_structure[];
+extern const char L_invalid_structure_2[];
+extern const char L_invite_not_enough_houses[];
+extern const char L_invite_people[];
+extern const char L_invite_people_description[];
+extern const char L_invite_people_done[];
+extern const char L_invite_people_success[];
+extern const char L_is_one_child[];
+extern const char L_keypad_builder_hint[];
+extern const char L_keypad_caps[];
+extern const char L_keypad_credits_1[];
+extern const char L_keypad_credits_2[];
+extern const char L_keypad_credits_3[];
+extern const char L_keypad_credits_4[];
+extern const char L_keypad_delete[];
+extern const char L_keypad_home_quit[];
+extern const char L_keypad_load_failed[];
+extern const char L_keypad_menu_hint[];
+extern const char L_keypad_save_failed[];
+extern const char L_keypad_save_failed_title[];
+extern const char L_keypad_saved[];
+extern const char L_keypad_space[];
+extern const char L_keypad_toolbox_hint[];
+extern const char L_keypad_typing_hint[];
+extern const char L_keypad_var_hint[];
+extern const char L_knowledge[];
+extern const char L_knowledge_use[];
+extern const char L_last_saved[];
+extern const char L_libraries[];
+extern const char L_limitedBuilding[];
+extern const char L_limited_per_citizens[];
+extern const char L_luxury_housing[];
+extern const char L_machine_parts[];
+extern const char L_machine_parts_use[];
+extern const char L_main_goal[];
+extern const char L_malfunctioned_haunted_labs[];
+extern const char L_management[];
+extern const char L_mandatory_overtime_unhappiness[];
+extern const char L_max[];
+extern const char L_medical_happiness[];
+extern const char L_mines_warning[];
+extern const char L_mirror[];
+extern const char L_more_babies_born[];
+extern const char L_more_happiness_info[];
+extern const char L_move[];
+extern const char L_move_ruins_howto[];
+extern const char L_music_festival[];
+extern const char L_music_festival_boost[];
+extern const char L_music_festival_doing[];
+extern const char L_music_festival_help[];
+extern const char L_music_festival_planned[];
+extern const char L_n_days[];
+extern const char L_n_days_ago[];
+extern const char L_n_hours[];
+extern const char L_n_minutes[];
+extern const char L_n_pct_explored[];
+extern const char L_nature[];
+extern const char L_new_city[];
+extern const char L_new_city_enthousiasm[];
+extern const char L_next_scenario[];
+extern const char L_night_clubs[];
+extern const char L_no_basic_houses[];
+extern const char L_no_destroy_allowed[];
+extern const char L_no_residents[];
+extern const char L_no_special_policy[];
+extern const char L_no_undo[];
+extern const char L_no_upgrades[];
+extern const char L_no_work_buildings[];
+extern const char L_no_workers[];
+extern const char L_normal_resources[];
+extern const char L_normal_speed[];
+extern const char L_not_enough_food[];
+extern const char L_ok_or_alpha[];
+extern const char L_one[];
+extern const char L_one_day[];
+extern const char L_one_hour[];
+extern const char L_one_minute[];
+extern const char L_onepointfive_speed[];
+extern const char L_only_show_unupgraded[];
+extern const char L_operating_cost[];
+extern const char L_operating_cost_pd[];
+extern const char L_organize_a_festival[];
+extern const char L_pct_grown[];
+extern const char L_pct_left[];
+extern const char L_per_building[];
+extern const char L_placing_a_decoration[];
+extern const char L_planned_festival[];
+extern const char L_planting_a_forest[];
+extern const char L_played_before[];
+extern const char L_pop_by_age[];
+extern const char L_pop_limit[];
+extern const char L_pop_limit_hint[];
+extern const char L_pop_stabilize[];
+extern const char L_population[];
+extern const char L_preparing[];
+extern const char L_prioritize[];
+extern const char L_prioritize_description_1[];
+extern const char L_prioritize_description_2[];
+extern const char L_prioritized[];
+extern const char L_priority_text[];
+extern const char L_production[];
+extern const char L_pubs_restaurants[];
+extern const char L_quality[];
+extern const char L_rationing_halves_this[];
+extern const char L_really_destroy[];
+extern const char L_really_uproot[];
+extern const char L_reduce_stone_mining_priority[];
+extern const char L_refined_metals[];
+extern const char L_refined_metals_use[];
+extern const char L_residents[];
+extern const char L_residents_of[];
+extern const char L_restart[];
+extern const char L_restart_scenario[];
+extern const char L_restart_scenario_question[];
+extern const char L_rock_management_mine[];
+extern const char L_rock_management_mine_description_1[];
+extern const char L_rock_management_mine_description_2[];
+extern const char L_rock_management_protect_description_1[];
+extern const char L_rock_management_protect_description_2[];
+extern const char L_rock_management_question_1[];
+extern const char L_rock_management_question_2[];
+extern const char L_rock_mining[];
+extern const char L_rock_prioritized_description[];
+extern const char L_rock_prioritized_description_2[];
+extern const char L_rocketFuel[];
+extern const char L_rocketFuel_use[];
+extern const char L_save[];
+extern const char L_sculptures[];
+extern const char L_secret_society_forbidden[];
+extern const char L_see_wood_here[];
+extern const char L_select_any[];
+extern const char L_sense_of_purpose[];
+extern const char L_set_management_all_rocks[];
+extern const char L_set_management_rock[];
+extern const char L_show_extra_info[];
+extern const char L_slow_pop_growth[];
+extern const char L_speedup_hint[];
+extern const char L_start_scenario[];
+extern const char L_starting_citizens[];
+extern const char L_starting_resources[];
+extern const char L_stone[];
+extern const char L_stone_use[];
+extern const char L_stone_warning[];
+extern const char L_students[];
+extern const char L_sure_restart[];
+extern const char L_tap_for_age_distribution[];
+extern const char L_tap_for_age_distribution_or_pop_limit[];
+extern const char L_tap_near_citizen_to_follow[];
+extern const char L_thanks_for_playing[];
+extern const char L_there_are_no_houses[];
+extern const char L_this_citizen[];
+extern const char L_threequarter_speed[];
+extern const char L_to_pause[];
+extern const char L_to_research[];
+extern const char L_to_unpause[];
+extern const char L_today[];
+extern const char L_total[];
+extern const char L_total_amount_of_citizens[];
+extern const char L_total_happiness[];
+extern const char L_unique[];
+extern const char L_unlock_all[];
+extern const char L_unnamed_city[];
+extern const char L_upgrade_afford[];
+extern const char L_upgrade_all_explain[];
+extern const char L_upgrade_all_labs[];
+extern const char L_upgrade_basic_for[];
+extern const char L_upgrade_basic_houses[];
+extern const char L_upgrade_basic_houses_hint[];
+extern const char L_upgrade_only_this[];
+extern const char L_upgrade_to_x[];
+extern const char L_upgraded_houses[];
+extern const char L_upgrades[];
+extern const char L_upgrades_and_policies[];
+extern const char L_usage[];
+extern const char L_wood[];
+extern const char L_wood_use[];
+extern const char L_work[];
+extern const char L_work_speed_modifier[];
+extern const char L_work_tooltip[];
+extern const char L_workers[];
+extern const char L_workers_of[];
+extern const char L_yesterday[];
+extern const char L_you_have_enough_stone[];
+extern const char L_you_have_enough_wood[];
+
+/* a class's texts and look in the build menu */
+typedef struct {
+ const char *name, *desc, *hint; /* hint: showUnlockHint, NULL none */
+ uint16_t back; /* its button's background (buttonBack; BACK_OWN: its sprite's at 44,0), 0 none */
+ uint16_t on_build; /* onBuildSprite, 0: the class's sprite */
+ uint16_t tip_icon; /* tooltipBottomIconInfo, 0 none */
+ uint8_t flags; /* CT_* */
+ uint8_t sub; /* its decoration subcategory + 1 (SUB_*), 0 none */
+ uint16_t limited; /* limitedToCitizens: one per that many citizens, 0 none */
+} ClsText;
+#define BACK_OWN 0xFFFF
+enum { CT_MULTI_DECOR = 1, CT_ANYCOLOR = 2, CT_MIRRORABLE = 4, CT_MULTI_SPEC = 8, CT_NOT_UNIQUE_GL = 16,
+ CT_UNIQUE = 32, CT_LIMITED = 64 };
+extern const ClsText cls_text[];
+/* the buildings in the original's order (buildinginfo.json), for the build menu */
+extern const uint8_t build_order[];
+extern const int nbuild_order;
+
+/* buildingCategoriesInfo.json, and the decorations' subcategories */
+typedef struct { const char *name, *desc; uint16_t icon; } CatText;
+#define NCATEGORIES 7
+extern const CatText cat_text[NCATEGORIES];
+#define NSUBCATEGORIES 5
+extern const CatText sub_text[NSUBCATEGORIES];
+
+/* decorationsInfo.json (snow left out): what one places on a world's ground */
+typedef struct { uint16_t spr; uint8_t flags; uint8_t food, wood, stone; const char *name, *desc; } DecoText;
+enum { DT_GENE_EDITING = 1, DT_REMOVE = 2 };
+extern const DecoText deco_text[];
+extern const int ndeco_text;
+/* buildableWorldResourcesInfo.json: forests and rocks one can place */
+typedef struct { uint8_t cls; int16_t grow, resources; float wood, stone; const char *name, *desc; } ResText;
+extern const ResText res_text[];
+extern const int nres_text;
+
+/* the citizens' names (citizenNames.txt): name i, front-coded */
+extern const int ncitizen_names;
+const char *citizen_name(int i, char *buf, int size);
+#endif
diff --git a/games/finalearth2/src/path.c b/games/finalearth2/src/path.c
new file mode 100644
index 00000000..d14e44fe
--- /dev/null
+++ b/games/finalearth2/src/path.c
@@ -0,0 +1,394 @@
+/* The Final Earth 2: the citizens' pathfinder (js/pathfinder.js, run in a
+ * web worker in the original, and pathfinder.PathfinderManager).
+ *
+ * The graph's nodes are the permanents. Edges: walking through a building to
+ * the one above (0), below (1), left (2) or right (3), all costing 20, left
+ * and right only above the ground or across worlds; along a world's surface
+ * between its ground-level permanents (5, costing the distance); between hyper
+ * elevators of a column (13); between teleporters (7); and flying between
+ * landing sites of an air group (11). A search is Dijkstra's from where the
+ * citizen is to a goal: a permanent, any open entertainment of some types,
+ * or several permanents for citizens leaving the same building.
+ *
+ * Requests are answered at the end of the tick that made them, a few per
+ * tick, as the original's workers answer within frames. */
+#include "sim.h"
+#include "bld.h"
+#include "scratch.h"
+
+/* node types of the original (get_typeID) */
+enum { NT_NORMAL = 0, NT_TELEPORTER = 1, NT_LANDING = 2, NT_RESOURCE = 3, NT_ELEVATOR = 4 };
+
+/* the search's memory (scratch.h), shared with the PermanentFinder (assign.c), which never runs at the same time */
+#define prio (scratch->prio)
+#define prev (scratch->prev)
+#define in_edge (scratch->in_edge)
+#define seen (scratch->seen)
+#define heap (scratch->heap)
+#define heap_pos (scratch->heap_pos)
+int heap_n;
+static int8_t ent_bits[MAX_PERMS]; /* isEntertainmentPossibleWithType: -1 none, else 1 << type if open */
+static uint8_t lowest_tunnel[MAX_COLS]; /* worldFlyingLowestTunnel */
+
+static int node_type(const Perm *p) {
+ if (!is_building(p)) return NT_RESOURCE;
+ const PermClass *pc = PC(p);
+ if (pc->base & B_TELEPORTER) return NT_TELEPORTER;
+ if (pc->base & B_LANDINGSITE) return NT_LANDING;
+ if (pc->base & B_ELEVATOR) return NT_ELEVATOR;
+ return NT_NORMAL;
+}
+
+/* ---------------------------------------------------------------- the heap (a min priority queue) */
+void heap_up(int i) {
+ uint16_t v = heap[i];
+ while (i > 1 && prio[heap[i >> 1]] > prio[v]) {
+ heap[i] = heap[i >> 1];
+ heap_pos[heap[i]] = (uint16_t)i;
+ i >>= 1;
+ }
+ heap[i] = v;
+ heap_pos[v] = (uint16_t)i;
+}
+static void heap_down(int i) {
+ uint16_t v = heap[i];
+ for (;;) {
+ int c = i << 1;
+ if (c > heap_n) break;
+ if (c < heap_n && prio[heap[c + 1]] < prio[heap[c]]) c++;
+ if (prio[heap[c]] >= prio[v]) break;
+ heap[i] = heap[c];
+ heap_pos[heap[i]] = (uint16_t)i;
+ i = c;
+ }
+ heap[i] = v;
+ heap_pos[v] = (uint16_t)i;
+}
+void heap_push(uint16_t id) { heap[++heap_n] = id; heap_up(heap_n); }
+uint16_t heap_pop(void) {
+ uint16_t top = heap[1];
+ heap[1] = heap[heap_n--];
+ if (heap_n) heap_down(1);
+ return top;
+}
+
+uint16_t heap_index(uint16_t id) { return heap_pos[id]; }
+
+static void relax(uint16_t from, uint16_t to, uint8_t type, float cost) {
+ float np = prio[from] + cost;
+ if (seen[to] == 0) {
+ in_edge[to] = type, prev[to] = from, prio[to] = np;
+ heap_push(to);
+ seen[to] = 1;
+ } else if (seen[to] == 1 && np < prio[to]) {
+ in_edge[to] = type, prev[to] = from, prio[to] = np;
+ heap_up(heap_pos[to]);
+ }
+}
+
+/* ---------------------------------------------------------------- one search */
+typedef struct {
+ uint16_t cit;
+ uint8_t kind; /* RQ_* */
+ uint8_t on_fail;
+ uint16_t goal; /* permanent, or entertainment type bits */
+ int16_t max_distance;
+} Request;
+enum { RQ_PATH, RQ_COMBINED, RQ_ENTERTAINMENT };
+#define MAX_REQ 128
+static Request req[MAX_REQ];
+static int nreq;
+static int done_last_tick;
+
+/* the path to id, as (type, value) pairs into out (returns the number of steps) */
+static int backtrace(uint16_t id, bool from_outside, int16_t *out, int max) {
+ int len = 0;
+ for (uint16_t b = id; prev[b]; b = prev[b]) len++;
+ int total = len + (from_outside ? 1 : 0);
+ if (total > max) return -1;
+ int k = total;
+ uint16_t b = id;
+ while (prev[b]) {
+ k--;
+ out[2 * k] = in_edge[b], out[2 * k + 1] = (int16_t)b;
+ b = prev[b];
+ }
+ if (from_outside) out[0] = 5, out[1] = (int16_t)b;
+ return total;
+}
+
+static int handled_air[64];
+static uint16_t teleporters_found[64];
+static int nteleporters;
+
+/* Dijkstra's from a citizen's place; goal_type GOAL_PERM (goals[0]), entertainment (bits in goals[0]) or several permanents */
+static void search(const Cit *c, int goal_type, const uint16_t *goals, int ngoals, float max_distance,
+ void (*found)(int goal_index, uint16_t at, bool from_outside)) {
+ memset(seen, 0, sizeof seen);
+ memset(handled_air, 0, sizeof handled_air);
+ heap_n = 0;
+ bool outside = c->inPermanent == NONE;
+ uint16_t private_tp = (c->home && bld_has_private_teleporter(P(c->home))) ? c->home : NONE;
+ if (!outside) {
+ uint16_t s = c->inPermanent;
+ prev[s] = NONE;
+ in_edge[s] = 0;
+ prio[s] = 0;
+ heap_push(s);
+ seen[s] = 1;
+ } else {
+ World *w = &worlds[c->onWorld];
+ for (int x = 0; x < w->ncols; x++) {
+ uint16_t b = perm_at(c->onWorld, x, 0);
+ if (!b) continue;
+ prev[b] = NONE;
+ in_edge[b] = 5;
+ prio[b] = fabsf(20.0f * x - (int)c->relativeX);
+ heap_push(b);
+ seen[b] = 1;
+ }
+ }
+ bool handled_tp = !operating_cost.teleportersEnabled;
+ int remaining = ngoals;
+ while (heap_n) {
+ uint16_t cur = heap_pop();
+ Perm *p = &perms[cur];
+ bool reached = false;
+ if (goal_type == GOAL_PERM) {
+ reached = cur == goals[0];
+ } else if (goal_type == GOAL_ENTERTAINMENT) {
+ int g = (int16_t)goals[0];
+ reached = (g == -1 && ent_bits[cur] >= 0) || (g > 0 && ent_bits[cur] > 0 && (g & ent_bits[cur]) > 0);
+ } else {
+ for (int i = 0; i < ngoals; i++)
+ if (goals[i] == cur) {
+ found(i, cur, outside);
+ remaining--;
+ }
+ if (remaining <= 0) return;
+ }
+ if (reached) {
+ found(0, cur, outside);
+ return;
+ }
+ if (prio[cur] > max_distance) break;
+ seen[cur] = 2;
+ int nt = node_type(p);
+ if (nt != NT_RESOURCE) {
+ /* walking through: left and right above the ground (or across worlds), up and down */
+ bool lr_ok = !(p->flags & PF_NO_BUILD_ON_TOP);
+ if (lr_ok && p->left && (p->row > 0 || P(p->left)->world != p->world) && !(P(p->left)->flags & PF_NO_BUILD_ON_TOP))
+ relax(cur, p->left, 2, 20);
+ if (lr_ok && p->right && (p->row > 0 || P(p->right)->world != p->world) && !(P(p->right)->flags & PF_NO_BUILD_ON_TOP))
+ relax(cur, p->right, 3, 20);
+ if (!(p->flags & PF_ROOFTOP)) {
+ uint16_t up = perm_at(p->world, p->col, p->row + 1);
+ if (up) relax(cur, up, 0, 20);
+ }
+ if (p->row > 0) {
+ Perm *dn = P(perm_at(p->world, p->col, p->row - 1));
+ if (dn && is_building(dn) && !(dn->flags & PF_ROOFTOP)) relax(cur, pid(dn), 1, 20);
+ }
+ if (nt == NT_ELEVATOR) {
+ /* the next hyper elevators up and down the column, costing the buildings between */
+ int h = col_stack_height(p->world, p->col);
+ for (int dir = -1; dir <= 1; dir += 2) {
+ int dist = 0;
+ for (int y = p->row + dir; y >= 0 && y < h; y += dir) {
+ Perm *q = P(perm_at(p->world, p->col, y));
+ if (!q) break;
+ dist++;
+ if (node_type(q) == NT_ELEVATOR) {
+ relax(cur, pid(q), 13, (float)dist);
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (nt == NT_LANDING) {
+ int g = landing_group_of[cur] - 1;
+ if (g >= 0 && g < 64 && handled_air[g] < 5) {
+ float x = (float)perm_city_x(p), y = (float)worlds[p->world].y - p->row * 20.0f;
+ for (int j = 1; j < MAX_PERMS; j++) {
+ if (landing_group_of[j] != g + 1 || j == cur) continue;
+ Perm *q = &perms[j];
+ float add;
+ if (q->world == p->world) {
+ int maxy = 0;
+ int lo = p->col < q->col ? p->col : q->col, hi = p->col > q->col ? p->col : q->col;
+ for (int xx = lo; xx <= hi; xx++)
+ if (lowest_tunnel[worlds[p->world].col0 + xx] > maxy) maxy = lowest_tunnel[worlds[p->world].col0 + xx];
+ int a = abs((int)p->row - (int)q->row);
+ int b = (q->row > maxy ? q->row : maxy) - q->row + (p->row > maxy ? p->row : maxy) - p->row;
+ add = 10 + (fabsf((float)(q->col - p->col) * 20) + 20.0f * (a > b ? a : b)) / 3;
+ } else {
+ add = (fabsf(perm_city_x(q) - x) + fabsf(worlds[q->world].y - q->row * 20.0f - y)) / 1.5f;
+ }
+ relax(cur, (uint16_t)j, 11, add);
+ }
+ handled_air[g]++;
+ }
+ } else if (!handled_tp && (nt == NT_TELEPORTER || cur == private_tp)) {
+ float rand_offset = rnd_range(0, 2);
+ float inv = nteleporters ? 2.0f / nteleporters : 0;
+ for (int t = 0; t < nteleporters; t++) {
+ float cost = 10 + fmodf(rand_offset + t * inv, 2.0f);
+ relax(cur, teleporters_found[t], 7, cost);
+ }
+ if (cur != private_tp && private_tp) relax(cur, private_tp, 7, 10);
+ handled_tp = true;
+ }
+ if (p->row == 0 && in_edge[cur] != 5) {
+ /* along the surface to the world's other ground-level permanents */
+ World *w = &worlds[p->world];
+ for (int x = 0; x < w->ncols; x++) {
+ uint16_t b = perm_at(p->world, x, 0);
+ if (b && b != cur) relax(cur, b, 5, fabsf(20.0f * (x - p->col)));
+ }
+ }
+ }
+ /* not found */
+ if (goal_type == GOAL_PERM || goal_type == GOAL_ENTERTAINMENT) found(-1, NONE, outside);
+ else
+ for (int i = 0; i < ngoals; i++) found(-1 - i, NONE, outside);
+}
+
+/* ---------------------------------------------------------------- answering */
+static int16_t pairs[256];
+static const Cit *cur_cit;
+static uint16_t multi_cits[32];
+
+static void give_found(int goal_index, uint16_t at, bool from_outside) {
+ Cit *c = (Cit *)cur_cit;
+ if (goal_index < 0) {
+ cit_set_found_path(c, NULL, -1);
+ return;
+ }
+ int n = backtrace(at, from_outside, pairs, 128);
+ cit_set_found_path(c, pairs, n);
+}
+static void give_found_multi(int goal_index, uint16_t at, bool from_outside) {
+ if (goal_index < 0) {
+ Cit *c = &cits[multi_cits[-1 - goal_index]];
+ if ((c->flags & CF_ALIVE) && (c->flags & CF_REQUESTING_PATH)) cit_set_found_path(c, NULL, -1);
+ return;
+ }
+ Cit *c = &cits[multi_cits[goal_index]];
+ multi_cits[goal_index] = 0; /* answered */
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_REQUESTING_PATH)) return;
+ int n = backtrace(at, from_outside, pairs, 128);
+ cit_set_found_path(c, pairs, n);
+}
+
+static void refresh_graph_info(void) {
+ /* entertainment that is open, teleporters, and the lowest gap of each column (for flying) */
+ nteleporters = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ ent_bits[i] = -1;
+ if (!(p->flags & PF_USED)) continue;
+ if ((p->flags & PF_IS_ENTERTAINMENT) && ent_is_open(p)) ent_bits[i] = (int8_t)(1 << ent_type(p));
+ if (is_a(p, B_TELEPORTER) && nteleporters < 64) teleporters_found[nteleporters++] = (uint16_t)i;
+ }
+ for (int w = 0; w < nworlds; w++)
+ for (int x = 0; x < worlds[w].ncols; x++) {
+ int h = col_stack_height(w, x), lowest = h;
+ for (int y = 0; y < h; y++) {
+ Perm *q = P(perm_at(w, x, y));
+ if ((!q || node_type(q) == NT_LANDING) && y < lowest) lowest = y;
+ }
+ lowest_tunnel[worlds[w].col0 + x] = (uint8_t)(lowest > 255 ? 255 : lowest);
+ }
+}
+
+static int ent_refresh_in;
+void path_update(float timeMod) {
+ ent_refresh_in -= (int)timeMod;
+ if (ent_refresh_in <= 0) {
+ refresh_graph_info();
+ ent_refresh_in = 30;
+ }
+ /* answer requests, a few searches a tick (more on the faster N0120) */
+ int budget = plat_slow() ? 6 : 14;
+ int i = 0, done = 0;
+ while (i < nreq && budget > 0) {
+ Request r = req[i];
+ Cit *c = &cits[r.cit];
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_REQUESTING_PATH)) { i++; continue; }
+ if (r.kind == RQ_COMBINED && c->inPermanent) {
+ /* everyone leaving the same building, in one search */
+ uint16_t goals[32];
+ int n = 0;
+ for (int j = i; j < nreq && n < 32; j++) {
+ Cit *d = &cits[req[j].cit];
+ if (req[j].kind == RQ_COMBINED && (d->flags & CF_ALIVE) && (d->flags & CF_REQUESTING_PATH) &&
+ d->inPermanent == c->inPermanent) {
+ goals[n] = req[j].goal;
+ multi_cits[n] = req[j].cit;
+ req[j].kind = 0xFF; /* taken */
+ n++;
+ }
+ }
+ cur_cit = c;
+ search(c, 2, goals, n, 1000000.0f, give_found_multi);
+ done += n;
+ } else if (r.kind != 0xFF) {
+ cur_cit = c;
+ uint16_t g = r.goal;
+ if (r.kind == RQ_ENTERTAINMENT) search(c, GOAL_ENTERTAINMENT, &g, 1, r.max_distance, give_found);
+ else search(c, GOAL_PERM, &g, 1, 10000000.0f, give_found);
+ done++;
+ }
+ budget--;
+ i++;
+ }
+ /* drop the answered requests */
+ int k = 0;
+ for (int j = i; j < nreq; j++)
+ if (req[j].kind != 0xFF) req[k++] = req[j];
+ nreq = k;
+ done_last_tick = done;
+}
+
+void path_distribute(void) {}
+
+static void add_request(Cit *c, uint8_t kind, uint16_t goal, int max_distance, uint8_t on_fail) {
+ c->flags |= CF_REQUESTING_PATH;
+ c->onFail = on_fail;
+ if (nreq >= MAX_REQ) { /* full: the citizen asks again next tick */
+ c->flags &= (uint16_t)~CF_REQUESTING_PATH;
+ return;
+ }
+ req[nreq++] = (Request){cid(c), kind, on_fail, goal, (int16_t)(max_distance > 32767 ? 32767 : max_distance)};
+}
+
+void path_find(Cit *c, uint16_t goal, uint8_t on_fail) {
+ c->requestingPathGoal = goal;
+ add_request(c, RQ_PATH, goal, 10000000, on_fail);
+}
+void path_find_combined(Cit *c, uint16_t goal, uint8_t on_fail) {
+ c->requestingPathGoal = goal;
+ add_request(c, c->inPermanent ? RQ_COMBINED : RQ_PATH, goal, 10000000, on_fail);
+}
+void path_find_entertainment(Cit *c, int max_distance, int type_bit) {
+ c->requestingPathGoal = NONE;
+ add_request(c, RQ_ENTERTAINMENT, (uint16_t)(int16_t)type_bit, max_distance, THEN_NONE);
+}
+/* mayRequestPathNow: not too many requests waiting (or one joining a building's shared search) */
+bool path_may_request_now(uint16_t in_perm) {
+ if (in_perm)
+ for (int i = 0; i < nreq; i++)
+ if (req[i].kind == RQ_COMBINED && cits[req[i].cit].inPermanent == in_perm) return true;
+ return nreq < done_last_tick + 100 && nreq < MAX_REQ - 8;
+}
+void path_reset(void) {
+ nreq = 0;
+ done_last_tick = 0;
+ ent_refresh_in = 0;
+}
+void path_invalidate_all(void) {
+ for (int i = 0; i < nreq; i++) cits[req[i].cit].flags &= (uint16_t)~CF_REQUESTING_PATH;
+ nreq = 0;
+ ent_refresh_in = 0;
+}
diff --git a/games/finalearth2/src/pcls.h b/games/finalearth2/src/pcls.h
new file mode 100644
index 00000000..ad4c97cd
--- /dev/null
+++ b/games/finalearth2/src/pcls.h
@@ -0,0 +1,114 @@
+/* The Final Earth 2: classes of permanents (buildings and world resources).
+ *
+ * Each class has its data (buildinginfo.json) and what it does: the
+ * original's subclasses of Building become a PermClass with function
+ * pointers, NULL where the class does what its base does. */
+#ifndef FE_PCLS_H
+#define FE_PCLS_H
+#include "fe.h"
+#include "gfx.h"
+
+enum { KIND_RESOURCE, KIND_BUILDING };
+/* unlocks: unlocked at the start, has a hint while only unlocked (showUnlockHint), not unlocked by "unlock all" */
+enum { UF_DEFAULT = 1, UF_HINT = 2, UF_NOT_WITH_ALL = 4 };
+/* the original's base classes, as bits (a class can be several: WorkWithHome is a House and a Work) */
+enum {
+ B_HOUSE = 1, B_WORK = 2, B_ENTERTAINMENT = 4, B_SCHOOL = 8, B_MEDICAL = 16, B_TELEPORTER = 32,
+ B_LANDINGSITE = 64, B_ELEVATOR = 128, B_UNIQUE = 256, B_ROOFTOP = 512, B_NO_BUILD_ON_TOP = 1024,
+ B_BUILD_ON_GROUND = 2048, B_FOREST = 4096, B_ROCK = 8192, B_RUINS = 16384,
+ B_HIDE_WALKERS = 32768, /* get_walkThroughCanViewSelfInThisBuilding false */
+ B_CITY_TOP = 1 << 16, /* nothing may be above it */
+ B_NO_INSERT = 1 << 17 /* disableInsertReplaceOrBuildOnTop */
+};
+
+/* drawing layers, back to front (the original's stages, buildings.md 2.6): the citizens inside
+ * buildings are drawn between LAYER_BG and LAYER_MID, those outside after LAYER_MAIN */
+enum { LAYER_BG, LAYER_MID, LAYER_MAIN, LAYER_ABOVE, LAYER_FRONT, LAYER_COUNT };
+
+/* a building's window: what it shows (win.h) */
+typedef struct WinOut WinOut;
+
+struct PermClass;
+typedef struct {
+ void (*init)(Perm *p); /* the constructor's defaults */
+ void (*on_build)(Perm *p);
+ void (*destroy)(Perm *p);
+ void (*update)(Perm *p, float timeMod);
+ void (*work)(Perm *p, Cit *c, float timeMod, bool shouldStopWorking);
+ void (*walk_around)(Perm *p, Cit *c, float stepsInBuilding); /* homes */
+ void (*on_citizen_leave)(Perm *p, Cit *c, uint16_t to);
+ void (*after_give_job)(Perm *p, Cit *c);
+ float (*attractiveness)(const Perm *p); /* get_baseAttractiveness, NULL: the class's quality */
+ int (*jobs)(const Perm *p); /* NULL: the class's jobs */
+ int (*residents)(const Perm *p); /* NULL: the class's residents */
+ uint16_t (*first_building_to_go_to)(Perm *p); /* NULL: itself */
+ /* schools */
+ void (*be_at_school)(Perm *p, Cit *c, float timeMod);
+ int (*student_capacity)(const Perm *p);
+ /* entertainment (IEntertainmentBuilding): NULL uses the class's numbers */
+ bool (*is_open)(const Perm *p);
+ bool (*is_open_for_existing_visitors)(const Perm *p); /* NULL: is_open */
+ bool (*finish_entertainment)(Perm *p, Cit *c, float timeMod); /* NULL: true */
+ void (*be_entertained)(Perm *p, Cit *c, float timeMod);
+ float (*entertainment_capacity)(const Perm *p); /* get_baseEntertainmentCapacity (any permanent can give some) */
+ int (*entertainment_type)(const Perm *p);
+ int (*secondary_entertainment_types)(const Perm *p); /* bits */
+ float (*entertainment_quality)(const Perm *p); /* NULL: the class's */
+ /* medical buildings */
+ float (*medical_quality)(const Perm *p);
+ float (*medical_capacity)(const Perm *p);
+ float (*herb_capacity)(const Perm *p); /* HerbGarden.getHerbCapacity */
+ /* homes */
+ float (*years_to_live_longer)(const Perm *p);
+ bool (*has_private_teleporter)(const Perm *p);
+ int (*fixed_capacity_for_workers)(const Perm *p);
+ /* work hours that change (policies, upgrades, modes) */
+ float (*start_time)(const Perm *p);
+ float (*end_time)(const Perm *p);
+ /* drawing: one layer of it, its top-left at (x, y) on screen (scaled by the band's zoom) */
+ void (*draw)(const GfxBand *b, const Perm *p, int layer, int x, int y);
+ /* its window's own lines and buttons (addWindowInfoLines and friends), and a button's action */
+ void (*window)(Perm *p, WinOut *w);
+ void (*window_action)(Perm *p, int action);
+ /* after any build or destroy (onCityChange) */
+ void (*on_city_change)(Perm *p);
+} PermOps;
+
+typedef struct PermClass {
+ const char *name; /* the original's class name */
+ uint8_t kind;
+ uint32_t base; /* B_* */
+ uint8_t category;
+ float cost[M_COUNT]; /* to build (knowledge is the research price: see unlocks) */
+ uint8_t residents, jobs;
+ uint8_t quality; /* homes' quality; the attractiveness of others is 50 unless ops say */
+ float startTime, endTime; /* work hours (Work: 6 to 19) */
+ uint8_t doorX; /* 13 */
+ float workTimePreferenceMod; /* Work: 1 */
+ /* entertainment: type (0 night clubs, 1 pubs and restaurants, 2 art, 3 nature, 4 gaming, 5 libraries),
+ * hours spent (min, max), days it satisfies (min, max), quality */
+ int8_t entType;
+ float entMinTime, entMaxTime, entMinSatisfy, entMaxSatisfy;
+ uint8_t entQuality;
+ int8_t medicalTypeID; /* get_medicalTypeID */
+ float medicalTypeLimit; /* get_medicalTypeLimit */
+ float teleporterOperatingCost; /* knowledge a day */
+ uint16_t limitedTo, limitedPerCitizens; /* specialInfo limited: at most n, or one per n citizens */
+ uint8_t unlockFlags; /* UF_* */
+ int8_t parent; /* the parent class's index (is() checks), -1 none in the table */
+ uint16_t sprite; /* SPR_* */
+ const PermOps *ops;
+} PermClass;
+
+extern const PermClass pcls[];
+extern const int npcls;
+int pcls_find(const char *name); /* -1 if unknown */
+static inline const PermClass *PC(const Perm *p) { return &pcls[p->cls]; }
+static inline bool is_a(const Perm *p, uint32_t base) { return p && (pcls[p->cls].base & base); }
+/* the original's is(): this class or one of its ancestors */
+static inline bool class_is(int cls, int ancestor) {
+ for (int c = cls; c >= 0; c = pcls[c].parent)
+ if (c == ancestor) return true;
+ return false;
+}
+#endif
diff --git a/games/finalearth2/src/plat.h b/games/finalearth2/src/plat.h
new file mode 100644
index 00000000..288af2a9
--- /dev/null
+++ b/games/finalearth2/src/plat.h
@@ -0,0 +1,50 @@
+/* The Final Earth 2: the platform (the calculator, or a computer for tests).
+ *
+ * plat_eadk.c: the calculator's EADK display, keyboard, time and files.
+ * plat_host.c: a frame buffer that tests save as images, scripted keys and
+ * simulated time (tests/play.c). */
+#ifndef FE_PLAT_H
+#define FE_PLAT_H
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define SCREEN_W 320
+#define SCREEN_H 240
+
+/* keys held now, as bits */
+enum {
+ K_LEFT = 1 << 0, K_RIGHT = 1 << 1, K_UP = 1 << 2, K_DOWN = 1 << 3,
+ K_OK = 1 << 4, /* OK, EXE */
+ K_BACK = 1 << 5, /* Back */
+ K_HOME = 1 << 6, /* Home, On/Off */
+ K_TOOLBOX = 1 << 7, /* Toolbox: the build menu */
+ K_VAR = 1 << 8, /* var: the city's menus (population, happiness, research...) */
+ K_SHIFT = 1 << 9, /* shift: faster cursor */
+ K_ALPHA = 1 << 10, /* alpha: the speed (pause, 1x, 2x, 3x) */
+ K_PLUS = 1 << 11, K_MINUS = 1 << 12, /* zoom */
+ K_BACKSPACE = 1 << 13,
+ K_ANY = 1 << 14
+};
+uint32_t plat_keys(void);
+/* the keys that type (a city's name): the one held now, as its number on the NumWorks keyboard (TK_EXP to TK_ANS,
+ * row by row; Epsilon's eadk_key_t), -1 none. Some of them are also K_* keys above (4, 6, 8, 2, 5, + and -) */
+enum { TK_EXP = 18, TK_SQUARE = 29, TK_SEVEN = 30, TK_RPAREN = 34, TK_FOUR = 36, TK_FIVE = 37, TK_SIX = 38,
+ TK_DIVISION = 40, TK_ONE = 42, TK_TWO = 43, TK_PLUS = 45, TK_MINUS = 46, TK_ZERO = 48, TK_ANS = 51, TK_EIGHT = 31 };
+int plat_text_key(void);
+uint32_t plat_millis(void);
+void plat_sleep(uint32_t ms);
+void plat_push(int x, int y, int w, int h, const uint16_t *px);
+void plat_fill(int x, int y, int w, int h, uint16_t c);
+bool plat_save(const char *name, const void *data, uint32_t len);
+const uint8_t *plat_load(const char *name, uint32_t *len); /* NULL if absent */
+/* a file of len bytes to write in place (the calculator's storage is RAM): plat_reserve gives its
+ * bytes, plat_reserved says they are written; NULL if there is no room */
+uint8_t *plat_reserve(const char *name, uint32_t len);
+void plat_reserved(const char *name, uint32_t len);
+bool plat_remove(const char *name);
+void plat_begin(void);
+int plat_end(void);
+/* an N0110 or N0115 (216 MHz, the N0120 has 550) */
+bool plat_slow(void);
+#endif
diff --git a/games/finalearth2/src/plat_eadk.c b/games/finalearth2/src/plat_eadk.c
new file mode 100644
index 00000000..75b89768
--- /dev/null
+++ b/games/finalearth2/src/plat_eadk.c
@@ -0,0 +1,55 @@
+/* The calculator: EADK display, keyboard, time and files. */
+#include <eadk.h>
+#include "../../common/epsilon_app.h"
+#include "../../common/epsilon_files.h"
+#include "plat.h"
+
+#define KEY(k) ((uint64_t)1 << (k))
+
+uint32_t plat_keys(void) {
+ uint64_t k = eadk_keyboard_scan();
+ uint32_t r = 0;
+ if (k & (KEY(eadk_key_left) | KEY(eadk_key_four))) r |= K_LEFT;
+ if (k & (KEY(eadk_key_right) | KEY(eadk_key_six))) r |= K_RIGHT;
+ if (k & (KEY(eadk_key_up) | KEY(eadk_key_eight))) r |= K_UP;
+ if (k & (KEY(eadk_key_down) | KEY(eadk_key_two))) r |= K_DOWN;
+ if (k & (KEY(eadk_key_ok) | KEY(eadk_key_exe) | KEY(eadk_key_five))) r |= K_OK;
+ if (k & KEY(eadk_key_back)) r |= K_BACK;
+ if (k & (KEY(eadk_key_home) | KEY(eadk_key_on_off))) r |= K_HOME;
+ if (k & KEY(eadk_key_toolbox)) r |= K_TOOLBOX;
+ if (k & KEY(eadk_key_var)) r |= K_VAR;
+ if (k & KEY(eadk_key_shift)) r |= K_SHIFT;
+ if (k & KEY(eadk_key_alpha)) r |= K_ALPHA;
+ if (k & KEY(eadk_key_plus)) r |= K_PLUS;
+ if (k & KEY(eadk_key_minus)) r |= K_MINUS;
+ if (k & KEY(eadk_key_backspace)) r |= K_BACKSPACE;
+ if (k) r |= K_ANY;
+ return r;
+}
+
+int plat_text_key(void) {
+ uint64_t k = eadk_keyboard_scan();
+ for (int i = TK_EXP; i <= TK_ANS; i++)
+ if (k & KEY(i)) return i;
+ return -1;
+}
+
+uint32_t plat_millis(void) { return (uint32_t)eadk_timing_millis(); }
+void plat_sleep(uint32_t ms) { eadk_timing_msleep(ms); }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ eadk_display_push_rect((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, px);
+}
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ if (w > 0 && h > 0) eadk_display_push_rect_uniform((eadk_rect_t){(uint16_t)x, (uint16_t)y, (uint16_t)w, (uint16_t)h}, c);
+}
+bool plat_save(const char *name, const void *data, uint32_t len) { return ef_write(name, data, len); }
+const uint8_t *plat_load(const char *name, uint32_t *len) { return ef_read(name, len); }
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ uint32_t n;
+ return ef_write(name, NULL, len) ? (uint8_t *)(uintptr_t)ef_read(name, &n) : NULL; /* (the storage is RAM) */
+}
+void plat_reserved(const char *name, uint32_t len) { (void)name, (void)len; }
+bool plat_remove(const char *name) { return ef_remove(name); }
+void plat_begin(void) { np_app_begin(); }
+int plat_end(void) { return np_app_end(); }
+bool plat_slow(void) { return epsilon_slow_model(); }
diff --git a/games/finalearth2/src/plat_host.c b/games/finalearth2/src/plat_host.c
new file mode 100644
index 00000000..048ce25b
--- /dev/null
+++ b/games/finalearth2/src/plat_host.c
@@ -0,0 +1,75 @@
+/* A computer: the screen goes to a frame buffer that tests save as images,
+ * keys come from a script, time is simulated. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "plat.h"
+
+uint16_t host_fb[SCREEN_W * SCREEN_H];
+uint32_t host_time; /* ms */
+uint32_t host_keys;
+
+int host_text_key = -1; /* the typing key held (TK_*), -1 none */
+uint32_t plat_keys(void) { return host_keys; }
+int plat_text_key(void) { return host_text_key; }
+uint32_t plat_millis(void) { return host_time; }
+void plat_sleep(uint32_t ms) { host_time += ms; }
+void plat_push(int x, int y, int w, int h, const uint16_t *px) {
+ for (int r = 0; r < h; r++)
+ for (int c = 0; c < w; c++)
+ if ((unsigned)(x + c) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + c] = px[r * w + c];
+}
+void plat_fill(int x, int y, int w, int h, uint16_t c) {
+ for (int r = 0; r < h; r++)
+ for (int k = 0; k < w; k++)
+ if ((unsigned)(x + k) < SCREEN_W && (unsigned)(y + r) < SCREEN_H) host_fb[(y + r) * SCREEN_W + x + k] = c;
+}
+
+static char save_dir[256] = "build/host-saves";
+void host_save_dir(const char *d) { snprintf(save_dir, sizeof save_dir, "%s", d); }
+bool plat_save(const char *name, const void *data, uint32_t len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "wb");
+ if (!f) return false;
+ bool ok = fwrite(data, 1, len, f) == len;
+ fclose(f);
+ return ok;
+}
+static uint8_t loaded[1 << 17];
+const uint8_t *plat_load(const char *name, uint32_t *len) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ FILE *f = fopen(p, "rb");
+ if (!f) return NULL;
+ *len = (uint32_t)fread(loaded, 1, sizeof loaded, f);
+ fclose(f);
+ return loaded;
+}
+static uint8_t reserved[1 << 17];
+bool host_storage_full; /* tests: no room for any file */
+uint8_t *plat_reserve(const char *name, uint32_t len) {
+ (void)name;
+ return len <= sizeof reserved && !host_storage_full ? reserved : NULL;
+}
+void plat_reserved(const char *name, uint32_t len) { plat_save(name, reserved, len); }
+bool plat_remove(const char *name) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s", save_dir, name);
+ return remove(p) == 0;
+}
+void plat_begin(void) {}
+int plat_end(void) { return 0; }
+bool plat_slow(void) { return false; }
+
+/* writes the screen as a PPM image */
+void host_shot(const char *path) {
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fprintf(f, "P6\n%d %d\n255\n", SCREEN_W, SCREEN_H);
+ for (int i = 0; i < SCREEN_W * SCREEN_H; i++) {
+ uint16_t c = host_fb[i];
+ uint8_t rgb[3] = {(uint8_t)((c >> 11) * 255 / 31), (uint8_t)(((c >> 5) & 63) * 255 / 63), (uint8_t)((c & 31) * 255 / 31)};
+ fwrite(rgb, 1, 3, f);
+ }
+ fclose(f);
+}
diff --git a/games/finalearth2/src/save.c b/games/finalearth2/src/save.c
new file mode 100644
index 00000000..50a4bb85
--- /dev/null
+++ b/games/finalearth2/src/save.c
@@ -0,0 +1,397 @@
+/* The Final Earth 2: saving the city in the calculator's file system.
+ *
+ * The calculator keeps 42 KB of files for everything (Python scripts
+ * included), so the save is packed: the city is written as a stream of bytes
+ * cut into 4 KB chunks, each packed on its own (np_lz.h). It is written twice:
+ * once only to measure it, then into the file's room in the storage itself
+ * (the storage is RAM), so the stream never needs RAM of its own beyond a
+ * chunk. Paths in progress are not kept: citizens ask for new ones.
+ *
+ * The file: "FE2S", version, the stream's length and checksum, then each
+ * chunk as its packed length (2 bytes) and its packed bytes. */
+#include <stddef.h>
+#include "bld.h"
+#include "../../common/np_lz.h"
+#include "save.h"
+#include "scratch.h"
+#include "story.h"
+#include "unlocks.h"
+#include "view.h"
+
+SavedView saved_view;
+
+#define SAVE_NAME "finalearth2.sav"
+#define SAVE_MAGIC 0x53324546u /* "FE2S" */
+#define SAVE_VERSION 1
+#define CHUNK 4096
+
+/* ---------------------------------------------------------------- the stream */
+struct SaveIO {
+ uint8_t *out; /* where packed chunks go (NULL: only measuring) */
+ uint32_t outlen; /* packed bytes so far (after the header) */
+ uint32_t chunklen; /* bytes in the current chunk */
+ uint32_t total, crc; /* the stream's length and checksum */
+ /* reading */
+ const uint8_t *in;
+ uint32_t inlen, inpos, chunkpos;
+ bool error;
+};
+
+static uint32_t crc_step(uint32_t crc, uint8_t b) {
+ crc ^= b;
+ for (int k = 0; k < 8; k++) crc = crc >> 1 ^ (0xEDB88320u & (uint32_t)-(int32_t)(crc & 1));
+ return crc;
+}
+
+static void flush_chunk(SaveIO *io) {
+ if (!io->chunklen) return;
+ uint8_t *dst = io->out ? io->out + 16 + io->outlen + 2 : NULL;
+ uint32_t n = np_lz_pack(scratch->save.chunk, io->chunklen, dst, scratch->save.table);
+ if (io->out) {
+ io->out[16 + io->outlen] = (uint8_t)n;
+ io->out[16 + io->outlen + 1] = (uint8_t)(n >> 8);
+ }
+ io->outlen += 2 + n;
+ io->chunklen = 0;
+}
+void save_bytes(SaveIO *io, const void *data, uint32_t n) {
+ const uint8_t *p = data;
+ for (uint32_t i = 0; i < n; i++) {
+ io->crc = crc_step(io->crc, p[i]);
+ scratch->save.chunk[io->chunklen++] = p[i];
+ if (io->chunklen == CHUNK) flush_chunk(io);
+ }
+ io->total += n;
+}
+void save_u8(SaveIO *io, uint8_t v) { save_bytes(io, &v, 1); }
+void save_u16(SaveIO *io, uint16_t v) { save_bytes(io, &v, 2); }
+void save_u32(SaveIO *io, uint32_t v) { save_bytes(io, &v, 4); }
+void save_f32(SaveIO *io, float v) { save_bytes(io, &v, 4); }
+void save_f64(SaveIO *io, double v) { save_bytes(io, &v, 8); }
+
+/* the next byte of the stream, unpacking the next chunk when needed */
+static bool next_chunk(SaveIO *io) {
+ if (io->inpos + 2 > io->inlen) return false;
+ uint32_t n = io->in[io->inpos] | (uint32_t)io->in[io->inpos + 1] << 8;
+ io->inpos += 2;
+ if (io->inpos + n > io->inlen) return false;
+ int32_t got = np_lz_unpack(io->in + io->inpos, n, scratch->save.chunk, CHUNK);
+ io->inpos += n;
+ if (got <= 0) return false;
+ io->chunklen = (uint32_t)got;
+ io->chunkpos = 0;
+ return true;
+}
+bool load_bytes(SaveIO *io, void *data, uint32_t n) {
+ uint8_t *p = data;
+ for (uint32_t i = 0; i < n; i++) {
+ if (io->chunkpos >= io->chunklen && !next_chunk(io)) {
+ io->error = true;
+ return false;
+ }
+ p[i] = scratch->save.chunk[io->chunkpos++];
+ io->crc = crc_step(io->crc, p[i]);
+ io->total++;
+ }
+ return true;
+}
+uint8_t load_u8(SaveIO *io) { uint8_t v = 0; load_bytes(io, &v, 1); return v; }
+uint16_t load_u16(SaveIO *io) { uint16_t v = 0; load_bytes(io, &v, 2); return v; }
+uint32_t load_u32(SaveIO *io) { uint32_t v = 0; load_bytes(io, &v, 4); return v; }
+float load_f32(SaveIO *io) { float v = 0; load_bytes(io, &v, 4); return v; }
+double load_f64(SaveIO *io) { double v = 0; load_bytes(io, &v, 8); return v; }
+
+/* ---------------------------------------------------------------- the city */
+extern uint8_t col_deco[MAX_COLS];
+void game_reset(void);
+
+/* Permanents and citizens are written field by field: each field of all of them, then the next field (a
+ * byte of a 16-bit field at a time). Like values then sit together, and they pack about twice as small. Their
+ * ids come first, as steps from the one before. */
+#define EACH_PERM(i) for (int i = 1; i < MAX_PERMS; i++) if (perms[i].flags & PF_USED)
+#define EACH_CIT(i) for (int i = 1; i < MAX_CITS; i++) if (cits[i].flags & CF_ALIVE)
+#define PLANE8(each, i, v) each(i) save_u8(io, (uint8_t)(v))
+#define PLANE16(each, i, v) do { PLANE8(each, i, (uint16_t)(v)); PLANE8(each, i, (uint16_t)(v) >> 8); } while (0)
+#define LOAD8(list, n, k, dst) for (int k = 0; k < n; k++) dst = load_u8(io)
+#define LOAD16(list, n, k, dst) do { \
+ for (int k = 0; k < n; k++) dst = load_u8(io); \
+ for (int k = 0; k < n; k++) dst = (uint16_t)((uint16_t)(dst) | load_u8(io) << 8); \
+ } while (0)
+
+static void save_ids(SaveIO *io, int count, int max, bool (*used)(int)) {
+ save_u16(io, (uint16_t)count);
+ int last = 0;
+ for (int i = 1; i < max; i++)
+ if (used(i)) {
+ if (i - last < 255) save_u8(io, (uint8_t)(i - last));
+ else save_u8(io, 255), save_u16(io, (uint16_t)i);
+ last = i;
+ }
+}
+/* the ids, into list (increasing); their count, or -1 if they are not right */
+static int load_ids(SaveIO *io, uint16_t *list, int max) {
+ int n = load_u16(io), last = 0;
+ if (n >= max) return -1;
+ for (int k = 0; k < n; k++) {
+ int d = load_u8(io), id = d == 255 ? load_u16(io) : last + d;
+ if (id <= last || id >= max) return -1;
+ list[k] = (uint16_t)(last = id);
+ }
+ return io->error ? -1 : n;
+}
+static bool perm_used(int i) { return perms[i].flags & PF_USED; }
+static bool cit_alive(int i) { return cits[i].flags & CF_ALIVE; }
+
+/* the permanents: what they are, where, who is in them and their own state (their neighbours and groups are made
+ * again) */
+static void write_perms(SaveIO *io) {
+ save_ids(io, perm_count(), MAX_PERMS, perm_used);
+ PLANE8(EACH_PERM, i, perms[i].cls);
+ PLANE8(EACH_PERM, i, perms[i].world);
+ PLANE8(EACH_PERM, i, perms[i].col);
+ PLANE8(EACH_PERM, i, perms[i].row);
+ PLANE8(EACH_PERM, i, perms[i].flags);
+ PLANE8(EACH_PERM, i, perms[i].upgrades);
+ PLANE8(EACH_PERM, i, perms[i].mode);
+ PLANE8(EACH_PERM, i, perms[i].bonusAttractiveness);
+ PLANE16(EACH_PERM, i, perms[i].bonusEntertainmentCapacity);
+ PLANE8(EACH_PERM, i, perms[i].nworkers);
+ PLANE8(EACH_PERM, i, perms[i].nresidents);
+ PLANE8(EACH_PERM, i, perms[i].nstudents);
+ PLANE8(EACH_PERM, i, perms[i].nvisitors);
+ for (int b = 0; b < (int)sizeof perms[0].s; b++) PLANE8(EACH_PERM, i, perms[i].s[b]);
+}
+static bool read_perms(SaveIO *io) {
+ uint16_t list[MAX_PERMS];
+ int n = load_ids(io, list, MAX_PERMS);
+ if (n < 0) return false;
+ /* (read into the permanents' places, then each one restored from there) */
+ LOAD8(list, n, k, perms[list[k]].cls);
+ LOAD8(list, n, k, perms[list[k]].world);
+ LOAD8(list, n, k, perms[list[k]].col);
+ LOAD8(list, n, k, perms[list[k]].row);
+ LOAD8(list, n, k, perms[list[k]].flags);
+ LOAD8(list, n, k, perms[list[k]].upgrades);
+ LOAD8(list, n, k, perms[list[k]].mode);
+ LOAD8(list, n, k, perms[list[k]].bonusAttractiveness);
+ LOAD16(list, n, k, perms[list[k]].bonusEntertainmentCapacity);
+ LOAD8(list, n, k, perms[list[k]].nworkers);
+ LOAD8(list, n, k, perms[list[k]].nresidents);
+ LOAD8(list, n, k, perms[list[k]].nstudents);
+ LOAD8(list, n, k, perms[list[k]].nvisitors);
+ for (int b = 0; b < (int)sizeof perms[0].s; b++) LOAD8(list, n, k, perms[list[k]].s[b]);
+ if (io->error) return false;
+ for (int k = 0; k < n; k++) {
+ Perm p = perms[list[k]];
+ if (p.cls >= npcls || !(p.flags & PF_USED)) return false;
+ memset(&perms[list[k]], 0, sizeof p);
+ if (!perm_restore(list[k], &p)) return false;
+ }
+ return true;
+}
+
+/* the citizens: what they are, where they are and what they do; not their paths */
+static void write_cits(SaveIO *io) {
+ save_ids(io, ncits, MAX_CITS, cit_alive);
+ PLANE16(EACH_CIT, i, cits[i].inPermanent);
+ PLANE16(EACH_CIT, i, cits[i].home);
+ PLANE16(EACH_CIT, i, cits[i].job);
+ PLANE16(EACH_CIT, i, cits[i].school);
+ PLANE8(EACH_CIT, i, cits[i].onWorld);
+ PLANE16(EACH_CIT, i, (int16_t)(cits[i].relativeX * 8));
+ PLANE8(EACH_CIT, i, cits[i].relativeY < 0 ? 0 : cits[i].relativeY > 31 ? 31 : cits[i].relativeY);
+ /* the age in 4-minute steps */
+ #define AGE(c) ((city.timeSinceStart - (c).bornOn) / 4.0 > 65535 ? 65535 : (city.timeSinceStart - (c).bornOn) / 4.0)
+ PLANE16(EACH_CIT, i, AGE(cits[i]));
+ PLANE16(EACH_CIT, i, cits[i].educationLevel * 256 > 65535 ? 65535 : cits[i].educationLevel * 256);
+ PLANE16(EACH_CIT, i, cits[i].dieAgeModifier);
+ PLANE16(EACH_CIT, i, cits[i].nameIndex);
+ PLANE8(EACH_CIT, i, cits[i].spriteIndex);
+ PLANE8(EACH_CIT, i, cits[i].workTimePref);
+ PLANE16(EACH_CIT, i, cits[i].flags & (CF_LIKES_NIGHTCLUBS | CF_FORCED_HOME | CF_WITHOUT_JOB | CF_HAS_WORK_TOOLS | CF_CONTROLLED));
+ PLANE8(EACH_CIT, i, cits[i].currentAction);
+ PLANE8(EACH_CIT, i, cits[i].wantsNightEntertainmentIn);
+ PLANE8(EACH_CIT, i, cits[i].hobby);
+}
+static bool read_cits(SaveIO *io) {
+ uint16_t list[MAX_CITS], tmp[MAX_CITS];
+ int n = load_ids(io, list, MAX_CITS);
+ if (n < 0) return false;
+ for (int k = 0; k < n; k++) memset(&cits[list[k]], 0, sizeof cits[0]);
+ LOAD16(list, n, k, cits[list[k]].inPermanent);
+ LOAD16(list, n, k, cits[list[k]].home);
+ LOAD16(list, n, k, cits[list[k]].job);
+ LOAD16(list, n, k, cits[list[k]].school);
+ LOAD8(list, n, k, cits[list[k]].onWorld);
+ /* (16-bit values kept in other forms: read whole, then set) */
+ #define LOAD16_SET(set) do { \
+ LOAD16(list, n, k, tmp[k]); \
+ for (int k = 0; k < n; k++) { Cit *c = &cits[list[k]]; uint16_t v = tmp[k]; set; } \
+ } while (0)
+ LOAD16_SET(c->relativeX = (int16_t)v / 8.0f);
+ LOAD8(list, n, k, cits[list[k]].relativeY);
+ LOAD16_SET(c->bornOn = (float)(city.timeSinceStart - v * 4.0));
+ LOAD16_SET(c->educationLevel = v / 256.0f);
+ LOAD16_SET(c->dieAgeModifier = (int16_t)v);
+ LOAD16(list, n, k, cits[list[k]].nameIndex);
+ LOAD8(list, n, k, cits[list[k]].spriteIndex);
+ LOAD8(list, n, k, cits[list[k]].workTimePref);
+ LOAD16(list, n, k, cits[list[k]].flags);
+ LOAD8(list, n, k, cits[list[k]].currentAction);
+ LOAD8(list, n, k, cits[list[k]].wantsNightEntertainmentIn);
+ LOAD8(list, n, k, cits[list[k]].hobby);
+ if (io->error) return false;
+ for (int k = 0; k < n; k++) {
+ Cit *c = &cits[list[k]];
+ if (c->inPermanent >= MAX_PERMS || c->home >= MAX_PERMS || c->job >= MAX_PERMS || c->school >= MAX_PERMS ||
+ c->onWorld >= nworlds)
+ return false;
+ c->flags = (uint16_t)(c->flags | CF_ALIVE | CF_CAN_VIEW_SELF | CF_PATH_RECONSIDER);
+ c->currentPathAction = -2;
+ c->pathWalkSpeed = 100;
+ /* (a citizen who was being carried somewhere is let go where they are) */
+ c->flags &= (uint16_t)~CF_CONTROLLED;
+ if (c->currentAction == 3) c->currentAction = 2;
+ }
+ return true;
+}
+
+static void write_city(SaveIO *io) {
+ /* the story and the time */
+ save_u8(io, story.index);
+ save_bytes(io, &story, sizeof story);
+ save_f64(io, city.timeSinceStart);
+ save_bytes(io, &city, sizeof city);
+ save_bytes(io, &unlocks, sizeof unlocks);
+ save_bytes(io, &happiness, sizeof happiness);
+ save_bytes(io, &stats, sizeof stats);
+ save_bytes(io, &eating, sizeof eating);
+ save_bytes(io, &babies, sizeof babies);
+ save_bytes(io, &bonuses, sizeof bonuses);
+ save_bytes(io, &policies, sizeof policies);
+ save_bytes(io, &upgrades, sizeof upgrades);
+ save_bytes(io, &operating_cost, sizeof operating_cost);
+ extern int priority_jobs[64];
+ save_bytes(io, priority_jobs, sizeof(int) * 64);
+ /* the worlds and their columns */
+ save_u8(io, (uint8_t)nworlds);
+ for (int w = 0; w < nworlds; w++) {
+ save_bytes(io, &worlds[w], sizeof worlds[w]);
+ save_bytes(io, col_height + worlds[w].col0, worlds[w].ncols);
+ save_bytes(io, col_deco + worlds[w].col0, worlds[w].ncols);
+ }
+ write_perms(io);
+ write_cits(io);
+ bld_save(io);
+ boosts_save(io);
+ /* the view: viewPos and zoomScale (as the camera's top-left), and the cursor */
+ save_f32(io, camera.x), save_f32(io, camera.y);
+ save_u8(io, (uint8_t)camera.zoom);
+ save_u16(io, (uint16_t)saved_view.cx), save_u16(io, (uint16_t)saved_view.cy);
+ save_u32(io, 0x454E44u); /* "END" */
+}
+
+
+static bool read_city(SaveIO *io) {
+ int index = load_u8(io);
+ if (index >= nstories) return false;
+ game_reset();
+ load_bytes(io, &story, sizeof story);
+ /* (the running SpawnCitizensRegularly parts point into the story's data: their places are kept by index) */
+ city.timeSinceStart = load_f64(io);
+ load_bytes(io, &city, sizeof city);
+ city.cityName[CITY_NAME_MAX] = 0;
+ load_bytes(io, &unlocks, sizeof unlocks);
+ load_bytes(io, &happiness, sizeof happiness);
+ load_bytes(io, &stats, sizeof stats);
+ load_bytes(io, &eating, sizeof eating);
+ load_bytes(io, &babies, sizeof babies);
+ load_bytes(io, &bonuses, sizeof bonuses);
+ load_bytes(io, &policies, sizeof policies);
+ load_bytes(io, &upgrades, sizeof upgrades);
+ load_bytes(io, &operating_cost, sizeof operating_cost);
+ extern int priority_jobs[64];
+ load_bytes(io, priority_jobs, sizeof(int) * 64);
+ int nw = load_u8(io);
+ if (nw > MAX_WORLDS) return false;
+ for (int w = 0; w < nw; w++) {
+ World wd;
+ load_bytes(io, &wd, sizeof wd);
+ int id = world_add(wd.x, wd.y, wd.w, wd.h, wd.seed, wd.appearance);
+ if (id != w) return false;
+ worlds[w].flags = wd.flags;
+ worlds[w].id = wd.id;
+ load_bytes(io, col_height + worlds[w].col0, worlds[w].ncols);
+ load_bytes(io, col_deco + worlds[w].col0, worlds[w].ncols);
+ }
+ if (!read_perms(io) || !read_cits(io)) return false;
+ cits_recount();
+ if (!bld_load(io)) return false;
+ saved_view.valid = false;
+ if (!boosts_load(io)) return false;
+ saved_view.x = load_f32(io), saved_view.y = load_f32(io);
+ saved_view.zoom = load_u8(io);
+ saved_view.cx = (int16_t)load_u16(io), saved_view.cy = (int16_t)load_u16(io);
+ saved_view.valid = saved_view.zoom == 1 || saved_view.zoom == 2;
+ return load_u32(io) == 0x454E44u && !io->error;
+}
+
+/* ---------------------------------------------------------------- the file */
+bool save_game(void) {
+ SaveIO io = {0};
+ write_city(&io);
+ flush_chunk(&io);
+ uint32_t size = 16 + io.outlen;
+ uint8_t *dst = plat_reserve(SAVE_NAME, size);
+ if (!dst) { /* the copy gives way to the save */
+ save_copy_drop();
+ dst = plat_reserve(SAVE_NAME, size);
+ if (!dst) return false;
+ }
+ uint32_t total = io.total, crc = io.crc;
+ memset(&io, 0, sizeof io);
+ io.out = dst;
+ write_city(&io);
+ flush_chunk(&io);
+ if (io.total != total || io.crc != crc || 16 + io.outlen != size) return false;
+ uint32_t head[4] = {SAVE_MAGIC, SAVE_VERSION, total, crc};
+ memcpy(dst, head, 16);
+ plat_reserved(SAVE_NAME, size);
+ save_copy();
+ return true;
+}
+
+bool save_exists(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(SAVE_NAME, &len);
+ uint32_t head[4];
+ if (!d || len < 16) return false;
+ memcpy(head, d, 16);
+ return head[0] == SAVE_MAGIC && head[1] == SAVE_VERSION;
+}
+
+bool load_game(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(SAVE_NAME, &len);
+ uint32_t head[4];
+ if (!d || len < 16) return false;
+ memcpy(head, d, 16);
+ if (head[0] != SAVE_MAGIC || head[1] != SAVE_VERSION) return false;
+ SaveIO io = {0};
+ io.in = d + 16;
+ io.inlen = len - 16;
+ bool ok = read_city(&io) && io.total == head[2] && io.crc == head[3];
+ if (!ok) {
+ saved_view.valid = false;
+ game_reset();
+ return false;
+ }
+ city_update_connections();
+ sim_update_pathfinder(true, NONE);
+ return true;
+}
+
+void save_delete(void) {
+ plat_remove(SAVE_NAME);
+ save_copy();
+}
diff --git a/games/finalearth2/src/save.h b/games/finalearth2/src/save.h
new file mode 100644
index 00000000..932c6c03
--- /dev/null
+++ b/games/finalearth2/src/save.h
@@ -0,0 +1,45 @@
+/* The Final Earth 2: saves (save.c). */
+#ifndef FE_SAVE_H
+#define FE_SAVE_H
+#include "fe.h"
+
+typedef struct SaveIO SaveIO;
+/* writing (in the order they will be read) */
+void save_bytes(SaveIO *io, const void *data, uint32_t n);
+void save_u8(SaveIO *io, uint8_t v);
+void save_u16(SaveIO *io, uint16_t v);
+void save_u32(SaveIO *io, uint32_t v);
+void save_f32(SaveIO *io, float v);
+void save_f64(SaveIO *io, double v);
+/* reading */
+bool load_bytes(SaveIO *io, void *data, uint32_t n);
+uint8_t load_u8(SaveIO *io);
+uint16_t load_u16(SaveIO *io);
+uint32_t load_u32(SaveIO *io);
+float load_f32(SaveIO *io);
+double load_f64(SaveIO *io);
+
+bool save_game(void);
+bool save_exists(void);
+bool load_game(void);
+void save_delete(void);
+/* the copy of the saves in a Python script (savecopy.c): written after each save, read back at start when the
+ * files are gone */
+void save_copy(void);
+void save_copy_drop(void);
+void save_restore(void);
+
+/* the buildings' own state outside their permanents (bld*.c, upgrades.c): saved after everything */
+void bld_save(SaveIO *io);
+bool bld_load(SaveIO *io);
+/* the view kept with the city (City's viewPos and zoomScale, and the keypad's cursor): the user interface sets
+ * the cursor before a save; a load sets it all and valid, until the city's view is set from it */
+typedef struct { float x, y; int16_t cx, cy; uint8_t zoom; bool valid; } SavedView;
+extern SavedView saved_view;
+/* systems.c: the happiness boosts running */
+void boosts_save(SaveIO *io);
+bool boosts_load(SaveIO *io);
+/* city.c, citizen.c */
+bool perm_restore(uint16_t id, const Perm *p);
+void cits_recount(void);
+#endif
diff --git a/games/finalearth2/src/savecopy.c b/games/finalearth2/src/savecopy.c
new file mode 100644
index 00000000..8d79ce12
--- /dev/null
+++ b/games/finalearth2/src/savecopy.c
@@ -0,0 +1,107 @@
+/* The Final Earth 2: a copy of the saves in a Python script. Installing apps
+ * from the NumWorks website keeps only Python scripts, so the city and the
+ * scenarios won are also kept in one, each as a comment line
+ * "#>name:base64" (the way NumPlay and its big games keep theirs), and come
+ * back from it when the files themselves are gone. The copy gives way to the
+ * save: when the storage is too full for both, there is no copy. */
+#include <string.h>
+#include "plat.h"
+#include "save.h"
+
+#define COPY_NAME "finalearth2_saves.py"
+static const char *const kept[] = {"finalearth2.sav", "fe2meta.dat"};
+#define NKEPT (int)(sizeof kept / sizeof kept[0])
+static const char copy_head[] =
+ "# The Final Earth 2 keeps a copy of your city here, so that\n"
+ "# reinstalling it doesn't erase it. If you delete this file,\n"
+ "# the game writes it again: your city stays either way.\n";
+static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+void save_copy_drop(void) { plat_remove(COPY_NAME); }
+
+void save_copy(void) {
+ /* (its size first, then written in place: the files read again, as writing it may have moved them) */
+ uint32_t total = 1 + (sizeof copy_head - 1) + 1, len;
+ int n = 0;
+ for (int k = 0; k < NKEPT; k++)
+ if (plat_load(kept[k], &len) && len) total += 2 + (uint32_t)strlen(kept[k]) + 1 + (len + 2) / 3 * 4 + 1, n++;
+ if (!n) {
+ save_copy_drop();
+ return;
+ }
+ save_copy_drop(); /* (the old copy's room counts for the new one) */
+ uint8_t *o = plat_reserve(COPY_NAME, total), *p = o;
+ if (!o) return;
+ *p++ = 0; /* (the script's status byte: not imported) */
+ memcpy(p, copy_head, sizeof copy_head - 1), p += sizeof copy_head - 1;
+ for (int k = 0; k < NKEPT; k++) {
+ const uint8_t *d = plat_load(kept[k], &len);
+ if (!d || !len) continue;
+ uint32_t nl = (uint32_t)strlen(kept[k]);
+ *p++ = '#', *p++ = '>';
+ memcpy(p, kept[k], nl), p += nl;
+ *p++ = ':';
+ for (uint32_t i = 0; i < len; i += 3, p += 4) {
+ /* (written out: GCC 15.2 for the calculator got a loop over the four wrong, see NumPlay's
+ * launcher/src/storage.c) */
+ uint32_t left = len - i, v = (uint32_t)d[i] << 16 | (left > 1 ? d[i + 1] << 8 : 0) | (left > 2 ? d[i + 2] : 0);
+ p[0] = (uint8_t)b64[v >> 18 & 63];
+ p[1] = (uint8_t)b64[v >> 12 & 63];
+ p[2] = left > 1 ? (uint8_t)b64[v >> 6 & 63] : '=';
+ p[3] = left > 2 ? (uint8_t)b64[v & 63] : '=';
+ }
+ *p++ = '\n';
+ }
+ *p++ = 0;
+ plat_reserved(COPY_NAME, (uint32_t)(p - o));
+}
+
+static int b64_value(uint8_t c) {
+ for (int i = 0; i < 64; i++)
+ if ((uint8_t)b64[i] == c) return i;
+ return -1;
+}
+
+/* where kept[k]'s line starts in the copy (just after its tag) and its length, or NULL */
+static const uint8_t *copy_line(int k, uint32_t *len) {
+ uint32_t n, nl = (uint32_t)strlen(kept[k]);
+ const uint8_t *c = plat_load(COPY_NAME, &n);
+ if (!c) return NULL;
+ for (uint32_t i = 0; i + nl + 3 <= n; i++)
+ if (c[i] == '#' && c[i + 1] == '>' && !memcmp(c + i + 2, kept[k], nl) && c[i + 2 + nl] == ':') {
+ const uint8_t *l = c + i + 3 + nl;
+ uint32_t m = 0;
+ while (l + m < c + n && l[m] != '\n' && l[m]) m++;
+ *len = m;
+ return l;
+ }
+ return NULL;
+}
+
+/* the files from the copy, those gone (after the app was installed again); a broken one is dropped */
+void save_restore(void) {
+ for (int k = 0; k < NKEPT; k++) {
+ uint32_t have, len;
+ if (plat_load(kept[k], &have)) continue;
+ const uint8_t *l = copy_line(k, &len);
+ if (!l || !len || len % 4) continue;
+ uint32_t size = len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=');
+ /* decoded straight into the file's room, then the copy read again (making the file may have moved it) */
+ uint8_t *out = plat_reserve(kept[k], size);
+ if (!out) continue;
+ l = copy_line(k, &len);
+ bool ok = l != NULL && len / 4 * 3 - (l[len - 1] == '=') - (l[len - 2] == '=') == size;
+ uint32_t o = 0;
+ for (uint32_t i = 0; ok && i < len; i += 4) {
+ int v0 = l[i] == '=' ? 0 : b64_value(l[i]), v1 = l[i + 1] == '=' ? 0 : b64_value(l[i + 1]);
+ int v2 = l[i + 2] == '=' ? 0 : b64_value(l[i + 2]), v3 = l[i + 3] == '=' ? 0 : b64_value(l[i + 3]);
+ if (v0 < 0 || v1 < 0 || v2 < 0 || v3 < 0) ok = false;
+ uint32_t w = (uint32_t)(v0 << 18 | v1 << 12 | v2 << 6 | v3);
+ if (o < size) out[o++] = (uint8_t)(w >> 16);
+ if (o < size) out[o++] = (uint8_t)(w >> 8);
+ if (o < size) out[o++] = (uint8_t)w;
+ }
+ if (ok && o == size) plat_reserved(kept[k], size);
+ else plat_remove(kept[k]);
+ }
+}
diff --git a/games/finalearth2/src/scratch.h b/games/finalearth2/src/scratch.h
new file mode 100644
index 00000000..982df853
--- /dev/null
+++ b/games/finalearth2/src/scratch.h
@@ -0,0 +1,35 @@
+/* The Final Earth 2: memory that is only needed while a search or a pass
+ * runs. It lives on main()'s stack (a region of its own on the calculator,
+ * not counted in the app's RAM), and the passes that use it never overlap. */
+#ifndef FE_SCRATCH_H
+#define FE_SCRATCH_H
+#include "fe.h"
+
+typedef union {
+ struct {
+ /* the searches (path.c's pathfinder, assign.c's PermanentFinder) */
+ float prio[MAX_PERMS];
+ uint16_t prev[MAX_PERMS];
+ uint8_t in_edge[MAX_PERMS];
+ uint8_t seen[MAX_PERMS];
+ uint16_t heap[MAX_PERMS + 1], heap_pos[MAX_PERMS];
+ uint8_t no_elevators[MAX_PERMS];
+ /* passes over the city (city.c's shards, assign.c's assigners) */
+ union {
+ struct { uint16_t stack[MAX_PERMS]; uint8_t seen[MAX_PERMS]; uint8_t handled_ls[MAX_PERMS]; } flood;
+ struct { uint16_t list[MAX_PERMS]; uint8_t movable[MAX_PERMS]; uint8_t impossible[MAX_SHARDS];
+ int16_t tp_left[MAX_SHARDS]; uint8_t shard_no_options[MAX_SHARDS]; int16_t short_by[256]; } assign;
+ struct { uint16_t list[MAX_PERMS]; } happy;
+ struct { uint16_t order[MAX_CITS]; } compact;
+ /* the flying pathfinder's waypoints (bld_transport.c): each one's y, column and free segment */
+ struct { int16_t y[MAX_PERMS]; uint8_t col[MAX_PERMS]; uint8_t seg[MAX_PERMS]; uint16_t colstart[257]; } fly;
+ } u;
+ };
+ /* saving and loading (save.c), when nothing else runs: a chunk of the save and the packer's table */
+ struct { uint8_t chunk[4096]; uint16_t table[4096]; } save;
+ /* the band being drawn (gfx.c), only during gfx_end: no search or pass may run while the city is drawn */
+ uint16_t band[320 * 16];
+} Scratch;
+
+extern Scratch *scratch;
+#endif
diff --git a/games/finalearth2/src/sim.c b/games/finalearth2/src/sim.c
new file mode 100644
index 00000000..6b688c90
--- /dev/null
+++ b/games/finalearth2/src/sim.c
@@ -0,0 +1,127 @@
+/* The Final Earth 2: the simulation's step (CitySimulation, CityTime and
+ * the parts of City.update that run it).
+ *
+ * The original updates once a frame at 60 frames a second, its timeMod (1)
+ * times 2/3 of the game speed, in as many steps as the speed needs. The
+ * calculator draws 30 frames a second, so each tick does two frames' worth of
+ * steps: the same steps, with the same timeMods, as the original. */
+#include "bld.h"
+#include "scratch.h"
+
+Scratch *scratch; /* set by main() to memory on its stack */
+
+uint8_t sim_flags = SIM_JOBS_CHANGED | SIM_HOUSES_CHANGED | SIM_SCHOOLS_CHANGED;
+static float infrequent_start;
+
+void sim_update_pathfinder(bool invalidate, uint16_t related_to) {
+ bld_city_changed(invalidate);
+ finder_invalidate();
+ if (!invalidate) return;
+ path_invalidate_all();
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || !(c->flags & CF_HAS_PATH)) continue;
+ if (!c->pathOnlyRelatedTo || !related_to || related_to == c->pathOnlyRelatedTo) cit_reset_path(c, false);
+ }
+}
+
+void cits_reset(void);
+void path_reset(void);
+void systems_reset(void);
+/* a fresh game: every part's state as at the start */
+void game_reset(void) {
+ city_reset();
+ cits_reset();
+ path_reset();
+ systems_reset();
+ finder_invalidate();
+ sim_flags = SIM_JOBS_CHANGED | SIM_HOUSES_CHANGED | SIM_SCHOOLS_CHANGED;
+ infrequent_start = 0;
+ bld_new_city();
+}
+
+/* CityTime.update: the clock (nights at the story's start go faster) */
+static void time_update(float timeMod) {
+ city.timeSinceStart += timeMod * city.minutesPerTick;
+ float h = city_hour();
+ if ((h > 23 || h < 4) && city.speedUpStartNights) {
+ int day = city_day();
+ if (day == 1 || day == 2 || (day == 3 && h < 4)) city.timeSinceStart += timeMod * city.minutesPerTick * 2.75f;
+ else if (day == 3) city.timeSinceStart += timeMod * city.minutesPerTick;
+ else if (day == 4) city.timeSinceStart += timeMod * city.minutesPerTick * 0.5f;
+ }
+}
+
+/* CitySimulation.update */
+static void sim_update(float timeMod) {
+ int prev_hour = ((int)city.timeSinceStart / 60) % 24;
+ time_update(timeMod);
+ int hour = ((int)city.timeSinceStart / 60) % 24;
+ if (prev_hour >= 23 && hour < 1) stats_midnight_update();
+ stats_update(timeMod);
+ finder_pre_update();
+ path_distribute();
+ flying_update(timeMod);
+ spawners_update(timeMod);
+ if (ncits > 0) {
+ /* CitizenUpdater */
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || (c->flags & CF_CONTROLLED)) continue;
+ if (festival_running()) {
+ festival_citizen(c, timeMod);
+ continue;
+ }
+ if (c->flags & CF_DELAY_CAN_VIEW_SELF) c->flags &= (uint16_t)~CF_DELAY_CAN_VIEW_SELF;
+ cit_update_path(c, timeMod);
+ if ((c->flags & CF_ALIVE) && !(c->flags & CF_HAS_PATH) && !(c->flags & CF_REQUESTING_PATH)) cit_update_daily_life(c, timeMod);
+ }
+ if (prev_hour < 12 && hour >= 12)
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) cit_mid_day_update(&cits[i]);
+ /* infrequent updates: a 60th of the citizens each step (in the order of the original's list: from the top) */
+ float per = ncits / 60.0f;
+ int lo = (int)ceilf(infrequent_start), hi = (int)ceilf(infrequent_start + per);
+ if (hi > ncits) hi = ncits;
+ int k = 0;
+ for (int i = 1; i < MAX_CITS && k < hi; i++) {
+ if (!(cits[i].flags & CF_ALIVE)) continue;
+ if (k >= lo) cit_infrequent_update(&cits[i]);
+ k++;
+ }
+ infrequent_start += per;
+ if (infrequent_start >= ncits) infrequent_start = 0;
+ }
+ animals_update(timeMod);
+ baby_update(timeMod);
+ path_update(timeMod);
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && PC(p)->ops && PC(p)->ops->update) PC(p)->ops->update(p, timeMod);
+ }
+ building_upgrades_update(timeMod);
+ boosts_update(timeMod);
+ operating_cost_update(timeMod);
+}
+
+/* CitySimulation.lateUpdate */
+static void sim_late_update(float timeMod) {
+ assign_jobs();
+ assign_schools();
+ assign_houses();
+ happiness_update(timeMod);
+ eating_update(timeMod);
+}
+
+/* a 30th of a second: two of the original's frames */
+void sim_tick(float frameTimeMod) {
+ float used = city.paused ? 0 : city.simulationSpeed * 0.6666667f;
+ for (int f = 0; f < 2; f++) {
+ worlds_update(frameTimeMod * used);
+ int steps = (int)ceilf(used / 1.67f);
+ for (int s = 0; s < steps; s++) sim_update(frameTimeMod * (used / steps));
+ if (steps == 0) stats_update(0);
+ progress_update(frameTimeMod);
+ sim_late_update(frameTimeMod * used);
+ }
+}
diff --git a/games/finalearth2/src/sim.h b/games/finalearth2/src/sim.h
new file mode 100644
index 00000000..5618f4b2
--- /dev/null
+++ b/games/finalearth2/src/sim.h
@@ -0,0 +1,120 @@
+/* The Final Earth 2: what the parts of the simulation call in each other. */
+#ifndef FE_SIM_H
+#define FE_SIM_H
+#include "fe.h"
+#include "pcls.h"
+
+#define PF_USED 128 /* a permanent's slot is in use */
+
+/* city.c */
+extern uint8_t col_deco[MAX_COLS];
+extern uint8_t landing_group_of[MAX_PERMS];
+extern int nlanding_groups;
+extern int direct_world_connections;
+void rnd_seed(uint32_t s);
+int world_add(int x, int y, int w, int h, uint32_t seed, uint8_t appearance);
+uint16_t perm_new(int cls, int w, int col, int row);
+void perm_destroy(uint16_t id, bool for_replacement);
+int perm_count(void);
+int col_stack_height(int w, int col);
+void city_update_connections(void);
+void city_reset(void);
+
+/* sim.c: CitySimulation */
+enum { SIM_JOBS_CHANGED = 1, SIM_HOUSES_CHANGED = 2, SIM_SCHOOLS_CHANGED = 4 };
+extern uint8_t sim_flags;
+void sim_update_pathfinder(bool invalidate, uint16_t related_to);
+void sim_tick(float timeMod);
+uint16_t cit_create(int world, float age, uint16_t start_in, int start_x); /* createCitizen; start_x < 0: random */
+
+/* systems.c: the city-wide systems */
+void stats_update(float timeMod);
+void stats_midnight_update(void);
+void flying_update(float timeMod);
+void spawners_update(float timeMod);
+void animals_update(float timeMod);
+void baby_update(float timeMod);
+void building_upgrades_update(float timeMod);
+void boosts_update(float timeMod);
+void operating_cost_update(float timeMod);
+void worlds_update(float timeMod);
+void progress_update(float timeMod);
+void happiness_update(float timeMod);
+void eating_update(float timeMod);
+
+/* citizen.c */
+void cit_update_path(Cit *c, float timeMod);
+void cit_update_daily_life(Cit *c, float timeMod);
+void cit_infrequent_update(Cit *c);
+void cit_mid_day_update(Cit *c);
+void cit_reset_path(Cit *c, bool reset_can_view_self);
+void cit_try_remove(Cit *c, bool for_send_away);
+void cit_lose_job(Cit *c, bool instant_replace);
+void cit_evict_from_home(Cit *c);
+void cit_leave_school(Cit *c);
+void cit_add_to_workers(Cit *c);
+float cit_age(const Cit *c);
+float cit_education_speed_modifier(const Cit *c);
+float cit_steps_in_building(const Cit *c);
+float cit_work_time_preference(const Cit *c);
+bool cit_should_work_now(const Cit *c);
+bool cit_should_school_now(const Cit *c);
+void cit_go_to_permanent(Cit *c, uint16_t perm);
+void cit_instant_leave_permanent(Cit *c);
+bool cit_leave_permanent(Cit *c, float timeMod); /* leavePermanent: true once outside */
+bool cit_move_towards_x(Cit *c, float x, float timeMod);
+void cit_city_position(const Cit *c, float *x, float *y);
+void cits_leave_destroyed(uint16_t perm);
+void cits_lose_job_at(uint16_t perm);
+void cits_evict_from(uint16_t perm);
+void cits_leave_school(uint16_t perm);
+
+/* scripted steps (paths of their own): what to do at their end */
+enum { THEN_NONE, THEN_COUNT_ = 160 };
+/* a function for the end of a scripted path (the original's closures), registered once at start: its number */
+uint8_t then_register(void (*fn)(Cit *c, uint16_t arg));
+typedef void (*ThenFn)(Cit *c, uint16_t arg);
+extern ThenFn then_fns[THEN_COUNT_];
+#define CIT_SCRIPTED_MAX 128 /* steps of a scripted path at most */
+void cit_set_path(Cit *c, const int16_t *steps, int n); /* setPath with a scripted path (copied) */
+void cit_set_path_then(Cit *c, const int16_t *steps, int n, uint8_t then, uint16_t arg);
+void cit_wait(Cit *c, int time, uint8_t then, uint16_t arg);
+void cit_wait_random(Cit *c, int tmin, int tmax, uint8_t then, uint16_t arg);
+void cit_move(Cit *c, int x, uint8_t then, uint16_t arg, bool slow);
+void cit_move_random(Cit *c, int xmin, int xmax, uint8_t then, uint16_t arg, bool slow);
+void cit_move_and_wait(Cit *c, int x, int time, uint8_t then, uint16_t arg, bool modify_with_happiness, bool slow);
+void cit_move_and_wait_random(Cit *c, int xmin, int xmax, int tmin, int tmax, uint8_t then, uint16_t arg,
+ bool modify_with_happiness, bool slow);
+void cit_wait_and_move_and_wait_random(Cit *c, int t1min, int t1max, int xmin, int xmax, int tmin, int tmax,
+ uint8_t then, uint16_t arg, bool modify_with_happiness, bool slow);
+void cit_move_towards_random_in_world_coords(Cit *c, int xmin, int xmax, uint8_t then, uint16_t arg);
+void cit_change_floor(Cit *c, uint8_t then, uint16_t arg);
+void cit_change_floor_and_wait(Cit *c, int wait, uint8_t then, uint16_t arg);
+void cit_change_floor_and_wait_random(Cit *c, int tmin, int tmax, uint8_t then, uint16_t arg);
+void cit_change_floor_and_move_random(Cit *c, int xmin, int xmax, uint8_t then, uint16_t arg);
+bool cit_is_at_ground_level(const Cit *c);
+void cit_wander(Cit *c, float timeMod);
+void cit_go_down_towards_world_surface(Cit *c, float timeMod);
+
+/* path.c: the pathfinder (pathfinder.js and pathfinder.PathfinderManager) */
+enum { GOAL_PERM, GOAL_ENTERTAINMENT };
+void path_find(Cit *c, uint16_t goal, uint8_t on_fail); /* findPath */
+void path_find_combined(Cit *c, uint16_t goal, uint8_t on_fail); /* findPathCombined */
+void path_find_entertainment(Cit *c, int max_distance, int type_bit); /* findPathEntertainment */
+bool path_may_request_now(uint16_t in_perm);
+void path_invalidate_all(void);
+void path_update(float timeMod); /* answers the requests of the tick */
+void path_distribute(void);
+uint16_t flying_find_any_other_landing_site(uint16_t ls);
+/* the search memory (path.c), also used by the PermanentFinder */
+extern int heap_n;
+void heap_up(int i);
+void heap_push(uint16_t id);
+uint16_t heap_pop(void);
+uint16_t heap_index(uint16_t id);
+void cit_set_found_path(Cit *c, const int16_t *pairs, int n);
+uint16_t *cit_steps(const Cit *c);
+uint16_t cit_new(int world, float x, float age, uint16_t start_in);
+/* the path pool: each citizen's path is a list of (step, value) pairs */
+void game_reset(void); /* an empty city, every system back to its start (before a new city or a load) */
+#endif
diff --git a/games/finalearth2/src/stories_data.c b/games/finalearth2/src/stories_data.c
new file mode 100644
index 00000000..cce1f242
--- /dev/null
+++ b/games/finalearth2/src/stories_data.c
@@ -0,0 +1,389 @@
+/* The Final Earth 2: the scenarios and free play maps, made by tools/gen_stories.py from the
+ * original's stories and texts. Don't edit: edit the generator. */
+#include "story.h"
+#include "classes.h"
+#include "data.h"
+
+static const StoryRes s0w0r[] = {{0, CLS_Forest}, {6, CLS_Rock}, {7, CLS_Forest}, {9, CLS_Rock}, {12, CLS_AlienRuins}, {14, CLS_Forest}, {17, CLS_AlienRuins}, {18, CLS_Rock}, {19, CLS_Forest}, {21, CLS_Forest}};
+static const uint16_t s0w0s0[] = {CLS_LandedExplorationShip};
+static const StoryStack s0w0s[] = {{3, 1, s0w0s0}};
+static const StoryCitizens s0w0c[] = {{3, 60, 64, 60, 80}};
+static const StoryWorld s0w[] = {
+ {0, 160, 440, 100, 1000u, 0, 0, 0, 10, s0w0r, 1, s0w0s, 1, s0w0c, 0, NULL}};
+static const SubGoal s0g0sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_WoodcuttingCentre, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g0u[] = {"WoodcuttingCentre"};
+static const SubGoal s0g1sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_StoneMine, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g1u[] = {"StoneMine"};
+static const SubGoal s0g2sub[] = {{.type = SG_GATHERMATERIALS, .mats = {[M_WOOD] = 6, [M_STONE] = 4}}};
+static const SubGoal s0g3sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_NormalHouse, .amount = 1, .world = -1, .notWorld = -1}, {.type = SG_BUILDPERMANENTS, .cls = CLS_IndoorFarm, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g3u[] = {"NormalHouse", "IndoorFarm"};
+static const SubGoal s0g4sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_ExplorationCentre, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g4u[] = {"ExplorationCentre"};
+static const StoryEvent s0g4e[] = {{.type = EV_SAUCER, .time = 1, .amount = 4, .ageMin = 60, .ageMax = 64, .world = 0}};
+static const SubGoal s0g5sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_StoneMine, .amount = 2, .world = -1, .notWorld = -1}};
+static const char *const s0g5u[] = {"School"};
+static const StoryEvent s0g5e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 60, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 36, .betweenMax = 40, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}, {.type = EV_SAUCER, .time = 360, .amount = 2, .ageMin = 18, .ageMax = 24, .world = 0}};
+static const SubGoal s0g6sub[] = {{.type = SG_PERFORMBUILDINGUPGRADES, .name = "BetterPickaxes", .amount = 1}};
+static const SubGoal s0g7sub[] = {{.type = SG_GATHERMATERIALS, .mats = {[M_FOOD] = 10}}, {.type = SG_BUILDPERMANENTS, .cls = CLS_Pub, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g7u[] = {"buildingModes", "managementOptions", "Pub", "Park"};
+static const SubGoal s0g8sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_MachinePartsFactory, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g8u[] = {"MachinePartsFactory"};
+static const SubGoal s0g9sub[] = {{.type = SG_MINIMUMHAPPINESS, .value = 52}};
+static const char *const s0g9u[] = {"Workshop", "ExperimentalFarm", "NightClub", "ModernRusticHome"};
+static const SubGoal s0g10sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_StoneTeleporter, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g10u[] = {"StoneTeleporter", "Laboratory"};
+static const SubGoal s0g11sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_Observatory, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s0g11u[] = {"Observatory"};
+static const char *const s0g12u[] = {"LandingSite", "Arcade", "TreePlantation", "RefinedMetalFactory", "decorations", "MedicalClinic", "ModernArtMuseum", "ComfortableHouse", "ColoredBlock", "RooftopDecoration", "RooftopDecoration2", "RooftopDecoration3", "RooftopDecoration4"};
+static const StoryGoal s0g[] = {
+ {"Start", 1, -1, 1, s0g0sub, 1, s0g0u, 0, NULL, 0, NULL, GF_DISABLEDYING | GF_DISABLEDESTROY | GF_HIDDENBOOST, GF_DISABLEDYING | GF_DISABLEDESTROY | GF_HIDDENBOOST, 1, "It's 2142, and earth is a wasteland. Colonizing this tiny world is humanity's only hope.\n\nFirst, you'll need some more building materials. Let's build a woodcutting center.", "Build a woodcutting center.", NULL},
+ {"BuildStoneMine", 2, -1, 1, s0g1sub, 1, s0g1u, 0, NULL, 0, NULL, 0, 0, 101, "Good job! Now, collect some wood and build a stone mine.", "Build a stone mine.", NULL},
+ {"GatherWoodAndStone", 3, -1, 1, s0g2sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 2, "Well done! Right now, nobody is going to gather stone, as everybody already has a job at the woodcutting center. Let's reassign one of these workers.", "Gather 6 wood and 4 stone. You'll need to reassign some workers.", NULL},
+ {"BuildIndoorFarmAndHouse", 4, -1, 2, s0g3sub, 2, s0g3u, 0, NULL, 0, NULL, GF_HIDDENBOOST, 0, 3, "You used a space ship to get here. Some of your friends are still on it. You'll want to give them a place to live. A steady food supply would be nice, too.\n\nTo accomplish these goals, let's build a house and an indoor farm.[nonmobi] Please note that buildings can be stacked.", "Build a house and an indoor farm.", NULL},
+ {"SpawnMorePeople", 5, -1, 1, s0g4sub, 1, s0g4u, 0, NULL, 1, s0g4e, 0, 0, 4, "Good job! Some more people will arrive soon.\nIt could be helpful to learn some more about this world. In particular, the alien ruins look quite interesting. Let's build an exploration center to learn all about them and maybe get some useful resources too.", "Build an exploration center.", NULL},
+ {"NowArrivingRegularly", 6, -1, 1, s0g5sub, 1, s0g5u, 0, NULL, 2, s0g5e, 0, 0, 0, "New people will now start arriving regularly. Make sure to keep them fed and housed. Also, children can be born from now on. You can build a school for them if you want.[n]\nTo build up your city, you'll need lots of stone, so let's build one more stone mine.", "Build a second stone mine.", NULL},
+ {"StoneMineUpgrade", 7, -1, 1, s0g6sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "[c]Your stone miners have good equipment thanks to the Better Pickaxes upgrade. Great job![/][n]Your stone miners are currently working with low-quality mining equipment. Better pickaxes would improve their mining speed. Upgrade at least one of your stone mines. To do so, [nonmobi]click[mobi]tap[/] on the stone mine, then on the Better Pickaxes upgrade.", "Upgrade a stone mine with better pickaxes.", NULL},
+ {"Happiness", 8, -1, 2, s0g7sub, 4, s0g7u, 0, NULL, 0, NULL, 0, 0, 0, "Now that you've got a pretty good economy, it's time to focus on your citizens' wellbeing for a bit. Not that there's no economic advantage to that at all, as happy citizens work faster. To make them more happy, let's build a pub. Also, make sure you have at least 10 food.", "Build a pub and have at least 10 food.", NULL},
+ {"BuildMachinePartsFactory", 9, -1, 1, s0g8sub, 1, s0g8u, 0, NULL, 0, NULL, GF_DISABLEDYING | GF_DISABLEDESTROY, 0, 0, "Great job! Make sure there's actually someone working at the pub or it won't have any effect.\nThe city will need machines. [c]Fortunately, you looked ahead and have already built a machine parts factory.[/c][n]Let's build a machine parts factory to be able to construct them.[/n]", "Build a machine parts factory.", NULL},
+ {"GetMinHappiness", 10, -1, 1, s0g9sub, 4, s0g9u, 0, NULL, 0, NULL, 0, 0, 4002, "The machine parts factory uses lots of stone, so make sure you have enough! If you need stone for something else, just switch it off for a while.[n]\nIt's always nice to see happy faces, isn't it? Let's make sure the happiness in your city is at least 52. Just [nnonmobi]click[nmobi]tap[n] on the Happiness button if you'd like to see which areas could use improvement.[/n]", "Bring the happiness in your city above 52.", NULL},
+ {"BuildStoneTeleporter", 11, -1, 1, s0g10sub, 2, s0g10u, 0, NULL, 0, NULL, 0, 0, 0, "The amount of stone on this planet is quite limited. Fortunately, you've just thought of a way to solve that problem: a rock teleporter could teleport mineable rocks from elsewhere. Let's research and build one. You may want to build some labs to get more knowledge.", "Build a rock teleporter.", NULL},
+ {"BuildObservatory", 12, -1, 1, s0g11sub, 1, s0g11u, 0, NULL, 0, NULL, 0, 0, 0, "Well done! You'll never run out of stone now. Keep your stone mines, as you need those workers to mine the meteroids.\nYour population is growing quickly, and this world is quite small. It's probably a good idea to look for other worlds to colonize, so let's build an observatory.", "Build the observatory.", NULL},
+ {"Win", -1, 1, 0, NULL, 13, s0g12u, 0, NULL, 0, NULL, 0, 0, 0, "Great job! Your scientists will now look for other worlds to colonize. You can play the next scenario to see what they'll find.\nIf you'd like to continue improving this city, you can always go to the next scenario later from the menu. Either way, you can always return to this city later.", "", "Scenario Complete!"}};
+static const StoryBackground s0b[] = {{SPR_PLANETS_SMALL, 40, 2, 120, -80, 0.5f}, {SPR_PLANETS_MEDIUM, 80, 1, 300, -200, 1.0f}, {SPR_PLANETS_SMALL, 40, 0, 40, -500, 0.2f}, {SPR_PLANETS_BIG, 100, 1, 900, 0, 1.3f}, {SPR_PLANETS_BIG, 100, 3, -900, 400, 1.5f}, {SPR_PLANETS_MEDIUM, 80, 3, -400, 100, 0.1f}};
+
+static const StoryRes s1w0r[] = {{3, CLS_Forest}, {6, CLS_Rock}, {7, CLS_Forest}, {8, CLS_Rock}, {9, CLS_AlienRuins}};
+static const uint16_t s1w0s0[] = {CLS_LandedExplorationShip};
+static const StoryStack s1w0s[] = {{2, 1, s1w0s0}};
+static const StoryCitizens s1w0c[] = {{3, 20, 25, 60, 80}};
+static const StoryRes s1w1r[] = {{1, CLS_Rock}, {2, CLS_Forest}, {4, CLS_Rock}, {5, CLS_AlienRuins}, {7, CLS_Rock}};
+static const StoryRes s1w2r[] = {{2, CLS_Forest}, {3, CLS_Rock}, {5, CLS_Rock}};
+static const StoryRes s1w3r[] = {{0, CLS_Forest}, {2, CLS_Rock}, {3, CLS_Forest}, {5, CLS_Rock}, {7, CLS_Forest}, {8, CLS_Rock}};
+static const StoryRes s1w4r[] = {{0, CLS_Forest}, {3, CLS_Forest}, {5, CLS_Rock}};
+static const StoryRes s1w5r[] = {{0, CLS_AlienRuins}, {1, CLS_Rock}, {5, CLS_Forest}, {6, CLS_Rock}, {8, CLS_Forest}, {10, CLS_Rock}};
+static const StoryRes s1w6r[] = {{1, CLS_Forest}, {2, CLS_AlienRuins}, {3, CLS_Forest}};
+static const StoryWorld s1w[] = {
+ {-20, 160, 200, 80, 2000u, 0, 0, 0, 5, s1w0r, 1, s1w0s, 1, s1w0c, 0, NULL},
+ {240, 140, 180, 100, 2001u, 0, 0, 0, 5, s1w1r, 0, NULL, 0, NULL, 0, NULL},
+ {-160, 120, 120, 60, 2002u, 0, 0, 0, 3, s1w2r, 0, NULL, 0, NULL, 0, NULL},
+ {420, 40, 180, 80, 2003u, 0, 0, 0, 6, s1w3r, 0, NULL, 0, NULL, 0, NULL},
+ {400, 200, 120, 60, 2004u, 0, 0, 0, 3, s1w4r, 0, NULL, 0, NULL, 0, NULL},
+ {640, 100, 220, 100, 2005u, 0, 0, 0, 6, s1w5r, 0, NULL, 0, NULL, 0, NULL},
+ {-300, 160, 100, 60, 2006u, 0, 0, 0, 3, s1w6r, 0, NULL, 0, NULL, 0, NULL}};
+static const SubGoal s1g0sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_WoodcuttingCentre, .amount = 1, .world = -1, .notWorld = -1}, {.type = SG_BUILDPERMANENTS, .cls = CLS_StoneMine, .amount = 1, .world = -1, .notWorld = -1}, {.type = SG_BUILDPERMANENTS, .cls = CLS_IndoorFarm, .amount = 1, .world = -1, .notWorld = -1}, {.type = SG_BUILDPERMANENTS, .cls = CLS_NormalHouse, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s1g1sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_Pub, .amount = 1, .world = -1, .notWorld = -1}};
+static const StoryEvent s1g1e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 70, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 3, .groupMax = 4, .betweenMin = 30, .betweenMax = 34, .afterDone = "All the people from your previous city have now arrived. Of course, your population can still grow through their offspring."}};
+static const SubGoal s1g2sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_MachinePartsFactory, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s1g3sub[] = {{.type = SG_PERFORMBUILDINGUPGRADES, .name = "MachinePartsFactoryEfficiency", .amount = 1}};
+static const SubGoal s1g4sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_LandingSite, .amount = 1, .world = 0, .notWorld = -1}, {.type = SG_BUILDPERMANENTS, .cls = CLS_LandingSite, .amount = 1, .world = -1, .notWorld = 0}};
+static const SubGoal s1g5sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_ExperimentalFarm, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s1g6sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_RefinedMetalFactory, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s1g7sub[] = {{.type = SG_MINIMUMHAPPINESS, .value = 80}};
+static const StoryGoal s1g[] = {
+ {"Start", 1, -1, 4, s1g0sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Soon after building the observatory, your scientists found a world that looked promising. You decided to fly there and take a look. Apparently, your scientists didn't look very closely, because what they thought to be one world are actually multiple tiny worlds. Still, this looks like a fairly suitable location to build a city.\nTo get started, let's build a woodcutting center, a stone mine, an indoor farm and a house.", "Build a woodcutting center, a stone mine, an indoor farm and a house.", NULL},
+ {"MorePeople", 2, -1, 1, s1g1sub, 0, NULL, 0, NULL, 1, s1g1e, 0, 0, 0, "That's a good start! You've invited some people from your previous city. They'll arrive in the coming days.\nYour citizens don't seem very happy right now. Let's build a pub to cheer them up a bit.", "Build a pub.", NULL},
+ {"GoBuildMPF", 3, -1, 1, s1g2sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "The pub should make your citizens a bit less sad! To get to the other worlds, you'll need machine parts, so let's create a machine parts factory.", "Build a machine parts factory.", NULL},
+ {"MachinePartsFactoryBuilt", 4, -1, 1, s1g3sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "The machine parts factory is very useful, but currently not very efficient. Let's upgrade it to recycle scrap metal. This will reduce the amount of stone it uses.", "Upgrade your machine parts factory to make it recycle scrap metal.", NULL},
+ {"GoToOtherWorlds", 5, -1, 2, s1g4sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "[c]You already built some landing pads to connect worlds. Great job![/][n]Good job! Now, it's finally time to get to another world. The easiest way to do that is by building landing pads. Let's build two of them: one on your current world and one on another world you'd like to populate.[/]", "Connect the currently populated world with another by building landing pads.", NULL},
+ {"GoToOtherWorldsDone", 6, -1, 1, s1g5sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "[c]You already built an experimental farm! Well done![/][n]Now that your city has some more space, it'll probably grow rapidly. You'll soon have many more mouths to feed. To make that a bit easier, let's build an experimental farm.[/]", "Build an experimental farm.", NULL},
+ {"GoBuildRefinedMetalFactory", 7, -1, 1, s1g6sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "[c]You already built a refined metals factory! Good job![/][n]To build some types of buildings, raw stone isn't good enough. You'll need to refine it first. Let's build a refined metals factory to do just that.[/]", "Build a refined metals factory.", NULL},
+ {"GetHighHappiness", 8, -1, 1, s1g7sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "[c]Wow, I'm impressed! You already got the happiness high enough to beat this goal.[/][n]Refined metals are nice, but happy citizens are certainly even nicer. So let's use some of these refined metals to improve the happiness of your citizens. Bring it to at least 80.[/]", "Bring the happiness above 80.", NULL},
+ {"Win", -1, 2, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Your citizens are really happy now, and they wouldn't want to live anywhere else. Great job!\n\nYou can now play the next scenario, or continue improving your city if you'd like. Thanks for playing!", "", "Scenario Complete!"}};
+static const StoryBackground s1b[] = {{SPR_PLANET_RING_BIG, 277, 0, 400, -200, 0.5f}, {SPR_PLANETS_GIANT, 140, 1, -400, -500, -0.8f}, {SPR_PLANETS_MEDIUM, 80, 5, 200, -100, 0.5f}, {SPR_PLANETS_SMALL, 40, 3, 950, 50, 0.2f}, {SPR_PLANETS_BIGGER, 120, 0, -900, 600, 0.8f}};
+
+static const StoryRes s2w0r[] = {{7, CLS_Forest}, {8, CLS_Rock}, {9, CLS_Forest}, {12, CLS_Rock}, {13, CLS_ComputerAlienRuins}, {14, CLS_Rock}, {15, CLS_Forest}};
+static const uint16_t s2w0s0[] = {CLS_StoneMine, CLS_NormalHouse, CLS_LandedExplorationShip | STACK_MIRROR};
+static const uint16_t s2w0s1[] = {CLS_IndoorFarm, CLS_NormalHouse, CLS_NormalHouse, CLS_RooftopDecoration2 | STACK_DECOR(1)};
+static const uint16_t s2w0s2[] = {CLS_WoodcuttingCentre, CLS_NormalHouse, CLS_LandedExplorationShip};
+static const StoryStack s2w0s[] = {{2, 3, s2w0s0}, {3, 4, s2w0s1}, {4, 3, s2w0s2}};
+static const StoryCitizens s2w0c[] = {{20, 20, 25, 40, 100}};
+static const StoryRes s2w1r[] = {{0, CLS_Forest}, {3, CLS_Forest}, {5, CLS_Rock}, {6, CLS_Forest}, {10, CLS_Rock}, {11, CLS_Rock}, {16, CLS_Forest}, {17, CLS_Rock}};
+static const StoryRes s2w2r[] = {{2, CLS_Rock}, {5, CLS_Forest}, {6, CLS_Rock}, {10, CLS_Forest}, {13, CLS_Rock}};
+static const StoryRes s2w3r[] = {{1, CLS_Rock}, {7, CLS_AlienRuins}, {9, CLS_Rock}, {12, CLS_Rock}};
+static const StoryRes s2w4r[] = {{0, CLS_Forest}, {1, CLS_Rock}, {3, CLS_AlienRuins}, {10, CLS_Rock}, {13, CLS_Forest}, {15, CLS_Rock}};
+static const StoryRes s2w5r[] = {{1, CLS_AlienRuins}};
+static const StoryRes s2w6r[] = {{3, CLS_AlienRuins}, {0, CLS_Rock}, {5, CLS_Rock}, {6, CLS_Forest}, {7, CLS_Forest}, {11, CLS_Rock}, {13, CLS_Forest}};
+static const StoryRes s2w7r[] = {{1, CLS_Forest}, {3, CLS_Rock}, {5, CLS_Rock}, {7, CLS_Rock}, {9, CLS_Forest}, {12, CLS_Forest}, {15, CLS_Rock}};
+static const StoryRes s2w8r[] = {{0, CLS_Forest}, {3, CLS_Rock}, {7, CLS_Forest}, {8, CLS_Forest}, {12, CLS_Rock}, {15, CLS_Forest}, {16, CLS_Rock}, {20, CLS_Rock}, {21, CLS_Rock}, {22, CLS_Rock}};
+static const StoryWorld s2w[] = {
+ {-20, 160, 400, 80, 3000u, 0, 0, 0, 7, s2w0r, 3, s2w0s, 1, s2w0c, 0, NULL},
+ {-300, 300, 400, 60, 3001u, 0, 0, 0, 8, s2w1r, 0, NULL, 0, NULL, 0, NULL},
+ {320, 320, 340, 60, 3002u, 0, 0, 0, 5, s2w2r, 0, NULL, 0, NULL, 0, NULL},
+ {-400, -40, 280, 60, 3003u, 0, WF_UNBUILDABLE_ALIENS, 0, 4, s2w3r, 0, NULL, 0, NULL, 0, NULL},
+ {500, -20, 320, 60, 3004u, 0, WF_UNBUILDABLE_ALIENS, 0, 6, s2w4r, 0, NULL, 0, NULL, 0, NULL},
+ {440, 100, 40, 20, 3005u, 0, WF_UNBUILDABLE_ALIENS, 0, 1, s2w5r, 0, NULL, 0, NULL, 0, NULL},
+ {-740, 180, 420, 60, 3006u, 0, WF_UNBUILDABLE_ALIENS, 0, 7, s2w6r, 0, NULL, 0, NULL, 0, NULL},
+ {720, 200, 360, 80, 3007u, 0, WF_UNBUILDABLE_ALIENS, 0, 7, s2w7r, 0, NULL, 0, NULL, 0, NULL},
+ {-100, 500, 500, 80, 3008u, 0, WF_UNBUILDABLE_ALIENS, 0, 10, s2w8r, 0, NULL, 0, NULL, 0, NULL},
+ {-780, 180, 20, 20, 3009u, 0, WF_UNBUILDABLE_ALIENS, 0, 0, NULL, 0, NULL, 0, NULL, 0, NULL}};
+static const SubGoal s2g0sub[] = {{.type = SG_HOUSINGCAPACITY, .amount = 50}};
+static const StoryEvent s2g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 3, .groupMax = 4, .betweenMin = 16, .betweenMax = 24, .afterDone = "The people who wanted to move here have now all arrived. Of course, your population can still grow through their offspring."}};
+static const SubGoal s2g1sub[] = {{.type = SG_EXPLOREALIENRUINS}};
+static const SubGoal s2g2sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_ResearchBot, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s2g2u[] = {"ResearchBot"};
+static const SubGoal s2g3sub[] = {{.type = SG_EXPLOREDWITHRESEARCHSPACECRAFT}};
+static const SubGoal s2g4sub[] = {{.type = SG_EXPLOREALIENRUINS}};
+static const SubGoal s2g5sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_RefinedMetalFactory, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s2g6sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_ComputerResearchCenter, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s2g7sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_ComputerChipFactory, .amount = 1, .world = -1, .notWorld = -1}, {.type = SG_GATHERMATERIALS, .mats = {[M_COMPUTERCHIPS] = 5}}};
+static const SubGoal s2g8sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_Arcade, .amount = 3, .world = -1, .notWorld = -1}};
+static const SubGoal s2g9sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_HackerHQ, .amount = 1, .world = -1, .notWorld = -1}};
+static const SubGoal s2g10sub[] = {{.type = SG_COMPLETEHACKERMISSIONS, .amount = 4}};
+static const SubGoal s2g11sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_AlienDecryptor, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s2g11u[] = {"AlienDecryptor"};
+static const SubGoal s2g12sub[] = {{.type = SG_WAITFORDECRYPTION}};
+static const StoryGoal s2g[] = {
+ {"Start", 2, -1, 1, s2g0sub, 0, NULL, 0, NULL, 1, s2g0e, 0, 0, 0, "Humanity is slowly colonizing space. This is the newest outpost. It is still quite small, but new people are arriving quickly.\nYou don't want them to be homeless, of course. To prevent this, build houses until you have at least fifty capacity. It's also a good idea to build some more production buildings and entertainment.", "Build houses until you have fifty capacity in total.", NULL},
+ {"ExploreAlienRuins", 5, -1, 1, s2g1sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "(this story event is for compatibility reasons)", "Explore the alien ruins on this world.", NULL},
+ {"ExploreAlienRuins2", 3, -1, 1, s2g2sub, 1, s2g2u, 0, NULL, 0, NULL, 0, 0, 0, "Well done!\nThe alien ruins here look different from the ones you saw before. Let's explore them to find out more.\n\nAlso, some of the worlds here have a strange glow. Let's build a research craft to investigate this while you're exploring the ruins.", "Build a research craft and explore the alien ruins on this world.", NULL},
+ {"InTheMeantime2", 4, -1, 1, s2g3sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Now you've built the spacecraft, it's time to do some research! Make sure a worker is assigned to the research spacecraft and wait until they explored a bit.", "Assign a worker to the research spacecraft and wait until they explored a bit.", NULL},
+ {"InTheMeantime3", 5, -1, 1, s2g4sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "The worker in the research spacecraft noticed a strange power prevented them from getting close to the glowing worlds. This also means you can't build on them. Maybe the alien ruins can help?", "Explore the alien ruins on this world.", NULL},
+ {"BuildRefinedMetalsFactory", 6, -1, 1, s2g5sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "While investigating the alien ruins, your explorers found a small device. You think it could have something to do with the inaccessible worlds.\nHowever, none of your citizens has been able to make sense of it. Maybe having some computers would help? To build them, you will first need some refined metals. Build a Refined Metals Factory to produce those.", "Build a Refined Metals Factory.", NULL},
+ {"BuildComputerResearchCenter", 7, -1, 1, s2g6sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Your new refined metals factory is looking good!\nBuilding a computer is actually pretty complicated. Therefore, you will need to build the Computing Research Center first.", "Build the Computing Research Center.", NULL},
+ {"BuildComputerChipFactory", 8, -1, 2, s2g7sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Great job! Now, you just need some chips to be able to make a computer. Let's build a Computer Chip Factory and make five computer chips.", "Build a Computer Chip Factory and make five computer chips.", NULL},
+ {"BuildArcades", 9, -1, 1, s2g8sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "You built a computer and plugged in the alien device... but there's a bit of a problem. All the data is encrypted!\nMaybe the Hackers of the Bolt can help. However, before they want to settle here, they request you to build three Arcades.", "Build three arcades.", NULL},
+ {"BuildHackers", 10, -1, 1, s2g9sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "The Hackers of the Bolt seem satisfied with your city. Let's build their HQ now!", "Build the Hackers of the Bolt HQ.", NULL},
+ {"CompleteHackerMissions", 11, -1, 1, s2g10sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "The Hackers of the Bolt have taken a look at the encrypted data, but they need some more experience to be able to crack it. Let's complete a few of their missions to help them with that!", "Complete a few Hackers of the Bolt missions.", NULL},
+ {"BuildDecryptBuilding", 12, -1, 1, s2g11sub, 1, s2g11u, 0, NULL, 0, NULL, 0, 0, 0, "The Hackers of the Bolt think they can now crack the encryption, but they need a specialized computer first. Let's build the Alien Decryptor for them!", "Build the Alien Decryptor.", NULL},
+ {"Wait", 13, -1, 1, s2g12sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Great job! Now the only thing left to do is to wait while the Decryptor does its job. This should take no more than a day.", "Let the Decryptor do its job.", NULL},
+ {"Win", -1, 3, 0, NULL, 0, NULL, 0, NULL, 0, NULL, GF_SETBUILDABLEALIENS, GF_SETBUILDABLEALIENS, 0, "The decryption succeeded, and the Hackers of the Bolt will soon be able to remove the restrictive glow from the locked worlds. You can now continue to build an amazing city here! You have also been invited to the City of the Key. Go to the next scenario to accept this invitiation.", "", "Scenario Complete!"}};
+static const StoryBackground s2b[] = {{SPR_PLANETS_BIGGER, 120, 3, -400, -300, 0.6f}, {SPR_PLANETS_MEDIUM, 80, 0, 300, -50, 0.6f}, {SPR_PLANETS_SMALL, 40, 1, -50, -200, -0.5f}, {SPR_PLANETS_BIGGER, 120, 1, -50, 600, 0.9f}, {SPR_PLANETS_MEDIUM, 80, 2, -600, 0, 0.7f}, {SPR_PLANETS_MEDIUM, 80, 4, 1100, -500, -0.4f}};
+
+static const StoryRes s3w0r[] = {{0, CLS_PineForest}, {4, CLS_AlienRuins}, {5, CLS_Rock}, {9, CLS_AlienRuins}, {12, CLS_Rock}, {14, CLS_Rock}, {18, CLS_PineForest}, {22, CLS_Rock}, {23, CLS_PineForest}, {28, CLS_Rock}, {27, CLS_PineForest}};
+static const uint16_t s3w0s0[] = {CLS_Pub};
+static const uint16_t s3w0s1[] = {CLS_LandedExplorationShip};
+static const uint16_t s3w0s2[] = {CLS_LandingSite};
+static const uint16_t s3w0s3[] = {CLS_RooftopDecoration | STACK_DECOR(9)};
+static const uint16_t s3w0s4[] = {CLS_Teleporter, CLS_RooftopDecoration2 | STACK_DECOR(9)};
+static const uint16_t s3w0s5[] = {CLS_RooftopDecoration | STACK_DECOR(9) | STACK_MIRROR};
+static const uint16_t s3w0s6[] = {CLS_Laboratory, CLS_IndoorFarm, CLS_Laboratory, CLS_TreePlantation, CLS_RooftopDecoration | STACK_DECOR(10) | STACK_MIRROR};
+static const uint16_t s3w0s7[] = {CLS_IndoorFarm, CLS_Laboratory, CLS_TreePlantation, CLS_Laboratory, CLS_RooftopDecoration2 | STACK_DECOR(10)};
+static const uint16_t s3w0s8[] = {CLS_Laboratory, CLS_IndoorFarm, CLS_Laboratory, CLS_TreePlantation, CLS_RooftopDecoration | STACK_DECOR(10)};
+static const uint16_t s3w0s9[] = {CLS_StoneMine, CLS_StoneMine, CLS_StoneMine, CLS_StoneMine, CLS_RooftopDecoration};
+static const uint16_t s3w0s10[] = {CLS_StoneMine, CLS_StoneTeleporter, CLS_StoneMine, CLS_StoneMine, CLS_StoneMine, CLS_RooftopDecoration2 | STACK_DECOR(0)};
+static const uint16_t s3w0s11[] = {CLS_StoneMine, CLS_StoneMine, CLS_StoneMine, CLS_StoneMine, CLS_RooftopDecoration | STACK_DECOR(0) | STACK_MIRROR};
+static const StoryStack s3w0s[] = {{1, 1, s3w0s0}, {20, 1, s3w0s1}, {40, 1, s3w0s2}, {35, 1, s3w0s3}, {36, 2, s3w0s4}, {37, 1, s3w0s5}, {24, 5, s3w0s6}, {25, 5, s3w0s7}, {26, 5, s3w0s8}, {30, 5, s3w0s9}, {31, 6, s3w0s10}, {32, 5, s3w0s11}};
+static const StoryCitizens s3w0c[] = {{24, 20, 25, 700, 790}};
+static const StoryDeco s3w0d[] = {{34, SPR_FLOWERS_KEYCITY}, {38, SPR_FLOWERS_KEYCITY}};
+static const uint16_t s3w1s0[] = {CLS_SecretSocietyHouse, CLS_LandingSite};
+static const StoryStack s3w1s[] = {{0, 2, s3w1s0}};
+static const StoryCitizens s3w1c[] = {{8, 40, 45, 2, 18}};
+static const StoryRes s3w2r[] = {{40, CLS_PineForest}, {36, CLS_AlienRuins}, {35, CLS_Rock}, {31, CLS_AlienRuins}, {28, CLS_Rock}, {26, CLS_Rock}, {22, CLS_PineForest}, {18, CLS_Rock}, {17, CLS_PineForest}, {13, CLS_PineForest}, {12, CLS_Rock}};
+static const uint16_t s3w2s0[] = {CLS_RooftopDecoration | STACK_DECOR(9)};
+static const uint16_t s3w2s1[] = {CLS_Teleporter, CLS_RooftopDecoration2 | STACK_DECOR(9)};
+static const uint16_t s3w2s2[] = {CLS_RooftopDecoration | STACK_DECOR(9) | STACK_MIRROR};
+static const uint16_t s3w2s3[] = {CLS_LandingSite};
+static const uint16_t s3w2s4[] = {CLS_MechanicalHouse, CLS_RefinedMetalFactory, CLS_ExperimentationLab, CLS_RefinedMetalFactory, CLS_LandingSite};
+static const uint16_t s3w2s5[] = {CLS_MachinePartsFactory, CLS_ComputerResearchCenter, CLS_ComputerChipFactory, CLS_LandingSite};
+static const uint16_t s3w2s6[] = {CLS_MechanicalHouse, CLS_RefinedMetalFactory, CLS_ExperimentationLab, CLS_RefinedMetalFactory, CLS_LandingSite};
+static const uint16_t s3w2s7[] = {CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_RooftopDecoration | STACK_DECOR(3) | STACK_MIRROR};
+static const uint16_t s3w2s8[] = {CLS_Workshop, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_RooftopDecoration2 | STACK_DECOR(3)};
+static const uint16_t s3w2s9[] = {CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_ComfortableHouse, CLS_RooftopDecoration | STACK_DECOR(3)};
+static const uint16_t s3w2s10[] = {CLS_LandedExplorationShip | STACK_MIRROR};
+static const uint16_t s3w2s11[] = {CLS_Pub};
+static const StoryStack s3w2s[] = {{3, 1, s3w2s0}, {4, 2, s3w2s1}, {5, 1, s3w2s2}, {0, 1, s3w2s3}, {14, 5, s3w2s4}, {15, 4, s3w2s5}, {16, 5, s3w2s6}, {10, 5, s3w2s7}, {9, 6, s3w2s8}, {8, 5, s3w2s9}, {20, 1, s3w2s10}, {39, 1, s3w2s11}};
+static const StoryCitizens s3w2c[] = {{24, 20, 25, 2, 100}};
+static const StoryDeco s3w2d[] = {{2, SPR_FLOWERS_KEYCITY}, {6, SPR_FLOWERS_KEYCITY}};
+static const StoryWorld s3w[] = {
+ {-900, 140, 820, 100, 14000u, 1, 0, SPR_DECORATION_KEYCITY, 11, s3w0r, 12, s3w0s, 1, s3w0c, 2, s3w0d},
+ {0, 140, 20, 20, 14003u, 2, WF_PROTECTED_KEY, SPR_DECORATION_KEYCITY, 0, NULL, 1, s3w1s, 1, s3w1c, 0, NULL},
+ {100, 140, 820, 100, 14001u, 1, 0, SPR_DECORATION_KEYCITY, 11, s3w2r, 12, s3w2s, 1, s3w2c, 2, s3w2d}};
+static const SubGoal s3g0sub[] = {{.type = SG_WAIT, .value = 1}};
+static const char *const s3g0u[] = {"ComputerChipFactory", "ExperimentationLab"};
+static const char *const s3g0r[] = {"ComputerChipFactory", "ExperimentationLab", "StoneTeleporter", "ComfortableHouse", "RefinedMetalFactory", "Workshop", "Teleporter", "SecretSocietyHouse", "LandingSite", "MachinePartsFactory", "MechanicalHouse"};
+static const SubGoal s3g1sub[] = {{.type = SG_INVITEPEOPLE}};
+static const SubGoal s3g2sub[] = {{.type = SG_PRODUCTIONGOAL, .mats = {[M_KNOWLEDGE] = 50, [M_STONE] = 100, [M_FOOD] = 100}}};
+static const SubGoal s3g3sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_StatueGarden, .amount = 5, .world = -1, .notWorld = -1}};
+static const char *const s3g3u[] = {"StatueGarden"};
+static const SubGoal s3g4sub[] = {{.type = SG_MINIMUMCITIZENS, .amount = 300}};
+static const SubGoal s3g5sub[] = {{.type = SG_PRODUCTIONGOAL, .mats = {[M_KNOWLEDGE] = 150}}};
+static const SubGoal s3g6sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_Teleporter, .amount = 5, .world = -1, .notWorld = -1}};
+static const SubGoal s3g7sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_LuxuryRestaurant, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s3g7u[] = {"LuxuryRestaurant"};
+static const SubGoal s3g8sub[] = {{.type = SG_PERFORMCITYUPGRADE, .name = "SecretiveLiving", .amount = 1}};
+static const SubGoal s3g9sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_Villa, .amount = 3, .world = -1, .notWorld = -1}};
+static const char *const s3g9u[] = {"Villa"};
+static const SubGoal s3g10sub[] = {{.type = SG_GLORYGOAL}};
+static const SubGoal s3g11sub[] = {{.type = SG_PRODUCTIONGOAL, .mats = {[M_KNOWLEDGE] = 750}}};
+static const SubGoal s3g12sub[] = {{.type = SG_BUILDPERMANENTS, .cls = CLS_TheMachine, .amount = 1, .world = -1, .notWorld = -1}};
+static const char *const s3g12u[] = {"TheMachine"};
+static const char *const s3g13u[] = {"HouseOfTheKeyFriends"};
+static const StoryGoal s3g[] = {
+ {"Start", 1, -1, 1, s3g0sub, 2, s3g0u, 11, s3g0r, 0, NULL, 0, 0, 0, "We, the Secret Society of the Key, hope and expect you are grateful to have arrived in our beautiful city. We want to build a city that proves our greatness, but we are tired of dealing with day-to-day business - we anticipate you can help.", "Wait for your first mission.", NULL},
+ {"InvitePeople", 2, -1, 1, s3g1sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 4001, "Nowadays, there is a lot of competition between cities. People don't just move to a new colony for free, not even to the glorious City of the Key. They want food as a relocation reward, and who knows what else they'll want in the future. We think this is ridiculous, but it is how it is. Please invite a few more citizens.", "Invite some citizens using the Management option.", NULL},
+ {"ImproveEconomy", 3, -1, 1, s3g2sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "You can invite new people whenever you desire.\n\nWe feel there may be room for improvement in the production department. We'd like you to produce at least 100 food, 100 stone and 50 knowledge in a day. It may be a good idea to disable our teleporters once in a while, as they seem to require a lot of knowledge.", "Produce at least 100 food, 100 stone and 50 knowledge in a day.", NULL},
+ {"BuildSculptures", 4, -1, 1, s3g3sub, 1, s3g3u, 0, NULL, 0, NULL, 0, 0, 0, "The people in this city, rightfully, care about the Glory of the Key. Build five sculpture gardens to improve our Glory, and thus the happiness of our citizens.", "Build five sculpture gardens.", NULL},
+ {"HaveEnoughPeople", 5, -1, 1, s3g4sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "[c]We are pleased to see our city has successfully grown to 300 citizens.[/][n]We would like to see our city grow to at least 300 citizens. Maybe you can invite a few people.", "Have at least 300 citizens in your city. You can use the invitiation feature.", NULL},
+ {"GatherKnowledge", 6, -1, 1, s3g5sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Our city should gather all the knowledge in the universe. To start, gather at least 150 in a day.", "Gather at least 150 knowledge in a day.", NULL},
+ {"BuildTeleporters", 7, -1, 1, s3g6sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "Having good transportation is important. [c]We are pleased to see you understand that and have already built some teleporters.[/][n]There should be at least five teleporters in our city.", "Have at least five teleporters in your city.", NULL},
+ {"BuildLuxuryRestaurants", 8, -1, 1, s3g7sub, 1, s3g7u, 0, NULL, 0, NULL, 0, 0, 0, "It is time for some more glory and luxury. Please build an upscale restaurant for us to improve the Glory of the Key.", "Build an upscale restaurant.", NULL},
+ {"ImproveOurHousing", 9, -1, 1, s3g8sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "It's good to care for our citizens, but in the end we are obviously the most important. Our house is fine, but it could be better. Research Secretive Living in the Living Research Center.", "Research Secretive Living in the Living Research Center.", NULL},
+ {"BuildLuxuryHousing", 10, -1, 1, s3g9sub, 1, s3g9u, 0, NULL, 0, NULL, 0, 0, 0, "Now that our house is better, it is time to build some great homes for people we like, too. Build three villas. This increases the Glory of the Key.", "Build three villas.", NULL},
+ {"FinalGlory", 11, -1, 1, s3g10sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "The Key should be ever glorious. [c]We are pleased to see that it indeed is.[/][n]Improve the Glory of the Key to 100.", "Improve the Glory of the Key to 100. You can check it in the Happiness window.", NULL},
+ {"GatherKnowledge2", 12, -1, 1, s3g11sub, 0, NULL, 0, NULL, 0, NULL, 0, 0, 0, "We have said it before, but we want to stress that knowledge is really important to us. Therefore, gather at least 750 knowledge in a day.", "Gather at least 750 knowledge in a day.", NULL},
+ {"BuildTheMachine", 13, -1, 1, s3g12sub, 1, s3g12u, 0, NULL, 0, NULL, 0, 0, 0, "Now that we have gathered enough knowledge, it is time to build our secret project. We would like you to build the Machine.", "Build the Machine.", NULL},
+ {"Win", -1, -1, 0, NULL, 1, s3g13u, 0, NULL, 0, NULL, 0, 0, 0, "We are quite pleased with your work. Therefore, you can now build a house for the Friends of the Key, who will live forever just like us.", "", "Scenario Complete!"}};
+static const StoryBackground s3b[] = {{SPR_PLANETS_SMALL, 40, 0, -50, -700, 0.62f}, {SPR_PLANET_RING_SMALL, 192, 0, 250, -200, 0.51f}, {SPR_PLANETS_BIGGER, 120, 0, 0, 0, 0.0f}, {SPR_PLANETS_MEDIUM, 80, 5, -430, -150, -0.56f}, {SPR_PLANETS_BIG, 100, 2, 800, -300, 0.93f}, {SPR_PLANETS_BIG, 100, 3, 700, 530, 1.35f}, {SPR_PLANETS_MEDIUM, 80, 0, -1080, 550, 1.25f}, {SPR_PLANETS_BIGGER, 120, 3, -800, -500, -0.99f}, {SPR_PLANETS_SMALL, 40, 1, 100, 100, 0.4f}, {SPR_PLANETS_SMALL, 40, 3, -100, -100, 0.4f}};
+
+static const StoryRes s4w0r[] = {{0, CLS_Forest}, {1, CLS_Forest}, {4, CLS_AlienRuins}, {5, CLS_Rock}, {10, CLS_Rock}, {11, CLS_Forest}, {12, CLS_Rock}, {15, CLS_AlienRuins}, {17, CLS_Forest}, {20, CLS_Rock}, {22, CLS_Forest}, {25, CLS_Rock}, {26, CLS_Rock}, {29, CLS_Forest}, {30, CLS_Rock}, {32, CLS_AlienRuins}, {36, CLS_Rock}, {38, CLS_Forest}, {40, CLS_Forest}, {41, CLS_Forest}, {44, CLS_Rock}, {46, CLS_Rock}, {47, CLS_Forest}, {48, CLS_AlienRuins}};
+static const uint16_t s4w0s0[] = {CLS_LandedExplorationShip};
+static const StoryStack s4w0s[] = {{2, 1, s4w0s0}};
+static const StoryCitizens s4w0c[] = {{3, 20, 25, 60, 80}};
+static const StoryWorld s4w[] = {
+ {0, 160, 1000, 80, 2000u, 0, 0, 0, 24, s4w0r, 1, s4w0s, 1, s4w0c, 0, NULL}};
+static const StoryEvent s4g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 20, .betweenMax = 30, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}};
+static const StoryGoal s4g[] = {
+ {"FreePlayStart", -1, -1, 0, NULL, 0, NULL, 0, NULL, 1, s4g0e, 0, 0, 0, "Welcome to this Free Play Scenario!\nA few citizens are already here. Some more will arrive over the coming days.", "", ""}};
+static const StoryBackground s4b[] = {{SPR_PLANETS_GIANT, 140, 0, 400, -300, 1.5f}, {SPR_PLANETS_BIG, 100, 0, 600, -200, 0.8f}, {SPR_PLANETS_SMALL, 40, 0, -400, 10, -0.5f}, {SPR_PLANETS_BIGGER, 120, 2, 150, 700, 0.84f}, {SPR_PLANETS_BIG, 100, 6, -950, 80, -0.9f}, {SPR_PLANETS_BIG, 100, 5, -100, -100, 0.3f}};
+
+static const StoryRes s5w0r[] = {{2, CLS_Rock}, {3, CLS_Rock}, {4, CLS_AlienRuins}, {10, CLS_Forest}, {12, CLS_Rock}, {14, CLS_Forest}, {15, CLS_Forest}, {18, CLS_Rock}, {19, CLS_AlienRuins}};
+static const uint16_t s5w0s0[] = {CLS_LandedExplorationShip};
+static const StoryStack s5w0s[] = {{5, 1, s5w0s0}};
+static const StoryCitizens s5w0c[] = {{3, 20, 25, 100, 120}};
+static const StoryWorld s5w[] = {
+ {0, 160, 400, 80, 8801u, 0, 0, 0, 9, s5w0r, 1, s5w0s, 1, s5w0c, 0, NULL}};
+static const StoryEvent s5g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 20, .betweenMax = 30, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}};
+static const StoryGoal s5g[] = {
+ {"FreePlayStart", -1, -1, 0, NULL, 0, NULL, 0, NULL, 1, s5g0e, 0, 0, 0, "Welcome to this Free Play Scenario!\nA few citizens are already here. Some more will arrive over the coming days.", "", ""}};
+static const GenItem s5x0[] = {{CLS_AlienRuins, 0, 1, 0}, {CLS_Forest, 12, 15, 0}, {CLS_Rock, 20, 25, 0}};
+static const GenItem s5x1[] = {{CLS_AlienRuins, 2, 3, 0}, {CLS_Forest, 60, 61, 0}, {CLS_Rock, 50, 51, 0}};
+static const WorldGenerator s5x[] = {{9, 10, -400, 120, 600, 500, 60, 240, 20, 60, 20, 3, s5x0, true, false, false, true}, {35, 42, -1000, 120, 940, 1200, 60, 300, 20, 60, 20, 3, s5x1, true, false, false, true}};
+static const StoryBackground s5b[] = {{SPR_PLANETS_SMALL, 40, 1, 0, -300, 0.3f}, {SPR_PLANETS_BIG, 100, 6, 100, -200, 0.8f}, {SPR_PLANETS_MEDIUM, 80, 2, 300, 10, -0.5f}, {SPR_PLANETS_MEDIUM, 80, 0, 300, 320, 0.84f}, {SPR_PLANETS_BIG, 100, 1, -950, 80, 0.9f}, {SPR_PLANETS_BIG, 100, 5, -300, 120, 1.3f}, {SPR_PLANETS_BIGGER, 120, 0, 900, -300, -0.9f}};
+
+static const uint16_t s6w0s0[] = {CLS_LandedExplorationShip};
+static const uint16_t s6w0s1[] = {CLS_LandingSite};
+static const StoryStack s6w0s[] = {{1, 1, s6w0s0}, {0, 1, s6w0s1}};
+static const StoryRes s6w1r[] = {{2, CLS_Rock}, {3, CLS_Forest}, {4, CLS_Rock}, {7, CLS_Rock}, {8, CLS_Forest}, {9, CLS_AlienRuins}, {10, CLS_Forest}};
+static const uint16_t s6w1s0[] = {CLS_LandingSite};
+static const StoryStack s6w1s[] = {{0, 1, s6w1s0}};
+static const StoryCitizens s6w1c[] = {{3, 20, 25, 20, 80}};
+static const StoryRes s6w2r[] = {{1, CLS_Rock}, {5, CLS_Rock}, {6, CLS_Forest}};
+static const uint16_t s6w2s0[] = {CLS_LandingSite};
+static const StoryStack s6w2s[] = {{0, 1, s6w2s0}};
+static const StoryRes s6w3r[] = {{3, CLS_Rock}, {4, CLS_AlienRuins}, {5, CLS_Rock}, {6, CLS_Forest}, {8, CLS_Forest}};
+static const StoryRes s6w4r[] = {{1, CLS_AlienRuins}};
+static const StoryRes s6w5r[] = {{1, CLS_Rock}, {2, CLS_Forest}, {4, CLS_Forest}, {5, CLS_Rock}, {6, CLS_Forest}, {9, CLS_AlienRuins}, {10, CLS_Forest}, {12, CLS_Rock}};
+static const StoryRes s6w6r[] = {{1, CLS_Forest}, {2, CLS_Forest}};
+static const StoryWorld s6w[] = {
+ {0, 160, 1200, 100, 9201u, 0, 0, 0, 0, NULL, 2, s6w0s, 0, NULL, 0, NULL},
+ {40, 400, 240, 60, 9202u, 0, 0, 0, 7, s6w1r, 1, s6w1s, 1, s6w1c, 0, NULL},
+ {340, 440, 160, 40, 9203u, 0, 0, 0, 3, s6w2r, 1, s6w2s, 0, NULL, 0, NULL},
+ {580, 380, 200, 60, 9204u, 0, 0, 0, 5, s6w3r, 0, NULL, 0, NULL, 0, NULL},
+ {860, 340, 60, 40, 9205u, 0, 0, 0, 1, s6w4r, 0, NULL, 0, NULL, 0, NULL},
+ {840, 440, 280, 60, 9206u, 0, 0, 0, 8, s6w5r, 0, NULL, 0, NULL, 0, NULL},
+ {1100, 320, 80, 40, 9207u, 0, 0, 0, 2, s6w6r, 0, NULL, 0, NULL, 0, NULL}};
+static const StoryEvent s6g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 20, .betweenMax = 30, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}};
+static const StoryGoal s6g[] = {
+ {"FreePlayStart", -1, -1, 0, NULL, 0, NULL, 0, NULL, 1, s6g0e, 0, 0, 0, "Welcome to this Free Play Scenario!\nA few citizens are already here. Some more will arrive over the coming days.", "", ""}};
+static const StoryBackground s6b[] = {{SPR_PLANETS_SMALL, 40, 2, 100, -900, 0.25f}, {SPR_PLANETS_BIGGER, 120, 1, 140, -140, 0.8f}, {SPR_PLANETS_MEDIUM, 80, 4, 300, -80, -0.9f}, {SPR_PLANETS_MEDIUM, 80, 1, 900, 320, -0.54f}, {SPR_PLANETS_BIG, 100, 2, -950, -500, 2.0f}, {SPR_PLANETS_SMALL, 40, 0, 450, -300, 0.33f}, {SPR_PLANETS_GIANT, 140, 0, -1200, 800, 0.4f}};
+
+static const StoryRes s7w0r[] = {{1, CLS_Forest}, {4, CLS_Forest}, {5, CLS_Forest}, {10, CLS_Forest}, {13, CLS_Forest}, {16, CLS_Forest}};
+static const uint16_t s7w0s0[] = {CLS_LandedExplorationShip};
+static const uint16_t s7w0s1[] = {CLS_LandingSite};
+static const StoryStack s7w0s[] = {{17, 1, s7w0s0}, {19, 1, s7w0s1}};
+static const StoryCitizens s7w0c[] = {{3, 20, 25, 340, 380}};
+static const StoryRes s7w1r[] = {{2, CLS_Rock}, {4, CLS_Rock}, {6, CLS_Rock}, {7, CLS_Rock}, {10, CLS_Rock}, {13, CLS_Rock}, {17, CLS_Rock}, {18, CLS_Rock}};
+static const uint16_t s7w1s0[] = {CLS_LandingSite};
+static const uint16_t s7w1s1[] = {CLS_NormalHouse};
+static const StoryStack s7w1s[] = {{0, 1, s7w1s0}, {1, 1, s7w1s1}};
+static const StoryCitizens s7w1c[] = {{3, 20, 25, 0, 60}};
+static const StoryRes s7w2r[] = {{1, CLS_AlienRuins}};
+static const uint16_t s7w2s0[] = {CLS_LandingSite};
+static const StoryStack s7w2s[] = {{0, 1, s7w2s0}};
+static const StoryRes s7w3r[] = {{1, CLS_Forest}, {4, CLS_Forest}, {5, CLS_Forest}, {6, CLS_Forest}, {9, CLS_Forest}, {11, CLS_Forest}, {12, CLS_Forest}, {15, CLS_Forest}};
+static const StoryRes s7w4r[] = {{0, CLS_Forest}, {1, CLS_Forest}, {4, CLS_Forest}, {5, CLS_Forest}, {8, CLS_Forest}, {12, CLS_Forest}, {15, CLS_Forest}, {18, CLS_Forest}};
+static const StoryRes s7w5r[] = {{1, CLS_Forest}, {3, CLS_Forest}, {4, CLS_Forest}, {8, CLS_Forest}, {15, CLS_Forest}, {16, CLS_Forest}, {18, CLS_Forest}, {21, CLS_Forest}};
+static const StoryRes s7w6r[] = {{1, CLS_Rock}, {5, CLS_Rock}, {7, CLS_Rock}, {10, CLS_Rock}, {11, CLS_Rock}, {14, CLS_Rock}, {15, CLS_AlienRuins}};
+static const StoryRes s7w7r[] = {{2, CLS_AlienRuins}};
+static const StoryRes s7w8r[] = {{1, CLS_AlienRuins}, {8, CLS_Rock}, {14, CLS_Rock}, {15, CLS_Rock}, {18, CLS_Rock}, {20, CLS_Rock}, {24, CLS_Rock}};
+static const StoryRes s7w9r[] = {{0, CLS_Forest}, {2, CLS_Forest}, {5, CLS_Forest}, {10, CLS_Forest}, {11, CLS_Forest}, {14, CLS_Forest}};
+static const StoryWorld s7w[] = {
+ {-360, 160, 400, 80, 9101u, 0, 0, 0, 6, s7w0r, 2, s7w0s, 1, s7w0c, 0, NULL},
+ {400, 160, 460, 80, 9102u, 0, 0, 0, 8, s7w1r, 2, s7w1s, 1, s7w1c, 0, NULL},
+ {480, 320, 80, 40, 9103u, 0, 0, 0, 1, s7w2r, 1, s7w2s, 0, NULL, 0, NULL},
+ {-700, 0, 340, 60, 9104u, 0, 0, 0, 8, s7w3r, 0, NULL, 0, NULL, 0, NULL},
+ {-600, 440, 420, 100, 9105u, 0, 0, 0, 8, s7w4r, 0, NULL, 0, NULL, 0, NULL},
+ {-940, 200, 460, 100, 9106u, 0, 0, 0, 8, s7w5r, 0, NULL, 0, NULL, 0, NULL},
+ {740, 400, 340, 80, 9107u, 0, 0, 0, 7, s7w6r, 0, NULL, 0, NULL, 0, NULL},
+ {940, 0, 80, 40, 9108u, 0, 0, 0, 1, s7w7r, 0, NULL, 0, NULL, 0, NULL},
+ {520, 640, 500, 80, 9109u, 0, 0, 0, 7, s7w8r, 0, NULL, 0, NULL, 0, NULL},
+ {-800, 660, 300, 80, 9110u, 0, 0, 0, 6, s7w9r, 0, NULL, 0, NULL, 0, NULL}};
+static const StoryEvent s7g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 50, .betweenMax = 70, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}, {.type = EV_REGULARLY, .time = 0, .amount = 50, .ageMin = 18, .ageMax = 40, .world = 1, .groupMin = 2, .groupMax = 3, .betweenMin = 40, .betweenMax = 50, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}};
+static const StoryGoal s7g[] = {
+ {"FreePlayStart", -1, -1, 0, NULL, 0, NULL, 0, NULL, 2, s7g0e, 0, 0, 0, "Welcome to this Free Play Scenario!\nA few citizens are already here. Some more will arrive over the coming days.", "", ""}};
+static const StoryBackground s7b[] = {{SPR_PLANETS_SMALL, 40, 1, -200, -100, 0.5f}, {SPR_PLANETS_GIANT, 120, 1, -800, 600, 0.4f}, {SPR_PLANETS_BIGGER, 120, 3, -400, -250, 1.0f}, {SPR_PLANETS_MEDIUM, 80, 5, -330, 150, -0.5f}, {SPR_PLANETS_MEDIUM, 80, 3, 500, 320, -0.5f}, {SPR_PLANETS_BIG, 100, 3, 700, -300, 1.0f}, {SPR_PLANETS_SMALL, 40, 1, 300, -240, 0.5f}};
+
+static const StoryRes s8w0r[] = {{0, CLS_Rock}, {2, CLS_Forest}, {1, CLS_AlienRuins}};
+static const uint16_t s8w0s0[] = {CLS_LandedExplorationShip};
+static const uint16_t s8w0s1[] = {CLS_LandingSite};
+static const StoryStack s8w0s[] = {{3, 1, s8w0s0}, {4, 1, s8w0s1}};
+static const StoryCitizens s8w0c[] = {{3, 20, 25, 0, 80}};
+static const StoryWorld s8w[] = {
+ {0, 160, 120, 40, 5601u, 0, 0, 0, 3, s8w0r, 2, s8w0s, 1, s8w0c, 0, NULL}};
+static const StoryEvent s8g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 20, .betweenMax = 30, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}};
+static const StoryGoal s8g[] = {
+ {"FreePlayStart", -1, -1, 0, NULL, 0, NULL, 0, NULL, 1, s8g0e, 0, 0, 0, "Welcome to this Free Play Scenario!\nA few citizens are already here. Some more will arrive over the coming days.", "", ""}};
+static const GenItem s8x0[] = {{CLS_LandingSite, 5, 6, 1}, {CLS_AlienRuins, 3, 4, 0}, {CLS_Forest, 150, 151, 0}, {CLS_Rock, 100, 101, 0}};
+static const WorldGenerator s8x[] = {{400, 401, -1000, 120, 940, 1600, 20, 100, 20, 40, 20, 4, s8x0, true, false, false, true}};
+static const StoryBackground s8b[] = {{SPR_PLANETS_SMALL, 40, 0, -400, -200, 0.31f}, {SPR_PLANETS_SMALL, 40, 2, 300, -300, -0.45f}, {SPR_PLANETS_BIGGER, 120, 0, 600, 100, 1.0f}, {SPR_PLANETS_MEDIUM, 80, 5, -380, 230, -0.5f}, {SPR_PLANETS_BIG, 100, 7, 0, -800, 1.0f}, {SPR_PLANETS_SMALL, 40, 3, -900, -100, 0.2f}, {SPR_PLANETS_BIG, 100, 5, 40, 0, 0.01f}, {SPR_PLANETS_BIG, 100, 1, -800, 500, 0.8f}};
+
+static const StoryRes s9w0r[] = {{2, CLS_Rock}, {3, CLS_Rock}, {4, CLS_AlienRuins}, {10, CLS_Forest}, {12, CLS_Forest}, {14, CLS_Forest}, {15, CLS_Forest}, {18, CLS_Rock}, {19, CLS_Forest}, {21, CLS_AlienRuins}, {22, CLS_Rock}, {23, CLS_Rock}};
+static const uint16_t s9w0s0[] = {CLS_LandedExplorationShip};
+static const StoryStack s9w0s[] = {{5, 1, s9w0s0}};
+static const StoryCitizens s9w0c[] = {{3, 20, 25, 100, 120}};
+static const StoryRes s9w1r[] = {{2, CLS_Rock}, {3, CLS_Rock}, {5, CLS_Rock}};
+static const StoryRes s9w2r[] = {{2, CLS_Forest}, {3, CLS_Rock}, {8, CLS_AlienRuins}};
+static const StoryRes s9w3r[] = {{0, CLS_Forest}};
+static const StoryRes s9w4r[] = {{1, CLS_Rock}, {2, CLS_Forest}, {4, CLS_Rock}, {5, CLS_Forest}};
+static const StoryRes s9w5r[] = {{2, CLS_Forest}, {4, CLS_Forest}, {7, CLS_Rock}, {8, CLS_Forest}, {12, CLS_Rock}};
+static const StoryRes s9w6r[] = {{2, CLS_Forest}};
+static const StoryRes s9w7r[] = {{2, CLS_Rock}, {5, CLS_Rock}, {6, CLS_Rock}, {8, CLS_Forest}};
+static const StoryRes s9w8r[] = {{1, CLS_Rock}};
+static const StoryRes s9w9r[] = {{0, CLS_Rock}, {3, CLS_Rock}, {4, CLS_Forest}, {5, CLS_Forest}};
+static const StoryRes s9w10r[] = {{0, CLS_Rock}, {3, CLS_Rock}, {4, CLS_Forest}, {5, CLS_Forest}};
+static const StoryRes s9w11r[] = {{1, CLS_AlienRuins}};
+static const StoryRes s9w12r[] = {{1, CLS_Rock}};
+static const StoryRes s9w13r[] = {{1, CLS_Rock}, {3, CLS_Rock}, {4, CLS_Forest}};
+static const StoryRes s9w14r[] = {{1, CLS_Forest}, {5, CLS_Rock}, {6, CLS_Rock}, {10, CLS_Forest}, {12, CLS_Forest}, {16, CLS_Rock}, {20, CLS_Rock}, {21, CLS_Forest}, {22, CLS_Rock}, {25, CLS_Rock}, {28, CLS_Forest}};
+static const StoryRes s9w15r[] = {{1, CLS_Forest}, {4, CLS_Rock}, {5, CLS_Rock}};
+static const StoryRes s9w16r[] = {{1, CLS_Forest}};
+static const StoryRes s9w17r[] = {{3, CLS_Rock}, {4, CLS_Rock}, {5, CLS_Forest}, {6, CLS_Rock}, {12, CLS_Rock}, {16, CLS_Forest}, {18, CLS_Rock}};
+static const StoryRes s9w18r[] = {{7, CLS_Forest}, {11, CLS_Forest}, {13, CLS_Rock}, {14, CLS_Rock}, {15, CLS_Forest}, {16, CLS_Forest}, {18, CLS_Forest}, {21, CLS_Rock}};
+static const StoryWorld s9w[] = {
+ {0, 160, 500, 80, 8901u, 0, 0, 0, 12, s9w0r, 1, s9w0s, 1, s9w0c, 0, NULL},
+ {-100, 320, 200, 60, 8902u, 0, 0, 0, 3, s9w1r, 0, NULL, 0, NULL, 0, NULL},
+ {200, 400, 180, 60, 8903u, 0, 0, 0, 3, s9w2r, 0, NULL, 0, NULL, 0, NULL},
+ {420, 280, 60, 40, 8904u, 0, 0, 0, 1, s9w3r, 0, NULL, 0, NULL, 0, NULL},
+ {-20, 500, 140, 40, 8905u, 0, 0, 0, 4, s9w4r, 0, NULL, 0, NULL, 0, NULL},
+ {560, 520, 260, 60, 8906u, 0, 0, 0, 5, s9w5r, 0, NULL, 0, NULL, 0, NULL},
+ {540, 100, 120, 40, 8907u, 0, 0, 0, 1, s9w6r, 0, NULL, 0, NULL, 0, NULL},
+ {580, 300, 180, 60, 8908u, 0, 0, 0, 4, s9w7r, 0, NULL, 0, NULL, 0, NULL},
+ {460, 420, 60, 40, 8909u, 0, 0, 0, 1, s9w8r, 0, NULL, 0, NULL, 0, NULL},
+ {-260, 80, 180, 60, 8910u, 0, 0, 0, 4, s9w9r, 0, NULL, 0, NULL, 0, NULL},
+ {-300, 400, 220, 60, 8911u, 0, 0, 0, 4, s9w10r, 0, NULL, 0, NULL, 0, NULL},
+ {-300, 260, 60, 40, 8912u, 0, 0, 0, 1, s9w11r, 0, NULL, 0, NULL, 0, NULL},
+ {-260, 540, 40, 40, 8913u, 0, 0, 0, 1, s9w12r, 0, NULL, 0, NULL, 0, NULL},
+ {300, 600, 180, 60, 8914u, 0, 0, 0, 3, s9w13r, 0, NULL, 0, NULL, 0, NULL},
+ {40, 860, 600, 100, 8915u, 0, 0, 0, 11, s9w14r, 0, NULL, 0, NULL, 0, NULL},
+ {-100, 840, 140, 60, 8916u, 0, 0, 0, 3, s9w15r, 0, NULL, 0, NULL, 0, NULL},
+ {-180, 740, 60, 40, 8917u, 0, 0, 0, 1, s9w16r, 0, NULL, 0, NULL, 0, NULL},
+ {600, 740, 400, 80, 8918u, 0, 0, 0, 7, s9w17r, 0, NULL, 0, NULL, 0, NULL},
+ {840, 400, 440, 80, 8919u, 0, 0, 0, 8, s9w18r, 0, NULL, 0, NULL, 0, NULL},
+ {1100, 620, 40, 20, 8920u, 0, 0, 0, 0, NULL, 0, NULL, 0, NULL, 0, NULL},
+ {960, 240, 120, 60, 8921u, 0, 0, 0, 0, NULL, 0, NULL, 0, NULL, 0, NULL}};
+static const StoryEvent s9g0e[] = {{.type = EV_REGULARLY, .time = 0, .amount = 100, .ageMin = 18, .ageMax = 40, .world = 0, .groupMin = 2, .groupMax = 3, .betweenMin = 20, .betweenMax = 30, .afterDone = "All the people from your ship have now arrived. Of course, your population can still grow through their offspring."}};
+static const StoryGoal s9g[] = {
+ {"FreePlayStart", -1, -1, 0, NULL, 0, NULL, 0, NULL, 1, s9g0e, 0, 0, 0, "Welcome to this Free Play Scenario!\nA few citizens are already here. Some more will arrive over the coming days.", "", ""}};
+static const StoryBackground s9b[] = {{SPR_PLANETS_SMALL, 40, 1, 0, -300, 0.3f}, {SPR_PLANETS_BIG, 100, 6, 100, -200, 0.8f}, {SPR_PLANETS_MEDIUM, 80, 2, 300, 10, -0.5f}, {SPR_PLANETS_MEDIUM, 80, 0, 300, 320, 0.84f}, {SPR_PLANETS_BIG, 100, 1, -950, 80, 0.9f}, {SPR_PLANETS_BIG, 100, 5, -300, 120, 1.3f}, {SPR_PLANETS_BIGGER, 120, 0, 900, -300, -0.9f}};
+
+const Story stories[] = {
+ {"theLostShip", "A New Beginning", "Earth is a wasteland. You built a space ship, but now food is running out. A tiny world is your only hope.", ST_LOCK_ALL | ST_SPEED_UP_NIGHTS, {[M_FOOD] = 50, [M_STONE] = 7, [M_WOOD] = 0.95, [M_KNOWLEDGE] = 0, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 1, s0w, 13, s0g, 0, 0, NULL, 0, NULL, 270, 50, 6, s0b},
+ {"multipleWorlds", "An Interworld City", "When a world turns out to be way too small, you decide to build a city that crosses worlds.", 0, {[M_FOOD] = 50, [M_STONE] = 5, [M_WOOD] = 3, [M_KNOWLEDGE] = 3, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 7, s1w, 9, s1g, 0, 0, NULL, 0, NULL, 270, 0, 5, s1b},
+ {"hackersandaliens", "Hacking Alien Tech", "You discover some alien influences on your newest outpost.", 0, {[M_FOOD] = 150, [M_STONE] = 10, [M_WOOD] = 10, [M_KNOWLEDGE] = 25, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 10, s2w, 14, s2g, 0, 0, NULL, 0, NULL, 270, 0, 6, s2b},
+ {"cityofthekey", "City of the Key", "The Secret Society of the Key generously invites you to manage their glorious city.", ST_INVITE, {[M_FOOD] = 400, [M_STONE] = 150, [M_WOOD] = 100, [M_KNOWLEDGE] = 200, [M_MACHINEPARTS] = 10, [M_REFINEDMETAL] = 10, [M_COMPUTERCHIPS] = 3}, 3, s3w, 14, s3g, 0, 0, NULL, 0, NULL, 200, 10, 10, s3b},
+ {"FreePlayMegaWorld", "Free Play - Mega World", "Build the city of your dreams on this huge world!", ST_FREEPLAY | ST_INVITE, {[M_FOOD] = 100, [M_STONE] = 20, [M_WOOD] = 20, [M_KNOWLEDGE] = 10, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 1, s4w, 1, s4g, 0, 0, NULL, 0, NULL, 270, 0, 6, s4b},
+ {"FreePlayManyWorldsRandom", "Free Play - Random Archipelago", "Construct a complex city on this random clique of worlds.", ST_FREEPLAY | ST_INVITE, {[M_FOOD] = 100, [M_STONE] = 20, [M_WOOD] = 20, [M_KNOWLEDGE] = 10, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 1, s5w, 1, s5g, 0, 2, s5x, 0, NULL, 270, 0, 7, s5b},
+ {"FreePlayEmptyCanvas", "Free Play - Empty Canvas", "A huge, barren world that you can furnish to your desire, plus some small worlds filled with resources.", ST_FREEPLAY | ST_INVITE, {[M_FOOD] = 100, [M_STONE] = 20, [M_WOOD] = 20, [M_KNOWLEDGE] = 10, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 7, s6w, 1, s6g, 0, 0, NULL, 0, NULL, 450, 0, 7, s6b},
+ {"FreePlayDivided", "Free Play - Divided", "Mind the gap! It separates forests and rocks.", ST_FREEPLAY | ST_INVITE, {[M_FOOD] = 150, [M_STONE] = 20, [M_WOOD] = 20, [M_KNOWLEDGE] = 10, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 10, s7w, 1, s7g, 0, 0, NULL, 0, NULL, 270, 0, 7, s7b},
+ {"FreePlayRandomMiniWorlds", "Free Play - Random Mini Worlds", "Countless tiny worlds, randomly placed in space.", ST_FREEPLAY | ST_INVITE, {[M_FOOD] = 100, [M_STONE] = 20, [M_WOOD] = 20, [M_KNOWLEDGE] = 10, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 1, s8w, 1, s8g, 0, 1, s8x, 0, NULL, 270, 0, 8, s8b},
+ {"FreePlayManyWorlds", "Free Play - Archipelago Classic", "Construct a complex city on this clique of worlds.", ST_FREEPLAY | ST_INVITE, {[M_FOOD] = 100, [M_STONE] = 20, [M_WOOD] = 20, [M_KNOWLEDGE] = 10, [M_MACHINEPARTS] = 0, [M_REFINEDMETAL] = 0, [M_COMPUTERCHIPS] = 0}, 21, s9w, 1, s9g, 0, 0, NULL, 0, NULL, 270, 0, 7, s9b}};
+const int nstories = 10;
diff --git a/games/finalearth2/src/story.c b/games/finalearth2/src/story.c
new file mode 100644
index 00000000..0ac820d0
--- /dev/null
+++ b/games/finalearth2/src/story.c
@@ -0,0 +1,431 @@
+/* The Final Earth 2: running a scenario or free play map (progress.Story,
+ * Story.makeWorlds, City.createBottomWorld, progress.scriptedStoryParts.
+ * SpawnCitizensRegularly, progress.worldGenerators.RandomMiniWorlds and
+ * inviting citizens). */
+#include "bld.h"
+#include "build.h"
+#include "classes.h"
+#include "story.h"
+#include "unlocks.h"
+#include "upgrades.h"
+#include "bg.h"
+
+StoryState story;
+void story_set_name(const char *n);
+
+/* ---------------------------------------------------------------- the worlds */
+/* the world's build of a stack entry (World.build, then postCreate) */
+static void build_on_top(int w, int col, int cls, int decor, bool mirrored) {
+ int y = col_stack_height(w, col);
+ if (y == 0) col_deco[worlds[w].col0 + col] = 0;
+ uint16_t id = perm_new(cls, w, col, y);
+ if (!id) return;
+ bld_on_build(P(id));
+ if (decor >= 0 || mirrored) bld_customize(P(id), decor, mirrored);
+ bld_post_create(P(id));
+}
+
+static void make_world(const StoryWorld *sw) {
+ int w = world_add(sw->x, sw->y, sw->w, sw->h, sw->seed, sw->appearance);
+ if (w < 0) return;
+ worlds[w].flags |= sw->flags;
+ if (sw->decoration) {
+ int kind = 0;
+ for (int k = 1; k < DECO_KINDS; k++)
+ if (bg_deco_sprite(k) == sw->decoration) kind = k;
+ for (int x = 0; x < worlds[w].ncols; x++) bg_set_decoration(col_deco + worlds[w].col0, x, kind, -1, false);
+ }
+ for (int i = 0; i < sw->nres; i++)
+ if (sw->res[i].col < worlds[w].ncols) {
+ col_deco[worlds[w].col0 + sw->res[i].col] = 0;
+ perm_new(sw->res[i].cls, w, sw->res[i].col, 0);
+ }
+ for (int i = 0; i < sw->nstacks; i++) {
+ const StoryStack *st = &sw->stacks[i];
+ for (int k = 0; k < st->n; k++) {
+ uint16_t it = st->items[k];
+ if ((it & 0xFF) == STACK_NULL) {
+ col_height[worlds[w].col0 + st->col]++; /* a hole */
+ continue;
+ }
+ build_on_top(w, st->col, it & 0xFF, (it >> 9) ? (int)(it >> 9) - 1 : -1, (it & STACK_MIRROR) != 0);
+ }
+ }
+ for (int i = 0; i < sw->ndecos; i++) {
+ int kind = 0;
+ for (int k = 1; k < DECO_KINDS; k++)
+ if (bg_deco_sprite(k) == sw->decos[i].sprite) kind = k;
+ bg_set_decoration(col_deco + worlds[w].col0, sw->decos[i].col, kind, -1, perm_at(w, sw->decos[i].col, 0) != NONE);
+ }
+ for (int i = 0; i < sw->ncits; i++) {
+ const StoryCitizens *sc = &sw->cits[i];
+ for (int k = 0; k < sc->amount; k++) {
+ float age = sc->ageMin == sc->ageMax ? sc->ageMin : rnd_range(sc->ageMin, sc->ageMax);
+ int x = sc->minX < 0 ? -1 : sc->minX == sc->maxX ? sc->minX : rnd_between(sc->minX, sc->maxX);
+ cit_create(w, age, NONE, x);
+ }
+ }
+}
+
+/* progress.worldGenerators.RandomMiniWorlds; the calculator holds MAX_WORLDS worlds and MAX_COLS
+ * columns, so a map asking for more (Random Mini Worlds: 400) gets as many as fit, and its
+ * permanents in proportion */
+static bool rect_hits(int x, int y, int w, int h) {
+ for (int i = 0; i < nworlds; i++) {
+ World *o = &worlds[i];
+ if (x < o->x + o->w && x + w > o->x && y < o->y + o->h && y + h > o->y) return true;
+ }
+ return false;
+}
+static int empty_cols(int w) {
+ int n = 0;
+ for (int x = 0; x < worlds[w].ncols; x++)
+ if (col_stack_height(w, x) == 0) n++;
+ return n;
+}
+static void generate(const WorldGenerator *g) {
+ int first = nworlds;
+ int want = rnd_between(g->worldsMin, g->worldsMax);
+ int room = MAX_WORLDS - 2 - nworlds; /* (the bottom world comes after) */
+ float scale = 1;
+ if (want > room) {
+ scale = (float)room / want;
+ want = room;
+ }
+ for (int i = 0; i < want; i++) {
+ for (int tries = 0; tries < 10000; tries++) {
+ int x = rnd_between(g->minX / 20, g->maxX / 20 + 1) * 20;
+ int y = rnd_between(g->minY / 20, g->maxY / 20 + 1) * 20;
+ int w = rnd_between(g->minWidth / 20, g->maxWidth / 20 + 1) * 20;
+ float hf = ((float)(w - g->minWidth) / (g->maxWidth - g->minWidth) * (g->maxHeight - g->minHeight) + g->minHeight +
+ rnd_int(g->heightVariation)) / 20.0f;
+ int h = (int)roundf(hf);
+ h = (h < 1 ? 1 : h > 100 ? 100 : h) * 20;
+ if (rect_hits(x - 20, y - 40, w + 41, h + 61)) continue;
+ world_add(x, y, w, h, (uint32_t)rnd_int(1000000), 0);
+ break;
+ }
+ }
+ int last = nworlds;
+ /* the permanents: buildings first, then world resources */
+ uint8_t list[512];
+ int n = 0;
+ for (int b = 1; b >= 0; b--)
+ for (int i = 0; i < g->nitems; i++) {
+ if (g->items[i].building != (b == 1)) continue;
+ int k = (int)(rnd_between(g->items[i].min, g->items[i].max) * scale + 0.5f);
+ for (int j = 0; j < k && n < 512; j++) list[n++] = g->items[i].cls;
+ }
+ uint8_t build_on[MAX_WORLDS];
+ int nb = 0;
+ for (int w = first; w < last; w++) build_on[nb++] = (uint8_t)w;
+ bool first_resource = true;
+ for (int i = 0; i < n; i++) {
+ bool building = pcls[list[i]].kind == KIND_BUILDING;
+ if (!building && first_resource) {
+ first_resource = false;
+ if (g->rememberSpread) {
+ nb = 0;
+ for (int w = first; w < last; w++) build_on[nb++] = (uint8_t)w;
+ }
+ }
+ bool spread = building ? g->spreadBuildings : g->spreadResources;
+ for (int attempt = 0; attempt < 2; attempt++) {
+ /* candidates: every empty column of the worlds allowed */
+ int count = 0;
+ for (int w = first; w < last; w++) {
+ bool ok = !spread;
+ for (int k = 0; k < nb && !ok; k++) ok = build_on[k] == w;
+ if (!ok) continue;
+ if (!building && g->avoidOverfull && (worlds[w].ncols <= 1 || empty_cols(w) <= 1)) continue;
+ count += empty_cols(w);
+ }
+ if (count == 0) {
+ nb = 0;
+ for (int w = first; w < last; w++) build_on[nb++] = (uint8_t)w;
+ continue;
+ }
+ int pick = rnd_int(count);
+ for (int w = first; w < last && pick >= 0; w++) {
+ bool ok = !spread;
+ for (int k = 0; k < nb && !ok; k++) ok = build_on[k] == w;
+ if (!ok) continue;
+ if (!building && g->avoidOverfull && (worlds[w].ncols <= 1 || empty_cols(w) <= 1)) continue;
+ for (int x = 0; x < worlds[w].ncols; x++) {
+ if (col_stack_height(w, x) != 0) continue;
+ if (pick-- == 0) {
+ for (int k = 0; k < nb; k++)
+ if (build_on[k] == w) { build_on[k] = build_on[--nb]; break; }
+ if (building) build_on_top(w, x, list[i], -1, false);
+ else {
+ col_deco[worlds[w].col0 + x] = 0;
+ perm_new(list[i], w, x, 0);
+ }
+ break;
+ }
+ }
+ }
+ break;
+ }
+ }
+}
+
+/* City.createBottomWorld: an invisible world under the whole city */
+static void create_bottom_world(void) {
+ int minx = 1 << 30, maxx = -(1 << 30), maxy = -(1 << 30);
+ for (int i = 0; i < nworlds; i++) {
+ World *w = &worlds[i];
+ if (w->x < minx) minx = w->x;
+ if (w->x + w->w > maxx) maxx = w->x + w->w;
+ if (w->y + w->h > maxy) maxy = w->y + w->h;
+ }
+ minx = (minx - 20) / 20 * 20;
+ world_add(minx, ((maxy + 40) + 19) / 20 * 20, maxx - minx + 20, 0, 0, 0);
+}
+
+/* ---------------------------------------------------------------- goals */
+static int count_class(int cls, int world, int not_world) {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED)) continue;
+ if (!class_is(p->cls, cls)) continue;
+ if (world >= 0 && p->world != world) continue;
+ if (not_world >= 0 && p->world == not_world) continue;
+ n++;
+ }
+ return n;
+}
+
+static bool subgoal_complete(const SubGoal *s) {
+ switch (s->type) {
+ case SG_BUILDPERMANENTS: return count_class(s->cls, s->world, s->notWorld) >= s->amount;
+ case SG_GATHERMATERIALS:
+ for (int m = 0; m < M_COUNT; m++)
+ if (s->mats[m] > 0 && city.materials.m[m] < s->mats[m]) return false;
+ return true;
+ case SG_PRODUCTIONGOAL:
+ for (int m = 0; m < M_COUNT; m++) {
+ if (s->mats[m] <= 0) continue;
+ bool ok = false;
+ for (int d = 0; d < STATS_DAYS; d++)
+ if (stats.materialProduction[m][d] >= s->mats[m]) ok = true;
+ if (!ok) return false;
+ }
+ return true;
+ case SG_PERFORMBUILDINGUPGRADES: return upgrades_buildings_with(s->name) >= s->amount;
+ case SG_PERFORMCITYUPGRADE: return upgrades_city_bought(s->name);
+ case SG_MINIMUMHAPPINESS: return happiness.happiness >= s->value;
+ case SG_MINIMUMCITIZENS: return ncits >= s->amount;
+ case SG_HOUSINGCAPACITY: return stats.houseCapacity >= s->amount;
+ case SG_WAIT: return story.goalTimer > s->value;
+ case SG_INVITEPEOPLE: return story.justInvitedPeople;
+ case SG_EXPLOREALIENRUINS: return bld_alien_ruins_explored() >= 99.99f;
+ case SG_EXPLOREDWITHRESEARCHSPACECRAFT: return bld_research_bot_time() >= 540;
+ case SG_COMPLETEHACKERMISSIONS: return bld_hacker_mission() >= s->amount;
+ case SG_WAITFORDECRYPTION: return bld_decryptor_time() >= 1440;
+ case SG_GLORYGOAL: return glory_of_the_key_happiness() >= 99.99f;
+ }
+ return false;
+}
+bool story_subgoal_complete(int i) {
+ const StoryGoal *g = story_goal();
+ return g && i < g->nsub && subgoal_complete(&g->sub[i]);
+}
+
+const StoryGoal *story_goal(void) {
+ return story.goal >= 0 ? &stories[story.index].goals[story.goal] : NULL;
+}
+
+static void handle_flags(const StoryGoal *g) {
+ if (g->flagsSet & GF_DISABLEDYING) city.disableDying = (g->flagsValue & GF_DISABLEDYING) != 0;
+ if (g->flagsSet & GF_DISABLEDESTROY) story.disableDestroy = (g->flagsValue & GF_DISABLEDESTROY) != 0;
+ if (g->flagsSet & GF_HIDDENBOOST) story.hiddenBoost = (g->flagsValue & GF_HIDDENBOOST) != 0;
+ if ((g->flagsSet & GF_SETBUILDABLEALIENS) && (g->flagsValue & GF_SETBUILDABLEALIENS))
+ for (int w = 0; w < nworlds; w++) worlds[w].flags &= (uint8_t)~WF_UNBUILDABLE_ALIENS;
+}
+
+static void start_goal(int gi) {
+ const Story *st = &stories[story.index];
+ const StoryGoal *g = &st->goals[gi];
+ story.goal = (int8_t)gi;
+ story.goalTimer = 0;
+ handle_flags(g);
+ if (!strcmp(g->name, "Win")) meta_win_scenario(story.index, (float)city.timeSinceStart);
+ if (g->text || g->title) ui_show_goal_text(gi);
+ for (int i = 0; i < g->nunlocks; i++) {
+ const char *u = g->unlocks[i];
+ if (!strcmp(u, "decorations")) unlocks.unlockedDecorationTab = true;
+ else if (!strcmp(u, "buildingModes")) unlocks.unlockedBuildingModeButton = true;
+ else if (!strcmp(u, "managementOptions")) unlocks.unlockedManagementOptions = true;
+ else unlocks_unlock(u);
+ }
+ for (int i = 0; i < g->nresearches; i++) {
+ int c = pcls_find(g->researches[i]);
+ if (c >= 0) unlocks_research_uid(c);
+ }
+ if (g->nevents && story.nplannings < STORY_MAX_PLANNINGS) {
+ StoryPlanning *pl = &story.plannings[story.nplannings++];
+ pl->goal = (uint8_t)gi;
+ pl->next = 0;
+ pl->timeStart = (float)(city.timeSinceStart / 60);
+ }
+ if (g->tutorial) ui_show_tutorial(g->tutorial);
+}
+
+/* SpawnCitizensRegularly */
+static void regularly_start(int goal, int event) {
+ if (story.nregular >= STORY_MAX_REGULAR) return;
+ Regularly *r = &story.regular[story.nregular++];
+ const StoryEvent *e = &stories[story.index].goals[goal].events[event];
+ r->goal = (uint8_t)goal;
+ r->event = (uint8_t)event;
+ r->left = e->amount;
+ r->nextSpawn = 0;
+}
+static bool regularly_update(Regularly *r) {
+ const StoryEvent *e = &stories[story.index].goals[r->goal].events[r->event];
+ if (r->left > 0 && city.timeSinceStart >= r->nextSpawn) {
+ int n = rnd_between(e->groupMin, e->groupMax + 1);
+ if (n > r->left) n = r->left;
+ r->left -= n;
+ saucer_spawn(e->world, n, e->ageMin, e->ageMax, -1);
+ float m = 1;
+ if (stats.houseCapacity > stats.peopleWithHome + e->groupMin && stats.jobs > stats.laborForce + e->groupMin && r->left > 5)
+ m = city.materials.m[M_FOOD] > 10 ? 0.6f : 0.7f;
+ r->nextSpawn = city.timeSinceStart + 60.0 * m * rnd_range(e->betweenMin, e->betweenMax);
+ }
+ if (r->left <= 0 && spawners_pending() == 0) {
+ if (e->afterDone) ui_show_message(e->afterDone);
+ return false;
+ }
+ return true;
+}
+
+void story_update(float timeMod) {
+ const Story *st = &stories[story.index];
+ if (story.goal >= 0 && !ui_story_window_open()) {
+ const StoryGoal *g = &st->goals[story.goal];
+ bool done = true;
+ for (int i = 0; i < g->nsub; i++)
+ if (!subgoal_complete(&g->sub[i])) done = false;
+ if (done) {
+ if (g->next >= 0) start_goal(g->next);
+ else story.goal = -1;
+ }
+ }
+ /* plannings: each event fires its time (game hours) after its goal started */
+ for (int i = story.nplannings - 1; i >= 0; i--) {
+ StoryPlanning *pl = &story.plannings[i];
+ const StoryGoal *g = &st->goals[pl->goal];
+ if (pl->next < g->nevents) {
+ const StoryEvent *e = &g->events[pl->next];
+ if (pl->timeStart + e->time < city.timeSinceStart / 60) {
+ if (e->type == EV_SAUCER) saucer_spawn(e->world, e->amount, e->ageMin, e->ageMax, -1);
+ else regularly_start(pl->goal, pl->next);
+ pl->next++;
+ }
+ }
+ if (pl->next >= g->nevents) story.plannings[i] = story.plannings[--story.nplannings];
+ }
+ for (int i = story.nregular - 1; i >= 0; i--)
+ if (!regularly_update(&story.regular[i])) story.regular[i] = story.regular[--story.nregular];
+ story.goalTimer += timeMod;
+}
+
+/* ---------------------------------------------------------------- a new city */
+void story_new_city(int index, const NewCityOptions *opt) {
+ game_reset();
+ memset(&story, 0, sizeof story);
+ story.index = (uint8_t)index;
+ story.goal = -1;
+ const Story *st = &stories[index];
+ story_set_name(st->link);
+ unlocks_init();
+ city.speedUpStartNights = (st->flags & ST_SPEED_UP_NIGHTS) != 0;
+ for (int i = 0; i < st->nworlds; i++) make_world(&st->worlds[i]);
+ for (int i = 0; i < st->ngens; i++) generate(&st->gens[i]);
+ create_bottom_world();
+ /* Story.start */
+ for (int m = 0; m < M_COUNT; m++) city.materials.m[m] += st->initialMaterials[m];
+ for (int i = 0; i < st->nlocks; i++) unlocks_lock(st->locks[i]);
+ if (st->flags & ST_LOCK_ALL) {
+ unlocks.unlockedDecorationTab = unlocks.unlockedBuildingModeButton = unlocks.unlockedManagementOptions = false;
+ for (int c = 0; c < npcls; c++)
+ if (pcls[c].kind == KIND_BUILDING) unlocks_lock_uid(c);
+ }
+ /* free play options: extra resources, and more or fewer citizens to start with */
+ if (opt && (st->flags & ST_FREEPLAY)) {
+ int have = ncits;
+ if (opt->extraResources) {
+ static const float extra[M_COUNT] = {[M_WOOD] = 1000, [M_STONE] = 1000, [M_FOOD] = 1000, [M_MACHINEPARTS] = 100, [M_KNOWLEDGE] = 500};
+ memset(&city.materials, 0, sizeof city.materials);
+ for (int m = 0; m < M_COUNT; m++) city.materials.m[m] = extra[m];
+ city.materials.m[M_FOOD] += 3.0 * (have > 3 ? have - 3 : 0);
+ }
+ if (opt->citizens > 0 && opt->citizens != have) {
+ int w = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) { w = cits[i].onWorld; break; }
+ while (ncits < opt->citizens) {
+ cit_create(w, rnd_range(18, 40), NONE, -1);
+ city.materials.m[M_FOOD] += 3;
+ }
+ for (int i = MAX_CITS - 1; i >= 1 && ncits > opt->citizens; i--)
+ if (cits[i].flags & CF_ALIVE) {
+ cit_try_remove(&cits[i], true);
+ city.materials.m[M_FOOD] -= 3;
+ }
+ }
+ }
+ start_goal(st->startGoal);
+ if (story_is("cityofthekey")) happiness.gloryOfTheKey = true;
+ city_update_connections();
+ sim_update_pathfinder(true, NONE);
+ unlocks_stop_all_notify();
+}
+
+/* ---------------------------------------------------------------- inviting citizens (InvitePeopleWindow) */
+static int invite_population(void) { return ncits + spawners_pending(); }
+void invite_price(float cost[M_COUNT]) {
+ memset(cost, 0, sizeof(float) * M_COUNT);
+ int n = invite_population();
+ if (n <= 500) {
+ int k = n / 10 - 5;
+ cost[M_FOOD] = 10.0f * (k > 1 ? k : 1);
+ } else {
+ cost[M_FOOD] = 10.0f * (n / 10 + 1);
+ cost[M_REFINEDMETAL] = 10.0f * (n / 50 - 8);
+ if (n > 5000) cost[M_COMPUTERCHIPS] = 50;
+ }
+}
+/* why one can't invite now (0 if one can): 1 the limit, 2 not enough homes, 3 not enough materials */
+int invite_problem(void) {
+ int n = invite_population();
+ int limit = (stories[story.index].flags & ST_FREEPLAY) ? babies.softPopLimit : 1900;
+ if (n + 10 >= limit) return 1;
+ if (stats.houseCapacity < n + 10) return 2;
+ float cost[M_COUNT];
+ invite_price(cost);
+ return mat_can_afford(cost) ? 0 : 3;
+}
+bool invite_citizens(void) {
+ if (invite_problem()) return false;
+ float cost[M_COUNT];
+ invite_price(cost);
+ mat_pay(cost);
+ story.justInvitedPeople = true;
+ /* to the top-most world with citizens (in cityofthekey the top-most of all) */
+ int best = -1;
+ bool key = story_is("cityofthekey");
+ for (int w = 0; w < nworlds; w++) {
+ if (worlds[w].h == 0) continue;
+ bool has = key;
+ for (int i = 1; i < MAX_CITS && !has; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].onWorld == w) has = true;
+ if (!has) continue;
+ if (best < 0 || worlds[w].y < worlds[best].y || (worlds[w].y == worlds[best].y && worlds[w].x < worlds[best].x)) best = w;
+ }
+ saucer_spawn(best < 0 ? 0 : best, 10, 18, 22, -1);
+ return true;
+}
diff --git a/games/finalearth2/src/story.h b/games/finalearth2/src/story.h
new file mode 100644
index 00000000..b5a3579d
--- /dev/null
+++ b/games/finalearth2/src/story.h
@@ -0,0 +1,135 @@
+/* The Final Earth 2: scenarios and free play maps (progress.Story): their
+ * data (stories_data.c, made by tools/gen_stories.py) and their running
+ * (story.c). */
+#ifndef FE_STORY_H
+#define FE_STORY_H
+#include "fe.h"
+
+/* a building stack's entry: a class, or a hole; mirrored; a decoration's look + 1 */
+#define STACK_NULL 0xFF
+#define STACK_MIRROR 0x100
+#define STACK_DECOR(n) (((n) + 1) << 9)
+
+typedef struct { uint8_t col, cls; } StoryRes;
+typedef struct { uint8_t col, n; const uint16_t *items; } StoryStack;
+typedef struct { uint16_t amount; uint8_t ageMin, ageMax; int16_t minX, maxX; } StoryCitizens;
+typedef struct { uint8_t col; uint16_t sprite; } StoryDeco;
+typedef struct {
+ int16_t x, y, w, h;
+ uint32_t seed;
+ uint8_t appearance; /* 0 normal, 1 "key", 2 "key2" */
+ uint8_t flags; /* WF_* */
+ uint16_t decoration; /* sprite for every column, 0: grass */
+ uint8_t nres; const StoryRes *res;
+ uint8_t nstacks; const StoryStack *stacks;
+ uint8_t ncits; const StoryCitizens *cits;
+ uint8_t ndecos; const StoryDeco *decos;
+} StoryWorld;
+
+enum {
+ SG_BUILDPERMANENTS, SG_GATHERMATERIALS, SG_PRODUCTIONGOAL, SG_PERFORMBUILDINGUPGRADES, SG_PERFORMCITYUPGRADE,
+ SG_MINIMUMHAPPINESS, SG_MINIMUMCITIZENS, SG_HOUSINGCAPACITY, SG_WAIT, SG_INVITEPEOPLE, SG_EXPLOREALIENRUINS,
+ SG_EXPLOREDWITHRESEARCHSPACECRAFT, SG_COMPLETEHACKERMISSIONS, SG_WAITFORDECRYPTION, SG_GLORYGOAL
+};
+typedef struct {
+ uint8_t type;
+ uint8_t cls;
+ int8_t world, notWorld; /* BuildPermanents: only on (or not on) that world, -1 any */
+ uint16_t amount;
+ float value;
+ const char *name; /* an upgrade's class */
+ float mats[M_COUNT];
+} SubGoal;
+
+enum { EV_SAUCER, EV_REGULARLY };
+typedef struct {
+ uint8_t type;
+ float time; /* game hours after the goal starts */
+ uint16_t amount; /* a saucer's citizens, or SpawnCitizensRegularly's spawnNumber */
+ uint8_t ageMin, ageMax, world;
+ uint8_t groupMin, groupMax;
+ float betweenMin, betweenMax; /* hours */
+ const char *afterDone;
+} StoryEvent;
+
+enum { GF_DISABLEDYING = 1, GF_DISABLEDESTROY = 2, GF_HIDDENBOOST = 4, GF_SETBUILDABLEALIENS = 8 };
+typedef struct {
+ const char *name;
+ int8_t next; /* the next goal's index, -1 none */
+ int8_t nextStory; /* index in stories[], -1 none */
+ uint8_t nsub; const SubGoal *sub;
+ uint8_t nunlocks; const char *const *unlocks;
+ uint8_t nresearches; const char *const *researches;
+ uint8_t nevents; const StoryEvent *events;
+ uint8_t flagsSet, flagsValue; /* GF_*: which the goal sets, and to what */
+ uint16_t tutorial;
+ const char *text, *quickText, *title;
+} StoryGoal;
+
+typedef struct { uint8_t cls; uint8_t min, max; bool building; } GenItem;
+typedef struct {
+ int16_t worldsMin, worldsMax, minX, minY, maxX, maxY, minWidth, maxWidth, minHeight, maxHeight, heightVariation;
+ uint8_t nitems; const GenItem *items;
+ bool spreadBuildings, spreadResources, rememberSpread, avoidOverfull;
+} WorldGenerator;
+
+typedef struct { uint16_t sprite; int16_t width, image, x, y; float velocity; } StoryBackground;
+
+enum { ST_FREEPLAY = 1, ST_LOCK_ALL = 2, ST_INVITE = 4, ST_SPEED_UP_NIGHTS = 8, ST_NO_EXTRA_RESOURCES = 16 };
+typedef struct {
+ const char *link, *name, *description;
+ uint8_t flags;
+ float initialMaterials[M_COUNT];
+ uint8_t nworlds; const StoryWorld *worlds;
+ uint8_t ngoals; const StoryGoal *goals;
+ uint8_t startGoal;
+ uint8_t ngens; const WorldGenerator *gens;
+ uint8_t nlocks; const char *const *locks;
+ int16_t viewYFromBottom, viewStartX;
+ uint8_t nbackgrounds; const StoryBackground *backgrounds;
+} Story;
+
+extern const Story stories[];
+extern const int nstories;
+
+/* ---------------------------------------------------------------- the running story (story.c) */
+#define STORY_MAX_PLANNINGS 4
+#define STORY_MAX_REGULAR 4
+typedef struct { uint8_t goal, next; float timeStart; } StoryPlanning; /* timeStart in game hours */
+typedef struct { uint8_t goal, event; int left; double nextSpawn; } Regularly; /* a SpawnCitizensRegularly running */
+typedef struct {
+ uint8_t index; /* in stories[] */
+ int8_t goal; /* the current goal, -1 none */
+ float goalTimer;
+ bool justInvitedPeople, disableDestroy, hiddenBoost;
+ uint8_t nplannings, nregular;
+ StoryPlanning plannings[STORY_MAX_PLANNINGS];
+ Regularly regular[STORY_MAX_REGULAR];
+} StoryState;
+extern StoryState story;
+
+typedef struct { bool extraResources; int citizens; } NewCityOptions; /* free play: citizens 0 = the map's */
+void story_new_city(int index, const NewCityOptions *opt);
+void story_update(float timeMod);
+const StoryGoal *story_goal(void);
+bool story_subgoal_complete(int i);
+void invite_price(float cost[M_COUNT]);
+int invite_problem(void);
+bool invite_citizens(void);
+
+/* from the buildings (bld*.c, upgrades.c) */
+int upgrades_buildings_with(const char *upgrade); /* buildings owning that upgrade */
+bool upgrades_city_bought(const char *upgrade);
+float bld_alien_ruins_explored(void); /* the first ComputerAlienRuins' explored */
+float bld_research_bot_time(void); /* the first ResearchBot's timeWorking */
+float bld_hacker_mission(void); /* the first HackerHQ's currentMission, -1 none */
+float bld_decryptor_time(void); /* the first AlienDecryptor's timeWorking */
+void bld_customize(Perm *p, int decor, bool mirrored);
+void saucer_spawn(int world, int amount, int ageMin, int ageMax, int toCol);
+/* from the user interface */
+void ui_show_goal_text(int goal);
+void ui_show_tutorial(int tutorial);
+void ui_show_message(const char *text);
+bool ui_story_window_open(void);
+void meta_win_scenario(int story, float time); /* MetaGame: the best time of a won scenario */
+#endif
diff --git a/games/finalearth2/src/systems.c b/games/finalearth2/src/systems.c
new file mode 100644
index 00000000..f5c37633
--- /dev/null
+++ b/games/finalearth2/src/systems.c
@@ -0,0 +1,560 @@
+/* The Final Earth 2: city-wide systems (simulation.Stats, Eating,
+ * BabyMaker, Happiness, HappinessBoost, OperatingCost, BoostManager). */
+#include "bld.h"
+#include "save.h"
+#include "scratch.h"
+#include "classes.h"
+#include "story.h"
+#include "unlocks.h"
+
+Bonuses bonuses;
+static void glory_update(void);
+
+/* ---------------------------------------------------------------- Stats */
+Stats stats;
+static float stats_update_in = -1;
+
+void stats_add_production(int m, double amount) { stats.materialProduction[m][0] += amount; }
+void stats_add_used(int m, double amount) { stats.materialUsed[m][0] += amount; }
+void mat_add(int m, double amount) {
+ city.materials.m[m] += amount;
+ stats_add_production(m, amount);
+}
+bool mat_take(int m, double amount) {
+ if (city.materials.m[m] < amount) return false;
+ city.materials.m[m] -= amount;
+ stats_add_used(m, amount);
+ return true;
+}
+bool mat_can_afford(const float cost[M_COUNT]) {
+ for (int i = 0; i < M_COUNT; i++)
+ if (city.materials.m[i] < cost[i]) return false;
+ return true;
+}
+void mat_pay(const float cost[M_COUNT]) {
+ for (int i = 0; i < M_COUNT; i++) city.materials.m[i] -= cost[i];
+}
+void stats_on_commute(float minutes) { stats.lastMorningCommute = minutes; }
+
+void stats_update(float timeMod) {
+ if (stats_update_in <= 0) {
+ stats.laborForce = stats.peopleWithAJob = stats.peopleWithHome = stats.children = 0;
+ stats.houseCapacity = stats.peopleWorkingAtLabs = stats.jobs = 0;
+ stats.people = ncits;
+ eating.herbsCap = 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ if (cit_age(c) >= 16) {
+ stats.laborForce++;
+ if (c->job) {
+ stats.peopleWithAJob++;
+ if (bld_is_lab(P(c->job))) stats.peopleWorkingAtLabs++;
+ }
+ } else {
+ stats.children++;
+ }
+ if (c->home) stats.peopleWithHome++;
+ }
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED)) continue;
+ if (is_a(p, B_HOUSE)) stats.houseCapacity += bld_residents(p);
+ if (is_a(p, B_WORK)) stats.jobs += bld_jobs(p);
+ eating.herbsCap += bld_herb_capacity(p);
+ }
+ stats_update_in += 20;
+ unlocks_check_stat_related();
+ } else {
+ stats_update_in -= timeMod > 1 ? timeMod : 1;
+ }
+}
+
+void stats_midnight_update(void) {
+ for (int m = 0; m < M_COUNT; m++) {
+ for (int i = STATS_DAYS - 1; i >= 1; i--) {
+ stats.materialProduction[m][i] = stats.materialProduction[m][i - 1];
+ stats.materialUsed[m][i] = stats.materialUsed[m][i - 1];
+ }
+ stats.materialProduction[m][0] = stats.materialUsed[m][0] = 0;
+ }
+}
+
+/* ---------------------------------------------------------------- Eating */
+EatingState eating = {.totalConsumedFoodPerDay = -1};
+
+void eating_update(float timeMod) {
+ float time = city_hour();
+ eating.currentFoodSaveByHerbsPct = eating.totalConsumedFoodPerDay != 0 ? fminf(1, eating.herbsCap / eating.totalConsumedFoodPerDay) : 0;
+ float saved = 0.2f * fminf(eating.totalConsumedFoodPerDay, eating.herbsCap);
+ eating.totalConsumedFoodPerDay = ncits - stats.children * 0.5f;
+ eating.totalConsumedFoodPerDay -= saved;
+ if (eating.foodRationing) eating.totalConsumedFoodPerDay *= 0.5f;
+ double *food = &city.materials.m[M_FOOD];
+ if (time >= 7 && time < 20) {
+ float part = city.minutesPerTick * timeMod / 60 / (20 - 7);
+ double wants = fmax(0, eating.totalConsumedFoodPerDay * part);
+ double now = fmin(*food, wants);
+ *food -= now;
+ stats_add_used(M_FOOD, now);
+ eating.foodShortage += (float)(wants - now);
+ eating.foodShortage = fminf(eating.foodShortage, ceilf(eating.totalConsumedFoodPerDay / 2));
+ }
+ if (eating.foodShortage > 0 && *food > 0.1) {
+ double r = fmin(*food, eating.foodShortage);
+ eating.foodShortage -= (float)r;
+ *food -= r;
+ stats_add_used(M_FOOD, r);
+ if (*food > 0) eating.foodShortage = 0;
+ }
+}
+
+/* ---------------------------------------------------------------- BabyMaker */
+BabyMakerState babies = {.softPopLimit = MAX_CITS - 1, .targetPopAmount = -1, .updateStatsIn = -2};
+static float baby_capacity[MAX_WORLDS], babies_per_year[MAX_WORLDS], people_per_world[MAX_WORLDS];
+static float total_baby_capacity;
+
+static float baby_production(void) {
+ if (happiness.happiness < 10 && stats.peopleWithHome < stats.people / 2 && city.materials.m[M_FOOD] < 1) return 0;
+ if (happiness.happiness < 10) return 0.8f;
+ float scale = powf((powf((float)ncits, 1.2f) + 500) / 1400, 0.4f);
+ switch (babies.mode) {
+ case 0: return 1 + happiness.happiness / 140 / scale;
+ case 1: return babies.targetPopAmount == -1 ? 1 : ncits >= babies.targetPopAmount ? 0.1f : 3.0f;
+ case 2: return 1 + 0.4f * (happiness.happiness / 140) / scale;
+ default: return 1 + (happiness.happiness / 140 + fmaxf(0, (happiness.happiness - 60) / 120)) / scale;
+ }
+}
+static void baby_update_stats(void) {
+ memset(baby_capacity, 0, sizeof baby_capacity);
+ memset(people_per_world, 0, sizeof people_per_world);
+ float total = 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ float age = cit_age(c);
+ float add = age >= 20 && age < 45 ? 1 : age >= 45 && age < 55 ? 1 - (age - 45) / 10 : 0;
+ baby_capacity[c->onWorld] += add;
+ if (age >= 20) people_per_world[c->onWorld] += 1;
+ total += add;
+ }
+ float per = baby_production();
+ for (int w = 0; w < nworlds; w++) {
+ if (ncits > 300 && total < 0.1f * ncits && baby_capacity[w] < 0.1f * people_per_world[w]) baby_capacity[w] = 0.1f * people_per_world[w];
+ babies_per_year[w] = baby_capacity[w] * per / 30.0f;
+ total_baby_capacity += baby_capacity[w];
+ }
+}
+static void create_baby(int w) {
+ if (ncits == 0) return;
+ /* a random citizen of that world aged 20 to 55 (else the first) */
+ int n = 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if ((c->flags & CF_ALIVE) && c->onWorld == w && cit_age(c) >= 20 && cit_age(c) < 55) n++;
+ }
+ Cit *parent = NULL;
+ if (n) {
+ int k = rnd_int(n);
+ for (int i = 1; i < MAX_CITS && !parent; i++) {
+ Cit *c = &cits[i];
+ if ((c->flags & CF_ALIVE) && c->onWorld == w && cit_age(c) >= 20 && cit_age(c) < 55 && k-- == 0) parent = c;
+ }
+ } else {
+ for (int i = 1; i < MAX_CITS && !parent; i++)
+ if (cits[i].flags & CF_ALIVE) parent = &cits[i];
+ }
+ cit_create(parent->onWorld, 0, parent->inPermanent, (int)parent->relativeX); /* (createCitizen: a hobby maybe) */
+}
+void baby_update(float timeMod) {
+ if (babies.updateStatsIn <= 0) {
+ babies.updateStatsIn += 60;
+ baby_update_stats();
+ }
+ babies.updateStatsIn -= timeMod;
+ float years = city.minutesPerTick * timeMod / 60 / 24;
+ for (int w = 0; w < nworlds; w++)
+ if (ncits + spawners_pending() < babies.softPopLimit && ncits >= 2 && baby_capacity[w] >= 2 && rnd_float() < babies_per_year[w] * years)
+ create_baby(w);
+}
+void baby_on_citizen_death(void) {
+ if (ncits != babies.softPopLimit) return;
+ if (total_baby_capacity == 0) baby_update_stats();
+ if (total_baby_capacity == 0) return;
+ float r = rnd_float();
+ int w = 0;
+ for (int i = 0; i < nworlds; i++) {
+ r -= baby_capacity[i] / total_baby_capacity;
+ if (r <= 0) w = i;
+ }
+ create_baby(w);
+}
+
+/* ---------------------------------------------------------------- Happiness */
+#define MAX_BOOSTS 8
+static struct { double until; float boost; bool canGoOverMax; uint8_t text; } boosts[MAX_BOOSTS];
+static int nboosts;
+static float update_happiness_in;
+
+void happiness_add_boost(double until, float boost, bool over_max, uint8_t text) {
+ if (nboosts < MAX_BOOSTS) boosts[nboosts++] = (typeof(boosts[0])){until, boost, over_max, text};
+}
+/* happinessBoosts, for the happiness window and the panel's tooltip */
+int happiness_boosts(void) { return nboosts; }
+float happiness_boost(int i, uint8_t *text) {
+ *text = boosts[i].text;
+ return boosts[i].boost;
+}
+/* saved with the city (HappinessBoost.save: until, boost, its text, canGoOverMax) */
+void boosts_save(SaveIO *io) {
+ save_u8(io, (uint8_t)nboosts);
+ for (int i = 0; i < nboosts; i++) {
+ save_f64(io, boosts[i].until);
+ save_f32(io, boosts[i].boost);
+ save_u8(io, boosts[i].text);
+ save_u8(io, boosts[i].canGoOverMax);
+ }
+}
+bool boosts_load(SaveIO *io) {
+ int n = load_u8(io);
+ if (n > MAX_BOOSTS) return false;
+ nboosts = 0;
+ for (int i = 0; i < n; i++) {
+ double until = load_f64(io);
+ float boost = load_f32(io);
+ uint8_t text = load_u8(io);
+ happiness_add_boost(until, boost, load_u8(io) != 0, text);
+ }
+ return true;
+}
+
+/* the entertainment, medical care and citizens of each group of worlds */
+static float actual_happiness(void) {
+ static float ent_per_group[MAX_WORLDS], cits_per_group[MAX_WORLDS];
+ int ngroups = 0;
+ for (int w = 0; w < nworlds; w++)
+ if (worlds[w].group + 1 > ngroups) ngroups = worlds[w].group + 1;
+ memset(ent_per_group, 0, sizeof ent_per_group);
+ memset(cits_per_group, 0, sizeof cits_per_group);
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED)) continue;
+ ent_per_group[worlds[p->world].group] += bld_entertainment_capacity(p);
+ }
+ happiness.homeHappiness = happiness.schoolHappiness = happiness.purposeHappiness = 0;
+ int kids = 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ if (c->home) happiness.homeHappiness += bld_attractiveness(P(c->home));
+ if (c->job) happiness.purposeHappiness += 100;
+ else if (cit_age(c) < 16) {
+ kids++;
+ if (c->school) happiness.schoolHappiness += 100, happiness.purposeHappiness += 100;
+ }
+ cits_per_group[worlds[c->onWorld].group] += 1;
+ }
+ if (ncits > 0) happiness.homeHappiness /= ncits, happiness.purposeHappiness /= ncits;
+ if (kids > 0) happiness.schoolHappiness /= kids;
+ else {
+ happiness.schoolHappiness = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_a(&perms[i], B_SCHOOL) && perms[i].nworkers >= 1) { happiness.schoolHappiness = 100; break; }
+ }
+ memset(happiness.perEntertainmentType, 0, sizeof happiness.perEntertainmentType);
+ happiness.entertainmentHappiness = happiness.medicalHappiness = 0;
+ memset(happiness.healthCapacityByType, 0, sizeof happiness.healthCapacityByType);
+ happiness.numberOfGroupsWithCitizens = 0;
+ uint16_t *list = scratch->u.happy.list;
+ for (int g = 0; g < ngroups; g++) {
+ if (cits_per_group[g] == 0) continue;
+ happiness.numberOfGroupsWithCitizens++;
+ float this_ent = 32.999999999999993f * fminf(ent_per_group[g], cits_per_group[g]);
+ /* each of the five entertainment types: the best buildings first, as many citizens as they hold */
+ for (int t = 0; t < 5; t++) {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || !(p->flags & PF_IS_ENTERTAINMENT) || worlds[p->world].group != g) continue;
+ if (ent_type(p) == t || (bld_secondary_entertainment_types(p) >> t & 1)) list[n++] = (uint16_t)i;
+ }
+ for (int a = 1; a < n; a++) { /* by quality, best first (stable) */
+ uint16_t k = list[a];
+ int b = a - 1;
+ while (b >= 0 && bld_entertainment_quality(P(list[b])) < bld_entertainment_quality(P(k))) list[b + 1] = list[b], b--;
+ list[b + 1] = k;
+ }
+ float left = cits_per_group[g], part = 0;
+ for (int a = 0; a < n; a++) {
+ Perm *p = P(list[a]);
+ float cap = bld_entertainment_capacity(p);
+ float take = left > cap ? cap : left;
+ part += take * bld_entertainment_quality(p);
+ left -= take;
+ if (left <= 0) break;
+ }
+ this_ent += part * (0.67f / 5);
+ happiness.perEntertainmentType[t] += part / ncits;
+ }
+ happiness.entertainmentHappiness += this_ent / ncits;
+ /* medical care */
+ int n = 0, types = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && (p->flags & PF_IS_MEDICAL) && !(p->flags & PF_IS_ENTERTAINMENT) && worlds[p->world].group == g) {
+ list[n++] = (uint16_t)i;
+ if (PC(p)->medicalTypeID + 1 > types) types = PC(p)->medicalTypeID + 1;
+ }
+ }
+ for (int a = 1; a < n; a++) {
+ uint16_t k = list[a];
+ int b = a - 1;
+ while (b >= 0) {
+ Perm *x = P(list[b]), *y = P(k);
+ float d = bld_medical_quality(y) - bld_medical_quality(x) + 0.01f * (PC(y)->medicalTypeID - PC(x)->medicalTypeID);
+ if (d <= 0) break;
+ list[b + 1] = list[b], b--;
+ }
+ list[b + 1] = k;
+ }
+ float used[10] = {0}, left = cits_per_group[g], part = 0;
+ for (int a = 0; a < n; a++) {
+ Perm *p = P(list[a]);
+ int id = PC(p)->medicalTypeID;
+ float take = left > bld_medical_capacity(p) ? bld_medical_capacity(p) : left;
+ float val = PC(p)->medicalTypeLimit * cits_per_group[g] - used[id];
+ if (val < 0) take = 0;
+ else if (!(val > take)) take = val;
+ used[id] += take;
+ happiness.healthCapacityByType[id] += take;
+ part += take * bld_medical_quality(p);
+ left -= take;
+ if (left <= 0) break;
+ }
+ happiness.medicalHappiness += part / ncits;
+ }
+ happiness.entertainmentHappiness = fminf(100, happiness.entertainmentHappiness + 0.01f);
+ happiness.medicalHappiness = fminf(100, happiness.medicalHappiness + 0.01f);
+ int special = 0;
+ int sm = pcls_find("SpecializedMedicalClinic");
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == sm) special++;
+ happiness.specializedMedicalHappiness = special == 0 ? 0 : fminf(100, fmaxf(0, (float)special / ncits * 1000 * 100));
+ float pp = 0.1f, hp = 0.4f, mp = 0.1f, sp = 0.1f, ep = 0.3f;
+ if (happiness.gloryOfTheKey) pp -= 0.02f, hp -= 0.02f, mp -= 0.02f, sp -= 0.02f, ep -= 0.02f;
+ float h = happiness.homeHappiness * hp + happiness.entertainmentHappiness * ep + happiness.schoolHappiness * sp +
+ happiness.medicalHappiness * mp + happiness.purposeHappiness * pp;
+ if (happiness.gloryOfTheKey) {
+ glory_update();
+ h += 0.1f * glory_of_the_key_happiness();
+ }
+ h = fminf(100, h + 0.01f);
+ happiness.actionSpeedModifierWithoutPenalties = h <= 50 ? 0.25f + h / 50 * 0.75f : 1 + (h - 50) / 50;
+ if (eating.foodShortage > 0) {
+ happiness.foodRationingUnhappiness = 0;
+ if (happiness.actionSpeedModifierWithoutPenalties < 1) happiness.actionSpeedModifierWithoutPenalties = 1;
+ if (eating.foodShortage >= 10) happiness.foodShortageUnhappiness = h, h = 0;
+ else if (h > 10) happiness.foodShortageUnhappiness = h - 10, h = 10;
+ else happiness.foodShortageUnhappiness = 0;
+ } else {
+ happiness.foodShortageUnhappiness = happiness.foodRationingUnhappiness = 0;
+ if (h > 10 && eating.foodRationing) {
+ float after = fmaxf(10, h * 0.67f);
+ happiness.foodRationingUnhappiness = h - after;
+ h = after;
+ }
+ }
+ float day = (float)(city.timeSinceStart / 1440);
+ if (policies.workTimeChange > 0) {
+ happiness.lastOvertime = day;
+ happiness.overtimeUnhappinessActual = fmaxf(happiness.overtimeUnhappinessActual, 5);
+ if (happiness.lastOvertimeDay == -1) happiness.lastOvertimeDay = day;
+ else if (day > happiness.lastOvertimeDay + 1) {
+ happiness.lastOvertimeDay = day;
+ happiness.overtimeUnhappinessActual = fminf(happiness.overtimeUnhappinessActual + 5, 50);
+ }
+ happiness.lastRestoreTime = -1;
+ } else if (day > happiness.lastOvertimeDay + 1) {
+ if (happiness.lastRestoreTime == -1) happiness.lastRestoreTime = day;
+ else {
+ float reduce = (day - happiness.lastRestoreTime) * 10;
+ happiness.lastRestoreTime = day;
+ happiness.overtimeUnhappinessActual = fmaxf(0, happiness.overtimeUnhappinessActual - reduce);
+ }
+ happiness.lastOvertimeDay = -1;
+ }
+ happiness.overtimeUnhappinessShown = 0;
+ if (happiness.overtimeUnhappinessActual > 0) {
+ happiness.overtimeUnhappinessShown = fminf(happiness.overtimeUnhappinessActual, h);
+ h -= happiness.overtimeUnhappinessShown;
+ }
+ if (h < happiness.happinessEnthusiasmLevel) {
+ happiness.enthusiasmHappiness = happiness.happinessEnthusiasmLevel - h;
+ h = happiness.happinessEnthusiasmLevel;
+ } else {
+ happiness.enthusiasmHappiness = 0;
+ }
+ for (int i = 0; i < nboosts; i++)
+ if (!boosts[i].canGoOverMax) h = fminf(100, h + boosts[i].boost);
+ for (int i = 0; i < nboosts; i++)
+ if (boosts[i].canGoOverMax) h += boosts[i].boost;
+ return fmaxf(h, 0);
+}
+
+static void set_happiness(float h) {
+ happiness.actionSpeedModifier = h <= 50 ? 0.25f + h / 50 * 0.75f : 1 + (h - 50) / 50;
+ happiness.happiness = h;
+}
+
+void happiness_update(float timeMod) {
+ for (int b = nboosts - 1; b >= 0; b--)
+ if (city.timeSinceStart > boosts[b].until) {
+ for (int k = b; k + 1 < nboosts; k++) boosts[k] = boosts[k + 1];
+ nboosts--;
+ }
+ if (update_happiness_in <= 0) {
+ happiness.actualHappiness = actual_happiness();
+ update_happiness_in = 60;
+ } else {
+ update_happiness_in -= fmaxf(1, timeMod);
+ }
+ if (happiness.happiness == -1) set_happiness(happiness.actualHappiness);
+ float change = 0.05f * timeMod;
+ if (fabsf(happiness.actualHappiness - happiness.happiness) < change) set_happiness(happiness.actualHappiness);
+ else set_happiness(happiness.happiness + (happiness.actualHappiness > happiness.happiness ? 1 : -1) * change);
+ if (happiness.happiness >= 99.99f) {
+ happiness.fullHappinessTime += timeMod * city.minutesPerTick;
+ happiness.fullHappinessTimeout = 300;
+ } else if (happiness.fullHappinessTimeout < 0) {
+ happiness.fullHappinessTime = 0;
+ } else {
+ happiness.fullHappinessTimeout -= timeMod;
+ }
+ if (happiness.happiness <= 10.01f) {
+ if (city_day() != happiness.lastShownVeryUnhappyWarning && happiness.veryUnhappyFromDay == -1) {
+ happiness.veryUnhappyFromDay = city_day();
+ happiness.lastShownVeryUnhappyWarning = city_day();
+ if (!happiness.ignoreUnhappyCitizens) ui_pause_for_window();
+ }
+ } else {
+ happiness.veryUnhappyFromDay = -1;
+ }
+}
+
+/* ---------------------------------------------------------------- GloryOfTheKey (cityofthekey)
+ * expensive homes, upscale restaurants and sculptures for the number of citizens */
+static GloryOfTheKey glory;
+float glory_of_the_key_happiness(void) { return glory.gloryOfTheKeyHappiness; }
+const GloryOfTheKey *glory_of_the_key(void) { return &glory; }
+static void glory_update(void) {
+ int vil = pcls_find("Villa"), pent = pcls_find("FlowerPenthouse"), rest = pcls_find("LuxuryRestaurant");
+ int s1 = pcls_find("StatueGarden"), s2 = pcls_find("StatueOfHappiness"), s3 = pcls_find("StatueOfTheKey");
+ int houses = 0, restaurants = 0, sculptures = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const Perm *p = &perms[i];
+ if (!(p->flags & PF_USED)) continue;
+ if (class_is(p->cls, vil) || class_is(p->cls, pent)) houses++;
+ else if (class_is(p->cls, rest)) restaurants++;
+ else if (class_is(p->cls, s1) || class_is(p->cls, s2) || class_is(p->cls, s3)) sculptures++;
+ }
+ float n = (float)ncits + 1;
+ glory.highEndHomeHappiness = fminf(100, fmaxf(0, 16000.0f * houses / n));
+ glory.expensiveRestaurantHappiness = fminf(100, fmaxf(0, 11000.0f * restaurants / n));
+ glory.sculpturesHappiness = fminf(100, fmaxf(0, 5000.0f * sculptures / n));
+ float sum = glory.highEndHomeHappiness + glory.expensiveRestaurantHappiness + glory.sculpturesHappiness;
+ glory.gloryOfTheKeyHappiness = fminf(100, fmaxf(0, sum / 3 + 0.01f));
+}
+
+/* ---------------------------------------------------------------- OperatingCost (teleporters cost knowledge) */
+static Materials op_cost;
+static bool tp_user_enabled = true;
+bool operating_cost_user_enabled(void) { return tp_user_enabled; } /* (bld_transport.c's windows) */
+
+void operating_cost_recalculate(void) {
+ memset(&op_cost, 0, sizeof op_cost);
+ if (!operating_cost.teleportersEnabled) return;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if ((p->flags & PF_USED) && is_building(p) && PC(p)->teleporterOperatingCost > 0)
+ op_cost.m[M_KNOWLEDGE] += PC(p)->teleporterOperatingCost * (bld_misdirector() ? 0.5f : 1) * (1 - upgrades.rocketTeleporterReward);
+ }
+}
+void operating_cost_set_teleporters(bool on, bool by_user) {
+ if (on == operating_cost.teleportersEnabled) {
+ if (by_user) tp_user_enabled = on;
+ return;
+ }
+ if (!by_user && !tp_user_enabled && !operating_cost.teleportersEnabled) return;
+ operating_cost.teleportersEnabled = on;
+ if (by_user) tp_user_enabled = on;
+ if (on) sim_flags |= SIM_HOUSES_CHANGED;
+ operating_cost_recalculate();
+}
+void operating_cost_update(float timeMod) {
+ if (city.materials.m[M_KNOWLEDGE] > 10 * timeMod && tp_user_enabled && !operating_cost.teleportersEnabled)
+ operating_cost_set_teleporters(true, false);
+ float f = timeMod / 1440 * city.minutesPerTick;
+ bool afford = true;
+ for (int m = 0; m < M_COUNT; m++)
+ if (city.materials.m[m] < op_cost.m[m] * f) afford = false;
+ if (afford) {
+ for (int m = 0; m < M_COUNT; m++)
+ if (op_cost.m[m] > 0) {
+ city.materials.m[m] -= op_cost.m[m] * f;
+ stats_add_used(m, op_cost.m[m] * f);
+ }
+ } else {
+ operating_cost_set_teleporters(false, false);
+ }
+}
+
+/* ---------------------------------------------------------------- the rest (filled in as they are ported) */
+void boosts_update(float timeMod) { (void)timeMod; } /* the boost needs an ad: never on the calculator */
+void animals_update(float timeMod) { (void)timeMod; }
+void story_update(float timeMod);
+void unlocks_update(float timeMod);
+/* GameProgress.update: the story, then the delayed unlock check */
+void progress_update(float timeMod) {
+ story_update(timeMod);
+ unlocks_update(timeMod);
+}
+static const char *story_name = "";
+void story_set_name(const char *n) { story_name = n; }
+bool story_is(const char *name) { return !strcmp(story_name, name); }
+/* (until progress.Unlocks and BuildingCost are ported) */
+#include "build.h"
+bool unique_not_unique(int cls) { (void)cls; return false; }
+/* progress.BuildingCost.getBuildingCost: the Lost Ship's first house is cheaper (scrap from the ship) */
+void building_cost_scale(int cls, Materials *cost) {
+ if (cls != CLS_NormalHouse || !story_is("theLostShip") || !story_goal() || strcmp(story_goal()->name, "BuildIndoorFarmAndHouse"))
+ return;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == CLS_NormalHouse) return;
+ memset(cost, 0, sizeof *cost);
+ cost->m[M_WOOD] = 2, cost->m[M_STONE] = 2;
+}
+
+void systems_reset(void) {
+ memset(&stats, 0, sizeof stats);
+ stats_update_in = -1;
+ memset(&eating, 0, sizeof eating);
+ eating.totalConsumedFoodPerDay = -1;
+ memset(&babies, 0, sizeof babies);
+ babies.softPopLimit = MAX_CITS - 1;
+ babies.targetPopAmount = -1;
+ babies.updateStatsIn = -2;
+ total_baby_capacity = 0;
+ memset(&happiness, 0, sizeof happiness);
+ happiness.happiness = -1;
+ happiness.actionSpeedModifier = happiness.actionSpeedModifierWithoutPenalties = 1;
+ happiness.lastOvertimeDay = happiness.lastRestoreTime = -1;
+ happiness.veryUnhappyFromDay = happiness.lastShownVeryUnhappyWarning = -1;
+ nboosts = 0;
+ memset(&glory, 0, sizeof glory);
+ update_happiness_in = 0;
+ memset(&op_cost, 0, sizeof op_cost);
+ tp_user_enabled = true;
+ operating_cost.teleportersEnabled = true;
+ memset(&bonuses, 0, sizeof bonuses);
+}
+
diff --git a/games/finalearth2/src/ui.c b/games/finalearth2/src/ui.c
new file mode 100644
index 00000000..8738db9b
--- /dev/null
+++ b/games/finalearth2/src/ui.c
@@ -0,0 +1,99 @@
+/* The Final Earth 2: the user interface's main parts (the original's GUI,
+ * CityGUI.update and the game states' switching): which screen shows, where
+ * the keys go, and the order things are drawn in. */
+#include "game.h"
+#include "save.h"
+#include "uii.h"
+#include "view.h"
+
+UiState ui;
+
+const WinDef windefs[WK_COUNT] = {
+ [WK_TEXT] = {text_content, NULL, 0},
+ [WK_BUILDING] = {bwin_content, bwin_action, 0},
+ [WK_CITIZEN] = {cwin_content, cwin_action, WD_TOP},
+ [WK_FOLLOW_LIST] = {flist_content, flist_action, WD_TOP},
+ [WK_MATERIAL] = {info_material, NULL, WD_OPAQUE},
+ [WK_POPULATION] = {info_population, info_population_action, 0},
+ [WK_HAPPINESS] = {info_happiness, info_happiness_action, 0},
+ [WK_HOUSES] = {info_houses, info_houses_action, 0},
+ [WK_WORKERS] = {info_workers, info_workers_action, 0},
+ [WK_BIRTH] = {info_birth, info_birth_action, 0},
+ [WK_ENTERTAINMENT] = {info_entertainment, NULL, 0},
+ [WK_FIND] = {info_find, info_find_action, 0},
+ [WK_UPGRADES] = {info_upgrades, info_upgrades_action, 0},
+ [WK_INVITE] = {info_invite, info_invite_action, 0},
+ [WK_GOAL] = {story_goal_content, story_goal_action, 0},
+ [WK_MISSIONS] = {story_missions_content, NULL, 0},
+ [WK_GAME_MENU] = {menu_game_content, menu_game_action, 0},
+ [WK_RESTART] = {menu_restart_content, menu_restart_action, 0},
+ [WK_SCENARIOS] = {menu_scenarios_content, menu_scenarios_action, 0},
+ [WK_FREE_PLAY] = {menu_free_play_content, menu_free_play_action, WD_OWN_CLOSE},
+ [WK_CREDITS] = {menu_credits_content, NULL, 0},
+ [WK_DESTROY] = {destroy_content, destroy_action, 0},
+ [WK_REPLACE] = {replace_content, replace_action, 0},
+ [WK_REPLACE_TO] = {replace_to_content, replace_to_action, 0},
+ [WK_CITY_NAME] = {city_name_content, city_name_action, 0},
+ [WK_COLOR] = {color_content, color_action, 0},
+};
+
+void ui_init(void) {
+ meta_load();
+ title_open();
+}
+
+/* before a city is made or loaded: the old city's windows and tutorial go */
+void ui_before_city(void) {
+ win_close_all();
+ story_ui_reset();
+ ui.paused_for_window = false;
+}
+
+/* a city was loaded or made (its story may have opened its first goal's window): the city's controls start
+ * afresh */
+void ui_after_load(void) {
+ view_edges(&city_edges);
+ city_ui_reset();
+ if (saved_view.valid) {
+ /* the cursor where it was saved */
+ cu.cx = saved_view.cx, cu.cy = saved_view.cy;
+ saved_view.valid = false;
+ }
+ ui.seconds_since_save = 0;
+}
+
+void ui_tick(void) {
+ if (ui.title) {
+ title_input();
+ story_ui_tick();
+ return;
+ }
+ story_ui_tick();
+ autosave_tick();
+ if (nwins) win_input();
+ else city_input();
+ /* the category shown keeps no "new" marker (createBuildingCategoryButtons: stopNotifyCategoryUnlock) */
+ if (!ui.title && cu.category >= 0) unlocks.notifyCategory &= (uint16_t)~(1u << cu.category);
+ /* while a text is typed, the keys that type don't also move the focus (input.c) */
+ input.typing = win_is_open(WK_CITY_NAME);
+}
+
+void ui_draw(UiFrame *f) {
+ ui_frame_begin(f);
+ if (!ui.title) {
+ city_draw_overlay();
+ }
+ if (ui.title) {
+ title_draw();
+ } else {
+ city_draw_ui();
+ }
+ win_draw();
+ /* the original's stages from here: help arrows, tooltips, notifications */
+ ui_noclip();
+ story_ui_draw_help();
+ if (!ui.title) city_draw_tips();
+ win_draw_tip();
+ story_ui_draw_notes();
+ ui_frame_end();
+}
diff --git a/games/finalearth2/src/ui.h b/games/finalearth2/src/ui.h
new file mode 100644
index 00000000..68930dd0
--- /dev/null
+++ b/games/finalearth2/src/ui.h
@@ -0,0 +1,17 @@
+/* The Final Earth 2: the user interface (ui*.c), as the game's loop sees it.
+ *
+ * The original's GUI made for keys: the city's cursor, the build menu, the
+ * city panel, windows, the story's goals and tutorial arrows, the title
+ * screen and the game menu. */
+#ifndef FE_UI_H
+#define FE_UI_H
+#include "fe.h"
+
+typedef struct UiFrame UiFrame; /* a frame's primitives, on game_draw's stack (uii.h) */
+
+void ui_init(void); /* at start: the title screen */
+void ui_tick(void); /* a tick's keys, after input_update (moves the camera too) */
+void ui_draw(UiFrame *f); /* the interface over everything */
+void ui_before_city(void); /* before a city is made or loaded */
+void ui_after_load(void); /* a city was loaded or made: the city's controls start afresh */
+#endif
diff --git a/games/finalearth2/src/ui_bwin.c b/games/finalearth2/src/ui_bwin.c
new file mode 100644
index 00000000..a1d010c4
--- /dev/null
+++ b/games/finalearth2/src/ui_bwin.c
@@ -0,0 +1,618 @@
+/* The Final Earth 2: a permanent's window (Permanent.createWindow,
+ * Building.createWindowAddBottomButtons, the House, Work and School lines,
+ * gui.CreateBuildingUpgrades, gui.CreateCityUpgrades, gui.CreatePolicies),
+ * the lists of its residents and workers (gui.MultiFollowWindow) and a
+ * citizen's window (gui.FollowingCitizen, cityActions.ChangeCitizenVitalBuildings). */
+#include "game.h"
+#include "uii.h"
+#include "view.h"
+
+enum {
+ BW_DESTROY = ACT_DESTROY,
+ BW_RESIDENTS = 1000, BW_WORKERS, BW_ONE, BW_ALL, BW_MODE_ONE, BW_MODE_ALL,
+ BW_OPTION = 2000, /* + the option's index */
+ BW_LOOK = 3000, /* + the option's index: change_variant */
+ BW_SMART_LABS = 3900
+};
+
+/* a class's name in the original's words */
+static const char *perm_title(const Perm *p) { return cls_text[p->cls].name; }
+
+/* Building.tryDestroy, with its warnings */
+void try_destroy(uint16_t id) {
+ if (cu.selected == id) cu.selected = 0;
+ switch (building_try_destroy(id)) {
+ case DR_PROTECTED: win_open_text(NULL, L_secret_society_forbidden); break;
+ case DR_INVALID_STRUCTURE: win_open_text(NULL, L_invalid_structure); break;
+ case DR_INVALID_STRUCTURE_HOLE: win_open_text(NULL, L_invalid_structure_2); break;
+ default: view_edges(&city_edges); break;
+ }
+}
+
+/* ---------------------------------------------------------------- upgrades (CreateBuildingUpgrades...) */
+#define MAX_OPTS 24
+
+static void upgrades_part(WinOut *w, Perm *p, bool global, int base) {
+ UpgradeOption opts[MAX_OPTS];
+ int n = upgrade_options(p, opts, MAX_OPTS);
+ bool all = (w->win->flags & WF2_ALL) || global;
+ int kinds[] = {UO_UPGRADE, UO_MODE, UO_CITY, UO_POLICY};
+ const char *headers[] = {L_upgrades, L_building_modes, L_city_upgrades, L_city_policies};
+ for (int k = 0; k < 4; k++) {
+ int kind = kinds[k], count = 0;
+ bool any_new = false, any_cost = false;
+ for (int i = 0; i < n; i++) {
+ if (opts[i].kind != kind) continue;
+ if (global && opts[i].owned && kind != UO_POLICY && kind != UO_MODE) {
+ /* the global window shows only what isn't bought yet */
+ float total[M_COUNT];
+ bool ca;
+ if (kind != UO_UPGRADE || upgrade_all_count(p, opts[i].upgrade, total, &ca) == 0) continue;
+ }
+ count++;
+ if (!opts[i].owned) {
+ any_new = true;
+ for (int m = 0; m < M_COUNT; m++)
+ if (m != M_KNOWLEDGE && opts[i].price[m] > 0) any_cost = true;
+ }
+ }
+ if (!count) continue;
+ if (!global) {
+ if ((kind == UO_UPGRADE || kind == UO_MODE) && any_new) {
+ int count_type = 0;
+ for (int q = 1; q < MAX_PERMS; q++)
+ if ((perms[q].flags & PF_USED) && perms[q].cls == p->cls) count_type++;
+ const char *all_text = kind == UO_UPGRADE ? (any_cost ? L_upgrade_afford : L_upgrade_all_explain)
+ : (any_cost ? L_building_mode_afford : L_building_mode_all_explain);
+ lo_1(w->tip_buf, sizeof w->tip_buf, all_text, LN(count_type));
+ win_heading(w, headers[k], kind == UO_UPGRADE ? BW_ONE : BW_MODE_ONE, kind == UO_UPGRADE ? BW_ALL : BW_MODE_ALL,
+ all, any_cost, kind == UO_UPGRADE ? L_upgrade_only_this : L_building_mode_only_this, w->tip_buf);
+ } else {
+ win_header(w, headers[k]);
+ }
+ }
+ for (int i = 0; i < n; i++) {
+ UpgradeOption *o = &opts[i];
+ if (o->kind != kind) continue;
+ if (kind == UO_POLICY) {
+ win_checkbox(w, o->owned, base + i, o->title, o->text, NULL);
+ continue;
+ }
+ if (global && o->owned && kind != UO_MODE) {
+ float total[M_COUNT];
+ bool ca;
+ if (kind != UO_UPGRADE || upgrade_all_count(p, o->upgrade, total, &ca) == 0) continue;
+ }
+ if (o->owned && !global) {
+ if (o->canChangeLook) {
+ /* the active box, with its "Change Variant" button inside */
+ win_activatable(w, true, -1, o->title, o->text, NULL, NULL);
+ w->y -= 2;
+ int save_cw = w->cw;
+ win_row_begin(w);
+ w->rx = 3;
+ win_text_button(w, L_change_variant, base + 32 + i, BX_BUTTON, false, false);
+ win_tip(w, NULL, L_change_appearance_upgrade);
+ win_row_end(w);
+ w->cw = save_cw;
+ w->y += 4;
+ } else {
+ win_activatable(w, true, -1, o->title, o->text, NULL, NULL);
+ }
+ continue;
+ }
+ /* its price: for this building, or (the "all" button) for every building of its class */
+ float price[M_COUNT];
+ memcpy(price, o->price, sizeof price);
+ char before[48];
+ before[0] = 0;
+ if (all && kind == UO_UPGRADE) {
+ float total[M_COUNT];
+ bool can_all;
+ int num = upgrade_all_count(p, o->upgrade, total, &can_all);
+ if (num <= 1) {
+ str_cat(before, sizeof before, num == 0 ? L_per_building : global ? L_for_one_building : L_for_this_building);
+ } else {
+ if (can_all) str_cat(before, sizeof before, L_for_all_buildings);
+ else lo_1(before, sizeof before, L_for_n_buildings, LN(num));
+ for (int m = 0; m < M_COUNT; m++)
+ if (m != M_KNOWLEDGE) price[m] = total[m];
+ }
+ }
+ win_activatable(w, false, base + i, o->title, o->text, price, before);
+ }
+ if (kind == UO_UPGRADE && global && p->cls == CLS_Laboratory) {
+ /* GlobalUpgradeWindow.addSmartUpgradeForLabs */
+ float price[M_COUNT];
+ bool any = upgrade_smart_labs_price(price);
+ win_activatable(w, !any, BW_SMART_LABS, L_auto_upgrade, L_upgrade_all_labs, any ? price : NULL, NULL);
+ }
+ win_space(w, 4);
+ }
+}
+
+static void upgrades_action(Perm *p, int a, bool global, int base) {
+ UpgradeOption opts[MAX_OPTS];
+ int n = upgrade_options(p, opts, MAX_OPTS);
+ Win *wn = win_top();
+ if (a == BW_ONE || a == BW_MODE_ONE) {
+ wn->flags &= (uint8_t)~WF2_ALL;
+ } else if (a == BW_ALL) {
+ wn->flags |= WF2_ALL;
+ } else if (a == BW_MODE_ALL) {
+ wn->flags |= WF2_ALL;
+ upgrade_mode_to_all(p);
+ } else if (a == BW_SMART_LABS) {
+ upgrade_smart_labs_buy();
+ } else if (a >= base + 32 && a < base + 32 + n) {
+ upgrade_change_look(p, opts[a - base - 32].upgrade);
+ } else if (a >= base && a < base + n) {
+ UpgradeOption *o = &opts[a - base];
+ upgrade_press(p, o->upgrade, global || (wn->flags & WF2_ALL));
+ }
+}
+
+/* the global upgrade window: a type's upgrades for all its buildings (createBuildingUpgradesForType) */
+void upgrades_for_type(WinOut *w, Perm *p, int unused) {
+ (void)unused;
+ upgrades_part(w, p, true, 10000 + p->cls * 64);
+}
+void upgrades_for_type_action(int a) {
+ if (a == BW_SMART_LABS) {
+ upgrade_smart_labs_buy();
+ return;
+ }
+ if (a < 10000) return;
+ int c = (a - 10000) / 64;
+ for (int k = 1; k < MAX_PERMS; k++)
+ if ((perms[k].flags & PF_USED) && perms[k].cls == c) {
+ upgrades_action(&perms[k], a, true, 10000 + c * 64);
+ return;
+ }
+}
+
+/* ---------------------------------------------------------------- the building's window */
+void bwin_content(WinOut *w) {
+ Win *wn = w->win;
+ Perm *p = P(wn->arg);
+ if (!p || !(p->flags & PF_USED)) {
+ win_title(w, "");
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+ return;
+ }
+ win_title(w, perm_title(p));
+ char t[64];
+ if (is_building(p)) {
+ /* House, WorkWithHome, Work and School: their lines (addWindowInfoLines) */
+ bool house = is_a(p, B_HOUSE), work = is_a(p, B_WORK);
+ if (house || work) {
+ win_row_begin(w);
+ if (house) win_simple_button(w, SPR_HOUSING, lo_2(t, sizeof t, L_residents, LN(p->nresidents), LN(bld_residents(p))), BW_RESIDENTS);
+ if (work) win_simple_button(w, SPR_WORK, lo_2(t, sizeof t, L_workers, LN(p->nworkers), LN(bld_jobs(p))), BW_WORKERS);
+ win_row_end(w);
+ win_space(w, 4);
+ if (is_a(p, B_SCHOOL)) win_para(w, FONT_STANDARD, lo_2(t, sizeof t, L_students, LN(p->nstudents), LN(bld_student_capacity(p))), 250, C_BLACK);
+ if (house) win_para(w, FONT_STANDARD, lo_1(t, sizeof t, L_quality, LN((int)bld_attractiveness(p))), 250, C_BLACK);
+ }
+ }
+ /* the class's own lines and buttons; its upgrades; then what the class shows after them (win_later) */
+ bool own = PC(p)->ops && PC(p)->ops->window;
+ if (own) PC(p)->ops->window(p, w);
+ w->muted = false;
+ if (is_building(p)) upgrades_part(w, p, false, BW_OPTION);
+ if (own) {
+ w->later = w->muted = true;
+ PC(p)->ops->window(p, w);
+ w->muted = false;
+ }
+ /* the bottom row: the class's buttons (win_bottom_button), a building's Destroy, then Close */
+ const char *labels[3], *heads[3], *tips[3];
+ int acts[3], n = 0;
+ for (int i = 0; i < w->nbottom; i++)
+ labels[n] = w->bottom[i].label, heads[n] = w->bottom[i].tip_header, tips[n] = w->bottom[i].tip, acts[n++] = w->bottom[i].action;
+ if (is_building(p)) {
+ if (!story.disableDestroy) {
+ labels[n] = (wn->flags & WF2_CONFIRM) ? L_really_destroy : L_destroy;
+ heads[n] = NULL, tips[n] = (wn->flags & WF2_CONFIRM) ? NULL : L_destroy_this_building;
+ acts[n++] = BW_DESTROY;
+ }
+ }
+ win_bottom_ex(w, labels, acts, heads, tips, n, L_close, ACT_CLOSE);
+}
+
+void bwin_action(Win *wn, int a) {
+ Perm *p = P(wn->arg);
+ if (!p || !(p->flags & PF_USED)) return;
+ if (a == BW_DESTROY) {
+ if (!(wn->flags & WF2_CONFIRM)) {
+ wn->flags |= WF2_CONFIRM;
+ } else {
+ win_close_all();
+ try_destroy(wn->arg);
+ }
+ return;
+ }
+ if (a == BW_RESIDENTS || a == BW_WORKERS) {
+ win_open(WK_FOLLOW_LIST, wn->arg, (uint16_t)(a == BW_WORKERS));
+ return;
+ }
+ if (a >= BW_ONE) {
+ upgrades_action(p, a, false, BW_OPTION);
+ return;
+ }
+ /* the user interface's own windows that a building's button asks for */
+ switch (a) {
+ case WA_UI_BIRTH_CONTROL: win_open(WK_BIRTH, 0, 0); return;
+ case WA_UI_MOVE_RUINS:
+ /* Builder with a world resource to move: the cursor picks an empty column */
+ {
+ uint16_t id = wn->arg;
+ win_close_all();
+ moving_resource = id;
+ cu.selected = id; /* spr_selectedbuilding on the ruins */
+ builder_start(BK_MOVE, 0, 0);
+ }
+ return;
+ case WA_UI_DUPLICATE: {
+ /* createOrRemoveBuilderForThis: a builder of its class, look, mirroring and colour (kept if it is one) */
+ bool mirrored;
+ int look = bld_decoration_look(p, &mirrored);
+ int32_t col = bld_decoration_color(p);
+ win_close_all();
+ if (!(cu.build_kind == BK_BUILDING && cu.build_cls == p->cls && cu.build_decor == look && cu.build_color == col))
+ builder_start_ex(BK_BUILDING, p->cls, look, mirrored, col);
+ return;
+ }
+ case WA_UI_CITY_NAME: text_window_open(TX_CITY_NAME); return;
+ case WA_UI_REPLACE_HOUSES: win_open(WK_REPLACE, 0, 0); return;
+ case WA_UI_COLOR_PICKER: color_picker_open(COLOR_FOR_BUILDING, wn->arg); return;
+ }
+ if (PC(p)->ops && PC(p)->ops->window_action) PC(p)->ops->window_action(p, a);
+}
+
+uint16_t moving_resource;
+
+/* ---------------------------------------------------------------- residents and workers (MultiFollowWindow) */
+/* a citizen's name (Resources.citizenNames, front-coded in lang_data.c) */
+const char *cit_name_of(const Cit *c, char *buf, int size) {
+ if (c->nameIndex < ncitizen_names) return citizen_name(c->nameIndex, buf, size);
+ buf[0] = 0;
+ str_cat(buf, size, L_this_citizen);
+ if (buf[0] >= 'a' && buf[0] <= 'z') buf[0] = (char)(buf[0] - 32);
+ return buf;
+}
+
+void flist_content(WinOut *w) {
+ Win *wn = w->win;
+ Perm *p = P(wn->arg);
+ bool workers = wn->arg2;
+ char t[96], name[48];
+ if (!p || !(p->flags & PF_USED)) {
+ win_close();
+ return;
+ }
+ cu.selected = wn->arg;
+ win_title(w, lo_1(t, sizeof t, workers ? L_workers_of : L_residents_of, LS(perm_title(p))));
+ /* the citizens, in the order they came (workers by their place in the list) */
+ int n = 0;
+ for (int pass = 0; pass < 256 && pass >= 0; pass++) {
+ bool any_left = false;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ if (workers ? c->job != wn->arg : c->home != wn->arg) continue;
+ if (workers && c->jobIndex != pass) {
+ if (c->jobIndex > pass) any_left = true;
+ continue;
+ }
+ if (!workers && pass > 0) continue;
+ win_text_button(w, cit_name_of(c, name, sizeof name), 4000 + i, BX_BUTTON, true, false);
+ win_space(w, 4);
+ n++;
+ }
+ if (!workers || !any_left) break;
+ }
+ if (!n) win_para(w, FONT_STANDARD, workers ? L_no_workers : L_no_residents, 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void flist_action(Win *wn, int a) {
+ (void)wn;
+ if (a > 4000 && a < 4000 + MAX_CITS) {
+ cu.following = (uint16_t)(a - 4000);
+ cu.selected = 0;
+ win_open(WK_CITIZEN, (uint16_t)(a - 4000), 0);
+ }
+}
+
+/* ---------------------------------------------------------------- a citizen (FollowingCitizen) */
+enum { CW_CHANGE = 1, CW_HOME, CW_WORK };
+static const char *education_text(float e) {
+ return e < 0.01f ? L_education_level_0 : e < 0.1f ? L_education_level_1 : e < 0.2f ? L_education_level_2
+ : e < 0.4f ? L_education_level_3 : e < 0.6f ? L_education_level_4 : e < 0.7f ? L_education_level_5
+ : e < 0.8f ? L_education_level_6 : e < 1 ? L_education_level_7 : L_education_level_8;
+}
+
+/* an ImageButton in spr_button_smaller (15 x 15, its icon 2 in) at x on the current row */
+static void image_button(WinOut *w, int x, uint16_t icon, int action) {
+ bool f = win_small_button(w, x, 15, 15, action);
+ int bx, by;
+ if (win_area(w, 0, 0, &bx, &by)) {
+ ui_frame(SPR_BUTTON_SMALLER, 15, f ? (key_held(K_OK) ? 2 : 1) : 0, bx + x, by, 0, 255);
+ ui_spr(icon, bx + x + 2, by + 2);
+ }
+ if (w->maxw < x + 15) w->maxw = x + 15;
+}
+
+void cwin_content(WinOut *w) {
+ Win *wn = w->win;
+ Cit *c = &cits[wn->arg];
+ char t[96], name[48];
+ cit_name_of(c, name, sizeof name);
+ if (!(c->flags & CF_ALIVE)) {
+ /* FollowingCitizen.onCitizenDie */
+ win_title(w, lo_1(t, sizeof t, L_following, LS(name)));
+ win_para(w, FONT_STANDARD, lo_1(t, sizeof t, L_citizen_passed_away, LS(name)), 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+ cu.following = 0;
+ return;
+ }
+ bool can_work = cit_age(c) >= 16 && !c->school;
+ if (wn->flags & WF2_CONFIRM) {
+ /* createChangeHomeAndWorkOfCitizenWindow: OK on a building makes it the citizen's (the arrows move the
+ * cursor over the city; var gives them to the window's buttons and back) */
+ char t2[96];
+ lo_1(t2, sizeof t2, L_for_citizen, LS(name));
+ t[0] = 0;
+ str_cat(str_cat(str_cat(t, sizeof t, can_work ? L_change_home_job : L_change_home_school), sizeof t, " "), sizeof t, t2);
+ win_title(w, t);
+ /* the bottom row: the buttons that centre the view on the home and on the job (or school), then Close */
+ bool school = c->school || cit_age(c) < 16;
+ int y0 = w->y;
+ image_button(w, 0, SPR_HOUSING, CW_HOME);
+ win_tip(w, NULL, L_center_on_house);
+ image_button(w, 15 + 4, school ? SPR_ICON_SCHOOL : SPR_WORK, CW_WORK);
+ win_tip(w, NULL, school ? L_center_on_school : L_center_on_work);
+ w->y = y0;
+ int close_w = ui_text_w(FONT_STANDARD, L_close) + 6;
+ if (w->maxw < 15 + 4 + 15 + 2 + close_w) w->maxw = 15 + 4 + 15 + 2 + close_w;
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+ return;
+ }
+ win_title(w, lo_1(t, sizeof t, L_following, LS(name)));
+ win_para(w, FONT_STANDARD, lo_2(t, sizeof t, L_age_and_education, LN((int)cit_age(c)), LS(education_text(c->educationLevel))), 250, C_BLACK);
+ const char *label = can_work ? L_change_home_job : L_change_home_school;
+ int a = CW_CHANGE;
+ if (!story_is("cityofthekey") || !c->job || P(c->job)->cls != CLS_SecretSocietyHouse)
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+ else
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+ /* the view follows the citizen */
+ float x, y;
+ cit_city_position(c, &x, &y);
+ camera_follow(x, y);
+}
+
+/* the view centred on a building (and the cursor on it) */
+static void center_on(uint16_t id) {
+ Perm *p = P(id);
+ if (!p) return;
+ camera_follow((float)perm_city_x(p) + 10, (float)perm_city_y(p) + 10);
+ cursor_to(perm_city_x(p) + 10, perm_city_y(p) + 10);
+}
+
+void cwin_action(Win *wn, int a) {
+ Cit *c = &cits[wn->arg];
+ if (a == CW_CHANGE) {
+ uint16_t arg = wn->arg;
+ win_open(WK_CITIZEN, arg, 0);
+ win_top()->flags |= WF2_CONFIRM;
+ /* the cursor starts on the citizen */
+ float x, y;
+ cit_city_position(&cits[arg], &x, &y);
+ cursor_to((int)x, (int)y - 10);
+ } else if (a == CW_HOME) {
+ center_on(c->home);
+ } else if (a == CW_WORK) {
+ center_on(c->job ? c->job : c->school);
+ }
+}
+
+/* ChangeCitizenVitalBuildings.performPermanentAction: the building under the cursor becomes the citizen's */
+bool change_vital_building(uint16_t citizen, uint16_t id) {
+ Cit *c = &cits[citizen];
+ Perm *b = P(id);
+ if (!b || !(c->flags & CF_ALIVE)) return false;
+ if (story_is("cityofthekey") && b->cls == CLS_SecretSocietyHouse) {
+ win_open_text(NULL, L_secret_society_forbidden);
+ return true;
+ }
+ if (is_a(b, B_WORK) && !c->school && cit_age(c) >= 16) {
+ Cit *lost = NULL;
+ if (c->job != id) {
+ for (int i = 1; i < MAX_CITS && !lost; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].job == id && cits[i].jobIndex == 0) lost = &cits[i];
+ if (lost && b->nworkers >= bld_jobs(b)) cit_lose_job(lost, false);
+ cit_lose_job(c, true);
+ c->flags &= (uint16_t)~CF_WITHOUT_JOB;
+ c->job = id;
+ b->nworkers++;
+ bld_after_give_job(b, c);
+ if (c->home && c->home != id && is_a(P(c->home), B_WORK) && bld_residents(P(c->home)) <= bld_jobs(P(c->home)))
+ cit_evict_from_home(c);
+ }
+ if (is_a(b, B_HOUSE) && c->home != id) {
+ bool full = b->nresidents >= bld_residents(b), can = false;
+ if (lost && lost->home == id && full) cit_evict_from_home(lost), can = true;
+ else if (full) {
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].home == id) { cit_evict_from_home(&cits[i]); break; }
+ can = true;
+ }
+ if (!full || can) {
+ cit_evict_from_home(c);
+ c->home = id;
+ b->nresidents++;
+ c->flags |= CF_FORCED_HOME;
+ }
+ }
+ } else if (is_a(b, B_HOUSE)) {
+ if (c->home != id) {
+ if (b->nresidents >= bld_residents(b))
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].home == id) { cit_evict_from_home(&cits[i]); break; }
+ cit_evict_from_home(c);
+ c->home = id;
+ b->nresidents++;
+ c->flags |= CF_FORCED_HOME;
+ if (c->job && c->home != c->job && is_a(P(c->job), B_HOUSE) && bld_residents(P(c->job)) <= bld_jobs(P(c->job)))
+ cit_lose_job(c, false);
+ }
+ } else if (is_a(b, B_SCHOOL) && cit_age(c) < 16 && c->school != id) {
+ if (b->nstudents >= bld_student_capacity(b))
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].school == id) { cit_leave_school(&cits[i]); break; }
+ cit_leave_school(c);
+ c->school = id;
+ b->nstudents++;
+ } else {
+ return false;
+ }
+ return true;
+}
+
+/* ---------------------------------------------------------------- the destroy step from the city (backspace) */
+void destroy_content(WinOut *w) { bwin_content(w); }
+void destroy_action(Win *wn, int a) { bwin_action(wn, a); }
+
+/* ---------------------------------------------------------------- upgrading basic houses (ReplaceAllHousesWindow) */
+/* the house types basic houses can become: unlocked (without a hint) or researched, not on rooftops */
+static bool replace_choice(int c) {
+ if (c == CLS_NormalHouse || pcls[c].category != pcls[CLS_NormalHouse].category || !pcls[c].residents) return false;
+ if (pcls[c].base & B_ROOFTOP) return false;
+ int st = unlock_state(c);
+ return (st == UNLOCK_UNLOCKED && !cls_text[c].hint) || st == UNLOCK_RESEARCHED || st == UNLOCK_CREATEABLE;
+}
+
+void replace_content(WinOut *w) {
+ win_title(w, L_upgrade_basic_houses);
+ win_para(w, FONT_STANDARD, L_upgrade_basic_houses_hint, 250, C_BLACK);
+ win_space(w, 2);
+ /* the types as ImageButtons, 9 in the first row and 10 in each after (as written) */
+ int in_row = 0;
+ win_row_begin(w);
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ if (!replace_choice(c)) continue;
+ if (++in_row > 9) {
+ win_row_end(w);
+ win_row_begin(w);
+ in_row = 0;
+ }
+ int x = w->rx, bx, by;
+ bool f = win_small_button(w, x, 22, 22, 10 + c);
+ win_tip(w, NULL, cls_text[c].name);
+ w->rx = x + 22;
+ if (w->rh < 22) w->rh = 22;
+ if (w->maxw < w->rx) w->maxw = w->rx;
+ int save = w->y;
+ if (win_area(w, 0, 0, &bx, &by)) {
+ ui_frame(SPR_BUILDINGBUTTON, 22, f ? (key_held(K_OK) ? 2 : 1) : 0, bx + x, by, 0, 255);
+ type_image(bx + x + 1, by + 1, c);
+ }
+ w->y = save;
+ }
+ win_row_end(w);
+ win_space(w, 6);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void replace_action(Win *wn, int a) {
+ (void)wn;
+ if (a >= 10 && a < 10 + CLS_COUNT) win_open(WK_REPLACE_TO, (uint16_t)(a - 10), 0);
+}
+
+/* ReplaceAllHousesWindowStep2: how many basic houses (NormalHouse itself, not its kinds), how many of them the city
+ * can pay for (one at least), and the price: the new type's, less a basic house's recycled wood and stone,
+ * rounded, times that number (knowledge once). shown: the price as displayed (no negative wood or stone) */
+typedef struct { int houses, n; float total[M_COUNT], shown[M_COUNT]; } ReplacePlan;
+static void replace_plan(int cls, ReplacePlan *rp) {
+ memset(rp, 0, sizeof *rp);
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == CLS_NormalHouse) rp->houses++;
+ if (!rp->houses) return;
+ float one[M_COUNT];
+ for (int m = 0; m < M_COUNT; m++) one[m] = pcls[cls].cost[m];
+ if (unlock_state(cls) == UNLOCK_RESEARCHED) one[M_KNOWLEDGE] = 0;
+ one[M_WOOD] -= 4 * upgrades.recyclingAmount, one[M_STONE] -= 4 * upgrades.recyclingAmount;
+ for (int m = 0; m < M_COUNT; m++) one[m] = floorf(one[m] + 0.5f); /* roundAll (Math.round) */
+ /* Materials.canAffordNumber without knowledge */
+ long can = 1000000000;
+ for (int m = 0; m < M_COUNT && can; m++) {
+ if (m == M_KNOWLEDGE) continue;
+ if (one[m] > city.materials.m[m]) can = 0;
+ else if (one[m] > 0 && floor(city.materials.m[m] / one[m]) < can) can = (long)floor(city.materials.m[m] / one[m]);
+ }
+ rp->n = can < 1 ? 1 : can > rp->houses ? rp->houses : (int)can;
+ for (int m = 0; m < M_COUNT; m++) rp->total[m] = m == M_KNOWLEDGE ? one[m] : one[m] * rp->n;
+ memcpy(rp->shown, rp->total, sizeof rp->shown);
+ if (rp->shown[M_WOOD] < 0) rp->shown[M_WOOD] = 0;
+ if (rp->shown[M_STONE] < 0) rp->shown[M_STONE] = 0;
+}
+
+void replace_to_content(WinOut *w) {
+ int cls = w->win->arg;
+ char t[200], t2[96];
+ win_title(w, lo_1(t, sizeof t, L_upgrade_to_x, LS(cls_text[cls].name)));
+ ReplacePlan rp;
+ replace_plan(cls, &rp);
+ if (!rp.houses) {
+ win_para(w, FONT_STANDARD, L_no_basic_houses, 250, C_BLACK);
+ } else {
+ t[0] = 0;
+ str_cat(str_cat(str_cat(t, sizeof t, L_no_undo), sizeof t, "\n\n"), sizeof t,
+ lo_2(t2, sizeof t2, L_upgrade_basic_for, LN(rp.n), LN(rp.houses)));
+ win_para(w, FONT_STANDARD, t, 250, C_BLACK);
+ }
+ win_space(w, 4);
+ /* the MaterialsCostDisplay (2 under it) */
+ int x, y;
+ float none[M_COUNT] = {0};
+ const float *cost = rp.houses ? rp.shown : none;
+ char after[24] = " ";
+ str_cat(after, sizeof after, L_to_research);
+ if (win_area(w, ui_cost(0, INT16_MIN, cost, "", after, true), 12 + 2, &x, &y)) ui_cost(x, y, cost, "", after, true);
+ win_space(w, 4);
+ win_text_button(w, rp.houses ? L_confirm : "-", 1, BX_BUTTON, false, false);
+ win_space(w, 6);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+/* Confirm: each basic house (as many as paid for) destroyed for replacement and the new type built there */
+void replace_to_action(Win *wn, int a) {
+ if (a != 1) return;
+ int cls = wn->arg;
+ ReplacePlan rp;
+ replace_plan(cls, &rp);
+ if (!rp.houses || rp.n <= 0 || !mat_can_afford(rp.total)) return;
+ unlocks_research(cls);
+ int done = 0;
+ for (int i = 1; i < MAX_PERMS && done < rp.n; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->cls != CLS_NormalHouse) continue;
+ int wo = p->world, col = p->col, row = p->row;
+ perm_destroy((uint16_t)i, true);
+ uint16_t id = perm_new(cls, wo, col, row);
+ if (id) bld_on_build(P(id));
+ done++;
+ }
+ city_update_connections();
+ sim_update_pathfinder(true, NONE);
+ /* (the original then calls postCreate on the old houses, which does nothing for the new ones) */
+ unlocks_check_build_related();
+ mat_pay(rp.total);
+ view_edges(&city_edges);
+ win_close_all();
+ lo_1(ui_text_buf, sizeof ui_text_buf, L_upgraded_houses, LN(done));
+ win_open_text(NULL, ui_text_buf);
+}
diff --git a/games/finalearth2/src/ui_city.c b/games/finalearth2/src/ui_city.c
new file mode 100644
index 00000000..48519aab
--- /dev/null
+++ b/games/finalearth2/src/ui_city.c
@@ -0,0 +1,1656 @@
+/* The Final Earth 2: the city screen (the original's CityView keyboard
+ * scrolling and zoom, Builder, gui.BuildingButtons, gui.CityGUI's city info
+ * and gui.Tooltip), made for keys: a cursor on the city's cells instead of
+ * the mouse, and focus moving over the build menu and the city panel. */
+#include <math.h>
+#include "bldi.h"
+#include "game.h"
+#include "save.h"
+#include "uii.h"
+#include "view.h"
+
+CityUi cu;
+const float simulation_speeds[5] = {1, 1.5f, 2, 0.5f, 0.75f};
+static const uint16_t speed_icon[5] = {SPR_ICON_PLAY_NORMALSPEED, SPR_ONEANDHALFSPEED, SPR_ICON_SPEEDUP,
+ SPR_ICON_HALFSPEED, SPR_ICON_SLIGHTLYSLOWERSPEED};
+static int8_t fixed_world = -1, fixed_col; /* Builder.fixBuilder (the first tutorial's woodcutting centre) */
+static uint8_t build_flash; /* a "can't build" flash of the ghost */
+
+void city_ui_reset(void) {
+ memset(&cu, 0, sizeof cu);
+ cu.category = -1;
+ cu.bfocus = -1;
+ building_mode = BM_NORMAL;
+ fixed_world = -1;
+ int s = 0;
+ for (int i = 0; i < 5; i++)
+ if (fabsf(simulation_speeds[i] - city.simulationSpeed) < fabsf(simulation_speeds[s] - city.simulationSpeed)) s = i;
+ cu.speed = (uint8_t)s;
+ /* the cursor in the middle of the screen */
+ float zx = SCREEN_W / 2.0f / camera.zoom, zy = SCREEN_H / 2.0f / camera.zoom;
+ cursor_to((int)(camera.x + zx), (int)(camera.y + zy));
+}
+
+/* ---------------------------------------------------------------- the camera and the cursor */
+/* CityView.updateMovingView: the view's centre stays within the city's edges */
+void camera_clamp_view(void) {
+ float hw = SCREEN_W / 2.0f / camera.zoom, hh = SCREEN_H / 2.0f / camera.zoom;
+ float cx = camera.x + hw, cy = camera.y + hh;
+ if (city_edges.maxX > city_edges.minX) cx = cx < city_edges.minX ? city_edges.minX : cx > city_edges.maxX ? city_edges.maxX : cx;
+ if (city_edges.maxY > city_edges.minY) cy = cy < city_edges.minY ? city_edges.minY : cy > city_edges.maxY ? city_edges.maxY : cy;
+ camera.x = cx - hw, camera.y = cy - hh;
+}
+
+void camera_follow(float x, float y) {
+ camera.x = x - SCREEN_W / 2.0f / camera.zoom;
+ camera.y = y - SCREEN_H / 2.0f / camera.zoom;
+ camera_clamp_view();
+}
+
+static int floor20(int v) { return v >= 0 ? v / 20 * 20 : -((-v + 19) / 20 * 20); }
+
+void cursor_to(int x, int y) {
+ /* not beyond the city (with a margin to build at its edges) */
+ if (city_edges.maxX > city_edges.minX) {
+ if (x < city_edges.minX - 60) x = city_edges.minX - 60;
+ if (x > city_edges.maxX + 40) x = city_edges.maxX + 40;
+ if (y < city_edges.minY - 100) y = city_edges.minY - 100;
+ if (y > city_edges.maxY + 20) y = city_edges.maxY + 20;
+ }
+ cu.cx = (int16_t)floor20(x);
+ cu.cy = (int16_t)floor20(y);
+}
+
+/* the view follows the cursor when it nears an edge */
+static void camera_to_cursor(void) {
+ float vw = (float)SCREEN_W / camera.zoom, vh = (float)SCREEN_H / camera.zoom;
+ float mx = 40.0f / camera.zoom + 10, my = 30.0f / camera.zoom + 10;
+ if (cu.cx < camera.x + mx) camera.x = cu.cx - mx;
+ if (cu.cx + 20 > camera.x + vw - mx) camera.x = cu.cx + 20 - vw + mx;
+ if (cu.cy < camera.y + my) camera.y = cu.cy - my;
+ if (cu.cy + 20 > camera.y + vh - my) camera.y = cu.cy + 20 - vh + my;
+ camera_clamp_view();
+}
+
+/* and the cursor stays on screen when the view moves on its own */
+static void cursor_to_camera(void) {
+ float vw = (float)SCREEN_W / camera.zoom, vh = (float)SCREEN_H / camera.zoom;
+ int x = cu.cx, y = cu.cy;
+ if (x < camera.x) x = (int)ceilf(camera.x / 20) * 20;
+ if (x + 20 > camera.x + vw) x = (int)floorf((camera.x + vw) / 20) * 20 - 20;
+ if (y < camera.y) y = (int)ceilf(camera.y / 20) * 20;
+ if (y + 20 > camera.y + vh) y = (int)floorf((camera.y + vh) / 20) * 20 - 20;
+ cu.cx = (int16_t)x, cu.cy = (int16_t)y;
+}
+
+/* the world, column and row of the cursor's cell (World.handleMouse); -1 when on none */
+int cursor_cell(int *col, int *row) {
+ for (int w = 0; w < nworlds; w++) {
+ World *wd = &worlds[w];
+ if (cu.cx < wd->x || cu.cx >= wd->x + wd->w || cu.cy >= wd->y) continue;
+ *col = (cu.cx - wd->x) / 20;
+ *row = (wd->y - (cu.cy + 10) - 1) / 20;
+ return w;
+ }
+ return -1;
+}
+
+static uint16_t cursor_perm(void) { return permanent_at_pos(cu.cx + 10, cu.cy + 10); }
+
+/* CityView.handleKeyboardMove: shift+arrows move the view (2 + 12 / zoom a frame) */
+static void camera_keys(void) {
+ float step = (2.0f + 12.0f / camera.zoom) * 2;
+ bool moved = false;
+ if (key_held(K_LEFT)) camera.x -= step, moved = true;
+ if (key_held(K_RIGHT)) camera.x += step, moved = true;
+ if (key_held(K_UP)) camera.y -= step, moved = true;
+ if (key_held(K_DOWN)) camera.y += step, moved = true;
+ if (moved) {
+ camera_clamp_view();
+ cursor_to_camera();
+ }
+}
+
+static void zoom_keys(void) {
+ if (key_pressed(K_PLUS) && camera.zoom == 1) {
+ /* around the cursor */
+ camera.x = cu.cx + 10 - SCREEN_W / 4.0f;
+ camera.y = cu.cy + 10 - SCREEN_H / 4.0f;
+ camera.zoom = 2;
+ camera_clamp_view();
+ cursor_to_camera();
+ }
+ if (key_pressed(K_MINUS) && camera.zoom == 2) {
+ camera.x -= SCREEN_W / 4.0f, camera.y -= SCREEN_H / 4.0f;
+ camera.zoom = 1;
+ camera_clamp_view();
+ cursor_to_camera();
+ }
+}
+
+/* ---------------------------------------------------------------- the builder */
+static bool decoration_available(int i) {
+ const DecoText *d = &deco_text[i];
+ return !(d->flags & DT_GENE_EDITING) || upgrades.hasGeneEditing;
+}
+
+/* City.createOrRemoveBuilder: a builder for a class (its look, mirroring and colour), a decoration or a world
+ * resource */
+void builder_start_ex(int kind, int index, int decor, bool mirror, int32_t color) {
+ cu.build_kind = (int8_t)kind;
+ cu.build_cls = (uint8_t)index;
+ cu.build_decor = (uint8_t)decor;
+ cu.build_mirror = mirror;
+ cu.build_color = color;
+ builder_look = (BuilderLook){decor, mirror, color};
+ if (color >= 0) color_picked = color;
+ if (building_mode == BM_DESTROY || building_mode == BM_DESTROY_LEAVING_HOLE) building_mode = BM_NORMAL;
+ cu.zone = Z_CITY;
+ /* City.postCreateBuilder: the first tutorial's builder only builds in its place */
+ extern bool tut_fix_builder;
+ if (tut_fix_builder && kind == BK_BUILDING) fixed_world = 0, fixed_col = 2;
+}
+void builder_start(int kind, int index, int decor) {
+ builder_start_ex(kind, index, decor, kind == BK_BUILDING && (cls_text[index].flags & CT_MIRRORABLE) && cu.mirrored, -1);
+}
+
+void builder_stop(void) {
+ if (cu.build_kind == BK_MOVE) cu.selected = 0, moving_resource = 0;
+ cu.build_kind = BK_NONE;
+ fixed_world = -1;
+}
+
+/* the cost now (Builder.calculateCurrentCost) */
+static void build_cost(float cost[M_COUNT]) {
+ memset(cost, 0, sizeof(float) * M_COUNT);
+ if (cu.build_kind == BK_BUILDING) {
+ Materials m;
+ builder_cost(cu.build_cls, &m);
+ for (int i = 0; i < M_COUNT; i++) cost[i] = (float)m.m[i];
+ } else if (cu.build_kind == BK_DECORATION) {
+ const DecoText *d = &deco_text[cu.build_cls];
+ cost[M_FOOD] = d->food, cost[M_WOOD] = d->wood, cost[M_STONE] = d->stone;
+ } else if (cu.build_kind == BK_RESOURCE) {
+ cost[M_WOOD] = res_text[cu.build_cls].wood, cost[M_STONE] = res_text[cu.build_cls].stone;
+ }
+}
+
+static bool can_build_on_surface(const World *w) { return !(w->flags & WF_PROTECTED_KEY) && w->h != 0 && !(w->flags & WF_UNBUILDABLE_ALIENS); }
+
+/* World.onCannotBuild */
+static void cannot_build(const World *w) {
+ if (w->flags & WF_UNBUILDABLE_ALIENS) win_open_text(NULL, L_building_prevented_strange_force);
+ if (w->flags & WF_PROTECTED_KEY) win_open_text(NULL, L_secret_society_forbidden);
+}
+
+/* what building at the cursor would do: BP_* for buildings; for the rest BP_OK or BP_IMPOSSIBLE */
+static int build_check(int *wo, int *col, int *row) {
+ int w = cursor_cell(col, row);
+ *wo = w;
+ if (w < 0) return BP_IMPOSSIBLE;
+ if (fixed_world >= 0 && (w != fixed_world || *col != fixed_col)) return BP_IMPOSSIBLE;
+ World *wd = &worlds[w];
+ if (cu.build_kind == BK_BUILDING) return builder_can_build(w, *col, *row, cu.build_cls);
+ /* decorations and world resources: on the ground of an empty column */
+ if (*row != 0) return BP_IMPOSSIBLE;
+ if (!can_build_on_surface(wd)) return BP_WORLD_NOT_ALLOWED;
+ if (perm_at(w, *col, 0)) return BP_IMPOSSIBLE;
+ return BP_OK;
+}
+
+/* Builder.buildingPrerequirementsValid */
+static bool build_prereq(void) {
+ if (cu.build_kind == BK_BUILDING) return builder_prerequisites(cu.build_cls);
+ float cost[M_COUNT];
+ build_cost(cost);
+ return mat_can_afford(cost);
+}
+
+/* OK while building (Builder.tryBuildingAt and its decoration and world resource cases) */
+static void build_here(void) {
+ int w, col, row;
+ int bp = build_check(&w, &col, &row);
+ if (bp == BP_WORLD_NOT_ALLOWED) {
+ cannot_build(&worlds[w]);
+ return;
+ }
+ if (bp != BP_OK || !build_prereq()) {
+ build_flash = 12;
+ return;
+ }
+ float cost[M_COUNT];
+ build_cost(cost);
+ if (cu.build_kind == BK_MOVE) {
+ /* createWorldResourceBuilderMove: the ruins go there, the builder ends */
+ if (bld_move_resource(moving_resource, w, col)) builder_stop();
+ } else if (cu.build_kind == BK_BUILDING) {
+ uint16_t id = builder_build(w, col, row, cu.build_cls);
+ if (!id) return;
+ const ClsText *ct = &cls_text[cu.build_cls];
+ if (ct->flags & CT_MULTI_DECOR) bld_customize(P(id), cu.build_decor, cu.build_mirror);
+ if ((ct->flags & CT_ANYCOLOR) && cu.build_color >= 0) bld_customize_color(P(id), cu.build_color);
+ fixed_world = -1;
+ } else if (cu.build_kind == BK_DECORATION) {
+ const DecoText *d = &deco_text[cu.build_cls];
+ uint8_t *decos = col_deco + worlds[w].col0;
+ if (d->flags & DT_REMOVE) {
+ decos[col] = 0;
+ } else {
+ int kind = 0;
+ for (int k = 1; k < DECO_KINDS; k++)
+ if (bg_deco_sprite(k) == d->spr) kind = k;
+ if (kind && decos[col] >> 4 == kind) bg_set_decoration(decos, col, kind, ((decos[col] & 15) + 1) % bg_deco_frames(kind), false);
+ else bg_set_decoration(decos, col, kind, -1, false);
+ }
+ mat_pay(cost);
+ } else if (cu.build_kind == BK_RESOURCE) {
+ const ResText *r = &res_text[cu.build_cls];
+ col_deco[worlds[w].col0 + col] = 0;
+ uint16_t id = perm_new(r->cls, w, col, 0);
+ if (!id) return;
+ resource_planted(P(id), r->resources < 0 ? 0 : r->resources, r->grow < 0 ? 0 : r->grow);
+ mat_pay(cost);
+ city_update_connections();
+ sim_update_pathfinder(false, id);
+ }
+ view_edges(&city_edges);
+}
+
+/* Builder.tryBuildingMulti: in the drag modes, while OK is held, each cell the cursor passes on its way from
+ * (x0, y0) is built on, where it can be and the city can pay (cells that can't are passed over silently) */
+static void build_line(int x0, int y0, int x1, int y1) {
+ int sx = cu.cx, sy = cu.cy;
+ int dx = (x1 - x0) / 20, dy = (y1 - y0) / 20, n = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
+ for (int i = 1; i <= n; i++) {
+ cu.cx = (int16_t)(x0 + 20 * (int)lroundf((float)dx * i / n));
+ cu.cy = (int16_t)(y0 + 20 * (int)lroundf((float)dy * i / n));
+ int w, col, row;
+ if (build_check(&w, &col, &row) == BP_OK && build_prereq()) build_here();
+ if (cu.build_kind != BK_BUILDING) break;
+ }
+ cu.cx = (int16_t)sx, cu.cy = (int16_t)sy;
+}
+
+/* the ghost: the building's first 20x20 (Builder's sprite), see-through, with the insert/replace mark */
+static void draw_builder(void) {
+ int z = camera.zoom;
+ int x = bg_screen_x(&camera, (float)cu.cx), y = bg_screen_y(&camera, (float)cu.cy);
+ int w, col, row;
+ int bp = build_check(&w, &col, &row);
+ bool prereq = build_prereq();
+ uint16_t spr = 0;
+ int sx = 0;
+ uint8_t flags = 0;
+ if (cu.build_kind == BK_BUILDING) {
+ const ClsText *ct = &cls_text[cu.build_cls];
+ spr = ct->on_build ? ct->on_build : pcls[cu.build_cls].sprite;
+ if (ct->flags & CT_MULTI_SPEC) spr = cu.build_decor ? SPR_TREEPLANTATION : SPR_INDOORFARM;
+ else sx = cu.build_decor * 22;
+ if (cu.build_mirror) flags = GFX_FLIPX;
+ } else if (cu.build_kind == BK_DECORATION) {
+ spr = deco_text[cu.build_cls].spr;
+ } else if (cu.build_kind == BK_RESOURCE) {
+ spr = pcls[res_text[cu.build_cls].cls].sprite;
+ } else if (cu.build_kind == BK_MOVE && P(moving_resource)) {
+ /* the ruins as they look */
+ static const uint16_t ruins[3] = {SPR_ALIENRUINS, SPR_ALIENRUINS_2, SPR_ALIENRUINS_3};
+ const Perm *p = P(moving_resource);
+ spr = is_a(p, B_RUINS) ? ruins[STC(RuinsState, p)->sprite % 3] : pcls[p->cls].sprite;
+ }
+ /* (a builder with a colour shows it, as decorationAppearanceColor tints the sprite) */
+ uint16_t own = cu.build_kind == BK_BUILDING && cu.build_color >= 0 ? rgb565_near((uint32_t)cu.build_color) : GFX_NO_TINT;
+ uint16_t tint = own;
+ uint8_t alpha = 51; /* 0.2 */
+ bool mark = false, replace = false;
+ if (!prereq || build_flash) {
+ tint = rgb565(0xFF8080), alpha = 153; /* 0.6 */
+ } else if (bp == BP_IN_WORLD) {
+ tint = rgb565(0xFF8080);
+ } else if (bp == BP_OK) {
+ alpha = key_held(K_OK) ? 204 : 128; /* 0.5 (0.8 while pressed) */
+ if (cu.build_kind == BK_BUILDING && w >= 0 && row < col_stack_height(w, col) && perm_at(w, col, row)) {
+ mark = true;
+ replace = building_mode_can_replace();
+ if (!replace && own == GFX_NO_TINT) tint = rgb565(0xC0C0C0);
+ }
+ }
+ if (spr) gfx_sprite_ex(spr, sx, 0, 20, 20, x, y, flags, alpha, tint);
+ if (mark) gfx_sprite(replace ? SPR_REPLACEBUILDINGHERE : SPR_INSERTBUILDINGHERE, x, y, 0, 255);
+ (void)z;
+}
+
+/* the mobile version's buildable places (Builder: spr_buildhereoutline, yellow where it would replace) */
+static void draw_buildable(void) {
+ if (cu.build_kind == BK_NONE || !build_prereq()) return;
+ int z = camera.zoom;
+ float x0 = camera.x - 20, x1 = camera.x + (float)SCREEN_W / z;
+ int drawn = 0;
+ for (int w = 0; w < nworlds && drawn < 64; w++) {
+ World *wd = &worlds[w];
+ if (wd->x + wd->w < x0 || wd->x > x1) continue;
+ if (fixed_world >= 0 && w != fixed_world) continue;
+ for (int c = 0; c < wd->ncols && drawn < 64; c++) {
+ int cx = wd->x + 20 * c;
+ if (cx < x0 || cx > x1) continue;
+ if (fixed_world >= 0 && c != fixed_col) continue;
+ int h = col_stack_height(w, c), top = h + 1;
+ if (c > 0 && col_stack_height(w, c - 1) > top) top = col_stack_height(w, c - 1);
+ if (c + 1 < wd->ncols && col_stack_height(w, c + 1) > top) top = col_stack_height(w, c + 1);
+ if (cu.build_kind != BK_BUILDING) top = 1;
+ for (int r = 0; r < top && drawn < 64; r++) {
+ int py = wd->y - 20 * (r + 1);
+ int sy = bg_screen_y(&camera, (float)py);
+ if (sy < -20 * z || sy > SCREEN_H) continue;
+ bool ok;
+ if (cu.build_kind == BK_BUILDING) ok = builder_can_build(w, c, r, cu.build_cls) == BP_OK;
+ else ok = r == 0 && can_build_on_surface(wd) && !perm_at(w, c, 0);
+ if (!ok) continue;
+ bool rep = building_mode_can_replace() && r < h && perm_at(w, c, r);
+ gfx_sprite_ex(SPR_BUILDHEREOUTLINE, 0, 0, 20, 20, bg_screen_x(&camera, (float)cx), sy, 0, 255,
+ rep ? rgb565(0xFFFF00) : GFX_NO_TINT);
+ drawn++;
+ }
+ }
+ }
+ if (fixed_world >= 0) {
+ World *wd = &worlds[fixed_world];
+ gfx_sprite(SPR_FORCEDBUILDINGLOCATION, bg_screen_x(&camera, (float)(wd->x + 20 * fixed_col - 1)),
+ bg_screen_y(&camera, (float)(wd->y - 20 - 31)), 0, 255);
+ }
+}
+
+/* ---------------------------------------------------------------- the city's layer */
+/* setHoverHightlight's pulse: 0.5 + (sin(guiTimer / 10) + 1) / 4 */
+static uint8_t pulse(float lo, float range) {
+ return (uint8_t)(255 * (lo + (sinf(cu.gui_timer / 10) + 1) / 2 * range));
+}
+
+/* the cursor: the original's hover outline on the cell, with a dark edge around it so that it shows on a light sky
+ * as well as on a dark one (the original's mouse pointer shows where it is; a keypad has none) */
+static void cursor_box(void) {
+ int x = bg_screen_x(&camera, (float)(cu.cx - 1)), y = bg_screen_y(&camera, (float)(cu.cy - 1)), s = 22 * camera.zoom;
+ uint16_t dark = rgb565(0x202020);
+ gfx_rect(x - 1, y - 1, s + 2, 1, dark, 150), gfx_rect(x - 1, y + s, s + 2, 1, dark, 150);
+ gfx_rect(x - 1, y, 1, s, dark, 150), gfx_rect(x + s, y, 1, s, dark, 150);
+ gfx_sprite(SPR_WHITEOUTLINE, x, y, 0, pulse(0.55f, 0.45f));
+}
+
+static void outline_perm(uint16_t id, uint16_t spr, uint16_t tint, uint8_t alpha, int frame) {
+ Perm *p = P(id);
+ if (!p) return;
+ int x = bg_screen_x(&camera, (float)(perm_city_x(p) - 1)), y = bg_screen_y(&camera, (float)(perm_city_y(p) - 1));
+ if (frame >= 0) gfx_sprite_ex(spr, frame * 24, 0, 22, 22, x, y, 0, alpha, tint);
+ else gfx_sprite_ex(spr, 0, 0, 22, 22, x, y, 0, alpha, tint);
+}
+
+void city_draw_overlay(void) {
+ gfx_zoom(camera.zoom);
+ /* FindBuildingsOfType: spr_hoverhint frames and white outlines on the buildings of the class */
+ if (cu.highlight_cls) {
+ int c = cu.highlight_cls - 1;
+ int z = camera.zoom, n = 0;
+ float x0 = camera.x - 22, x1 = camera.x + (float)SCREEN_W / z, y0 = camera.y - 22, y1 = camera.y + (float)SCREEN_H / z;
+ for (int i = 1; i < MAX_PERMS && n < 40; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->cls != c) continue;
+ float px = (float)perm_city_x(p), py = (float)perm_city_y(p);
+ if (px < x0 || px > x1 || py < y0 || py > y1) continue;
+ int frame = 1;
+ UpgradeOption opts[1];
+ (void)opts;
+ outline_perm((uint16_t)i, SPR_HOVERHINT, GFX_NO_TINT, pulse(0.5f, 0.5f), frame);
+ outline_perm((uint16_t)i, SPR_WHITEOUTLINE, GFX_NO_TINT, 255, -1);
+ n++;
+ }
+ }
+ /* FollowingCitizen (and in its change window, the citizen's job, home and school) */
+ bool changing = nwins && wins[nwins - 1].kind == WK_CITIZEN && (wins[nwins - 1].flags & WF2_CONFIRM);
+ if (cu.following && (cits[cu.following].flags & CF_ALIVE)) {
+ Cit *c = &cits[cu.following];
+ uint16_t green = rgb565(0x66C600);
+ if (!changing) {
+ } else if (c->job && c->job == c->home) {
+ outline_perm(c->job, SPR_HOVERHINTS_CITIZEN, GFX_NO_TINT, pulse(0.5f, 0.5f), 3);
+ outline_perm(c->job, SPR_WHITEOUTLINE, green, 255, -1);
+ } else {
+ if (c->job) outline_perm(c->job, SPR_HOVERHINTS_CITIZEN, GFX_NO_TINT, pulse(0.5f, 0.5f), 0), outline_perm(c->job, SPR_WHITEOUTLINE, green, 255, -1);
+ if (c->home) outline_perm(c->home, SPR_HOVERHINTS_CITIZEN, GFX_NO_TINT, pulse(0.5f, 0.5f), 1), outline_perm(c->home, SPR_WHITEOUTLINE, green, 255, -1);
+ }
+ if (c->school && changing) outline_perm(c->school, SPR_HOVERHINTS_CITIZEN, GFX_NO_TINT, pulse(0.5f, 0.5f), 2), outline_perm(c->school, SPR_WHITEOUTLINE, green, 255, -1);
+ /* the selected citizen (spr_selectedhuman) */
+ float x, y;
+ cit_city_position(c, &x, &y);
+ gfx_sprite(SPR_SELECTEDHUMAN, bg_screen_x(&camera, x - 1), bg_screen_y(&camera, y - 6), 0, 255);
+ }
+ /* the building whose window is open (spr_selectedbuilding) */
+ if (cu.selected && (perms[cu.selected].flags & PF_USED)) outline_perm(cu.selected, SPR_SELECTEDBUILDING, GFX_NO_TINT, 255, -1);
+ /* the story's goal: buildings that can take the upgrade it asks for (BuildingButtons.updateGoalAttentions) */
+ extern void goal_upgrade_highlights(void);
+ goal_upgrade_highlights();
+ if (changing) cursor_box();
+ if (cu.zone == Z_CITY && !nwins && !ui.title) {
+ if (cu.build_kind != BK_NONE) {
+ draw_buildable();
+ draw_builder();
+ /* the cursor stays in sight over the ghost, also where nothing can be built (the ghost is faint there) */
+ cursor_box();
+ } else {
+ uint16_t id = cursor_perm();
+ if ((building_mode == BM_DESTROY || building_mode == BM_DESTROY_LEAVING_HOLE) && is_building(P(id))) {
+ /* Building.onHover in destroy mode: spr_destroying */
+ Perm *p = P(id);
+ gfx_sprite(SPR_DESTROYING, bg_screen_x(&camera, (float)perm_city_x(p)), bg_screen_y(&camera, (float)perm_city_y(p)), 0,
+ key_held(K_OK) ? 255 : 128);
+ }
+ cursor_box();
+ }
+ }
+ gfx_zoom(1);
+}
+
+/* ---------------------------------------------------------------- the tooltip (gui.Tooltip) */
+void ui_tooltip(const Tip *t, int ax, int ay, bool continuous) {
+ if (!t || ((!t->header || !*t->header) && (!t->text || !*t->text))) return;
+ int max_w = continuous ? SCREEN_W : SCREEN_W / 2;
+ if (!continuous) {
+ int m = ax - 10 > SCREEN_W - ax - 10 ? ax - 10 : SCREEN_W - ax - 10;
+ if (m > 240) m = 240;
+ if (m > max_w) max_w = m;
+ }
+ int extra_w = t->nextra ? ui_icon_list(0, INT16_MIN, t->extra, t->nextra) : 0;
+ int width = continuous ? max_w : 0, y = 0, header_w = 0, hw = 0, tw = 0, th = 0, hh = 0;
+ int hmax = max_w - extra_w - 10, tmax = max_w - 10;
+ int cap = continuous ? 1000 : 350;
+ hmax = hmax < 100 ? 100 : hmax > cap ? cap : hmax;
+ tmax = tmax < 100 ? 100 : tmax > cap ? cap : tmax;
+ int header_y = 0, text_y = 0, extra2_y = 0, cost_y = 0, cost2_y = 0;
+ if (t->header && *t->header) {
+ y--;
+ hh = ui_para(FONT_16, 0, INT16_MIN, hmax, t->header, C_BLACK, true, &hw);
+ header_w = hw + 6;
+ if (header_w > width) width = header_w;
+ header_y = y;
+ y += hh + 2;
+ }
+ if (t->text && *t->text) {
+ y++;
+ th = ui_para(FONT_STANDARD, 0, INT16_MIN, tmax, t->text, C_BLACK, true, &tw);
+ text_y = y;
+ if (tw + 6 > width) width = tw + 6;
+ y += th;
+ }
+ if (t->nextra2) {
+ extra2_y = y + 1;
+ int w2 = ui_icon_list(0, INT16_MIN, t->extra2, t->nextra2) + 6;
+ if (w2 > width) width = w2;
+ y += 12;
+ }
+ bool any_cost = false;
+ if (t->cost)
+ for (int m = 0; m < M_COUNT; m++) any_cost |= t->cost[m] > 0;
+ char after[24] = " ";
+ str_cat(after, sizeof after, L_to_research);
+ if (any_cost) {
+ y += 2;
+ cost_y = y;
+ int cw = ui_cost(0, INT16_MIN, t->cost, "", after, true);
+ if (cw > width) width = cw;
+ y += 11;
+ }
+ bool any_cost2 = false;
+ int c2x = 3;
+ if (t->cost2)
+ for (int m = 0; m < M_COUNT; m++) any_cost2 |= t->cost2[m] > 0;
+ if (any_cost2) {
+ cost2_y = y;
+ if (t->cost2_text && *t->cost2_text) c2x += ui_text_w(FONT_STANDARD, t->cost2_text) + 3;
+ y += 2;
+ int cw = ui_cost(0, INT16_MIN, t->cost2, "", "", false) + c2x;
+ if (cw > width) width = cw;
+ y += 11;
+ }
+ if (t->nextra && header_w + extra_w > width) width = header_w + extra_w;
+ y += 2;
+ int height = y;
+ /* where: at the top-left (continuous), else above the button (or under it if there's no room) */
+ int px, py;
+ if (continuous) {
+ px = 0, py = 0;
+ } else {
+ px = ax, py = ay > height ? ay - height : ay + 21;
+ if (px + width > SCREEN_W) {
+ px -= width;
+ if (px < 0) px = 0;
+ }
+ }
+ ui_noclip();
+ ui_box(px, py, width, height, BX_TOOLTIP);
+ /* (copied: tooltips are often made in a buffer that is gone by the time the frame is drawn) */
+ if (hh) ui_para(FONT_16, px + 2, py + header_y, hmax, t->header, C_BLACK, false, NULL);
+ if (th) ui_para(FONT_STANDARD, px + 3, py + text_y, tmax, t->text, C_BLACK, false, NULL);
+ if (t->nextra2) ui_icon_list(px + 2, py + extra2_y, t->extra2, t->nextra2);
+ if (any_cost) ui_cost(px + 3, py + cost_y, t->cost, "", after, true);
+ if (any_cost2) {
+ if (t->cost2_text) ui_text(FONT_STANDARD, px + 3, py + cost2_y, t->cost2_text, C_BLACK);
+ ui_cost(px + c2x, py + cost2_y + 2, t->cost2, "", "", false);
+ }
+ if (t->nextra) ui_icon_list(px + width - 1 - extra_w, py + header_y + 3, t->extra, t->nextra);
+}
+
+/* ---------------------------------------------------------------- the build menu (gui.BuildingButtons) */
+enum { BB_CATEGORY, BB_MODE, BB_MODES_MORE, BB_MANAGEMENT, BB_BUILDING, BB_DECORATION, BB_RESOURCE, BB_SUBCATEGORY,
+ BB_SUB_BACK, BB_SUB_MIRROR, BB_MODE_PICK, BB_INVITE, BB_FOLLOW, BB_UPGRADES, BB_FIND,
+ BB_ANYCOLOR_LAST, BB_ANYCOLOR_PICK }; /* an any-colour class's last colour, and its colour picker */
+typedef struct {
+ int16_t x, y;
+ uint8_t w, kind, arg, arg2; /* arg: category, class, decoration, resource, mode...; arg2: a decoration's look */
+} BButton;
+#define BB_MAX 64
+typedef struct {
+ BButton b[BB_MAX];
+ int n, nrow; /* the first nrow are the bottom row (categories, modes, management) */
+ int at_width; /* the shown category's button's x */
+ int8_t sub; /* the shown subcategory + 1 */
+} BMenu;
+static int8_t shown_sub; /* the decoration subcategory shown, 0 none */
+static int8_t last_category = -1; /* the category the menu showed last */
+static uint8_t menu_opened; /* times the menu was opened (its keys are told the first times) */
+static struct { int8_t kind; uint8_t arg, arg2; } last_pick = {-1, 0, 0}; /* the button picked last */
+bool follow_mode; /* viewActions.showFollow: OK picks the citizen nearest the cursor */
+
+static bool cat_any_unlocked(int c) {
+ for (int i = 0; i < nbuild_order; i++) {
+ int k = build_order[i];
+ if (pcls[k].category == c && !cls_text[k].sub && unlock_state(k) != UNLOCK_LOCKED) return true;
+ }
+ if (c == 6 && unlocks.unlockedDecorationTab) return true; /* decorations and world resources */
+ return false;
+}
+
+static void bb_add(BMenu *m, int x, int y, int w, int kind, int arg, int arg2) {
+ if (m->n >= BB_MAX) return;
+ m->b[m->n++] = (BButton){(int16_t)x, (int16_t)y, (uint8_t)w, (uint8_t)kind, (uint8_t)arg, (uint8_t)arg2};
+}
+
+/* the left edge of the city panel for a row of the screen (rows of buttons stop before it) */
+static int panel_left_at(int y0, int y1);
+
+/* a row of buttons to the right of x0 at y, going on in rows above it when it doesn't fit */
+static void bb_row(BMenu *m, const BButton *list, int n, int x0, int y) {
+ int k = 0;
+ while (k < n && y >= 0) {
+ int limit = panel_left_at(y, y + 22), x = x0;
+ if (limit - x0 < 22) limit = x0 + 22;
+ for (; k < n && x + 22 <= limit; k++, x += 22) {
+ BButton b = list[k];
+ b.x = (int16_t)x, b.y = (int16_t)y;
+ if (m->n < BB_MAX) m->b[m->n++] = b;
+ }
+ y -= 22;
+ }
+}
+
+/* The build menu, as UI.md has it: the categories' buttons (gui.BuildingButtons) in a column at the
+ * bottom left, then the building mode and the management buttons; the shown category's buildings in a row
+ * to the right of its button (more rows above it if they don't fit before the city panel). */
+static void bmenu_layout(BMenu *m) {
+ m->n = 0;
+ int y = SCREEN_H - 22;
+ int cat_y = -1, mode_y = -1, mgmt_y = -1;
+ m->at_width = -1;
+ for (int c = 0; c < NCATEGORIES; c++) {
+ if (!cat_any_unlocked(c)) continue;
+ if (c == cu.category) cat_y = y;
+ bb_add(m, 0, y, 22, BB_CATEGORY, c, 0);
+ y -= 22;
+ }
+ if (unlocks.unlockedBuildingModeButton) {
+ mode_y = y;
+ bb_add(m, 0, y, 22, BB_MODE, 0, 0);
+ y -= 22;
+ }
+ if (unlocks.unlockedManagementOptions) {
+ mgmt_y = y;
+ bb_add(m, 0, y, 22, BB_MANAGEMENT, 0, 0);
+ }
+ m->nrow = m->n;
+ m->at_width = cat_y;
+ /* the building modes, right of the mode button */
+ if (cu.modes_open && mode_y >= 0) {
+ BButton list[BM_COUNT];
+ for (int i = 0; i < BM_COUNT; i++) list[i] = (BButton){0, 0, 22, BB_MODE_PICK, (uint8_t)i, 0};
+ bb_row(m, list, BM_COUNT, 22, mode_y);
+ }
+ /* the management options, right of the management button */
+ if (cu.mgmt_open && mgmt_y >= 0) {
+ BButton list[4];
+ int k = 0;
+ if (stories[story.index].flags & ST_INVITE) list[k++] = (BButton){0, 0, 22, BB_INVITE, 0, 0};
+ list[k++] = (BButton){0, 0, 22, BB_FOLLOW, 0, 0};
+ list[k++] = (BButton){0, 0, 22, BB_UPGRADES, 0, 0};
+ list[k++] = (BButton){0, 0, 22, BB_FIND, 0, 0};
+ bb_row(m, list, k, 22, mgmt_y);
+ }
+ if (cu.category < 0 || cat_y < 0) return;
+ /* the buttons of the category, in the original's order */
+ BButton list[BB_MAX];
+ int n = 0;
+#define ADD(kind, a, a2) do { if (n < BB_MAX) list[n++] = (BButton){0, 0, 22, (kind), (uint8_t)(a), (uint8_t)(a2)}; } while (0)
+ int c = cu.category;
+ if (shown_sub) {
+ ADD(BB_SUB_BACK, 0, 0);
+ if (shown_sub - 1 == 1) ADD(BB_SUB_MIRROR, 0, 0); /* slanted roofs */
+ }
+ for (int i = 0; i < nbuild_order; i++) {
+ int k = build_order[i];
+ if (unlock_state(k) == UNLOCK_LOCKED) continue;
+ if (shown_sub ? cls_text[k].sub != shown_sub : (pcls[k].category != c || cls_text[k].sub)) continue;
+ const ClsText *ct = &cls_text[k];
+ bool needs_unlock = ct->hint && unlock_state(k) == UNLOCK_UNLOCKED;
+ if ((ct->flags & CT_MULTI_DECOR) && !needs_unlock) {
+ int looks = (ct->flags & CT_MULTI_SPEC) ? 2 : (spr_w(pcls[k].sprite) + 2) / 22;
+ if (ct->flags & CT_ANYCOLOR) {
+ /* the last look in the colour picked when the menu opened, the looks, then the last look: the picker */
+ if (color_picked_on_menu_open >= 0) ADD(BB_ANYCOLOR_LAST, k, looks - 1);
+ for (int l = 0; l < looks - 1; l++) ADD(BB_BUILDING, k, l);
+ ADD(BB_ANYCOLOR_PICK, k, looks - 1);
+ } else {
+ for (int l = 0; l < looks; l++) ADD(BB_BUILDING, k, l);
+ }
+ } else {
+ ADD(BB_BUILDING, k, 0);
+ }
+ }
+ if (!shown_sub && c == 6 && unlocks.unlockedDecorationTab) {
+ for (int i = 0; i < ndeco_text; i++)
+ if (decoration_available(i)) ADD(BB_DECORATION, i, 0);
+ for (int i = 0; i < nres_text; i++)
+ if (unlock_state(res_text[i].cls) != UNLOCK_LOCKED) ADD(BB_RESOURCE, i, 0);
+ for (int s = 0; s < NSUBCATEGORIES; s++) ADD(BB_SUBCATEGORY, s, 0);
+ }
+#undef ADD
+ bb_row(m, list, n, 22, cat_y);
+}
+
+static const uint16_t mode_icon[] = {
+ [BM_NORMAL] = SPR_ICON_BUILDINGMODE_ONTOP, [BM_INSERT] = SPR_ICON_BUILDINGMODE_INSERT,
+ [BM_REPLACE] = SPR_ICON_BUILDINGMODE_REPLACE, [BM_DRAG] = SPR_ICON_BUILDINGMODE_DRAG,
+ [BM_DRAG_REPLACE] = SPR_ICON_BUILDINGMODE_DRAGREPLACE, [BM_DESTROY] = SPR_ICON_BUILDINGMODE_DESTROY,
+ [BM_DESTROY_LEAVING_HOLE] = SPR_ICON_BUILDINGMODE_DESTROYLEAVINGHOLE};
+
+static bool bb_active(const BButton *b) {
+ switch (b->kind) {
+ case BB_CATEGORY: return cu.category == b->arg;
+ case BB_MODE: return cu.modes_open;
+ case BB_MANAGEMENT: return cu.mgmt_open;
+ case BB_MODE_PICK: return building_mode == b->arg;
+ case BB_BUILDING:
+ case BB_ANYCOLOR_PICK:
+ /* (the picker's button is never on once there is a last-colour button) */
+ if (b->kind == BB_ANYCOLOR_PICK && color_picked_on_menu_open >= 0) return false;
+ return cu.build_kind == BK_BUILDING && cu.build_cls == b->arg && cu.build_decor == b->arg2 && cu.build_color < 0;
+ case BB_ANYCOLOR_LAST:
+ return cu.build_kind == BK_BUILDING && cu.build_cls == b->arg && cu.build_decor == b->arg2 &&
+ cu.build_color == color_picked_on_menu_open;
+ case BB_DECORATION: return cu.build_kind == BK_DECORATION && cu.build_cls == b->arg;
+ case BB_RESOURCE: return cu.build_kind == BK_RESOURCE && cu.build_cls == b->arg;
+ case BB_INVITE: return win_is_open(WK_INVITE);
+ case BB_FOLLOW: return follow_mode;
+ case BB_UPGRADES: return win_is_open(WK_UPGRADES);
+ case BB_FIND: return win_is_open(WK_FIND);
+ }
+ return false;
+}
+
+/* ---------------------------------------------------------------- the story's highlights (updateGoalAttentions) */
+#define ATTENTION_TINT 0x6620 /* HSV (89, 1, 0.77) */
+/* the classes and upgrades the current goal still asks for */
+static struct { float stamp; int8_t n; int16_t cls[4], ups[4]; } wants; /* worked out once a frame */
+static int goal_wants(int *cls, int *ups, int max) {
+ if (wants.stamp != cu.gui_timer) {
+ wants.stamp = cu.gui_timer;
+ wants.n = 0;
+ const StoryGoal *g = story_goal();
+ for (int i = 0; g && !ui.title && i < g->nsub && wants.n < 4; i++) {
+ if (story_subgoal_complete(i)) continue;
+ const SubGoal *sg = &g->sub[i];
+ if (sg->type == SG_BUILDPERMANENTS) {
+ wants.cls[wants.n] = sg->cls, wants.ups[wants.n] = -1, wants.n++;
+ } else if (sg->type == SG_PERFORMBUILDINGUPGRADES || sg->type == SG_PERFORMCITYUPGRADE) {
+ wants.cls[wants.n] = -1, wants.ups[wants.n] = (int16_t)upgrade_find(sg->name), wants.n++;
+ }
+ }
+ }
+ int n = wants.n < max ? wants.n : max;
+ for (int i = 0; i < n; i++) cls[i] = wants.cls[i], ups[i] = wants.ups[i];
+ return n;
+}
+
+static bool cls_needs_attention(int k) {
+ int cls[4], ups[4], n = goal_wants(cls, ups, 4);
+ for (int i = 0; i < n; i++) {
+ if (cls[i] != k) continue;
+ float cost[M_COUNT];
+ for (int m = 0; m < M_COUNT; m++) cost[m] = pcls[k].cost[m];
+ return mat_can_afford(cost);
+ }
+ return false;
+}
+
+static bool cat_needs_attention(int c) {
+ int cls[4], ups[4], n = goal_wants(cls, ups, 4);
+ for (int i = 0; i < n; i++)
+ if (cls[i] >= 0 && pcls[cls[i]].category == c && cls_needs_attention(cls[i])) return true;
+ return false;
+}
+
+/* buildings that can take the upgrade the goal asks for: a pulsing green outline (unless their window shows it) */
+void goal_upgrade_highlights(void) {
+ int cls[4], ups[4], n = goal_wants(cls, ups, 4);
+ for (int i = 0; i < n; i++) {
+ int u = ups[i];
+ if (u < 0) continue;
+ if (!mat_can_afford(upgrade_info[u].cost)) continue;
+ int drawn = 0;
+ for (int id = 1; id < MAX_PERMS && drawn < 24; id++) {
+ Perm *p = &perms[id];
+ if (!(p->flags & PF_USED) || !is_building(p)) continue;
+ UpgradeOption opts[16];
+ int k = upgrade_options(p, opts, 16), j = 0;
+ for (; j < k; j++)
+ if (opts[j].upgrade == u && !opts[j].owned) break;
+ if (j == k) continue;
+ if (nwins && wins[nwins - 1].kind == WK_BUILDING && wins[nwins - 1].arg == id) continue;
+ outline_perm((uint16_t)id, SPR_WHITEOUTLINE, ATTENTION_TINT, pulse(0, 1), -1);
+ drawn++;
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- drawing the build menu */
+static void draw_bbutton(const BButton *b, bool focused) {
+ bool active = bb_active(b), down = focused && key_held(K_OK);
+ int frame = down || active ? 2 : focused ? 1 : 0;
+ int x = b->x, y = b->y;
+ bool attention = false;
+ if (b->kind == BB_CATEGORY || b->kind == BB_MODE || b->kind == BB_MANAGEMENT) {
+ ui_frame(SPR_TRANSPARENTBUTTON, 22, frame, x, y, 0, 255);
+ } else if (b->kind == BB_MODES_MORE) {
+ ui_frame(SPR_MOREBUILDINGMODEBUTTONS, 12, frame, x, y, 0, 255);
+ } else {
+ ui_frame(SPR_BUILDINGBUTTON, 22, frame, x, y, 0, 255);
+ }
+ switch (b->kind) {
+ case BB_CATEGORY:
+ ui_spr(cat_text[b->arg].icon, x + 1, y + 1);
+ attention = cat_needs_attention(b->arg);
+ if ((unlocks.notifyCategory >> b->arg & 1) && cu.category != b->arg) ui_spr(SPR_BUTTONNOTIFICATION, x, y);
+ break;
+ case BB_MODE: ui_spr(mode_icon[building_mode], x + 1, y + 1); break;
+ case BB_MODES_MORE: ui_spr(SPR_MOREBUILDINGMODES_ARROWUP, x + 1, y + 1); break;
+ case BB_MANAGEMENT: ui_spr(SPR_ICON_MANAGEMENT, x + 1, y + 1); break;
+ case BB_MODE_PICK: ui_spr(mode_icon[b->arg], x + 1, y + 1); break;
+ case BB_INVITE: ui_spr(SPR_ICON_INVITEPEOPLE, x + 1, y + 1); break;
+ case BB_FOLLOW: ui_spr(SPR_ICON_FOLLOWCITIZEN, x + 1, y + 1); break;
+ case BB_UPGRADES: ui_spr(SPR_ICON_UPGRADE, x + 1, y + 1); break;
+ case BB_FIND: ui_spr(SPR_ICON_FINDBUILDING, x + 1, y + 1); break;
+ case BB_SUB_BACK: ui_spr(SPR_ARROW_BACK, x + 1, y + 1); break;
+ case BB_SUB_MIRROR: ui_spr(SPR_MIRROR, x + 1, y + 1); break;
+ case BB_SUBCATEGORY: ui_spr_ex(sub_text[b->arg].icon, 0, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT); break;
+ case BB_DECORATION: ui_spr_ex(deco_text[b->arg].spr, 0, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT); break;
+ case BB_RESOURCE: ui_spr_ex(pcls[res_text[b->arg].cls].sprite, 0, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT); break;
+ case BB_ANYCOLOR_LAST:
+ case BB_ANYCOLOR_PICK:
+ case BB_BUILDING: {
+ int k = b->arg;
+ const ClsText *ct = &cls_text[k];
+ bool locked = ct->hint && unlock_state(k) == UNLOCK_UNLOCKED;
+ uint8_t flags = (ct->flags & CT_MIRRORABLE) && cu.mirrored ? GFX_FLIPX : 0;
+ uint16_t spr = pcls[k].sprite;
+ if (locked) {
+ ui_spr_ex(SPR_LOCKEDBUILDING, 22, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT);
+ ui_spr_ex(SPR_LOCKEDBUILDING, 0, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT);
+ } else if (ct->flags & CT_MULTI_SPEC) {
+ uint16_t s2 = b->arg2 ? SPR_TREEPLANTATION : SPR_INDOORFARM;
+ ui_spr_ex(s2, 44, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT);
+ ui_spr_ex(s2, 0, 0, 20, 20, x + 1, y + 1, 0, 255, GFX_NO_TINT);
+ } else if (ct->flags & CT_MULTI_DECOR) {
+ uint16_t tint = b->kind == BB_ANYCOLOR_LAST ? rgb565_near((uint32_t)color_picked_on_menu_open) : GFX_NO_TINT;
+ ui_spr_ex(spr, 22 * b->arg2, 0, 20, 20, x + 1, y + 1, flags, 255, tint);
+ if (b->kind == BB_ANYCOLOR_PICK) ui_spr(SPR_RECOLORABLE, x, y);
+ } else {
+ if (ct->back == BACK_OWN && spr_w(spr) >= 64) ui_spr_ex(spr, 44, 0, 20, 20, x + 1, y + 1, flags, 255, GFX_NO_TINT);
+ else if (ct->back && ct->back != BACK_OWN) ui_spr_ex(ct->back, 0, 0, 20, 20, x + 1, y + 1, flags, 255, GFX_NO_TINT);
+ ui_spr_ex(spr, 0, 0, 20, 20, x + 1, y + 1, flags, 255, GFX_NO_TINT);
+ }
+ if (unlocks_should_notify(k)) ui_spr(SPR_BUTTONNOTIFICATION, x, y);
+ attention = cls_needs_attention(k);
+ break;
+ }
+ }
+ if (attention && frame == 0) ui_spr_ex(SPR_WHITEOUTLINE, 0, 0, 22, 22, x, y, 0, pulse(0, 1), ATTENTION_TINT);
+}
+
+/* the focused build menu button's tooltip */
+static void bbutton_tooltip(const BButton *b) {
+ Tip t = {0};
+ char text[400], hb[64];
+ float cost[M_COUNT], cost2[M_COUNT];
+ IconText extra[4];
+ char e0[16], e1[16], e2[16], e3[40];
+ IconText extra2[1];
+ switch (b->kind) {
+ case BB_CATEGORY: t.header = cat_text[b->arg].name, t.text = cat_text[b->arg].desc; break;
+ case BB_MODE:
+ case BB_MODE_PICK: {
+ int mode = b->kind == BB_MODE ? (int)building_mode : b->arg;
+ static const char *const names[BM_COUNT] = {L_build_mode_normal, L_build_mode_insert, L_build_mode_replace,
+ L_build_mode_multi, L_build_mode_multi_replace, L_build_mode_destroy,
+ L_build_mode_destroyleavinghole};
+ static const char *const texts[BM_COUNT] = {L_build_mode_normal_explanation, L_build_anywhere,
+ L_build_mode_replace_explanation, L_build_mode_multi_explanation,
+ L_build_mode_multi_replace_explanation, L_build_mode_destroy_explanation,
+ L_build_mode_destroyleavinghole_explanation};
+ t.header = names[mode], t.text = texts[mode];
+ break;
+ }
+ case BB_MODES_MORE: t.text = L_all_building_modes; break;
+ case BB_MANAGEMENT: t.text = L_management; break;
+ case BB_INVITE: t.text = L_invite_people; break;
+ case BB_FOLLOW: t.text = L_follow_citizen; break;
+ case BB_UPGRADES: t.text = L_upgrades_and_policies; break;
+ case BB_FIND: t.text = L_highlight_buildings; break;
+ case BB_SUB_BACK: t.text = L_back; break;
+ case BB_SUB_MIRROR: t.text = L_mirror; break;
+ case BB_SUBCATEGORY: t.text = sub_text[b->arg].name; break;
+ case BB_DECORATION: {
+ const DecoText *d = &deco_text[b->arg];
+ memset(cost, 0, sizeof cost);
+ cost[M_FOOD] = d->food, cost[M_WOOD] = d->wood, cost[M_STONE] = d->stone;
+ t.header = d->name, t.text = d->desc, t.cost = cost;
+ break;
+ }
+ case BB_RESOURCE: {
+ const ResText *r = &res_text[b->arg];
+ memset(cost, 0, sizeof cost);
+ cost[M_WOOD] = r->wood, cost[M_STONE] = r->stone;
+ t.header = r->name, t.text = r->desc, t.cost = cost;
+ break;
+ }
+ case BB_ANYCOLOR_LAST:
+ case BB_ANYCOLOR_PICK:
+ case BB_BUILDING: {
+ /* BuildingButtons.showBuildingTooltip */
+ int k = b->arg;
+ const ClsText *ct = &cls_text[k];
+ if (ct->hint && unlock_state(k) == UNLOCK_UNLOCKED) {
+ t.text = ct->hint;
+ break;
+ }
+ Materials m;
+ builder_cost(k, &m);
+ for (int i = 0; i < M_COUNT; i++) cost[i] = (float)m.m[i];
+ t.cost = cost;
+ int n = 0, count = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == k) count++;
+ if (pcls[k].jobs) fmt_int(e0, sizeof e0, pcls[k].jobs), extra[n++] = (IconText){SPR_WORK, e0};
+ if (pcls[k].residents) fmt_int(e1, sizeof e1, pcls[k].residents), extra[n++] = (IconText){SPR_RESIDENTS, e1};
+ if (pcls[k].quality) fmt_int(e2, sizeof e2, pcls[k].quality), extra[n++] = (IconText){SPR_HAPPINESS, e2};
+ if (upgrades.hasGalacticLibrary && (ct->flags & CT_NOT_UNIQUE_GL)) {
+ e3[0] = 0;
+ if (count >= 2) str_cat(e3, sizeof e3, "[red]");
+ char lim[32];
+ str_cat(e3, sizeof e3, lo_1(lim, sizeof lim, L_limitedBuilding, LS("2")));
+ extra[n++] = (IconText){SPR_UNIQUEBUILDING, e3};
+ } else if (ct->flags & CT_UNIQUE) {
+ extra[n++] = (IconText){SPR_UNIQUEBUILDING, count ? "[red]Already Built" : L_unique};
+ }
+ if (ct->flags & CT_LIMITED) {
+ char lim[40];
+ lo_1(lim, sizeof lim, L_limited_per_citizens, LN(ct->limited));
+ e3[0] = 0;
+ if (count >= (ncits + ct->limited - 1) / ct->limited) str_cat(e3, sizeof e3, "[red]");
+ str_cat(e3, sizeof e3, lim);
+ extra[n++] = (IconText){SPR_UNIQUEBUILDING, e3};
+ }
+ t.extra = extra, t.nextra = n;
+ if (ct->tip_icon) extra2[0] = (IconText){ct->tip_icon, ""}, t.extra2 = extra2, t.nextra2 = 1;
+ /* "!unlocks", and the first house's lower price */
+ text[0] = 0;
+ const char *d = ct->desc, *u = strstr(d, "!unlocks");
+ if (u) {
+ int len = (int)(u - d);
+ if (len > (int)sizeof text - 1) len = (int)sizeof text - 1;
+ memcpy(text, d, (size_t)len);
+ text[len] = 0;
+ if (!count) str_cat(str_cat(text, sizeof text, " "), sizeof text, L_also_unlocks_new);
+ str_cat(text, sizeof text, u + 8);
+ } else {
+ str_cat(text, sizeof text, d);
+ }
+ if (k == CLS_NormalHouse && story_is("theLostShip") && story_goal() && !strcmp(story_goal()->name, "BuildIndoorFarmAndHouse") && !count)
+ str_cat(str_cat(text, sizeof text, " "), sizeof text, L_first_house_cheaper);
+ t.header = ct->name, t.text = text;
+ if (pcls[k].teleporterOperatingCost > 0) {
+ memset(cost2, 0, sizeof cost2);
+ cost2[M_KNOWLEDGE] = pcls[k].teleporterOperatingCost * (bld_misdirector() ? 0.5f : 1) * (1 - upgrades.rocketTeleporterReward);
+ t.cost2 = cost2;
+ hb[0] = 0;
+ t.cost2_text = str_cat(str_cat(hb, sizeof hb, L_operating_cost_pd), sizeof hb, " ");
+ }
+ break;
+ }
+ }
+ /* the menu's keys, the first times it opens */
+ char with_hint[480];
+ if (menu_opened <= 2) {
+ with_hint[0] = 0;
+ if (t.text && *t.text) str_cat(str_cat(with_hint, sizeof with_hint, t.text), sizeof with_hint, "\n");
+ t.text = str_cat(with_hint, sizeof with_hint, L_keypad_menu_hint);
+ }
+ ui_tooltip(&t, b->x + 11, b->y, false);
+}
+
+/* while building, the mobile version's continuous tooltip at the top: what is being built, its cost */
+static void builder_tooltip(void) {
+ if (cu.build_kind == BK_NONE || nwins) return;
+ Tip t = {0};
+ char head[96];
+ float cost[M_COUNT];
+ build_cost(cost);
+ t.cost = cost;
+ if (cu.build_kind == BK_BUILDING) {
+ t.header = lo_1(head, sizeof head, L_building_a_building, LS(cls_text[cu.build_cls].name));
+ t.text = L_keypad_builder_hint; /* (the keypad's keys, where the original needs none) */
+ } else if (cu.build_kind == BK_DECORATION) {
+ const DecoText *d = &deco_text[cu.build_cls];
+ t.header = d->flags & DT_REMOVE ? d->name : lo_1(head, sizeof head, L_placing_a_decoration, LS(d->name));
+ t.text = d->desc;
+ } else if (cu.build_kind == BK_RESOURCE) {
+ const ResText *r = &res_text[cu.build_cls];
+ t.header = lo_1(head, sizeof head, pcls[r->cls].base & B_FOREST ? L_planting_a_forest : L_placing_a_decoration, LS(r->name));
+ t.text = r->desc;
+ } else {
+ /* moving alien ruins (the original's simple window at the top) */
+ t.cost = NULL;
+ t.text = L_move_ruins_howto;
+ }
+ ui_tooltip(&t, 0, 0, true);
+}
+
+static void bmenu_draw(bool tip) {
+ BMenu m;
+ bmenu_layout(&m);
+ int focus = cu.zone == Z_BUILD && !nwins ? cu.bfocus : -2;
+ if (!tip) {
+ for (int i = 0; i < m.n; i++) draw_bbutton(&m.b[i], i == focus);
+ /* the keypad's focus: the window buttons' green frame, over the button's edge */
+ if (focus >= 0 && focus < m.n) ui_ring(m.b[focus].x + 2, m.b[focus].y + 2, m.b[focus].w - 4, 18, 2, FOCUS_RING);
+ } else if (focus >= 0 && focus < m.n) {
+ bbutton_tooltip(&m.b[focus]);
+ }
+}
+
+/* a build menu button for the tutorial arrows */
+bool city_build_rect(int which, int16_t r[4]) {
+ BMenu m;
+ bmenu_layout(&m);
+ int pick = -1;
+ if (which == BR_FIRST_CATEGORY) {
+ for (int i = 0; i < m.nrow && pick < 0; i++)
+ if (m.b[i].kind == BB_CATEGORY) pick = i;
+ } else if (which == BR_LAST_BUILDING || which == BR_SECOND_LAST_BUILDING) {
+ /* the last button of the category's first row (the latest added) */
+ int best = -1;
+ for (int i = m.nrow; i < m.n; i++)
+ if (m.b[i].y == m.at_width && (best < 0 || m.b[i].x > m.b[best].x)) best = i;
+ pick = best;
+ } else if (which == BR_INVITE || which == BR_MANAGEMENT) {
+ for (int i = 0; i < m.n && pick < 0; i++)
+ if (m.b[i].kind == (which == BR_INVITE ? BB_INVITE : BB_MANAGEMENT)) pick = i;
+ }
+ if (pick < 0) return false;
+ r[0] = m.b[pick].x, r[1] = m.b[pick].y, r[2] = m.b[pick].w, r[3] = 22;
+ return true;
+}
+
+/* ---------------------------------------------------------------- the build menu's keys */
+
+/* ---------------------------------------------------------------- the build menu on a keypad
+ * The column at the left works as tabs: the focus on one shows its row (a category's buildings, the building
+ * modes, the management options). toolbox opens the menu on a category's buildings, left and right go along the
+ * row, up and down to the next tab (its row shown at once), OK picks. */
+
+/* the column's button of the row shown (its tab), -1 none */
+static int bmenu_tab(const BMenu *m) {
+ for (int i = 0; i < m->nrow; i++) {
+ const BButton *b = &m->b[i];
+ if ((b->kind == BB_CATEGORY && b->arg == cu.category && !cu.modes_open && !cu.mgmt_open) ||
+ (b->kind == BB_MODE && cu.modes_open) || (b->kind == BB_MANAGEMENT && cu.mgmt_open))
+ return i;
+ }
+ return -1;
+}
+
+/* a tab's row shown (a builder stays) */
+static void bmenu_show_tab(int kind, int arg) {
+ cu.modes_open = cu.mgmt_open = false;
+ shown_sub = 0;
+ cu.category = -1;
+ if (kind == BB_CATEGORY) {
+ cu.category = (int8_t)arg, last_category = (int8_t)arg;
+ unlocks.notifyCategory &= (uint16_t)~(1 << arg);
+ } else if (kind == BB_MODE) {
+ cu.modes_open = true;
+ } else if (kind == BB_MANAGEMENT) {
+ cu.mgmt_open = true;
+ }
+}
+
+/* the focus into the row shown: the button of what is being built (or was picked last), else the one nearest x on
+ * the row's bottom line (x < 0: its first); a row without buttons: its tab */
+static void bmenu_focus_row(int x) {
+ BMenu m;
+ bmenu_layout(&m);
+ for (int i = m.nrow; i < m.n; i++)
+ if (bb_active(&m.b[i]) && m.b[i].kind != BB_UPGRADES && m.b[i].kind != BB_FIND && m.b[i].kind != BB_INVITE) {
+ cu.bfocus = (int8_t)i;
+ return;
+ }
+ if (x < 0)
+ for (int i = m.nrow; i < m.n; i++)
+ if (m.b[i].kind == last_pick.kind && m.b[i].arg == last_pick.arg && m.b[i].arg2 == last_pick.arg2) {
+ cu.bfocus = (int8_t)i;
+ return;
+ }
+ int base = -1, best = -1, bd = 1 << 30;
+ for (int i = m.nrow; i < m.n; i++)
+ if (m.b[i].y > base) base = m.b[i].y;
+ for (int i = m.nrow; i < m.n; i++) {
+ if (m.b[i].y != base) continue;
+ int d = x < 0 ? m.b[i].x : abs(m.b[i].x + 11 - x);
+ if (d < bd) bd = d, best = i;
+ }
+ cu.bfocus = (int8_t)(best >= 0 ? best : bmenu_tab(&m));
+}
+
+/* toolbox: the menu, on the category it showed last (else the first), the focus on its buildings */
+static void bmenu_open(void) {
+ cu.zone = Z_BUILD;
+ if (menu_opened < 255) menu_opened++;
+ if (cu.category < 0 && !cu.modes_open && !cu.mgmt_open) {
+ BMenu m;
+ bmenu_layout(&m);
+ int pick = -1;
+ for (int i = 0; i < m.nrow; i++)
+ if (m.b[i].kind == BB_CATEGORY && (pick < 0 || m.b[i].arg == last_category)) pick = i;
+ if (pick >= 0) bmenu_show_tab(BB_CATEGORY, m.b[pick].arg);
+ }
+ bmenu_focus_row(-1);
+}
+
+/* out of the menu: its rows close (a builder keeps its category shown) */
+static void bmenu_close(void) {
+ if (cu.build_kind == BK_NONE) cu.category = -1;
+ cu.modes_open = cu.mgmt_open = false;
+ if (cu.build_kind == BK_NONE) shown_sub = 0;
+ cu.zone = Z_CITY;
+}
+
+/* a button of the row pressed (the tabs are bmenu_input's) */
+static void bmenu_press(BMenu *m, int i) {
+ BButton *b = &m->b[i];
+ switch (b->kind) {
+ case BB_MODE_PICK:
+ building_mode = (BuildingMode)b->arg;
+ if (b->arg == BM_DESTROY || b->arg == BM_DESTROY_LEAVING_HOLE) {
+ builder_stop();
+ cu.zone = Z_CITY; /* to pick what to destroy */
+ }
+ cu.modes_open = false;
+ cu.bfocus = -1;
+ break;
+ case BB_INVITE: win_open_only(WK_INVITE, 0, 0); break;
+ case BB_FOLLOW:
+ follow_mode = !follow_mode;
+ if (follow_mode) {
+ builder_stop();
+ cu.zone = Z_CITY;
+ notify_top(L_tap_near_citizen_to_follow, NULL, 240);
+ }
+ break;
+ case BB_UPGRADES: win_open_only(WK_UPGRADES, 0, 0); break;
+ case BB_FIND: win_open_only(WK_FIND, 0, 0); break;
+ case BB_SUB_BACK: shown_sub = 0; break;
+ case BB_SUB_MIRROR:
+ /* the builder stays, mirrored or not */
+ cu.mirrored = !cu.mirrored;
+ if (cu.build_kind == BK_BUILDING)
+ builder_start_ex(BK_BUILDING, cu.build_cls, cu.build_decor, (cls_text[cu.build_cls].flags & CT_MIRRORABLE) && cu.mirrored,
+ cu.build_color);
+ break;
+ case BB_SUBCATEGORY: {
+ color_picked_on_menu_open = color_picked;
+ shown_sub = (int8_t)(b->arg + 1);
+ /* the subcategory's first button is picked (addBuildingButton): an any-colour class's last colour */
+ for (int k = 0; k < nbuild_order; k++) {
+ int c = build_order[k];
+ if (cls_text[c].sub != shown_sub || unlock_state(c) == UNLOCK_LOCKED) continue;
+ const ClsText *ct = &cls_text[c];
+ if ((ct->flags & CT_ANYCOLOR) && !(ct->hint && unlock_state(c) == UNLOCK_UNLOCKED))
+ builder_start_ex(BK_BUILDING, c, (spr_w(pcls[c].sprite) + 2) / 22 - 1, (ct->flags & CT_MIRRORABLE) && cu.mirrored,
+ color_picked_on_menu_open);
+ else
+ builder_start(BK_BUILDING, c, 0);
+ cu.zone = Z_BUILD;
+ break;
+ }
+ cu.bfocus = (int8_t)i;
+ break;
+ }
+ case BB_ANYCOLOR_LAST:
+ case BB_ANYCOLOR_PICK:
+ case BB_BUILDING: {
+ int k = b->arg;
+ const ClsText *ct = &cls_text[k];
+ unlocks_stop_notify(k);
+ if (ct->hint && unlock_state(k) == UNLOCK_UNLOCKED) {
+ /* showSimpleWindow(showUnlockHint) */
+ builder_stop();
+ win_open_text(NULL, ct->hint);
+ break;
+ }
+ if (b->kind == BB_ANYCOLOR_PICK) {
+ /* the colour picker, then a builder of this look in its colour */
+ builder_stop();
+ color_picker_open(COLOR_FOR_BUILDER, (uint16_t)k);
+ break;
+ }
+ int32_t col = b->kind == BB_ANYCOLOR_LAST ? color_picked_on_menu_open : -1;
+ if (cu.build_kind == BK_BUILDING && cu.build_cls == k && cu.build_decor == b->arg2 && cu.build_color == col) {
+ builder_stop(); /* createOrRemoveBuilder: the same again removes it */
+ break;
+ }
+ builder_start_ex(BK_BUILDING, k, b->arg2, (ct->flags & CT_MIRRORABLE) && cu.mirrored, col);
+ break;
+ }
+ case BB_DECORATION:
+ if (cu.build_kind == BK_DECORATION && cu.build_cls == b->arg) builder_stop();
+ else builder_start(BK_DECORATION, b->arg, 0);
+ break;
+ case BB_RESOURCE:
+ if (cu.build_kind == BK_RESOURCE && cu.build_cls == b->arg) builder_stop();
+ else builder_start(BK_RESOURCE, b->arg, 0);
+ break;
+ }
+}
+
+static void bmenu_input(void) {
+ BMenu m;
+ bmenu_layout(&m);
+ if (!m.n) {
+ cu.zone = Z_CITY;
+ return;
+ }
+ if (cu.bfocus < 0 || cu.bfocus >= m.n) {
+ bmenu_focus_row(-1);
+ if (cu.bfocus < 0 || cu.bfocus >= m.n) cu.bfocus = 0;
+ }
+ const BButton f = m.b[cu.bfocus];
+ bool in_row = cu.bfocus >= m.nrow;
+ int dx = key_repeat(K_RIGHT) ? 1 : key_repeat(K_LEFT) ? -1 : 0;
+ int dy = key_repeat(K_DOWN) ? 1 : key_repeat(K_UP) ? -1 : 0;
+ if (dx && in_row) {
+ /* along the row (its lines read as one), and from its first button to its tab */
+ int to = cu.bfocus + dx;
+ if (to >= m.nrow && to < m.n) cu.bfocus = (int8_t)to;
+ else if (dx < 0 && bmenu_tab(&m) >= 0) cu.bfocus = (int8_t)bmenu_tab(&m);
+ } else if (dx > 0) {
+ /* from a tab into its row */
+ if (bmenu_tab(&m) != cu.bfocus) bmenu_show_tab(f.kind, f.arg);
+ bmenu_focus_row(-1);
+ } else if (dy) {
+ /* another line of the row, else the next tab that way (its row shown at once) */
+ int to = -1, best = 1 << 30;
+ for (int i = m.nrow; in_row && i < m.n; i++) {
+ int ddy = m.b[i].y - f.y, ddx = m.b[i].x - f.x;
+ if (ddy * dy <= 0) continue;
+ int score = (ddy < 0 ? -ddy : ddy) * 16 + (ddx < 0 ? -ddx : ddx);
+ if (score < best) best = score, to = i;
+ }
+ if (to >= 0) {
+ cu.bfocus = (int8_t)to;
+ } else {
+ int tab = in_row ? bmenu_tab(&m) : cu.bfocus, next = -1;
+ for (int i = 0; tab >= 0 && i < m.nrow; i++)
+ if (m.b[i].y == m.b[tab].y + 22 * dy) next = i;
+ if (next >= 0) {
+ bmenu_show_tab(m.b[next].kind, m.b[next].arg);
+ if (in_row) bmenu_focus_row(f.x + 11);
+ else cu.bfocus = (int8_t)next; /* (the column doesn't move when the rows change) */
+ }
+ }
+ }
+ if (cu.bfocus >= m.nrow) {
+ BMenu m2;
+ bmenu_layout(&m2);
+ if (cu.bfocus < m2.n && (m2.b[cu.bfocus].kind == BB_BUILDING || m2.b[cu.bfocus].kind >= BB_ANYCOLOR_LAST))
+ unlocks_stop_notify(m2.b[cu.bfocus].arg);
+ }
+ if (input.released & K_OK) {
+ bmenu_layout(&m);
+ if (cu.bfocus < m.nrow) {
+ /* a tab: into its row */
+ if (bmenu_tab(&m) != cu.bfocus) bmenu_show_tab(m.b[cu.bfocus].kind, m.b[cu.bfocus].arg);
+ bmenu_focus_row(-1);
+ } else {
+ BButton b = m.b[cu.bfocus];
+ if (b.kind != BB_MODE_PICK) last_pick.kind = (int8_t)b.kind, last_pick.arg = b.arg, last_pick.arg2 = b.arg2;
+ bmenu_press(&m, cu.bfocus);
+ /* a building mode picked to build with: back to the buildings */
+ if (b.kind == BB_MODE_PICK && cu.zone == Z_BUILD) {
+ cu.category = -1;
+ bmenu_open();
+ }
+ }
+ }
+ if (key_pressed(K_BACK)) bmenu_close();
+}
+
+/* ---------------------------------------------------------------- the city panel (CityGUI.createCityInfo) */
+typedef struct { int16_t x, y, w, h; } Rect;
+typedef struct {
+ Rect r[PR_MAT0 + M_COUNT];
+ bool shown[PR_MAT0 + M_COUNT];
+ uint8_t mats[M_COUNT];
+ int nmats;
+} Panel;
+static const uint8_t mat_order[] = {M_FOOD, M_WOOD, M_STONE, M_KNOWLEDGE, M_MACHINEPARTS, M_REFINEDMETAL, M_COMPUTERCHIPS,
+ M_GRAPHENE, M_ROCKETFUEL};
+
+static const char *panel_text(int which, char *buf, int size) {
+ buf[0] = 0;
+ switch (which) {
+ case PR_POP: fmt_int(buf, size, ncits); break;
+ case PR_HAPPY:
+ if (happiness.happiness >= 124.99f) str_cat(buf, size, "xD");
+ else if (happiness.happiness >= 99.99f) str_cat(buf, size, ":D");
+ else fmt_int(buf, size, (long)happiness.happiness);
+ break;
+ case PR_HOUSES:
+ if (stats.peopleWithHome >= stats.people) fmt_int(buf, size, stats.houseCapacity - stats.peopleWithHome);
+ else {
+ str_cat(buf, size, "[red]-");
+ fmt_int(buf + 6, size - 6, stats.people - stats.peopleWithHome);
+ }
+ break;
+ case PR_WORK:
+ fmt_int(buf, size, stats.peopleWithAJob);
+ str_cat(buf, size, "/");
+ fmt_int(buf + strlen(buf), size - (int)strlen(buf), stats.laborForce);
+ break;
+ default:
+ if (which >= PR_MAT0) {
+ int m = which - PR_MAT0;
+ if (m == M_FOOD && eating.foodShortage > 0) str_cat(buf, size, "[red]");
+ fmt_int(buf + strlen(buf), size - (int)strlen(buf), (long)floor(city.materials.m[m]));
+ }
+ }
+ return buf;
+}
+
+static int info_w(int which, int min_w) {
+ char t[24];
+ uint16_t col;
+ const char *s = ui_color_prefix(panel_text(which, t, sizeof t), &col);
+ int w = 10 + 1 + ui_text_w(FONT_STANDARD, s);
+ return (w > min_w ? w : min_w) + 5;
+}
+
+static void panel_layout(Panel *pl) {
+ memset(pl, 0, sizeof *pl);
+ int right = SCREEN_W, bottom = SCREEN_H;
+ if (!cu.panel_hidden) {
+ /* the materials' column */
+ int mw = 0;
+ pl->nmats = 0;
+ for (unsigned i = 0; i < sizeof mat_order; i++)
+ if (unlocks_material_shown(mat_order[i])) pl->mats[pl->nmats++] = mat_order[i];
+ for (int i = 0; i < pl->nmats; i++) {
+ char t[24];
+ uint16_t col;
+ const char *s = ui_color_prefix(panel_text(PR_MAT0 + pl->mats[i], t, sizeof t), &col);
+ int w = 10 + 1 + ui_text_w(FONT_STANDARD, s) + 1;
+ w = (w > 42 ? w : 42) + 4;
+ if (w > mw) mw = w;
+ }
+ int my = bottom - 14 * pl->nmats;
+ for (int i = 0; i < pl->nmats; i++) {
+ int k = PR_MAT0 + pl->mats[i];
+ pl->r[k] = (Rect){(int16_t)(right - mw), (int16_t)(my + 14 * i), (int16_t)mw, 14};
+ pl->shown[k] = true;
+ }
+ right -= mw;
+ /* population and happiness, homes, work */
+ int pw = info_w(PR_POP, 23), hw = info_w(PR_HAPPY, 26), ow = info_w(PR_HOUSES, 20), ww = info_w(PR_WORK, 20);
+ int sw = pw + hw;
+ if (ow > sw) sw = ow;
+ if (ww > sw) sw = ww;
+ int sy = bottom - 42, sx = right - sw;
+ pl->r[PR_POP] = (Rect){(int16_t)sx, (int16_t)sy, (int16_t)pw, 14};
+ pl->r[PR_HAPPY] = (Rect){(int16_t)(sx + pw), (int16_t)sy, (int16_t)(sw - pw), 14};
+ pl->r[PR_HOUSES] = (Rect){(int16_t)sx, (int16_t)(sy + 14), (int16_t)sw, 14};
+ pl->r[PR_WORK] = (Rect){(int16_t)sx, (int16_t)(sy + 28), (int16_t)sw, 14};
+ pl->shown[PR_POP] = pl->shown[PR_HAPPY] = pl->shown[PR_HOUSES] = pl->shown[PR_WORK] = true;
+ right = sx;
+ }
+ /* the quick buttons: help, pause, speed, menu and the hide-UI toggle (14 x 14) */
+ int k = 0;
+ static const uint8_t quick[] = {PR_HELP, PR_PAUSE, PR_SPEED, PR_MENU, PR_HIDE};
+ int qx = right - 14 * 5;
+ for (k = 0; k < 5; k++) {
+ pl->r[quick[k]] = (Rect){(int16_t)(qx + 14 * k), (int16_t)(bottom - 14), 14, 14};
+ pl->shown[quick[k]] = quick[k] != PR_HELP || story_has_quick_text();
+ }
+}
+
+static int panel_left_at(int y0, int y1) {
+ Panel pl;
+ panel_layout(&pl);
+ int left = SCREEN_W;
+ for (int k = 0; k < PR_MAT0 + M_COUNT; k++) {
+ if (!pl.shown[k] && k != PR_HELP) continue;
+ Rect *r = &pl.r[k];
+ if (r->y < y1 && r->y + r->h > y0 && r->x < left) left = r->x;
+ }
+ return left;
+}
+
+bool city_panel_rect(int which, int16_t r[4]) {
+ Panel pl;
+ panel_layout(&pl);
+ if (which < 0 || which >= PR_MAT0 + M_COUNT || !pl.shown[which]) return false;
+ r[0] = pl.r[which].x, r[1] = pl.r[which].y, r[2] = pl.r[which].w, r[3] = pl.r[which].h;
+ return true;
+}
+
+/* whether a panel button's window is the one open (its active look) */
+static bool panel_active(int which) {
+ Win *wn = win_top();
+ switch (which) {
+ case PR_HELP: return win_is_open(WK_MISSIONS);
+ case PR_PAUSE: return city.paused;
+ case PR_MENU: return win_is_open(WK_GAME_MENU);
+ case PR_POP: return win_is_open(WK_POPULATION);
+ case PR_HAPPY: return win_is_open(WK_HAPPINESS);
+ case PR_HOUSES: return win_is_open(WK_HOUSES);
+ case PR_WORK: return win_is_open(WK_WORKERS);
+ default:
+ if (which >= PR_MAT0) return wn && wn->kind == WK_MATERIAL && wn->arg == which - PR_MAT0;
+ }
+ return false;
+}
+
+/* InfoBox's downward trend arrow: more used than made lately */
+static bool mat_downtrend(int m) {
+ double used1 = stats.materialUsed[m][1], prod1 = stats.materialProduction[m][1];
+ bool no_arrow = used1 + 0.2 < prod1 || (used1 < 0.2 && m != M_FOOD) || city_day() <= 5;
+ if (!no_arrow) {
+ double use3 = 0, prod3 = 0;
+ for (int d = 1; d <= 3; d++) use3 += stats.materialUsed[m][d], prod3 += stats.materialProduction[m][d];
+ no_arrow = use3 + 0.2 <= prod3;
+ }
+ if (!no_arrow) {
+ double prod0 = stats.materialProduction[m][0], cons0 = stats.materialUsed[m][0];
+ float hour = city_hour();
+ if (hour > 10 && prod0 > cons0 && prod0 * (1.1 + 0.1 * fmax(0, 12.0 - hour)) > cons0) no_arrow = true;
+ }
+ return !no_arrow;
+}
+
+static void panel_draw(void) {
+ Panel pl;
+ panel_layout(&pl);
+ int focus = cu.zone == Z_PANEL && !nwins ? cu.pfocus : -1;
+ for (int k = 0; k < PR_MAT0 + M_COUNT; k++) {
+ if (!pl.shown[k]) continue;
+ Rect *r = &pl.r[k];
+ bool f = k == focus, down = (f && key_held(K_OK)) || panel_active(k);
+ if (k <= PR_HIDE) {
+ ui_frame(SPR_TRANSPARENTBUTTON_INFO_MINI, 14, down ? 2 : f ? 1 : 0, r->x, r->y, 0, 255);
+ uint16_t icon = k == PR_HELP ? SPR_ICON_HELP : k == PR_PAUSE ? SPR_ICON_PAUSE : k == PR_SPEED ? speed_icon[cu.speed]
+ : k == PR_MENU ? SPR_ICON_MENU : 0;
+ if (icon) ui_spr(icon, r->x + 1, r->y + 1);
+ else ui_frame(SPR_HIDEUI, 12, cu.panel_hidden ? 0 : 1, r->x + 1, r->y + 1, 0, 255);
+ continue;
+ }
+ ui_box(r->x, r->y, r->w, r->h, down ? BX_TRANS_DOWN : f ? BX_TRANS_HOVER : BX_TRANS);
+ uint16_t icon = k == PR_POP ? SPR_POPULATION : k == PR_HAPPY ? SPR_HAPPINESS : k == PR_HOUSES ? SPR_HOUSING
+ : k == PR_WORK ? SPR_WORK : mat_icon[k - PR_MAT0];
+ ui_spr(icon, r->x + 2, r->y + 2);
+ if (k >= PR_MAT0 && mat_downtrend(k - PR_MAT0)) ui_spr(SPR_RESOURCE_DOWNTREND, r->x + 2, r->y + 2);
+ char t[24];
+ uint16_t col = C_BLACK;
+ const char *s = ui_color_prefix(panel_text(k, t, sizeof t), &col);
+ ui_text(FONT_STANDARD, r->x + 2 + 10 + 1, r->y + 1, s, col);
+ }
+ if (focus >= 0 && pl.shown[focus]) ui_ring(pl.r[focus].x + 2, pl.r[focus].y + 2, pl.r[focus].w - 4, pl.r[focus].h - 4, 2, FOCUS_RING);
+}
+
+/* the focused panel button's tooltip */
+static void panel_draw_tip(void) {
+ Panel pl;
+ panel_layout(&pl);
+ int focus = cu.zone == Z_PANEL && !nwins ? cu.pfocus : -1;
+ if (focus >= 0 && focus < PR_MAT0 + M_COUNT && pl.shown[focus]) {
+ extern void panel_tooltip(int which, int x, int y);
+ panel_tooltip(focus, pl.r[focus].x + pl.r[focus].w / 2, pl.r[focus].y);
+ }
+}
+
+/* the panel's buttons, pressed */
+static void panel_press(int k) {
+ switch (k) {
+ case PR_HELP:
+ if (win_is_open(WK_MISSIONS)) win_close();
+ else if (story_has_quick_text()) {
+ win_open_only(WK_MISSIONS, 0, 0);
+ tut_flags |= TF_HELP_USED;
+ }
+ break;
+ case PR_PAUSE:
+ city.paused = !city.paused;
+ if (!city.paused) ui.paused_for_window = false;
+ break;
+ case PR_SPEED:
+ /* a click toggles 1x and 2x (from the slow speeds, 1x); Ctrl+Click (here shift and OK) the next of the five.
+ * The game goes on */
+ if (key_held(K_SHIFT)) cu.speed = (uint8_t)((cu.speed + 1) % 5);
+ else cu.speed = cu.speed > 1 ? 0 : 2;
+ city.simulationSpeed = simulation_speeds[cu.speed];
+ city.paused = false;
+ tut_flags |= TF_SPEED_USED;
+ break;
+ case PR_MENU:
+ if (win_is_open(WK_GAME_MENU)) win_close();
+ else win_open_only(WK_GAME_MENU, 0, 0);
+ break;
+ case PR_HIDE: cu.panel_hidden = !cu.panel_hidden; break;
+ case PR_POP: win_open_only(WK_POPULATION, 0, 0); break;
+ case PR_HAPPY: win_open_only(WK_HAPPINESS, 0, 0); break;
+ case PR_HOUSES: win_open_only(WK_HOUSES, 0, 0); break;
+ case PR_WORK: win_open_only(WK_WORKERS, 0, 0); break;
+ default:
+ if (k >= PR_MAT0) win_open_only(WK_MATERIAL, (uint16_t)(k - PR_MAT0), 0);
+ }
+}
+
+static void panel_input(void) {
+ Panel pl;
+ panel_layout(&pl);
+ if (cu.pfocus < 0 || cu.pfocus >= PR_MAT0 + M_COUNT || !pl.shown[cu.pfocus]) cu.pfocus = PR_PAUSE;
+ int dx = key_repeat(K_RIGHT) ? 1 : key_repeat(K_LEFT) ? -1 : 0;
+ int dy = key_repeat(K_DOWN) ? 1 : key_repeat(K_UP) ? -1 : 0;
+ if (dx || dy) {
+ Rect *c = &pl.r[cu.pfocus];
+ int cx = c->x + c->w / 2, cy = c->y + c->h / 2, best = -1, best_score = 1 << 30;
+ for (int k = 0; k < PR_MAT0 + M_COUNT; k++) {
+ if (!pl.shown[k] || k == cu.pfocus) continue;
+ Rect *r = &pl.r[k];
+ int ddx = r->x + r->w / 2 - cx, ddy = r->y + r->h / 2 - cy, score;
+ if (dx) {
+ if (ddx * dx <= 0) continue;
+ score = ddx * dx + (ddy < 0 ? -ddy : ddy) * 3;
+ } else {
+ if (ddy * dy <= 0) continue;
+ score = ddy * dy + (ddx < 0 ? -ddx : ddx) * 3;
+ }
+ if (score < best_score) best_score = score, best = k;
+ }
+ if (best >= 0) cu.pfocus = (int8_t)best;
+ }
+ if (input.released & K_OK) panel_press(cu.pfocus);
+ if (key_pressed(K_BACK)) cu.zone = Z_CITY;
+}
+
+/* ---------------------------------------------------------------- the city's keys */
+/* the arrows move the cursor a cell (the view follows), shift and the arrows the view */
+bool city_cursor_keys(void) {
+ if (key_held(K_SHIFT)) {
+ camera_keys();
+ return true;
+ }
+ int dx = 0, dy = 0;
+ if (key_repeat(K_LEFT)) dx -= 20;
+ if (key_repeat(K_RIGHT)) dx += 20;
+ if (key_repeat(K_UP)) dy -= 20;
+ if (key_repeat(K_DOWN)) dy += 20;
+ if (dx || dy) {
+ cursor_to(cu.cx + dx, cu.cy + dy);
+ camera_to_cursor();
+ }
+ return dx || dy;
+}
+
+/* the citizen nearest the cursor (viewActions.showFollow) */
+static uint16_t citizen_near_cursor(void) {
+ uint16_t best = 0;
+ float bd = 30 * 30;
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ float x, y;
+ cit_city_position(c, &x, &y);
+ float dx = x - (cu.cx + 10), dy = y - (cu.cy + 10), d = dx * dx + dy * dy;
+ if (d < bd) bd = d, best = (uint16_t)i;
+ }
+ return best;
+}
+
+/* Building.onClick (and the destroy modes), Permanent.onClick */
+static void city_press(void) {
+ if (cu.build_kind != BK_NONE) {
+ build_here();
+ return;
+ }
+ if (follow_mode) {
+ uint16_t c = citizen_near_cursor();
+ if (c) {
+ follow_mode = false;
+ cu.following = c;
+ win_open_only(WK_CITIZEN, c, 0);
+ }
+ return;
+ }
+ uint16_t id = cursor_perm();
+ if (!id) return;
+ Perm *p = P(id);
+ if ((building_mode == BM_DESTROY || building_mode == BM_DESTROY_LEAVING_HOLE) && is_building(p)) {
+ if (story.disableDestroy) {
+ win_open_text(NULL, L_no_destroy_allowed);
+ return;
+ }
+ extern void try_destroy(uint16_t id);
+ try_destroy(id);
+ return;
+ }
+ cu.selected = id;
+ win_open_only(WK_BUILDING, id, 0);
+}
+
+void city_input(void) {
+ cu.gui_timer += TIMEMOD;
+ if (build_flash) build_flash--;
+ if (key_pressed(K_ALPHA)) {
+ /* the original's space bar */
+ city.paused = !city.paused;
+ if (!city.paused) ui.paused_for_window = false;
+ }
+ zoom_keys();
+ if (key_pressed(K_TOOLBOX)) {
+ if (cu.zone == Z_BUILD) bmenu_close();
+ else bmenu_open();
+ return;
+ }
+ if (key_pressed(K_VAR)) {
+ cu.zone = cu.zone == Z_PANEL ? Z_CITY : Z_PANEL;
+ return;
+ }
+ if (cu.zone == Z_BUILD) {
+ bmenu_input();
+ return;
+ }
+ if (cu.zone == Z_PANEL) {
+ panel_input();
+ return;
+ }
+ int16_t from_x = cu.cx, from_y = cu.cy;
+ city_cursor_keys();
+ if (cu.build_kind == BK_BUILDING && building_mode_can_drag()) {
+ /* the drag modes: OK builds at once, and while held, on every cell the cursor moves over */
+ static bool dragging;
+ if (key_pressed(K_OK)) dragging = true, build_here();
+ else if (dragging && key_held(K_OK) && (cu.cx != from_x || cu.cy != from_y)) build_line(from_x, from_y, cu.cx, cu.cy);
+ if (!key_held(K_OK)) dragging = false;
+ } else if (input.released & K_OK) {
+ city_press();
+ }
+ if (key_pressed(K_BACKSPACE)) {
+ /* the destroy button of the building under the cursor, already asking "Really Destroy?" */
+ uint16_t id = cursor_perm();
+ if (is_building(P(id))) {
+ if (story.disableDestroy) {
+ win_open_text(NULL, L_no_destroy_allowed);
+ } else {
+ cu.selected = id;
+ win_open_only(WK_BUILDING, id, WF2_CONFIRM);
+ }
+ }
+ }
+ if (key_pressed(K_BACK)) {
+ /* stop building, leave a destroy mode or follow mode, else the game menu (onEscapePressWithoutWindow) */
+ if (cu.build_kind != BK_NONE) {
+ /* the builder goes, and the menu comes back on its button, to pick another */
+ bool menu = cu.build_kind != BK_MOVE;
+ builder_stop();
+ if (menu) bmenu_open();
+ } else if (follow_mode) follow_mode = false;
+ else if (building_mode == BM_DESTROY || building_mode == BM_DESTROY_LEAVING_HOLE) building_mode = BM_NORMAL;
+ else win_open_only(WK_GAME_MENU, 0, 0);
+ }
+}
+
+void city_draw_ui(void) {
+ ui_noclip();
+ bmenu_draw(false);
+ panel_draw();
+}
+
+/* the tooltips (the original's tooltip stage: over the windows and the help arrows) */
+void city_draw_tips(void) {
+ ui_noclip();
+ panel_draw_tip();
+ bmenu_draw(true);
+ if (cu.zone == Z_CITY) builder_tooltip();
+}
diff --git a/games/finalearth2/src/ui_draw.c b/games/finalearth2/src/ui_draw.c
new file mode 100644
index 00000000..6eb83979
--- /dev/null
+++ b/games/finalearth2/src/ui_draw.c
@@ -0,0 +1,499 @@
+/* The Final Earth 2: drawing the user interface (the original's
+ * gui.NinePatch, graphics.BitmapText, gui.MaterialsCostDisplay and
+ * gui.IconListDisplay), as a list of primitives drawn by one band function,
+ * and the texts' numbers (common.Localize.lo, MathExtensions). */
+#include <math.h>
+#include "uii.h"
+
+UiFrame *uf;
+
+/* the original's 9-patches: each is a 1-pixel border round a fill (colours and alphas from its sprite) */
+/* rgb565_near, as a constant */
+#define NEAR565(c) ((uint16_t)(((((c) >> 16 & 255) * 31 + 127) / 255) << 11 | ((((c) >> 8 & 255) * 63 + 127) / 255) << 5 | \
+ (((c) & 255) * 31 + 127) / 255))
+#define BOX(b, f, ba, fa) {NEAR565(b), NEAR565(f), ba, fa}
+const Box boxes[BX_COUNT] = {
+ [BX_WINDOW] = BOX(0x000000, 0xFFFFFF, 255, 180),
+ [BX_WINDOW_OPAQUE] = BOX(0x000000, 0xF4F4F4, 255, 250),
+ [BX_TOOLTIP] = BOX(0x969696, 0xF2F2F2, 230, 230),
+ [BX_INFO] = BOX(0x000000, 0xFFFFFF, 255, 180),
+ [BX_HINTINFO] = BOX(0x4D9600, 0xC3FF7F, 230, 230),
+ [BX_ACTIVE] = BOX(0x94BA8D, 0xFFFFFF, 255, 255),
+ [BX_DISABLED] = BOX(0xDBDBDB, 0xFFFFFF, 255, 255),
+ [BX_BUTTON] = BOX(0x000000, 0xFFFFFF, 255, 255),
+ [BX_BUTTON_HOVER] = BOX(0x7F7F7F, 0xFFFFFF, 255, 255),
+ [BX_BUTTON_DOWN] = BOX(0xBCBCBC, 0xFFFFFF, 255, 255),
+ [BX_TRANS] = BOX(0x000000, 0xFFFFFF, 255, 180),
+ [BX_TRANS_HOVER] = BOX(0x969696, 0xFFFFFF, 255, 180),
+ [BX_TRANS_DOWN] = BOX(0xFFFFFF, 0xFFFFFF, 255, 180),
+ [BX_BLD] = BOX(0x000000, 0xFFFFFF, 255, 128),
+ [BX_BLD_HOVER] = BOX(0x7F7F7F, 0xFFFFFF, 255, 128),
+ [BX_BLD_DOWN] = BOX(0xFFFFFF, 0xFFFFFF, 255, 128),
+ [BX_TRANSB] = BOX(0x000000, 0xFFFFFF, 255, 128),
+ [BX_TRANSB_HOVER] = BOX(0x969696, 0xFFFFFF, 255, 128),
+ [BX_TRANSB_DOWN] = BOX(0xFFFFFF, 0xFFFFFF, 255, 128),
+ [BX_CHECKED] = BOX(0x94BA8D, 0xFFFFFF, 255, 255),
+ [BX_CHECKED_HOVER] = BOX(0xB6CCB1, 0xFFFFFF, 255, 255),
+ [BX_CHECKED_DOWN] = BOX(0xD8E2D5, 0xFFFFFF, 255, 255),
+ [BX_ACTIVABLE] = BOX(0x000000, 0xFFFFFF, 255, 255),
+ [BX_ACTIVABLE_HOVER] = BOX(0x7F7F7F, 0xFFFFFF, 255, 255),
+ [BX_ACTIVABLE_DOWN] = BOX(0x94BA8D, 0xFFFFFF, 255, 255),
+ [BX_GRAY] = BOX(0x404040, 0xE0E0E0, 255, 255),
+ [BX_GRAY_HOVER] = BOX(0x7F7F7F, 0xE0E0E0, 255, 255),
+ [BX_GRAY_DOWN] = BOX(0xBCBCBC, 0xE0E0E0, 255, 255),
+ [BX_SCROLL] = BOX(0x000000, 0x000000, 255, 0),
+ [BX_HANDLE] = BOX(0x000000, 0xFFFFFF, 255, 255),
+};
+
+/* ---------------------------------------------------------------- the list */
+static UiPrim *prim(uint8_t kind, int x, int y, int w, int h) {
+ if (!uf) return NULL;
+ if (kind != PR_CLIP) {
+ /* outside the clip: nothing to draw (text: its line, give or take) */
+ int y0 = y, y1 = y + h;
+ if (kind == PR_TEXT) y0 -= 4, y1 += 4;
+ if (y1 <= uf->cy0 || y0 >= uf->cy1 || x >= uf->cx1 || x + w <= uf->cx0) return NULL;
+ }
+ if (uf->n >= UI_PRIMS) {
+ uf->dropped++;
+ return NULL;
+ }
+ UiPrim *p = &uf->p[uf->n++];
+ memset(p, 0, sizeof *p);
+ p->kind = kind;
+ p->x = (int16_t)x;
+ p->y = (int16_t)y;
+ p->w = (int16_t)w;
+ p->h = (int16_t)h;
+ p->a1 = p->a2 = 255;
+ return p;
+}
+
+void ui_clip(int x, int y, int w, int h) {
+ if (!uf) return;
+ int x1 = x + w, y1 = y + h;
+ if (x < 0) x = 0;
+ if (y < 0) y = 0;
+ if (x1 > SCREEN_W) x1 = SCREEN_W;
+ if (y1 > SCREEN_H) y1 = SCREEN_H;
+ if (uf->n && uf->p[uf->n - 1].kind == PR_CLIP) uf->n--; /* a clip nothing used */
+ uf->cx0 = (int16_t)x, uf->cy0 = (int16_t)y, uf->cx1 = (int16_t)x1, uf->cy1 = (int16_t)y1;
+ prim(PR_CLIP, x, y, x1 - x, y1 - y);
+}
+void ui_noclip(void) { ui_clip(0, 0, SCREEN_W, SCREEN_H); }
+
+void ui_rect(int x, int y, int w, int h, uint16_t c, uint8_t a) {
+ if (w <= 0 || h <= 0 || !a) return;
+ UiPrim *p = prim(PR_RECT, x, y, w, h);
+ if (p) p->c1 = c, p->a1 = a;
+}
+
+void ui_box(int x, int y, int w, int h, int box) {
+ if (w <= 0 || h <= 0) return;
+ UiPrim *p = prim(PR_BOX, x, y, w, h);
+ if (!p) return;
+ const Box *b = &boxes[box];
+ p->c1 = b->border, p->c2 = b->fill, p->a1 = b->ba, p->a2 = b->fa;
+}
+
+/* a box added now (so it is under what follows) whose height comes later; never culled */
+UiPrim *ui_box_later(int x, int y, int w, int box) {
+ if (!uf || uf->n >= UI_PRIMS) {
+ if (uf) uf->dropped++;
+ return NULL;
+ }
+ UiPrim *p = &uf->p[uf->n++];
+ memset(p, 0, sizeof *p);
+ p->kind = PR_BOX;
+ p->x = (int16_t)x, p->y = (int16_t)y, p->w = (int16_t)w, p->h = 0;
+ const Box *b = &boxes[box];
+ p->c1 = b->border, p->c2 = b->fill, p->a1 = b->ba, p->a2 = b->fa;
+ return p;
+}
+
+void ui_spr_ex(uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags, uint8_t alpha, uint16_t tint) {
+ if (!spr || w <= 0 || h <= 0 || !alpha) return;
+ UiPrim *p = prim(PR_SPR, x, y, w, h);
+ if (!p) return;
+ p->c1 = spr, p->c2 = tint, p->a1 = alpha, p->f = flags;
+ p->u.part.sx = (int16_t)sx, p->u.part.sy = (int16_t)sy;
+}
+void ui_spr(uint16_t spr, int x, int y) { ui_spr_ex(spr, 0, 0, spr_w(spr), spr_h(spr), x, y, 0, 255, GFX_NO_TINT); }
+void ui_keys(int x, int y, int cw, int h, const char *chars, int n, int focused, bool down) {
+ if (!uf || uf->ntext + n > UI_TEXT) {
+ if (uf) uf->dropped++;
+ return;
+ }
+ UiPrim *p = prim(PR_KEYS, x, y, cw * n, h);
+ if (!p) return;
+ memcpy(uf->text + uf->ntext, chars, (size_t)n);
+ p->u.s = uf->text + uf->ntext;
+ uf->ntext += n;
+ p->f = (uint8_t)n, p->a1 = (uint8_t)cw, p->a2 = (uint8_t)focused, p->c1 = down;
+}
+void ui_ring(int x, int y, int w, int h, int t, uint16_t c) {
+ ui_rect(x - t, y - t, w + 2 * t, t, c, 255);
+ ui_rect(x - t, y + h, w + 2 * t, t, c, 255);
+ ui_rect(x - t, y, t, h, c, 255);
+ ui_rect(x + w, y, t, h, c, 255);
+}
+void ui_spr_small(uint16_t spr, int x, int y) {
+ UiPrim *p = prim(PR_SPR_SMALL, x, y, (spr_w(spr) * 3 + 4) / 5, (spr_h(spr) * 3 + 4) / 5);
+ if (p) p->c1 = spr;
+}
+void ui_frame(uint16_t spr, int fw, int i, int x, int y, uint8_t flags, uint8_t alpha) {
+ ui_spr_ex(spr, (fw + 2) * i, 0, fw, spr_h(spr), x, y, flags, alpha, GFX_NO_TINT);
+}
+
+int ui_text_n(uint8_t font, int x, int y, const char *s, int n, uint16_t color, uint8_t alpha, bool keep) {
+ if (!s) return 0;
+ if (n < 0) n = (int)strlen(s);
+ int w = gfx_text_width_n(font, s, n);
+ if (!n || !uf) return w;
+ UiPrim *p = prim(PR_TEXT, x, y, w, ui_line_h(font));
+ if (!p) return w;
+ if (!keep) {
+ if (uf->ntext + n > UI_TEXT) {
+ uf->dropped++;
+ uf->n--;
+ return w;
+ }
+ memcpy(uf->text + uf->ntext, s, (size_t)n);
+ s = uf->text + uf->ntext;
+ uf->ntext += n;
+ }
+ p->u.s = s;
+ p->w = (int16_t)n;
+ p->f = font;
+ p->c1 = color;
+ p->a1 = alpha;
+ return w;
+}
+
+void ui_text_rot(uint8_t font, int x, int y, const char *s, uint16_t color) {
+ int n = (int)strlen(s), w = gfx_text_width(font, s);
+ UiPrim *p = prim(PR_TEXTROT, x - ui_line_h(font) - 4, y, ui_line_h(font) + 8, w);
+ if (!p || uf->ntext + n > UI_TEXT) {
+ if (p) uf->n--, uf->dropped++;
+ return;
+ }
+ memcpy(uf->text + uf->ntext, s, (size_t)n);
+ p->u.s = uf->text + uf->ntext;
+ uf->ntext += n;
+ p->x = (int16_t)x, p->w = (int16_t)n, p->f = font, p->c1 = color;
+}
+
+int ui_text_w(uint8_t font, const char *s) { return s ? gfx_text_width(font, s) : 0; }
+
+int ui_para(uint8_t font, int x, int y, int max_w, const char *s, uint16_t color, bool keep, int *width) {
+ int lh = ui_line_h(font), h = 0, widest = 0;
+ if (!s) s = "";
+ const char *p = s;
+ do {
+ int lw;
+ const char *next;
+ int n = gfx_text_wrap(font, p, max_w, &lw, &next);
+ if (y != INT16_MIN) ui_text_n(font, x, y + h, p, n, color, 255, keep);
+ if (lw > widest) widest = lw;
+ h += lh;
+ p = next;
+ } while (*p);
+ if (width) *width = widest;
+ return h;
+}
+
+const char *ui_color_prefix(const char *s, uint16_t *color) {
+ if (!s) return "";
+ if (!strncmp(s, "[red]", 5)) return *color = C_RED, s + 5;
+ if (!strncmp(s, "[blue]", 6)) return *color = C_BLUE, s + 6;
+ if (!strncmp(s, "[green]", 7)) return *color = C_GREEN, s + 7;
+ if (!strncmp(s, "[white]", 7)) return *color = C_WHITE, s + 7;
+ return s;
+}
+
+/* ---------------------------------------------------------------- the band function */
+static void draw_box(const GfxBand *b, const UiPrim *p) {
+ int x0 = p->x, x1 = p->x + p->w, y0 = p->y, y1 = p->y + p->h;
+ for (int y = y0 > b->cy0 ? y0 : b->cy0; y < y1 && y < b->cy1; y++) {
+ if (y == y0 || y == y1 - 1) {
+ gfx_band_span(b, y, x0, x1, p->c1, p->a1);
+ } else {
+ gfx_band_span(b, y, x0, x0 + 1, p->c1, p->a1);
+ gfx_band_span(b, y, x0 + 1, x1 - 1, p->c2, p->a2);
+ gfx_band_span(b, y, x1 - 1, x1, p->c1, p->a1);
+ }
+ }
+}
+
+/* PR_SPR_SMALL: row by row, the sprite's row (5/3 as far down) is drawn over what is under its pixels, then each
+ * screen pixel takes the nearest of them */
+static void draw_small(const GfxBand *b, const UiPrim *p) {
+ int sw = spr_w(p->c1), sh = spr_h(p->c1);
+ if (sw > SCREEN_W) return;
+ uint16_t line[SCREEN_W];
+ GfxBand one = {line, 0, 1, 0, 0, sw, 1, 1};
+ int x0 = p->x > b->cx0 ? p->x : b->cx0, x1 = p->x + p->w < b->cx1 ? p->x + p->w : b->cx1;
+ for (int y = p->y > b->cy0 ? p->y : b->cy0; y < p->y + p->h && y < b->cy1; y++) {
+ int sy = (y - p->y) * 5 / 3;
+ if (sy >= sh || x0 >= x1) continue;
+ uint16_t *row = b->px + (y - b->y0) * SCREEN_W;
+ for (int sx = 0; sx < sw; sx++) {
+ int dx = p->x + sx * 3 / 5;
+ line[sx] = dx >= 0 && dx < SCREEN_W ? row[dx] : 0;
+ }
+ gfx_band_sprite(&one, p->c1, 0, sy, sw, 1, 0, 0, 0, 255, GFX_NO_TINT);
+ for (int x = x0; x < x1; x++) row[x] = line[(x - p->x) * 5 / 3 < sw ? (x - p->x) * 5 / 3 : sw - 1];
+ }
+}
+
+/* PR_KEYS: each key a button (spr_button's normal, hover or down 9-patch) round its character */
+static void draw_keys(const GfxBand *b, const UiPrim *p) {
+ for (int i = 0; i < p->f; i++) {
+ UiPrim k = *p;
+ int box = i == p->a2 ? (p->c1 ? BX_BUTTON_DOWN : BX_BUTTON_HOVER) : BX_BUTTON;
+ k.x = (int16_t)(p->x + i * p->a1), k.w = p->a1;
+ k.c1 = boxes[box].border, k.c2 = boxes[box].fill, k.a1 = boxes[box].ba, k.a2 = boxes[box].fa;
+ draw_box(b, &k);
+ int tw = gfx_text_width_n(FONT_STANDARD, p->u.s + i, 1);
+ gfx_band_text(b, FONT_STANDARD, k.x + (p->a1 - tw) / 2, p->y + 1, p->u.s + i, 1, C_BLACK, 255, false);
+ }
+}
+
+static void ui_band(const GfxBand *band, void *ctx) {
+ UiFrame *f = ctx;
+ GfxBand b = *band;
+ for (int i = 0; i < f->n; i++) {
+ const UiPrim *p = &f->p[i];
+ if (p->kind == PR_CLIP) {
+ b.cx0 = p->x > band->cx0 ? p->x : band->cx0;
+ b.cx1 = p->x + p->w < band->cx1 ? p->x + p->w : band->cx1;
+ b.cy0 = p->y > band->cy0 ? p->y : band->cy0;
+ b.cy1 = p->y + p->h < band->cy1 ? p->y + p->h : band->cy1;
+ continue;
+ }
+ if (b.cy0 >= b.cy1 || b.cx0 >= b.cx1) continue;
+ switch (p->kind) {
+ case PR_RECT:
+ if (p->y + p->h <= b.cy0 || p->y >= b.cy1) break;
+ for (int y = p->y > b.cy0 ? p->y : b.cy0; y < p->y + p->h && y < b.cy1; y++)
+ gfx_band_span(&b, y, p->x, p->x + p->w, p->c1, p->a1);
+ break;
+ case PR_BOX:
+ if (p->y + p->h <= b.cy0 || p->y >= b.cy1) break;
+ draw_box(&b, p);
+ break;
+ case PR_SPR:
+ if (p->y + p->h <= b.cy0 || p->y >= b.cy1) break;
+ gfx_band_sprite(&b, p->c1, p->u.part.sx, p->u.part.sy, p->w, p->h, p->x, p->y, p->f, p->a1, p->c2);
+ break;
+ case PR_TEXT:
+ if (p->y + p->h + 6 <= b.cy0 || p->y - 6 >= b.cy1) break;
+ gfx_band_text(&b, p->f, p->x, p->y, p->u.s, p->w, p->c1, p->a1, false);
+ break;
+ case PR_TEXTROT:
+ if (p->y + p->h <= b.cy0 || p->y >= b.cy1) break;
+ gfx_band_text(&b, p->f, p->x, p->y, p->u.s, p->w, p->c1, 255, true);
+ break;
+ case PR_SPR_SMALL:
+ if (p->y + p->h <= b.cy0 || p->y >= b.cy1) break;
+ draw_small(&b, p);
+ break;
+ case PR_KEYS:
+ if (p->y + p->h + 6 <= b.cy0 || p->y - 6 >= b.cy1) break;
+ draw_keys(&b, p);
+ break;
+ }
+ }
+}
+
+void ui_frame_begin(UiFrame *f) {
+ f->n = f->ntext = f->dropped = 0;
+ f->tip.on = false;
+ f->cx0 = f->cy0 = 0;
+ f->cx1 = SCREEN_W, f->cy1 = SCREEN_H;
+ uf = f;
+}
+
+int ui_peak_prims, ui_peak_text, ui_dropped_total; /* for the tests */
+int ui_redraws; /* windows laid out again in the frame they changed size (tests) */
+
+void ui_frame_end(void) {
+ if (!uf) return;
+ if (uf->n > ui_peak_prims) ui_peak_prims = uf->n;
+ if (uf->ntext > ui_peak_text) ui_peak_text = uf->ntext;
+ ui_dropped_total += uf->dropped;
+ if (uf->n) {
+ gfx_zoom(1);
+ gfx_clip(0, 0, SCREEN_W, SCREEN_H);
+ gfx_call(ui_band, uf, 0, SCREEN_H);
+ }
+}
+
+/* ---------------------------------------------------------------- numbers and texts */
+int fmt_int(char *out, int size, long v) {
+ char tmp[24];
+ int n = 0;
+ unsigned long u = v < 0 ? (unsigned long)-v : (unsigned long)v;
+ do tmp[n++] = (char)('0' + u % 10), u /= 10;
+ while (u);
+ if (v < 0) tmp[n++] = '-';
+ int k = 0;
+ while (n && k < size - 1) out[k++] = tmp[--n];
+ out[k] = 0;
+ return k;
+}
+
+/* String(v) for the numbers the interface shows: integers, or up to 6 decimals (trailing zeros dropped) */
+int fmt_num(char *out, int size, double v) {
+ if (v != v) v = 0;
+ bool neg = v < 0;
+ if (neg) v = -v;
+ double ip = floor(v);
+ long frac = (long)((v - ip) * 1e6 + 0.5);
+ if (frac >= 1000000) ip += 1, frac = 0;
+ char tmp[40];
+ int n = 0;
+ if (neg && (ip > 0 || frac > 0)) tmp[n++] = '-';
+ n += fmt_int(tmp + n, (int)sizeof tmp - n, ip > 2e9 ? 2000000000L : (long)ip);
+ if (frac > 0) {
+ char fd[7];
+ for (int i = 5; i >= 0; i--) fd[i] = (char)('0' + frac % 10), frac /= 10;
+ int last = 5;
+ while (last >= 0 && fd[last] == '0') last--;
+ tmp[n++] = '.';
+ for (int i = 0; i <= last; i++) tmp[n++] = fd[i];
+ }
+ tmp[n] = 0;
+ int k = 0;
+ for (; k < n && k < size - 1; k++) out[k] = tmp[k];
+ out[k] = 0;
+ return k;
+}
+
+/* MathExtensions.floatFormat: v with at most that many decimals, as JavaScript shows it */
+int ui_float_fmt(char *out, int size, double v, int decimals) {
+ double m = pow(10, decimals);
+ return fmt_num(out, size, round(v * m) / m);
+}
+
+/* MathExtensions.largeNumberFormat(Alt): thousands and millions shortened */
+int fmt_large(char *out, int size, double v, bool alt) {
+ char num[24];
+ const char *suffix = "";
+ if (v >= 1e6) v = (alt ? floor(v / 1e5) : floor(v / 1e5)) / 10, suffix = "M";
+ else if (v >= 1e4) v = floor(v / 100) / 10, suffix = "k";
+ fmt_num(num, sizeof num, v);
+ out[0] = 0;
+ str_cat(out, size, num);
+ return (int)strlen(str_cat(out, size, suffix));
+}
+
+char *str_cat(char *dst, int size, const char *src) {
+ int n = (int)strlen(dst);
+ while (src && *src && n < size - 1) dst[n++] = *src++;
+ dst[n] = 0;
+ return dst;
+}
+
+const char *lo(char *buf, int size, const char *text, int n, const LoArg *args) {
+ int o = 0;
+ if (!text) text = "";
+ for (const char *s = text; *s && o < size - 1;) {
+ if (s[0] == '[' && s[1] >= '0' && s[1] <= '9' && s[2] == ']' && s[1] - '0' < n) {
+ const LoArg *a = &args[s[1] - '0'];
+ if (a->s) {
+ for (const char *t = a->s; *t && o < size - 1;) buf[o++] = *t++;
+ } else {
+ o += fmt_num(buf + o, size - o, a->v);
+ }
+ s += 3;
+ } else {
+ buf[o++] = *s++;
+ }
+ }
+ buf[o] = 0;
+ return buf;
+}
+const char *lo_1(char *buf, int size, const char *text, LoArg a) { return lo(buf, size, text, 1, &a); }
+const char *lo_2(char *buf, int size, const char *text, LoArg a, LoArg b) {
+ LoArg v[2] = {a, b};
+ return lo(buf, size, text, 2, v);
+}
+const char *lo_3(char *buf, int size, const char *text, LoArg a, LoArg b, LoArg c) {
+ LoArg v[3] = {a, b, c};
+ return lo(buf, size, text, 3, v);
+}
+
+/* ---------------------------------------------------------------- materials */
+const uint16_t mat_icon[M_COUNT] = {
+ [M_FOOD] = SPR_RESOURCE_FOOD, [M_WOOD] = SPR_RESOURCE_WOOD, [M_STONE] = SPR_RESOURCE_STONE,
+ [M_MACHINEPARTS] = SPR_RESOURCE_MACHINEPARTS, [M_REFINEDMETAL] = SPR_RESOURCE_REFINEDMETAL,
+ [M_COMPUTERCHIPS] = SPR_RESOURCE_COMPUTERCHIPS, [M_GRAPHENE] = SPR_RESOURCE_GRAPHENE,
+ [M_ROCKETFUEL] = SPR_RESOURCE_ROCKETFUEL, [M_KNOWLEDGE] = SPR_RESOURCE_KNOWLEDGE,
+};
+/* lo(name): as the original names them in its texts */
+const char *const mat_lname[M_COUNT] = {
+ [M_FOOD] = L_food, [M_WOOD] = L_wood, [M_STONE] = L_stone, [M_MACHINEPARTS] = L_machine_parts,
+ [M_REFINEDMETAL] = L_refined_metals, [M_COMPUTERCHIPS] = L_computer_chips, [M_CACAO] = "cacao",
+ [M_CHOCOLATE] = "chocolate", [M_GRAPHENE] = L_graphene, [M_ROCKETFUEL] = L_rocketFuel, [M_KNOWLEDGE] = L_knowledge,
+};
+/* firstToUpper(lo(name)) */
+const char *mat_title(int m, char *buf, int size) {
+ buf[0] = 0;
+ str_cat(buf, size, mat_lname[m]);
+ if (buf[0] >= 'a' && buf[0] <= 'z') buf[0] = (char)(buf[0] - 32);
+ return buf;
+}
+
+/* MaterialsCostDisplay.updateCostDisplay: food, wood, stone, machine parts, refined metal, computer chips,
+ * graphene, rocket fuel, then knowledge (with the texts around it) */
+int ui_cost(int x, int y, const float cost[M_COUNT], const char *before_k, const char *after_k, bool city_red) {
+ static const uint8_t order[] = {M_FOOD, M_WOOD, M_STONE, M_MACHINEPARTS, M_REFINEDMETAL, M_COMPUTERCHIPS, M_CACAO,
+ M_CHOCOLATE, M_GRAPHENE, M_ROCKETFUEL, M_KNOWLEDGE};
+ bool draw = y != INT16_MIN;
+ int xx = 0;
+ bool any_before = false, shown_before_k = false;
+ char num[48];
+ if (!before_k) before_k = "";
+ for (unsigned k = 0; k < sizeof order; k++) {
+ int m = order[k];
+ if (cost[m] <= 0) continue;
+ if (m == M_KNOWLEDGE && *before_k && any_before) {
+ if (draw) ui_text(FONT_STANDARD, x + xx, y - 1, before_k, C_BLACK);
+ xx += ui_text_w(FONT_STANDARD, before_k) + 3;
+ shown_before_k = true;
+ }
+ if (m == M_FOOD) xx -= 2;
+ any_before = true;
+ if (draw) ui_spr(mat_icon[m], x + xx, y);
+ xx += 10 + 1;
+ if (m == M_FOOD) xx -= 2;
+ fmt_num(num, sizeof num, cost[m]);
+ if (m == M_KNOWLEDGE && after_k) str_cat(num, sizeof num, after_k);
+ bool red = city_red && city.materials.m[m] < cost[m];
+ if (draw) ui_text(FONT_STANDARD, x + xx, y - 1, num, red ? C_RED : C_BLACK);
+ xx += ui_text_w(FONT_STANDARD, num) + 3;
+ }
+ if (!shown_before_k && *before_k) {
+ if (draw) ui_text(FONT_STANDARD, x + xx, y - 1, before_k, C_BLACK);
+ xx += ui_text_w(FONT_STANDARD, before_k) + 3;
+ }
+ return xx;
+}
+
+int ui_icon_list(int x, int y, const IconText *it, int n) {
+ int xx = 0;
+ bool draw = y != INT16_MIN;
+ for (int i = 0; i < n; i++) {
+ if (draw) ui_spr(it[i].spr, x + xx, y);
+ xx += spr_w(it[i].spr) + 2;
+ uint16_t col = C_BLACK;
+ const char *t = ui_color_prefix(it[i].text, &col);
+ bool one = !strcmp(t, "1");
+ if (one) xx--;
+ if (draw) ui_text(FONT_STANDARD, x + xx, y - 1, t, col);
+ if (one) xx--;
+ xx += ui_text_w(FONT_STANDARD, t) + 3;
+ }
+ return xx;
+}
diff --git a/games/finalearth2/src/ui_info.c b/games/finalearth2/src/ui_info.c
new file mode 100644
index 00000000..2a8a4ff3
--- /dev/null
+++ b/games/finalearth2/src/ui_info.c
@@ -0,0 +1,903 @@
+/* The Final Earth 2: the city's information windows (the original's
+ * gui.infoWindows.MaterialInfoWindow, gui.PopulationInfoWindow,
+ * gui.HappinessWindow, gui.HouseInformationWindow,
+ * gui.WorkerDistributionWindow, gui.BirthControlWindow,
+ * gui.EntertainmentInformationWindow, gui.infoWindows.FindBuildingsOfType,
+ * gui.GlobalUpgradeWindow and gui.infoWindows.InvitePeopleWindow) and the
+ * city panel's tooltips (gui.CityGUI). */
+#include <math.h>
+#include "uii.h"
+
+static int count_class(int c) {
+ int n = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == c) n++;
+ return n;
+}
+
+/* a building type's picture (gui.BuildingTypeImage): its button back and its first 20x20 */
+void type_image(int x, int y, int cls) {
+ const ClsText *ct = &cls_text[cls];
+ uint16_t spr = pcls[cls].sprite;
+ if (ct->back == BACK_OWN && spr_w(spr) >= 64) ui_spr_ex(spr, 44, 0, 20, 20, x, y, 0, 255, GFX_NO_TINT);
+ else if (ct->back && ct->back != BACK_OWN) ui_spr_ex(ct->back, 0, 0, 20, 20, x, y, 0, 255, GFX_NO_TINT);
+ ui_spr_ex(spr, 0, 0, 20, 20, x, y, 0, 255, GFX_NO_TINT);
+}
+
+/* ---------------------------------------------------------------- materials */
+/* getProductionInfo: what the citizens made and (factories, buildings) used yesterday and today */
+static void production_info(char *buf, int size, int m) {
+ char t[200];
+ const char *name = mat_lname[m];
+ long used1 = (long)floor(stats.materialUsed[m][1]), used0 = (long)floor(stats.materialUsed[m][0]);
+ str_cat(buf, size, "\n");
+ str_cat(buf, size, lo_3(t, sizeof t, L_citizen_production_cost, LN(floor(stats.materialProduction[m][1])), LS(name),
+ LN(floor(stats.materialProduction[m][0]))));
+ if ((used1 || used0) && m != M_FOOD) {
+ str_cat(buf, size, "\n");
+ str_cat(buf, size, lo_3(t, sizeof t, m == M_KNOWLEDGE ? L_operating_cost : L_factory_operating_cost, LN(used1), LS(name), LN(used0)));
+ }
+}
+
+/* Eating.getFoodText */
+static void food_text(char *buf, int size) {
+ char t[96];
+ str_cat(buf, size, L_food_description_1);
+ str_cat(buf, size, "\n");
+ str_cat(buf, size, L_food_description_2);
+ str_cat(buf, size, " ");
+ if (eating.foodRationing) str_cat(str_cat(buf, size, L_rationing_halves_this), size, " ");
+ if (eating.currentFoodSaveByHerbsPct >= 0.0001f)
+ str_cat(str_cat(buf, size, lo_2(t, sizeof t, L_food_description_3, LN(round(eating.currentFoodSaveByHerbsPct * 0.2 * 100)), LN(20))), size, " ");
+ if (eating.totalConsumedFoodPerDay != -1) str_cat(buf, size, lo_1(t, sizeof t, L_food_description_4, LN((int)eating.totalConsumedFoodPerDay)));
+}
+
+static const char *const mat_use[M_COUNT] = {
+ [M_WOOD] = L_wood_use, [M_STONE] = L_stone_use, [M_KNOWLEDGE] = L_knowledge_use, [M_MACHINEPARTS] = L_machine_parts_use,
+ [M_REFINEDMETAL] = L_refined_metals_use, [M_COMPUTERCHIPS] = L_computer_chips_use, [M_GRAPHENE] = L_graphene_use,
+ [M_ROCKETFUEL] = L_rocketFuel_use};
+
+/* the tooltip of a material in the panel */
+static void material_tip(int m, char *buf, int size) {
+ buf[0] = 0;
+ if (m == M_FOOD) {
+ food_text(buf, size);
+ production_info(buf, size, m);
+ if (eating.foodShortage > 0.1f) {
+ char t[160];
+ str_cat(buf, size, "\n");
+ str_cat(buf, size, lo_1(t, sizeof t, L_not_enough_food, LN(ceil(eating.foodShortage))));
+ }
+ } else {
+ str_cat(buf, size, mat_use[m]);
+ production_info(buf, size, m);
+ }
+}
+
+/* MaterialInfoWindow: the production (blue) and use (red) of the last seven days */
+void info_material(WinOut *w) {
+ int m = w->win->arg;
+ char t[64];
+ win_title_icon(w, mat_title(m, t, sizeof t), mat_icon[m]);
+ if (m == M_STONE) {
+ /* no rock anyone can reach, or far more rock teleporters than mines */
+ bool group_cit[MAX_WORLDS] = {0}, group_mine[MAX_WORLDS] = {0}, group_rock[MAX_WORLDS] = {0};
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) group_cit[worlds[cits[i].onWorld].group % MAX_WORLDS] = true;
+ int mines = 0, tps = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED)) continue;
+ int g = worlds[p->world].group % MAX_WORLDS;
+ if (p->cls == CLS_StoneMine) group_mine[g] = true, mines++;
+ if (is_a(p, B_ROCK) || p->cls == CLS_StoneTeleporter) group_rock[g] = true;
+ if (p->cls == CLS_StoneTeleporter) tps++;
+ }
+ bool warn = true, any_mine = false;
+ for (int g = 0; g < MAX_WORLDS; g++) {
+ if (group_cit[g] && group_rock[g]) warn = false;
+ any_mine |= group_mine[g];
+ }
+ if (warn && any_mine && ncits > 0) win_para(w, FONT_STANDARD, L_stone_warning, 250, C_BLACK);
+ if (tps >= 12 && (mines <= 5 || (float)mines / tps < 0.3f)) win_para(w, FONT_STANDARD, L_mines_warning, 250, C_BLACK);
+ }
+ const int top = 5, bar_h = 100, bar_w = 9, spacing = 4, days = 7;
+ const int gw = 34 + bar_w * 2 * days + spacing * days;
+ double maxv = 9;
+ bool any_used = false;
+ for (int d = 0; d < days; d++) {
+ if (stats.materialProduction[m][d] > maxv) maxv = stats.materialProduction[m][d];
+ if (stats.materialUsed[m][d] > maxv) maxv = stats.materialUsed[m][d];
+ if (stats.materialUsed[m][d] > 0) any_used = true;
+ }
+ int zeroes = (int)floor(log(maxv) / log(10));
+ int dividers = (int)floor(pow(10, zeroes));
+ int q = (int)(ceil(maxv) / dividers);
+ if (q < 2) dividers /= 5;
+ else if (q < 4) dividers /= 2;
+ if (dividers < 1) dividers = 1;
+ double graph_top = floor(maxv / dividers) * dividers + dividers;
+ double scaling = bar_h / graph_top;
+ int naxis = (int)(graph_top / dividers) + 1;
+ /* the day labels under the bars (turned), then the legend: the graph's height */
+ int max_y = 0;
+ for (int d = 0; d < days; d++) {
+ char lab[24];
+ const char *s = d == 0 ? L_today : d == 1 ? L_yesterday : lo_1(lab, sizeof lab, L_n_days_ago, LN(d));
+ int yy = top + bar_h + 4 + ui_text_w(FONT_10, s);
+ if (yy > max_y) max_y = yy;
+ }
+ int legend_y = max_y + 5;
+ int height = legend_y + 10 + (any_used ? 13 : 0) + 3;
+ int gx, gy;
+ if (win_area(w, gw, height, &gx, &gy)) {
+ int xx = gw - bar_w;
+ for (int d = 0; d < days; d++) {
+ int hp = (int)(scaling * stats.materialProduction[m][d]), hc = (int)(scaling * stats.materialUsed[m][d]);
+ if (any_used) {
+ ui_rect(gx + xx, gy + top + bar_h - hc, bar_w, hc, C_RED, 255);
+ xx -= bar_w;
+ ui_rect(gx + xx, gy + top + bar_h - hp, bar_w, hp, 0x001F, 255);
+ xx -= bar_w + spacing;
+ } else {
+ xx -= bar_w;
+ ui_rect(gx + xx, gy + top + bar_h - hp, bar_w * 2, hp, 0x001F, 255);
+ xx -= bar_w + spacing;
+ }
+ }
+ int guide = xx + bar_w + spacing - 2;
+ ui_rect(gx + guide - 1, gy, 1, bar_h + top, C_BLACK, 255);
+ ui_rect(gx + guide - 1, gy + bar_h + top, gw - guide + 3, 1, C_BLACK, 255);
+ int interval = (int)floor(graph_top / (naxis - 1));
+ for (int i = 0; i < naxis; i++) {
+ char num[16];
+ fmt_large(num, sizeof num, (double)interval * i, true);
+ int yp = top + bar_h - (int)(scaling * interval * i);
+ ui_rect(gx + guide - 3, gy + yp, 2, 1, C_BLACK, 255);
+ /* anchor (1, 0.5): right-aligned, centred on the tick */
+ ui_text(FONT_10, gx + guide - 5 - ui_text_w(FONT_10, num), gy + yp - 4 - 3, num, C_BLACK);
+ }
+ xx = gw;
+ for (int d = 0; d < days; d++) {
+ char lab[24];
+ const char *s = d == 0 ? L_today : d == 1 ? L_yesterday : lo_1(lab, sizeof lab, L_n_days_ago, LN(d));
+ /* turned a quarter: anchor (0, 0.5) at the bar pair's middle */
+ ui_text_rot(FONT_10, gx + xx - bar_w + 4 + 3, gy + top + bar_h + 4, s, C_BLACK);
+ xx -= bar_w * 2 + spacing;
+ }
+ ui_rect(gx, gy + legend_y, 10, 10, 0x001F, 255);
+ ui_text(FONT_10, gx + 13, gy + legend_y - 3, L_production, C_BLACK);
+ if (any_used) {
+ ui_rect(gx, gy + legend_y + 13, 10, 10, C_RED, 255);
+ ui_text(FONT_10, gx + 13, gy + legend_y + 13 - 3, L_usage, C_BLACK);
+ }
+ }
+ if (m == M_FOOD) {
+ char buf[300];
+ buf[0] = 0;
+ food_text(buf, sizeof buf);
+ win_para(w, FONT_STANDARD, buf, gw - 10, C_BLACK);
+ }
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+/* ---------------------------------------------------------------- population */
+void info_population(WinOut *w) {
+ char t[128];
+ win_title_icon(w, L_pop_by_age, SPR_POPULATION);
+ int per_age[121] = {0}, children = 0, oldest = 0;
+ bool exceeding = false;
+ for (int i = 1; i < MAX_CITS; i++) {
+ if (!(cits[i].flags & CF_ALIVE)) continue;
+ int age = (int)cit_age(&cits[i]);
+ if (age > 120) per_age[120]++, exceeding = true;
+ else if (age >= 0) per_age[age]++;
+ if (age < 16) children++;
+ if (age > oldest) oldest = age;
+ }
+ win_para(w, FONT_STANDARD, lo_2(t, sizeof t, L_citizens_and_children, LN(ncits), LN(children)), 250, C_BLACK);
+ win_para(w, FONT_STANDARD, L_citizens_by_age_explain, 250, C_BLACK);
+ int gx, gy;
+ if (win_area(w, 40 + 210, 121 + 3, &gx, &gy)) {
+ int maxc = 0;
+ for (int a = 0; a <= 120; a++)
+ if (per_age[a] > maxc) maxc = per_age[a];
+ ui_rect(gx, gy, 1, 120, C_BLACK, 255);
+ ui_rect(gx + 39, gy, 1, 120, C_BLACK, 255);
+ ui_rect(gx, gy + 120, 40, 1, C_BLACK, 255);
+ for (int a = 0; a <= 120; a++) {
+ if (maxc) ui_rect(gx + 40, gy + a, (int)((float)per_age[a] / maxc * 210), 1, C_BLACK, 255);
+ if (a % 10 == 0) ui_rect(gx, gy + a, 40, 1, C_BLACK, 255);
+ }
+ for (int i = 0; i < 12; i++) {
+ char lab[16], n2[8];
+ fmt_int(lab, sizeof lab, i * 10);
+ if (i == 11 && exceeding) {
+ str_cat(lab, sizeof lab, "+");
+ } else {
+ str_cat(lab, sizeof lab, "-");
+ fmt_int(n2, sizeof n2, i * 10 + 10);
+ str_cat(lab, sizeof lab, n2);
+ }
+ ui_text(FONT_10, gx + 2, gy + i * 10, lab, C_BLACK);
+ }
+ }
+ if (ncits >= 1950) {
+ /* the population limit (NumberSelectControl) */
+ char num[16];
+ fmt_int(num, sizeof num, babies.softPopLimit);
+ win_row_begin(w);
+ int tw = ui_text_w(FONT_STANDARD, L_pop_limit);
+ int x0 = w->rx;
+ (void)x0;
+ w->rx += tw + 4 + 4;
+ win_text_button(w, num, 10, BX_BUTTON, false, false);
+ win_text_button(w, "+", 11, BX_BUTTON, false, false);
+ win_text_button(w, "-", 12, BX_BUTTON, false, false);
+ win_row_end(w);
+ int lx, ly;
+ win_area(w, 0, 0, &lx, &ly);
+ ui_text(FONT_STANDARD, lx, ly - 15 + 1, L_pop_limit, C_BLACK);
+ win_space(w, 6);
+ win_para(w, FONT_STANDARD, L_pop_limit_hint, 250, C_BLACK);
+ }
+ const char *label = L_follow_citizen;
+ int a = 1;
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+}
+
+void info_population_action(Win *wn, int a) {
+ (void)wn;
+ extern bool follow_mode;
+ if (a == 1) {
+ win_close_all();
+ follow_mode = true;
+ cu.zone = Z_CITY;
+ notify_top(L_tap_near_citizen_to_follow, NULL, 240);
+ } else if (a == 10) {
+ babies.softPopLimit = 3000;
+ } else if (a == 11 && babies.softPopLimit + 25 <= 10000) {
+ babies.softPopLimit += 25;
+ } else if (a == 12 && babies.softPopLimit - 25 >= 2000) {
+ babies.softPopLimit -= 25;
+ }
+}
+
+/* ---------------------------------------------------------------- happiness */
+static const char *ent_name(int t) {
+ static const char *const names[] = {L_night_clubs, L_pubs_restaurants, L_art, L_nature, L_gaming, L_libraries};
+ return t >= 0 && t < 6 ? names[t] : "";
+}
+
+/* HappinessBoost's texts (HB_*) */
+static const char *boost_text(int t) {
+ static const char *const texts[] = {L_music_festival_boost, L_citizen_gratefulness_bonus, L_malfunctioned_haunted_labs};
+ return t >= 0 && t < 3 ? texts[t] : "";
+}
+
+/* HappinessWindow: two columns, the texts (some indented) and their numbers, laid out first so that the numbers'
+ * column starts after the widest text (addTexts: each text, then 5 pixels) */
+typedef struct { char text[44], num[12]; int8_t pad_left, pad_top; } HappyRow;
+#define HAPPY_ROWS 24
+
+static void happy_add(HappyRow *r, int *n, const char *text, const char *colon, const char *num, int pad_left, int pad_top) {
+ if (*n >= HAPPY_ROWS) return;
+ HappyRow *h = &r[(*n)++];
+ h->text[0] = 0;
+ str_cat(str_cat(h->text, sizeof h->text, text), sizeof h->text, colon);
+ h->num[0] = 0;
+ str_cat(h->num, sizeof h->num, num);
+ h->pad_left = (int8_t)pad_left, h->pad_top = (int8_t)pad_top;
+}
+
+/* a whole number as "[sign]n" ((x | 0) as the original shows it) */
+static const char *happy_num(char *b, int size, const char *sign, float v) {
+ b[0] = 0;
+ str_cat(b, size, sign);
+ fmt_int(b + strlen(b), size - (int)strlen(b), (long)v);
+ return b;
+}
+
+void info_happiness(WinOut *w) {
+ char n[16];
+ win_title_icon(w, L_happiness, SPR_HAPPINESS);
+ HappinessState *h = &happiness;
+ HappyRow rows[HAPPY_ROWS];
+ int nrows = 0, ent_row;
+ happy_add(rows, &nrows, L_home_happiness, "", happy_num(n, sizeof n, "", h->homeHappiness), 0, 0);
+ happy_add(rows, &nrows, L_sense_of_purpose, "", happy_num(n, sizeof n, "", h->purposeHappiness), 0, 0);
+ ent_row = nrows;
+ happy_add(rows, &nrows, L_entertainment_happiness, "", happy_num(n, sizeof n, "", h->entertainmentHappiness), 0, 0);
+ static const char *const ent_names[] = {L_night_clubs, L_pubs_restaurants, L_art, L_nature, L_gaming};
+ for (int i = 0; i < 5; i++) happy_add(rows, &nrows, ent_names[i], ":", happy_num(n, sizeof n, "", h->perEntertainmentType[i]), 10, 0);
+ if (story_is("cityofthekey")) {
+ /* the Glory of the Key and its three parts */
+ const GloryOfTheKey *g = glory_of_the_key();
+ happy_add(rows, &nrows, L_glory_of_the_key, ":", happy_num(n, sizeof n, "", g->gloryOfTheKeyHappiness), 0, 0);
+ happy_add(rows, &nrows, L_sculptures, ":", happy_num(n, sizeof n, "", g->sculpturesHappiness), 10, 0);
+ happy_add(rows, &nrows, L_luxury_housing, ":", happy_num(n, sizeof n, "", g->highEndHomeHappiness), 10, 0);
+ happy_add(rows, &nrows, L_high_end_restaurants, ":", happy_num(n, sizeof n, "", g->expensiveRestaurantHappiness), 10, 0);
+ }
+ happy_add(rows, &nrows, L_education_happiness, "", happy_num(n, sizeof n, "", h->schoolHappiness), 0, 0);
+ happy_add(rows, &nrows, L_medical_happiness, "", happy_num(n, sizeof n, "", h->medicalHappiness), 0, 0);
+ if (h->foodShortageUnhappiness > 0)
+ happy_add(rows, &nrows, L_food_shortage_unhappiness, "", happy_num(n, sizeof n, "-", h->foodShortageUnhappiness), 0, 0);
+ if (h->foodRationingUnhappiness > 0)
+ happy_add(rows, &nrows, L_food_rationing_unhappiness, "", happy_num(n, sizeof n, "-", h->foodRationingUnhappiness), 0, 0);
+ if (h->overtimeUnhappinessShown > 0)
+ happy_add(rows, &nrows, L_mandatory_overtime_unhappiness, "", happy_num(n, sizeof n, "-", h->overtimeUnhappinessShown), 0, 0);
+ if (h->enthusiasmHappiness != 0)
+ happy_add(rows, &nrows, L_new_city_enthousiasm, "", happy_num(n, sizeof n, "+", h->enthusiasmHappiness), 0, 0);
+ /* the boosts running: "text:" and "+n" (or "-n"), one a line, 4 below the rest */
+ for (int b = 0, nb = happiness_boosts(); b < nb; b++) {
+ uint8_t t;
+ float v = happiness_boost(b, &t);
+ happy_add(rows, &nrows, boost_text(t), ":", happy_num(n, sizeof n, v > 0 ? "+" : "", v), 0, b == 0 ? 4 : 0);
+ }
+ happy_add(rows, &nrows, L_total_happiness, "", happy_num(n, sizeof n, "", h->happiness), 0, 4);
+ ui_float_fmt(n, sizeof n, h->actionSpeedModifier, 2);
+ happy_add(rows, &nrows, L_work_speed_modifier, "", n, 0, 0);
+ /* the numbers' column: right of the widest text (the entertainment row: its text, 3, and its "..." button) */
+ int dots_w = 2 + 3 + ui_text_w(FONT_STANDARD, "...") + 3 + 3;
+ int col = 0;
+ for (int i = 0; i < nrows; i++) {
+ int tw = rows[i].pad_left + ui_text_w(FONT_STANDARD, rows[i].text) + (i == ent_row ? 3 + dots_w : 5);
+ if (tw > col) col = tw;
+ }
+ for (int i = 0; i < nrows; i++) {
+ HappyRow *r = &rows[i];
+ w->y += r->pad_top;
+ int x, y;
+ if (i == ent_row) {
+ /* the entertainment row's "..." button (a ContainerButton) to its information window */
+ int tw = ui_text_w(FONT_STANDARD, r->text), bx = tw + 3;
+ bool vis = win_area(w, 0, 0, &x, &y);
+ bool f = win_small_button(w, bx, dots_w, 12, 1);
+ if (vis) {
+ ui_text(FONT_STANDARD, x, y - 2, r->text, C_BLACK);
+ ui_box(x + bx, y, dots_w, 12, f ? (key_held(K_OK) ? BX_BUTTON_DOWN : BX_BUTTON_HOVER) : BX_BUTTON);
+ ui_text(FONT_STANDARD, x + bx + 2 + 3, y - 3, "...", C_BLACK);
+ ui_text(FONT_STANDARD, x + col, y - 2, r->num, C_BLACK);
+ }
+ w->y += 12;
+ continue;
+ }
+ if (win_area(w, col + ui_text_w(FONT_STANDARD, r->num), 12, &x, &y)) {
+ ui_text(FONT_STANDARD, x + r->pad_left, y - 2, r->text, C_BLACK);
+ ui_text(FONT_STANDARD, x + col, y - 2, r->num, C_BLACK);
+ }
+ }
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_happiness_action(Win *wn, int a) {
+ (void)wn;
+ if (a == 1) win_open(WK_ENTERTAINMENT, 0, 0);
+}
+
+/* ---------------------------------------------------------------- houses */
+static const char *housing_help(char *buf, int size) {
+ if (stats.peopleWithHome >= stats.people) {
+ if (stats.houseCapacity == stats.peopleWithHome) return L_houses_exactly_enough;
+ return lo_1(buf, size, L_house_n_cap_remaining, LN(stats.houseCapacity - stats.peopleWithHome));
+ }
+ int homeless = stats.people - stats.peopleWithHome;
+ return homeless == 1 ? L_homeless_one : lo_1(buf, size, L_homeless_n, LN(homeless));
+}
+
+/* "x<number>: ", as wide as BitmapText measures it (a line's last space adds nothing): the "x1:3/4" of the original */
+static int count_w(int number) {
+ char t[16] = "x";
+ fmt_int(t + 1, sizeof t - 1, number);
+ str_cat(t, sizeof t, ":");
+ return ui_text_w(FONT_STANDARD, t);
+}
+
+/* a table of building types: picture, "x<number>: " and a text (HouseInformationWindow, WorkerDistributionWindow) */
+static int type_row(WinOut *w, int cls, int number, int num_col, const char *text) {
+ char t[24] = "x";
+ fmt_int(t + 1, sizeof t - 1, number);
+ str_cat(t, sizeof t, ": ");
+ int x, y;
+ if (win_area(w, num_col + ui_text_w(FONT_STANDARD, text) + 2, 20, &x, &y)) {
+ type_image(x, y, cls);
+ ui_text(FONT_STANDARD, x + 20 + 2, y + 5 - 2, t, C_BLACK);
+ ui_text(FONT_STANDARD, x + num_col + 2, y + 5 - 2, text, C_BLACK);
+ }
+ return 0;
+}
+
+void info_houses(WinOut *w) {
+ char t[96];
+ win_title_icon(w, L_housing_information, SPR_HOUSING);
+ win_para(w, FONT_STANDARD, housing_help(t, sizeof t), 250, C_BLACK);
+ if (stats.peopleWithHome < stats.people) {
+ win_button(w, 0, L_find_homeless, 1, true);
+ win_space(w, 6 - 4);
+ }
+ int num_col = 0, any = 0;
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ if (!(pcls[c].base & B_HOUSE)) continue;
+ int n = count_class(c);
+ if (!n) continue;
+ int wd = 20 + 2 + count_w(n);
+ if (wd > num_col) num_col = wd;
+ }
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ if (!(pcls[c].base & B_HOUSE)) continue;
+ int n = 0, filled = 0, cap = 0;
+ for (int k = 1; k < MAX_PERMS; k++) {
+ Perm *p = &perms[k];
+ if (!(p->flags & PF_USED) || p->cls != c) continue;
+ n++, filled += p->nresidents, cap += bld_residents(p);
+ }
+ if (!n) continue;
+ any++;
+ type_row(w, c, n, num_col, lo_2(t, sizeof t, L_residents, LN(filled), LN(cap)));
+ }
+ if (!any) win_para(w, FONT_STANDARD, L_there_are_no_houses, 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_houses_action(Win *wn, int a) {
+ (void)wn;
+ if (a != 1) return;
+ int n = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && !cits[i].home) n++;
+ if (!n) return;
+ int pick = rnd_int(n);
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && !cits[i].home && pick-- == 0) {
+ cu.following = (uint16_t)i;
+ win_open(WK_CITIZEN, (uint16_t)i, 0);
+ break;
+ }
+}
+
+/* ---------------------------------------------------------------- workers */
+extern int priority_jobs[64];
+
+void info_workers(WinOut *w) {
+ char t[96];
+ win_title_icon(w, L_assign_workers, SPR_WORK);
+ int num_col = 0, text_col = 0, any = 0;
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ if (!(pcls[c].base & B_WORK)) continue;
+ int n = 0, filled = 0, jobs = 0;
+ for (int k = 1; k < MAX_PERMS; k++) {
+ Perm *p = &perms[k];
+ if (!(p->flags & PF_USED) || p->cls != c) continue;
+ n++, filled += p->nworkers, jobs += bld_jobs(p);
+ }
+ if (!n) continue;
+ int wd = 20 + 2 + count_w(n);
+ if (wd > num_col) num_col = wd;
+ lo_2(t, sizeof t, L_workers, LN(filled), LN(jobs));
+ str_cat(t, sizeof t, ",");
+ int tw = ui_text_w(FONT_STANDARD, t) + 2;
+ if (tw > text_col) text_col = tw;
+ }
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ if (!(pcls[c].base & B_WORK)) continue;
+ if (story_is("cityofthekey") && c == CLS_SecretSocietyHouse) continue;
+ int n = 0, filled = 0, jobs = 0;
+ for (int k = 1; k < MAX_PERMS; k++) {
+ Perm *p = &perms[k];
+ if (!(p->flags & PF_USED) || p->cls != c) continue;
+ n++, filled += p->nworkers, jobs += bld_jobs(p);
+ }
+ if (!n) continue;
+ any++;
+ lo_2(t, sizeof t, L_workers, LN(filled), LN(jobs));
+ str_cat(t, sizeof t, ",");
+ int y0 = w->y;
+ type_row(w, c, n, num_col, t);
+ /* NumberSelectControl: the priority jobs (a button: the current workers), then up and down (spr_minibutton) */
+ int prio = c < 64 ? priority_jobs[c] : 0;
+ char num[16];
+ if (prio == 1000000) num[0] = 0, str_cat(num, sizeof num, L_max);
+ else fmt_int(num, sizeof num, prio);
+ int px = num_col + 2 + text_col + 4, nw = ui_text_w(FONT_STANDARD, num);
+ nw = (nw > 20 ? nw : 20) + 6;
+ w->y = y0 + 2;
+ bool f0 = win_small_button(w, px, nw, 14, 100 + c);
+ bool f1 = win_small_button(w, px + nw, 9, 7, 200 + c);
+ w->y = y0 + 2 + 7;
+ bool f2 = win_small_button(w, px + nw, 9, 7, 300 + c);
+ w->y = y0;
+ int bx, by;
+ if (win_area(w, 0, 0, &bx, &by)) {
+ ui_box(bx + px, by + 2, nw, 14, f0 ? BX_BUTTON_HOVER : BX_BUTTON);
+ ui_text(FONT_STANDARD, bx + px + 3, by + 2 + 3 - 2, num, C_BLACK);
+ ui_frame(SPR_MINIBUTTON, 9, f1 ? 1 : 0, bx + px + nw, by + 2, 0, 255);
+ ui_spr(SPR_ARROWUP, bx + px + nw + 1, by + 2 + 1);
+ ui_frame(SPR_MINIBUTTON, 9, f2 ? 1 : 0, bx + px + nw, by + 2 + 7, 0, 255);
+ ui_spr(SPR_ARROWDOWN, bx + px + nw + 1, by + 2 + 7 + 1);
+ ui_text(FONT_STANDARD, bx + px + nw + 9, by + 2 + 1, L_priority_text, C_BLACK);
+ }
+ int right = px + nw + 9 + ui_text_w(FONT_STANDARD, L_priority_text);
+ if (w->maxw < right) w->maxw = right;
+ w->y = y0 + 20;
+ }
+ if (!any) win_para(w, FONT_STANDARD, L_no_work_buildings, 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_workers_action(Win *wn, int a) {
+ (void)wn;
+ int c = a % 100, op = a / 100;
+ if (c >= 64) return;
+ int jobs = 0, filled = 0;
+ for (int k = 1; k < MAX_PERMS; k++) {
+ Perm *p = &perms[k];
+ if ((p->flags & PF_USED) && p->cls == c) jobs += bld_jobs(p), filled += p->nworkers;
+ }
+ int n = priority_jobs[c];
+ if (op == 1) n = filled;
+ else if (op == 2) n = n == 1000000 ? n : n + 1 <= jobs ? n + 1 : 1000000;
+ else if (op == 3) n = n == 1000000 ? jobs : n > 0 ? n - 1 : 0;
+ priority_jobs[c] = n;
+ sim_flags |= SIM_JOBS_CHANGED;
+ tut_flags |= TF_PRIO;
+}
+
+/* ---------------------------------------------------------------- birth control */
+void info_birth(WinOut *w) {
+ win_title(w, L_birth_control);
+ int mode = babies.mode;
+ win_activatable(w, mode == 1, 1, L_greatly_discourage_children, L_pop_stabilize, NULL, NULL);
+ win_activatable(w, mode == 2, 2, L_encourage_contraception, L_slow_pop_growth, NULL, NULL);
+ win_activatable(w, mode == 0, 3, L_no_special_policy, L_babies_born_normal, NULL, NULL);
+ win_activatable(w, mode == 3, 4, L_encourage_parenthood, L_more_babies_born, NULL, NULL);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_birth_action(Win *wn, int a) {
+ (void)wn;
+ if (a == 1) babies.mode = 1, babies.targetPopAmount = ncits;
+ else if (a == 2) babies.mode = 2;
+ else if (a == 3) babies.mode = 0;
+ else if (a == 4) babies.mode = 3;
+}
+
+/* ---------------------------------------------------------------- entertainment */
+void info_entertainment(WinOut *w) {
+ win_title_icon(w, cat_text[3].name, SPR_HAPPINESS);
+ int shard = -1;
+ bool failed = false;
+ for (int i = 1; i < MAX_PERMS && !failed; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || !is_building(p) || !(p->flags & PF_IS_ENTERTAINMENT)) continue;
+ if (shard < 0) shard = p->shard;
+ else if (p->shard != shard) failed = true;
+ }
+ if (failed) win_para(w, FONT_STANDARD, L_entertainment_information_multiple_wg_with_citizens, 150, C_BLACK);
+ /* (the original's line for citizens in more than one group of worlds is left out: its text is missing from the
+ * original, which shows Localize's "!!! missing text !!!") */
+ for (int t = 0; t < 5; t++) {
+ win_para(w, FONT_15, ent_name(t), 250, C_BLACK);
+ float total = 0;
+ int shown = 0;
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ int n = 0;
+ float cap = 0;
+ for (int k = 1; k < MAX_PERMS; k++) {
+ Perm *p = &perms[k];
+ if (!(p->flags & PF_USED) || p->cls != c || !is_building(p) || !(p->flags & PF_IS_ENTERTAINMENT)) continue;
+ if (ent_type(p) != t && !(bld_secondary_entertainment_types(p) >> t & 1)) continue;
+ n++, cap += bld_entertainment_capacity(p);
+ }
+ if (!n) continue;
+ shown++;
+ total += cap;
+ char x[16] = "x", num[24];
+ fmt_int(x + 1, sizeof x - 1, n);
+ str_cat(x, sizeof x, ": ");
+ fmt_num(num, sizeof num, cap);
+ int bx, by;
+ if (win_area(w, 20 + 2 + count_w(n) + 20 + ui_text_w(FONT_STANDARD, num), 20, &bx, &by)) {
+ type_image(bx, by, c);
+ ui_text(FONT_STANDARD, bx + 22, by + 3, x, C_BLACK);
+ ui_text(FONT_STANDARD, bx + w->cw - ui_text_w(FONT_STANDARD, num), by + 3, num, C_BLACK);
+ }
+ }
+ if (!shown) {
+ win_para(w, FONT_STANDARD, "--", 250, C_BLACK);
+ } else {
+ char tl[24] = "", num[24];
+ str_cat(str_cat(tl, sizeof tl, L_total), sizeof tl, ":");
+ fmt_num(num, sizeof num, total);
+ int bx, by;
+ if (win_area(w, ui_text_w(FONT_STANDARD, tl) + 20 + ui_text_w(FONT_STANDARD, num), 20, &bx, &by)) {
+ ui_text(FONT_STANDARD, bx, by + 3, tl, C_BLACK);
+ ui_text(FONT_STANDARD, bx + w->cw - ui_text_w(FONT_STANDARD, num), by + 3, num, C_BLACK);
+ }
+ }
+ win_space(w, 4);
+ }
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+/* ---------------------------------------------------------------- highlight buildings */
+void info_find(WinOut *w) {
+ Win *wn = w->win;
+ char t[96];
+ if (wn->arg2) {
+ /* FindBuildingsOfTypeActive: highlighting one type */
+ int c = wn->arg;
+ cu.highlight_cls = (uint16_t)(c + 1);
+ win_title(w, lo_1(t, sizeof t, L_highlighting, LS(cls_text[c].name)));
+ const char *label = L_select_any;
+ int a = 1;
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+ return;
+ }
+ cu.highlight_cls = 0;
+ win_title(w, L_highlight_buildings);
+ bool first = true;
+ for (int cat = 0; cat < NCATEGORIES; cat++) {
+ int n = 0;
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ if (pcls[c].category != cat || cls_text[c].sub) continue;
+ int st = unlock_state(c);
+ bool needs_unlock = cls_text[c].hint && st == UNLOCK_UNLOCKED;
+ if (st == UNLOCK_LOCKED || needs_unlock) continue;
+ if (!n) {
+ if (!first) win_space(w, 6);
+ win_para(w, FONT_15, cat_text[cat].name, 250, C_BLACK);
+ first = false;
+ win_row_begin(w);
+ }
+ if (n && n % 9 == 0) {
+ win_row_end(w);
+ win_row_begin(w);
+ }
+ /* an ImageButton (spr_buildingbutton) with the type's picture */
+ int x = w->rx;
+ int bx, by;
+ bool f = win_small_button(w, x, 22, 22, 10 + c);
+ w->rx = x + 22;
+ if (w->rh < 22) w->rh = 22;
+ if (w->maxw < w->rx) w->maxw = w->rx;
+ int save = w->y;
+ if (win_area(w, 0, 0, &bx, &by)) {
+ ui_frame(SPR_BUILDINGBUTTON, 22, f ? (key_held(K_OK) ? 2 : 1) : 0, bx + x, by, 0, 255);
+ type_image(bx + x + 1, by + 1, c);
+ }
+ w->y = save;
+ n++;
+ }
+ if (n) win_row_end(w);
+ }
+ win_space(w, 6);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_find_action(Win *wn, int a) {
+ if (wn->arg2) {
+ if (a == 1) {
+ /* cityActions_CityHighlightBuildingsOfType.findLeastUpgraded */
+ int c = wn->arg, best = 0, best_n = 1 << 30;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->cls != c) continue;
+ int n = __builtin_popcount(p->upgrades);
+ if (n < best_n) best_n = n, best = i;
+ }
+ if (best) {
+ cu.selected = (uint16_t)best;
+ win_open(WK_BUILDING, (uint16_t)best, 0);
+ Perm *p = P(best);
+ camera_follow((float)perm_city_x(p) + 10, (float)perm_city_y(p) + 10);
+ }
+ }
+ return;
+ }
+ if (a >= 10 && a < 10 + CLS_COUNT) win_open(WK_FIND, (uint16_t)(a - 10), 1);
+}
+
+/* ---------------------------------------------------------------- upgrades and policies */
+static bool only_new;
+
+void info_upgrades(WinOut *w) {
+ win_title(w, L_upgrades_and_policies);
+ win_checkbox(w, only_new, 1, L_only_show_unupgraded, "", NULL);
+ win_space(w, 6);
+ int any = 0;
+ for (int i = 0; i < nbuild_order; i++) {
+ int c = build_order[i];
+ /* the first building of the type with anything to buy */
+ Perm *p = NULL;
+ for (int k = 1; k < MAX_PERMS && !p; k++)
+ if ((perms[k].flags & PF_USED) && perms[k].cls == c) p = &perms[k];
+ if (!p) continue;
+ UpgradeOption opts[24];
+ int n = upgrade_options(p, opts, 24);
+ if (!n) continue;
+ if (only_new) {
+ bool keep = false;
+ for (int k = 0; k < n && !keep; k++) {
+ if (opts[k].kind == UO_POLICY) keep = true;
+ else if (opts[k].kind == UO_UPGRADE) {
+ float total[M_COUNT];
+ bool ca;
+ keep = upgrade_all_count(p, opts[k].upgrade, total, &ca) > 0;
+ } else if (opts[k].kind == UO_CITY) keep = !opts[k].owned;
+ }
+ if (!keep) continue;
+ }
+ any++;
+ /* the type's picture and name (Arial16) */
+ int x, y;
+ if (win_area(w, 23 + ui_text_w(FONT_16, cls_text[c].name), 20, &x, &y)) {
+ type_image(x, y, c);
+ ui_text(FONT_16, x + 23, y + 3 - 2, cls_text[c].name, C_BLACK);
+ }
+ win_space(w, 4);
+ extern void upgrades_for_type(WinOut *w, Perm *p, int base);
+ upgrades_for_type(w, p, 100 + 30 * any);
+ }
+ if (!any) win_para(w, FONT_STANDARD, L_no_upgrades, 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_upgrades_action(Win *wn, int a) {
+ (void)wn;
+ if (a == 1) {
+ only_new = !only_new;
+ return;
+ }
+ extern void upgrades_for_type_action(int a);
+ upgrades_for_type_action(a);
+}
+
+/* ---------------------------------------------------------------- invite citizens */
+static const char *invite_result;
+
+void info_invite(WinOut *w) {
+ char t[128];
+ win_title(w, L_invite_people);
+ int limit = (stories[story.index].flags & ST_FREEPLAY) ? babies.softPopLimit : 1900;
+ bool full_window = ncits + spawners_pending() + 10 < limit;
+ if (full_window) {
+ win_para(w, FONT_STANDARD, lo_1(t, sizeof t, L_invite_people_description, LN(10)), 250, C_BLACK);
+ float cost[M_COUNT];
+ invite_price(cost);
+ /* displayCityAmounts: what the city has / the price */
+ int x, y;
+ if (win_area(w, 120, 12, &x, &y)) {
+ int xx = 0;
+ for (int m = 0; m < M_COUNT; m++) {
+ if (cost[m] <= 0) continue;
+ if (m == M_FOOD) xx -= 2;
+ ui_spr(mat_icon[m], x + xx, y);
+ xx += 11 + (m == M_FOOD ? -2 : 0);
+ char a[24], b[16];
+ fmt_large(a, sizeof a, floor(city.materials.m[m]), false);
+ str_cat(a, sizeof a, "/");
+ fmt_num(b, sizeof b, cost[m]);
+ str_cat(a, sizeof a, b);
+ xx += ui_text(FONT_STANDARD, x + xx, y - 1, a, city.materials.m[m] < cost[m] ? C_RED : C_BLACK) + 3;
+ }
+ }
+ win_space(w, 2);
+ win_button(w, 0, L_invite_people, 1, true);
+ win_space(w, 0);
+ win_para(w, FONT_STANDARD, invite_result ? invite_result : " ", 250, C_BLACK);
+ win_space(w, 6);
+ } else {
+ win_para(w, FONT_STANDARD, L_invite_people_done, 250, C_BLACK);
+ }
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void info_invite_action(Win *wn, int a) {
+ (void)wn;
+ if (a != 1) return;
+ static char result[96];
+ int p = invite_problem();
+ if (p == 3) invite_result = L_cant_afford;
+ else if (p == 2) invite_result = L_invite_not_enough_houses;
+ else if (invite_citizens()) invite_result = lo_1(result, sizeof result, L_invite_people_success, LN(10));
+}
+
+/* ---------------------------------------------------------------- the panel's tooltips */
+void panel_tooltip(int which, int x, int y) {
+ Tip t = {0};
+ char text[600], head[48];
+ text[0] = 0;
+ switch (which) {
+ case PR_HELP: {
+ extern int goal_help(char *buf, int size, const char **header);
+ goal_help(text, sizeof text, &t.header);
+ t.text = text;
+ break;
+ }
+ case PR_PAUSE:
+ str_cat(str_cat(str_cat(text, sizeof text, L_ok_or_alpha), sizeof text, " "), sizeof text, city.paused ? L_to_unpause : L_to_pause);
+ t.header = city.paused ? L_game_paused : L_game_running;
+ t.text = text;
+ break;
+ case PR_SPEED: {
+ static const char *const names[] = {L_normal_speed, L_onepointfive_speed, L_double_speed, L_half_speed, L_threequarter_speed};
+ t.header = names[cu.speed];
+ t.text = L_change_game_speed_pc;
+ break;
+ }
+ case PR_MENU: t.header = L_game_menu; break;
+ case PR_HIDE: t.text = cu.panel_hidden ? L_show_extra_info : L_hide_extra_info; break;
+ case PR_POP: {
+ char a[64];
+ int children = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cit_age(&cits[i]) <= 16) children++;
+ str_cat(text, sizeof text, L_total_amount_of_citizens);
+ str_cat(text, sizeof text, "\n");
+ str_cat(text, sizeof text, children == 1 ? L_is_one_child : lo_1(a, sizeof a, L_are_n_children, LN(children)));
+ str_cat(text, sizeof text, "\n");
+ str_cat(text, sizeof text, ncits >= 1950 ? L_tap_for_age_distribution_or_pop_limit : L_tap_for_age_distribution);
+ t.header = L_population, t.text = text;
+ break;
+ }
+ case PR_HAPPY: {
+ /* HappinessWindow's tooltip */
+ char n[32];
+ HappinessState *h = &happiness;
+#define LINE(label, v) do { str_cat(text, sizeof text, "\n"); str_cat(text, sizeof text, label); str_cat(text, sizeof text, " "); fmt_int(n, sizeof n, (long)(v)); str_cat(text, sizeof text, n); } while (0)
+ str_cat(text, sizeof text, L_happiness_explainer);
+ LINE(L_home_happiness, h->homeHappiness);
+ LINE(L_sense_of_purpose, h->purposeHappiness);
+ LINE(L_entertainment_happiness, h->entertainmentHappiness);
+ LINE(L_education_happiness, h->schoolHappiness);
+ LINE(L_medical_happiness, h->medicalHappiness);
+ str_cat(text, sizeof text, "\n");
+ if (h->foodShortageUnhappiness > 0) {
+ str_cat(text, sizeof text, L_food_shortage_unhappiness), str_cat(text, sizeof text, " ");
+ fmt_int(n, sizeof n, (long)h->foodShortageUnhappiness), str_cat(text, sizeof text, n), str_cat(text, sizeof text, "\n");
+ }
+ if (h->foodRationingUnhappiness > 0) {
+ str_cat(text, sizeof text, L_food_rationing_unhappiness), str_cat(text, sizeof text, " ");
+ fmt_int(n, sizeof n, (long)ceil(h->foodRationingUnhappiness)), str_cat(text, sizeof text, n), str_cat(text, sizeof text, "\n");
+ }
+ if (h->overtimeUnhappinessShown > 0) {
+ str_cat(text, sizeof text, L_mandatory_overtime_unhappiness), str_cat(text, sizeof text, " ");
+ fmt_int(n, sizeof n, (long)ceil(h->overtimeUnhappinessShown)), str_cat(text, sizeof text, n), str_cat(text, sizeof text, "\n");
+ }
+ for (int b = 0, nb = happiness_boosts(); b < nb; b++) {
+ /* the boosts: "text: n" */
+ uint8_t bt;
+ float v = happiness_boost(b, &bt);
+ str_cat(str_cat(text, sizeof text, boost_text(bt)), sizeof text, ": ");
+ fmt_int(n, sizeof n, (long)v), str_cat(text, sizeof text, n), str_cat(text, sizeof text, "\n");
+ }
+ if (h->enthusiasmHappiness != 0) {
+ str_cat(text, sizeof text, L_new_city_enthousiasm), str_cat(text, sizeof text, " ");
+ fmt_int(n, sizeof n, (long)h->enthusiasmHappiness), str_cat(text, sizeof text, n), str_cat(text, sizeof text, "\n");
+ }
+ char sp[16], line[96];
+ ui_float_fmt(sp, sizeof sp, h->actionSpeedModifier, 2);
+ str_cat(text, sizeof text, "\n");
+ str_cat(text, sizeof text, lo_1(line, sizeof line, L_citizens_work_at_speed, LS(sp)));
+#undef LINE
+ t.header = L_happiness, t.text = text;
+ break;
+ }
+ case PR_HOUSES: t.header = L_housing, t.text = housing_help(text, sizeof text); break;
+ case PR_WORK: t.header = L_work, t.text = lo_1(text, sizeof text, L_work_tooltip, LN(stats.jobs)); break;
+ default:
+ if (which >= PR_MAT0) {
+ int m = which - PR_MAT0;
+ material_tip(m, text, sizeof text);
+ t.header = mat_title(m, head, sizeof head);
+ t.text = text;
+ }
+ }
+ ui_tooltip(&t, x, y, false);
+}
diff --git a/games/finalearth2/src/ui_menu.c b/games/finalearth2/src/ui_menu.c
new file mode 100644
index 00000000..95ca9917
--- /dev/null
+++ b/games/finalearth2/src/ui_menu.c
@@ -0,0 +1,437 @@
+/* The Final Earth 2: the title screen and the menus (the original's
+ * MainMenu, gui.MainMenuGUI, gui.FreePlayConfigureWindow, gui.CreditsWindow,
+ * gui.GameMenu), saves (City.handleAutoSave) and the progress kept between
+ * cities (MetaGame: the scenarios won, in a small file of its own). */
+#include <math.h>
+#include "game.h"
+#include "save.h"
+#include "uii.h"
+#include "view.h"
+
+Meta meta;
+#define META_FILE "fe2meta.dat"
+static bool meta_unlocked_all; /* MetaGame.unlockedAll */
+
+void meta_load(void) {
+ uint32_t len;
+ const uint8_t *d = plat_load(META_FILE, &len);
+ memset(&meta, 0, sizeof meta);
+ meta_unlocked_all = false;
+ if (!d || len < 1 + 16 + 1) return;
+ meta.won = d[0];
+ memcpy(meta.best, d + 1, 16);
+ meta_unlocked_all = d[17] != 0;
+}
+
+void meta_save(void) {
+ uint8_t d[18];
+ d[0] = meta.won;
+ memcpy(d + 1, meta.best, 16);
+ d[17] = meta_unlocked_all;
+ plat_save(META_FILE, d, sizeof d);
+ save_copy();
+}
+
+/* progress.StoryLoader.hasCompletedRequirements: each scenario needs the one before it won */
+bool story_requirements(int s) {
+ if (s <= 0 || s >= 4) return true; /* the first scenario and the free play maps */
+ return meta_unlocked_all || (meta.won >> (s - 1) & 1);
+}
+
+/* ---------------------------------------------------------------- saving */
+bool ui_save(bool tell) {
+ if (ui.title) return true;
+ saved_view.cx = cu.cx, saved_view.cy = cu.cy; /* (the cursor is kept with the view) */
+ bool ok = save_game();
+ ui.seconds_since_save = 0;
+ if (!ok) {
+ win_close_all();
+ win_open_text(L_keypad_save_failed_title, L_keypad_save_failed);
+ } else if (tell) {
+ notify_top(L_keypad_saved, NULL, 120);
+ }
+ return ok;
+}
+
+/* Home: saves, then the game quits. A failed save says so and the game goes on; Home again in that window quits
+ * without saving */
+bool ui_home(void) {
+ if (ui.title || (ui.home_unsaved && win_is_open(WK_TEXT))) return true;
+ saved_view.cx = cu.cx, saved_view.cy = cu.cy;
+ if (save_game()) return true;
+ ui_text_buf[0] = 0;
+ str_cat(str_cat(str_cat(ui_text_buf, sizeof ui_text_buf, L_keypad_save_failed), sizeof ui_text_buf, " "), sizeof ui_text_buf,
+ L_keypad_home_quit);
+ win_close_all();
+ win_open_text(L_keypad_save_failed_title, ui_text_buf);
+ ui.home_unsaved = true;
+ return false;
+}
+
+/* handleAutoSave: the original saves every two seconds; here, at the start of every other day */
+void autosave_tick(void) {
+ static int last_day;
+ ui.seconds_since_save += 1.0f / FPS;
+ int day = city_day();
+ if (ui.title) {
+ last_day = day;
+ return;
+ }
+ if (day != last_day) {
+ if (day % 2 == 0) ui_save(false);
+ last_day = day;
+ }
+}
+
+/* ---------------------------------------------------------------- starting a city */
+static void start_story(int s) {
+ ui.title = false;
+ ui_before_city();
+ game_start(s, NULL);
+ ui_after_load();
+ ui_save(false);
+}
+
+/* createNewGameState: free play maps get their options first (the map shows behind) */
+void menu_new_city(int s) {
+ win_close_all();
+ if (stories[s].flags & ST_FREEPLAY) {
+ ui.title = true; /* not playing yet: no panel (the welcome goal waits under the options) */
+ ui.setup = true;
+ ui_before_city();
+ game_start(s, NULL);
+ ui_after_load();
+ win_open(WK_FREE_PLAY, (uint16_t)s, (uint16_t)ncits);
+ return;
+ }
+ start_story(s);
+}
+
+/* ---------------------------------------------------------------- the scenarios (MainMenuGUI.createNewScenarioWindow) */
+static bool any_locked(void) {
+ for (int s = 1; s < 4; s++)
+ if (!story_requirements(s)) return true;
+ return false;
+}
+
+static void add_story(WinOut *w, int s) {
+ char desc[400], t[64];
+ desc[0] = 0;
+ if (s < 4 && (meta.won >> s & 1)) {
+ int time = meta.best[s];
+ str_cat(desc, sizeof desc, lo_3(t, sizeof t, L_best_time, LN(time / 1440), LN(time / 60 % 24), LN(time % 60)));
+ str_cat(desc, sizeof desc, " \n");
+ }
+ str_cat(desc, sizeof desc, stories[s].description);
+ /* "Free Play - " left out of the name */
+ const char *name = stories[s].name;
+ if (!strncmp(name, "Free Play - ", 12)) name += 12;
+ win_activatable(w, false, 10 + s, name, desc, NULL, NULL);
+}
+
+void menu_scenarios_content(WinOut *w) {
+ win_title(w, L_start_scenario);
+ for (int s = 0; s < nstories; s++)
+ if (!(stories[s].flags & ST_FREEPLAY) && story_requirements(s)) add_story(w, s);
+ if (any_locked()) {
+ /* the "Unlock All" button: a ContainerButton (padding 3, 3, 3, 1) with a text */
+ win_text_button(w, L_unlock_all, 1, BX_BUTTON, true, false);
+ w->y += 1;
+ }
+ win_space(w, 6);
+ char t[32] = "";
+ str_cat(str_cat(t, sizeof t, L_free_play), sizeof t, ":");
+ win_para(w, FONT_STANDARD, t, 250, C_BLACK);
+ for (int s = 0; s < nstories; s++)
+ if ((stories[s].flags & ST_FREEPLAY) && story_requirements(s)) add_story(w, s);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+void menu_scenarios_action(Win *wn, int a) {
+ (void)wn;
+ if (a == 1) {
+ meta_unlocked_all = true;
+ meta_save();
+ } else if (a >= 10 && a < 10 + nstories) {
+ menu_new_city(a - 10);
+ }
+}
+
+/* ---------------------------------------------------------------- free play (FreePlayConfigureWindow) */
+static void set_citizens(int n) {
+ int w = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) {
+ w = cits[i].onWorld;
+ break;
+ }
+ for (int i = MAX_CITS - 1; i >= 1 && ncits > n; i--)
+ if (cits[i].flags & CF_ALIVE) {
+ cit_try_remove(&cits[i], true);
+ city.materials.m[M_FOOD] -= 3;
+ }
+ while (ncits < n) {
+ if (!cit_new(w, (float)rnd_int(worlds[w].w - 2), rnd_range(18, 40), NONE)) break;
+ city.materials.m[M_FOOD] += 3;
+ }
+}
+
+void menu_free_play_content(WinOut *w) {
+ Win *wn = w->win;
+ int s = wn->arg, standard = wn->arg2;
+ win_title(w, L_customize_free_play);
+ win_space(w, 2);
+ win_para(w, FONT_15, L_starting_resources, 250, C_BLACK);
+ bool extra = city.materials.m[M_WOOD] >= 1000;
+ win_text_button(w, L_normal_resources, 1, BX_ACTIVABLE | (!extra ? BXF_ACTIVE : 0), true, false);
+ if (!(stories[s].flags & ST_NO_EXTRA_RESOURCES)) {
+ win_space(w, 2);
+ win_text_button(w, L_extra_resources, 2, BX_ACTIVABLE | (extra ? BXF_ACTIVE : 0), true, false);
+ }
+ win_space(w, 6);
+ win_para(w, FONT_15, L_starting_citizens, 250, C_BLACK);
+ win_row_begin(w);
+ const int counts[] = {standard, 10, 25, 100};
+ for (int i = 0; i < 4; i++) {
+ char n[8];
+ fmt_int(n, sizeof n, counts[i]);
+ win_text_button(w, n, 10 + i, BX_ACTIVABLE | (ncits == counts[i] ? BXF_ACTIVE : 0), false, false);
+ w->rx += 2;
+ }
+ win_row_end(w);
+ win_space(w, 6);
+ const char *label = L_back;
+ int a = 3;
+ win_bottom(w, &label, &a, 1, L_continue, 4);
+}
+
+void menu_free_play_action(Win *wn, int a) {
+ int standard = wn->arg2;
+ static const float extra[M_COUNT] = {[M_WOOD] = 1000, [M_STONE] = 1000, [M_FOOD] = 1000, [M_MACHINEPARTS] = 100, [M_KNOWLEDGE] = 500};
+ if (a == 1 || a == 2) {
+ memset(&city.materials, 0, sizeof city.materials);
+ for (int m = 0; m < M_COUNT; m++)
+ city.materials.m[m] = a == 2 ? extra[m] : stories[wn->arg].initialMaterials[m];
+ city.materials.m[M_FOOD] += 3.0 * (ncits - standard);
+ } else if (a >= 10 && a < 14) {
+ const int counts[] = {standard, 10, 25, 100};
+ set_citizens(counts[a - 10]);
+ } else if (a == 3 || a == ACT_CLOSE || a == ACT_BACK) {
+ /* back (onCancel): to the title */
+ win_close_all();
+ title_open();
+ } else if (a == 4) {
+ /* the city starts: its welcome goal's window shows */
+ win_close();
+ ui.title = ui.setup = false;
+ ui_after_load();
+ ui_save(false);
+ }
+}
+
+/* ---------------------------------------------------------------- credits */
+void menu_credits_content(WinOut *w) {
+ win_title(w, L_credits);
+ win_para(w, FONT_15, L_keypad_credits_1, 250, C_BLACK);
+ win_para(w, FONT_STANDARD, L_keypad_credits_2, 250, C_BLACK);
+ win_space(w, 6);
+ win_para(w, FONT_STANDARD, L_keypad_credits_3, 250, C_BLACK);
+ win_para(w, FONT_STANDARD, L_credits_additional_sprites, 250, C_BLACK);
+ win_space(w, 6);
+ win_para(w, FONT_15, L_keypad_credits_4, 250, C_BLACK);
+ win_space(w, 6);
+ win_para(w, FONT_STANDARD, L_thanks_for_playing, 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+/* ---------------------------------------------------------------- the game menu (gui.GameMenu) */
+enum { GM_SAVE = 1, GM_NEW, GM_RESTART, GM_NEXT, GM_TITLE, GM_CREDITS };
+
+void menu_game_content(WinOut *w) {
+ char t[64], num[16];
+ win_title(w, L_game_menu);
+ ui_float_fmt(num, sizeof num, ui.seconds_since_save, 1);
+ win_para(w, FONT_STANDARD, lo_1(t, sizeof t, L_last_saved, LS(num)), 250, C_BLACK);
+ win_row_begin(w);
+ win_text_button(w, L_save, GM_SAVE, BX_BUTTON, false, false);
+ win_row_end(w);
+ win_space(w, 6);
+ /* New City (filling the row), then Restart Scenario or Next Scenario */
+ const StoryGoal *win_goal = NULL;
+ for (int g = 0; g < stories[story.index].ngoals; g++)
+ if (!strcmp(stories[story.index].goals[g].name, "Win")) win_goal = &stories[story.index].goals[g];
+ bool next = story.goal < 0 && win_goal && win_goal->nextStory >= 0 && story_requirements(win_goal->nextStory);
+ const char *second = next ? L_next_scenario : L_restart_scenario;
+ int sw = ui_text_w(FONT_STANDARD, second) + 6;
+ int nw = w->cw - sw - 2;
+ int min_nw = ui_text_w(FONT_STANDARD, L_new_city) + 6;
+ if (nw < min_nw) nw = min_nw;
+ win_row_begin(w);
+ int x0 = w->rx;
+ /* a TextButton made wider (extraWidth): its text in the middle */
+ int save_cw = w->cw;
+ w->cw = nw;
+ win_text_button(w, L_new_city, GM_NEW, BX_BUTTON, true, true);
+ w->cw = save_cw;
+ w->rx = x0 + nw + 2;
+ win_text_button(w, second, next ? GM_NEXT : GM_RESTART, BX_BUTTON, false, false);
+ win_row_end(w);
+ win_space(w, 6);
+ /* the credits button: an ImageButton (spr_button_small) with spr_credits tinted black */
+ {
+ bool f = win_small_button(w, 0, 18, 18, GM_CREDITS);
+ int bx, by;
+ if (win_area(w, 18, 18, &bx, &by)) {
+ ui_frame(SPR_BUTTON_SMALL, 18, f ? (key_held(K_OK) ? 2 : 1) : 0, bx, by, 0, 255);
+ ui_spr_ex(SPR_CREDITS, 0, 0, 14, 14, bx + 2, by + 2, 0, 255, 0x0000);
+ }
+ }
+ win_space(w, 6);
+ const char *label = L_back_to_title;
+ int a = GM_TITLE;
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+}
+
+void menu_game_action(Win *wn, int a) {
+ (void)wn;
+ switch (a) {
+ case GM_SAVE:
+ ui_save(true);
+ break;
+ case GM_NEW: win_open(WK_SCENARIOS, 0, 0); break;
+ case GM_RESTART: win_open(WK_RESTART, 0, 0); break;
+ case GM_NEXT: {
+ for (int g = 0; g < stories[story.index].ngoals; g++)
+ if (!strcmp(stories[story.index].goals[g].name, "Win")) {
+ win_close_all();
+ menu_new_city(stories[story.index].goals[g].nextStory);
+ return;
+ }
+ break;
+ }
+ case GM_TITLE:
+ win_close_all();
+ if (ui_save(false)) title_open();
+ break;
+ case GM_CREDITS: win_open(WK_CREDITS, 0, 0); break;
+ }
+}
+
+void menu_restart_content(WinOut *w) {
+ win_title(w, L_restart_scenario_question);
+ win_para(w, FONT_STANDARD, L_sure_restart, 250, C_BLACK);
+ const char *label = L_restart;
+ int a = 1;
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+}
+
+void menu_restart_action(Win *wn, int a) {
+ (void)wn;
+ if (a == 1) {
+ win_close_all();
+ start_story(story.index);
+ }
+}
+
+/* ---------------------------------------------------------------- the title screen (MainMenu) */
+enum { TB_CONTINUE, TB_PLAY, TB_PLAYED_BEFORE, TB_NEW, TB_CREDITS, TB_COUNT };
+static uint8_t title_focus;
+static float title_time;
+
+static int title_buttons(uint8_t *list) {
+ int n = 0;
+ if (save_exists()) {
+ list[n++] = TB_CONTINUE;
+ list[n++] = TB_NEW;
+ } else {
+ list[n++] = TB_PLAY;
+ list[n++] = TB_PLAYED_BEFORE;
+ }
+ list[n++] = TB_CREDITS;
+ return n;
+}
+
+/* the display city: the first scenario's island at night (the menu keeps its time at 0) */
+void title_open(void) {
+ ui.title = true;
+ ui.setup = false;
+ ui_before_city();
+ game_start(0, NULL);
+ ui_after_load();
+ ui.title = true;
+ /* displayCity's view: its bottom at 270 */
+ camera.zoom = 1;
+ camera.x = 220 - SCREEN_W / 2.0f;
+ camera.y = 270 - SCREEN_H;
+ title_focus = 0;
+ title_time = 0;
+}
+
+void title_input(void) {
+ title_time += TIMEMOD;
+ if (!ui.setup) city.timeSinceStart = 0; /* MainMenu.updateDisplayCity */
+ if (nwins) {
+ win_input();
+ return;
+ }
+ uint8_t list[TB_COUNT];
+ int n = title_buttons(list);
+ if (title_focus >= n) title_focus = 0;
+ if (key_repeat(K_DOWN) || key_repeat(K_RIGHT)) title_focus = (uint8_t)((title_focus + 1) % n);
+ if (key_repeat(K_UP) || key_repeat(K_LEFT)) title_focus = (uint8_t)((title_focus + n - 1) % n);
+ if (input.released & K_OK) {
+ switch (list[title_focus]) {
+ case TB_CONTINUE:
+ ui_before_city();
+ if (load_game()) {
+ ui.title = false;
+ game_after_load();
+ ui_after_load();
+ } else {
+ win_open_text(NULL, L_keypad_load_failed);
+ }
+ break;
+ case TB_PLAY: start_story(0); break;
+ case TB_PLAYED_BEFORE:
+ case TB_NEW: win_open(WK_SCENARIOS, 0, 0); break;
+ case TB_CREDITS: win_open(WK_CREDITS, 0, 0); break;
+ }
+ }
+}
+
+void title_draw(void) {
+ ui_noclip();
+ if (nwins) return;
+ /* the title, its lines down to "A game by Florian van Strien" (the music credit left out) */
+ ui_spr_ex(SPR_TITLE, 0, 0, SPR_TITLE_W, 42, SCREEN_W / 2 - SPR_TITLE_W / 2, 10, 0, 255, GFX_NO_TINT);
+ uint8_t list[TB_COUNT];
+ int n = title_buttons(list), ntext = n - 1;
+ int big = list[0] == TB_PLAY ? 1 : 0;
+ int y = SCREEN_H - 10 - 16 * ntext - 3 * (big ? 0 : 0);
+ for (int i = 0; i < ntext; i++) {
+ const char *t;
+ char buf[48] = "- ";
+ switch (list[i]) {
+ case TB_CONTINUE: t = L_continue; break;
+ case TB_PLAY: t = L_click_here_to_play; break;
+ case TB_PLAYED_BEFORE: t = L_played_before; break;
+ default: t = L_new_city; break;
+ }
+ str_cat(str_cat(buf, sizeof buf, t), sizeof buf, " -");
+ uint8_t font = list[i] == TB_PLAY ? FONT_18 : FONT_16;
+ float a = i == title_focus ? 1.0f : 0.7f;
+ if (list[i] == TB_PLAY && i != title_focus) a = 0.7f + 0.3f * sinf(title_time * 0.08f);
+ uint16_t col = list[i] == TB_PLAYED_BEFORE ? rgb565(0xA0A0B0) : C_WHITE;
+ int w = ui_text_w(font, buf);
+ ui_text_n(font, SCREEN_W / 2 - w / 2, y, buf, -1, col, (uint8_t)(255 * a), false);
+ y += font == FONT_18 ? 19 : 16;
+ }
+ /* the credits button at the bottom left (spr_credits) */
+ bool f = list[title_focus] == TB_CREDITS;
+ ui_spr_ex(SPR_CREDITS, 0, 0, 14, 14, 10, SCREEN_H - 24, 0, f ? 255 : 178, GFX_NO_TINT);
+ if (f) {
+ Tip tip = {0};
+ tip.text = L_credits;
+ ui_tooltip(&tip, 10, SCREEN_H - 24, false);
+ }
+}
diff --git a/games/finalearth2/src/ui_pick.c b/games/finalearth2/src/ui_pick.c
new file mode 100644
index 00000000..1f43d4d6
--- /dev/null
+++ b/games/finalearth2/src/ui_pick.c
@@ -0,0 +1,341 @@
+/* The Final Earth 2: windows that pick a value with the keys: the colour
+ * picker (gui.ColorPickerWindow and gui.ColorPicker, at the mobile version's
+ * scale) and the texts the original asks for in a text box or with
+ * window.prompt (gui.ChangeCityNameWindow, the colour picker's colour code).
+ * A text is typed with the calculator's own letters (alpha, then a key; shift
+ * and alpha for capitals) or picked from letters on screen with the arrows. */
+#include <math.h>
+#include "uii.h"
+
+/* ---------------------------------------------------------------- typing (gui.TextInput) */
+enum { AL_OFF, AL_ONCE, AL_LOCK, AL_CAPS_ONCE, AL_CAPS_LOCK }; /* the alpha key's state */
+static uint8_t alpha_mode;
+static bool shift_armed; /* shift pressed: the next alpha gives capitals */
+static bool grid_caps; /* the on-screen letters are capitals */
+static char code_buf[12]; /* the colour code being typed */
+
+/* each typing key's character without alpha (0: none) and with it (NumWorks' alpha layout) */
+static const char plain_chars[TK_ANS + 1] = {
+ [22] = ',', [30] = '7', [31] = '8', [32] = '9', [33] = '(', [34] = ')', [36] = '4', [37] = '5', [38] = '6', [40] = '/',
+ [42] = '1', [43] = '2', [44] = '3', [45] = '+', [46] = '-', [48] = '0', [49] = '.'};
+static const char alpha_chars[TK_ANS + 1] = {
+ [18] = 'a', [19] = 'b', [20] = 'c', [21] = 'd', [22] = 'e', [23] = 'f', [24] = 'g', [25] = 'h', [26] = 'i', [27] = 'j',
+ [28] = 'k', [29] = 'l', [30] = 'm', [31] = 'n', [32] = 'o', [33] = 'p', [34] = 'q', [36] = 'r', [37] = 's', [38] = 't',
+ [39] = 'u', [40] = 'v', [42] = 'w', [43] = 'x', [44] = 'y', [45] = 'z', [46] = ' ', [48] = '?', [49] = '!'};
+
+static char *text_of(int which, int *size) {
+ if (which == TX_CITY_NAME) {
+ *size = (int)sizeof city.cityName;
+ return city.cityName;
+ }
+ *size = (int)sizeof code_buf;
+ return code_buf;
+}
+
+static void text_add(int which, char c) {
+ int size;
+ char *t = text_of(which, &size);
+ int n = (int)strlen(t);
+ if (n < size - 1) t[n] = c, t[n + 1] = 0;
+ /* the on-screen letters: capitals to start a word */
+ grid_caps = c == ' ';
+}
+
+static void text_delete(int which) {
+ int size;
+ char *t = text_of(which, &size);
+ int n = (int)strlen(t);
+ if (n) t[n - 1] = 0;
+ grid_caps = n <= 1 || t[n - 2] == ' ';
+}
+
+void text_window_open(int which) {
+ alpha_mode = AL_OFF;
+ shift_armed = false;
+ if (which == TX_COLOR_CODE) code_buf[0] = 0;
+ int size;
+ char *t = text_of(which, &size);
+ int n = (int)strlen(t);
+ grid_caps = !n || t[n - 1] == ' ';
+ win_open(WK_CITY_NAME, (uint16_t)which, 0);
+}
+
+/* the calculator's keys while typing: alpha (and shift) choose letters, the keys type, backspace deletes */
+static void text_keys(Win *wn) {
+ if (key_pressed(K_SHIFT)) shift_armed = !shift_armed;
+ if (key_pressed(K_ALPHA)) {
+ if (shift_armed || key_held(K_SHIFT)) alpha_mode = alpha_mode == AL_CAPS_ONCE ? AL_CAPS_LOCK : AL_CAPS_ONCE;
+ else alpha_mode = alpha_mode == AL_ONCE ? AL_LOCK : alpha_mode == AL_OFF ? AL_ONCE : AL_OFF;
+ shift_armed = false;
+ }
+ if (key_repeat(K_BACKSPACE)) text_delete(wn->arg);
+ int k = input.text_key;
+ if (k < 0 || k > TK_ANS) return;
+ char c = alpha_mode != AL_OFF || !plain_chars[k] ? alpha_chars[k] : plain_chars[k];
+ if (!c) return;
+ if ((alpha_mode == AL_CAPS_ONCE || alpha_mode == AL_CAPS_LOCK) && c >= 'a' && c <= 'z') c = (char)(c - 32);
+ if (alpha_mode == AL_ONCE || alpha_mode == AL_CAPS_ONCE) alpha_mode = AL_OFF;
+ text_add(wn->arg, c);
+}
+
+/* the on-screen letters: three rows of 13, then capitals, space and delete */
+static const char grid_rows[3][14] = {"ABCDEFGHIJKLM", "NOPQRSTUVWXYZ", "0123456789-'."};
+enum { TA_CAPS = 1, TA_SPACE, TA_DELETE, TA_CONFIRM, TA_CHAR = 100 };
+#define CELL_W 19
+#define CELL_H 15
+
+static void grid_key(WinOut *w, int x, int wd, const char *label, int action) {
+ bool f = win_small_button(w, x, wd, CELL_H, action);
+ int bx, by;
+ if (win_area(w, 0, 0, &bx, &by)) {
+ bool on = action == TA_CAPS && grid_caps;
+ ui_box(bx + x, by, wd, CELL_H, on || (f && key_held(K_OK)) ? BX_BUTTON_DOWN : f ? BX_BUTTON_HOVER : BX_BUTTON);
+ ui_text(FONT_STANDARD, bx + x + (wd - ui_text_w(FONT_STANDARD, label)) / 2, by + 1, label, C_BLACK);
+ }
+}
+
+void city_name_content(WinOut *w) {
+ int which = w->win->arg, size;
+ char *t = text_of(which, &size);
+ if (which == TX_CITY_NAME) {
+ win_title(w, L_change_city_name);
+ win_para(w, FONT_STANDARD, L_give_city_name, 250, C_BLACK);
+ } else {
+ win_para(w, FONT_STANDARD, L_color_code_enter, 250, C_BLACK);
+ }
+ win_space(w, 4);
+ /* the text box (TextInput: 250 x 20), its caret, and alpha's state at its right ("a", "A"; underlined: locked) */
+ int x, y;
+ if (win_area(w, 250, 20, &x, &y)) {
+ ui_box(x, y, 250, 20, BX_BUTTON);
+ int tw = 0;
+ if (*t) tw = ui_text(FONT_STANDARD, x + 3, y + 4, t, C_BLACK);
+ else if (which == TX_CITY_NAME) ui_text(FONT_STANDARD, x + 3, y + 4, L_city_name, 0x8410);
+ if ((int)cu.gui_timer % 40 < 24) ui_rect(x + 3 + tw + 1, y + 4, 1, 12, C_BLACK, 255);
+ if (alpha_mode != AL_OFF) {
+ const char *a = alpha_mode >= AL_CAPS_ONCE ? "A" : "a";
+ int aw = ui_text_w(FONT_STANDARD, a);
+ ui_text(FONT_STANDARD, x + 250 - 4 - aw, y + 4, a, C_BLUE);
+ if (alpha_mode == AL_LOCK || alpha_mode == AL_CAPS_LOCK) ui_rect(x + 250 - 4 - aw, y + 16, aw, 1, C_BLUE, 255);
+ }
+ }
+ win_space(w, 3);
+ win_para(w, FONT_10, L_keypad_typing_hint, 250, C_BLACK);
+ win_space(w, 2);
+ /* the letters (capitals or not), the digits and signs, then capitals, space and delete */
+ for (int r = 0; r < 3; r++) {
+ /* (a row is one primitive: each key is still a button of its own for the arrows) */
+ char row[13];
+ int focused = 255;
+ for (int i = 0; i < 13; i++) {
+ char c = grid_rows[r][i];
+ if (!grid_caps && c >= 'A' && c <= 'Z') c = (char)(c + 32);
+ row[i] = c;
+ if (win_small_button(w, i * CELL_W, CELL_W, CELL_H, TA_CHAR + (uint8_t)c)) focused = i;
+ }
+ if (win_area(w, 13 * CELL_W, 0, &x, &y)) ui_keys(x, y, CELL_W, CELL_H, row, 13, focused, key_held(K_OK));
+ w->y += CELL_H;
+ }
+ grid_key(w, 0, 3 * CELL_W, L_keypad_caps, TA_CAPS);
+ grid_key(w, 3 * CELL_W, 7 * CELL_W, L_keypad_space, TA_SPACE);
+ grid_key(w, 10 * CELL_W, 3 * CELL_W, L_keypad_delete, TA_DELETE);
+ w->y += CELL_H;
+ if (w->maxw < 250) w->maxw = 250;
+ win_space(w, 4);
+ if (which == TX_COLOR_CODE) {
+ const char *label = L_confirm;
+ int a = TA_CONFIRM;
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+ } else {
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+ }
+}
+
+static bool parse_color(const char *s, int32_t *rgb);
+static void color_confirm(Win *picker, int32_t col);
+
+void city_name_action(Win *wn, int a) {
+ int which = wn->arg;
+ if (a >= TA_CHAR) text_add(which, (char)(a - TA_CHAR));
+ else if (a == TA_SPACE) text_add(which, ' ');
+ else if (a == TA_DELETE) text_delete(which);
+ else if (a == TA_CAPS) grid_caps = !grid_caps;
+ else if (a == TA_CONFIRM) {
+ /* the colour code: the picker's colour if it reads as one, else the original's alert */
+ int32_t col;
+ bool ok = parse_color(code_buf, &col);
+ win_close();
+ Win *picker = win_top();
+ if (!ok) win_open_text(NULL, L_color_not_parsed);
+ else if (picker && picker->kind == WK_COLOR) color_confirm(picker, col);
+ }
+}
+
+/* ColorParser.parseHex: "RRGGBB" (or "AARRGGBB"), or after "#" or "0x": RGB, RGBA (doubled), RRGGBB, AARRGGBB */
+static bool parse_color(const char *s, int32_t *rgb) {
+ char h[9];
+ int n = 0;
+ bool prefixed = s[0] == '#' || (s[0] == '0' && (s[1] == 'x' || s[1] == 'X'));
+ const char *d = s[0] == '#' ? s + 1 : prefixed ? s + 2 : s;
+ int len = (int)strlen(d);
+ if (len > 8) return false;
+ for (int i = 0; i < len; i++) {
+ char c = d[i];
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) return false;
+ }
+ if (!prefixed && len != 6 && len != 8) return false;
+ if (s[0] == '#' && (len == 3 || len == 4)) {
+ for (int i = 0; i < len; i++) h[n++] = d[i], h[n++] = d[i];
+ } else {
+ for (int i = 0; i < len; i++) h[n++] = d[i];
+ }
+ if (n != 6 && n != 8) return false;
+ h[n] = 0;
+ uint32_t v = 0;
+ for (int i = n == 8 ? 2 : 0; i < n; i++) {
+ char c = h[i];
+ v = v << 4 | (uint32_t)(c <= '9' ? c - '0' : (c | 32) - 'a' + 10);
+ }
+ *rgb = (int32_t)(v & 0xFFFFFF);
+ return true;
+}
+
+/* ---------------------------------------------------------------- the colour picker */
+int32_t color_picked = 0xFFFFFF; /* gui.ColorPicker.colorPicked */
+int32_t color_picked_on_menu_open = -1; /* gui.ColorPicker.colorPickedOnLastMultiMenuOpen */
+static float pick_h, pick_s, pick_v; /* its hue (degrees), saturation and value */
+#define CIRCLE_W 120 /* spr_colorcircle at 0.6: 120 x 133.8 */
+#define CIRCLE_H 134
+
+/* thx.color: Rgbx.toHsv (grey has hue -1) and Hsv.toRgbx, then Rgbx.toRgb */
+static void rgb_to_hsv(int32_t rgb, float *h, float *s, float *v) {
+ float r = (rgb >> 16 & 255) / 255.0f, g = (rgb >> 8 & 255) / 255.0f, b = (rgb & 255) / 255.0f;
+ float mn = fminf(fminf(r, g), b), mx = fmaxf(fmaxf(r, g), b), delta = mx - mn;
+ *v = mx;
+ if (delta == 0) {
+ *s = 0, *h = -1;
+ return;
+ }
+ *s = delta / mx;
+ float hh = r == mx ? (g - b) / delta : g == mx ? 2 + (b - r) / delta : 4 + (r - g) / delta;
+ hh *= 60;
+ *h = hh < 0 ? hh + 360 : hh;
+}
+static int32_t hsv_rgb(float h, float s, float v) {
+ float r, g, b;
+ if (s == 0) {
+ r = g = b = v;
+ } else {
+ float hh = h / 60, f;
+ int i = (int)floorf(hh);
+ f = hh - i;
+ float p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s);
+ switch (i) {
+ case 0: r = v, g = t, b = p; break;
+ case 1: r = q, g = v, b = p; break;
+ case 2: r = p, g = v, b = t; break;
+ case 3: r = p, g = q, b = v; break;
+ case 4: r = t, g = p, b = v; break;
+ default: r = v, g = p, b = q;
+ }
+ }
+ return (int32_t)(((int)roundf(r * 255) & 255) << 16 | ((int)roundf(g * 255) & 255) << 8 | ((int)roundf(b * 255) & 255));
+}
+
+/* ColorPickerWindow.createWindow: for a decoration's colour (arg: the permanent) or the build menu's any-colour
+ * look (arg: the class) */
+void color_picker_open(int target, uint16_t arg) {
+ if (target == COLOR_FOR_BUILDING) {
+ int32_t c = bld_decoration_color(P(arg));
+ if (c >= 0) color_picked = c;
+ win_open(WK_COLOR, (uint16_t)target, arg);
+ } else {
+ win_open_only(WK_COLOR, (uint16_t)target, arg);
+ }
+ rgb_to_hsv(color_picked, &pick_h, &pick_s, &pick_v);
+}
+
+static void update_color(void) { color_picked = hsv_rgb(pick_h, pick_s, pick_v); }
+
+/* onConfirm, then goPreviousWindow */
+static void color_confirm(Win *picker, int32_t col) {
+ int target = picker->arg;
+ uint16_t arg = picker->arg2;
+ if (target == COLOR_FOR_BUILDING) {
+ Perm *p = P(arg);
+ if (p && (p->flags & PF_USED)) bld_customize_color(p, col);
+ win_close();
+ } else {
+ /* the builder for the class's last look in that colour */
+ const ClsText *ct = &cls_text[arg];
+ int looks = (spr_w(pcls[arg].sprite) + 2) / 22;
+ win_close();
+ builder_start_ex(BK_BUILDING, arg, looks - 1, (ct->flags & CT_MIRRORABLE) && cu.mirrored, col);
+ color_picked = col;
+ }
+}
+
+enum { CP_CIRCLE = 1, CP_VALUE, CP_CONFIRM, CP_CODE };
+
+void color_content(WinOut *w) {
+ win_title_tint(w, L_choose_color, SPR_COLORPICKER_COLORPICKED, rgb565_near((uint32_t)color_picked));
+ /* the circle (hue and saturation) with its bar (value) under it, the handles, and the colour (15 high) */
+ int y0 = w->y, x, y;
+ /* (the part the arrows change is framed as any focused button) */
+ win_small_button(w, 5, CIRCLE_W, CIRCLE_W, CP_CIRCLE);
+ w->y = y0 + CIRCLE_W;
+ win_small_button(w, 5, CIRCLE_W, CIRCLE_H - CIRCLE_W + 12, CP_VALUE);
+ w->y = y0;
+ if (win_area(w, CIRCLE_W + 10, CIRCLE_H + 10 + 25, &x, &y)) {
+ ui_spr_small(SPR_COLORCIRCLE, x + 5, y);
+ float a = (pick_h < 0 ? 0 : pick_h) / 360 * 2 * (float)M_PI, r = pick_s * CIRCLE_W / 2;
+ int cx = x + 5 + CIRCLE_W / 2 + (int)lroundf(r * cosf(a)), cy = y + CIRCLE_W / 2 + (int)lroundf(r * sinf(a));
+ ui_spr(SPR_COLORPICKER_CIRCLE, cx - 6, cy - 6);
+ ui_spr(SPR_COLORPICKER_TRIANGLE, x + 5 + (int)lroundf(pick_v * CIRCLE_W) - 6, y + CIRCLE_H - 1);
+ ui_rect(x, y + CIRCLE_H + 20, CIRCLE_W + 10, 15, rgb565_near((uint32_t)color_picked), 255);
+ }
+ win_space(w, 4);
+ const char *labels[2] = {L_confirm, L_color_code};
+ int acts[2] = {CP_CONFIRM, CP_CODE};
+ win_bottom(w, labels, acts, 2, L_close, ACT_CLOSE);
+}
+
+void color_action(Win *wn, int a) {
+ if (a == CP_CONFIRM || a == CP_CIRCLE || a == CP_VALUE) color_confirm(wn, color_picked);
+ else if (a == CP_CODE) text_window_open(TX_COLOR_CODE);
+}
+
+/* the arrows over the circle move its handle (a pixel a press, two a tick when held); down from its lowest point
+ * goes to the bar, whose left and right change the value. False: the window's usual keys */
+static int step_of(int bit) { return input.held_ticks[bit] > 8 ? 2 : (input.pressed >> bit & 1) ? 1 : 0; }
+static bool color_keys(Win *wn) {
+ if (key_held(K_SHIFT)) return false;
+ int dx = step_of(1) - step_of(0), dy = step_of(3) - step_of(2);
+ if (wn->focus == 0) {
+ if (!dx && !dy) return false;
+ float a = (pick_h < 0 ? 0 : pick_h) / 360 * 2 * (float)M_PI, r = pick_s * CIRCLE_W / 2;
+ float px = r * cosf(a), py = r * sinf(a), nx = px + dx, ny = py + dy, len = sqrtf(nx * nx + ny * ny);
+ if (len > CIRCLE_W / 2) nx *= CIRCLE_W / 2 / len, ny *= CIRCLE_W / 2 / len, len = CIRCLE_W / 2;
+ if (dy > 0 && !dx && ny <= py + 0.01f) return false; /* the lowest point: on to the bar */
+ pick_s = fminf(len / (CIRCLE_W / 2), 1);
+ pick_h = fmodf(atan2f(ny, nx) / (2 * (float)M_PI) * 360 + 360, 360);
+ update_color();
+ return true;
+ }
+ if (wn->focus == 1 && dx) {
+ pick_v = fminf(1, fmaxf(0, pick_v + dx / (float)CIRCLE_W));
+ update_color();
+ return true;
+ }
+ return false;
+}
+
+/* the keys of these windows before the usual ones (win_input) */
+bool pick_keys(Win *wn) {
+ if (wn->kind == WK_CITY_NAME) {
+ text_keys(wn);
+ return false;
+ }
+ if (wn->kind == WK_COLOR) return color_keys(wn);
+ return false;
+}
diff --git a/games/finalearth2/src/ui_story.c b/games/finalearth2/src/ui_story.c
new file mode 100644
index 00000000..7e807f77
--- /dev/null
+++ b/games/finalearth2/src/ui_story.c
@@ -0,0 +1,437 @@
+/* The Final Earth 2: the story's windows and overlays (progress.Story's
+ * showGoalText, gui.CurrentMissionsWindow with progress.GoalHelp,
+ * gui.HelpArrow and CityGUI's tutorial arrows, gui.TopScreenNotification,
+ * the end of a scenario) and the story's hooks into the interface. */
+#include <math.h>
+#include "game.h"
+#include "uii.h"
+
+uint8_t tut_flags;
+int16_t tut_close_warning;
+bool tut_fix_builder; /* City.postCreateBuilder: the first builder is fixed in place */
+static uint16_t tutorial; /* the goal's showTutorial */
+static float arrow_time; /* HelpArrow.arrowTime */
+/* useBigMovement: the first build arrow and the workers' arrow come in on a quarter circle round the screen's
+ * centre, fading in (their angle, pi/2 to 0; they turn as well in the original) */
+static float circle1, circle2;
+static const char *pending_message; /* a story message waiting for no window to be open */
+/* the top-screen notification */
+static const char *note_text, *note_title;
+static int16_t note_time;
+static float note_fade;
+static char note_buf[160];
+
+void story_ui_reset(void) {
+ tut_flags = 0;
+ tut_close_warning = 0;
+ tut_fix_builder = false;
+ tutorial = 0;
+ arrow_time = 0;
+ pending_message = NULL;
+ note_text = note_title = NULL;
+ note_time = 0;
+}
+
+/* ---------------------------------------------------------------- goal texts */
+/* Story.showGoalText: the inline commands ([n] not done, [c] done, [nonmobi] the computer version's words, [mobi]
+ * the mobile version's, [/] all again, [d] the time taken); others are dropped, as the original does. The
+ * computer version's words are kept (its notes read well on a keypad), then "click on" and "tap on" become the
+ * keypad's "press OK on" */
+const char *goal_text(int gi, char *buf, int size) {
+ const StoryGoal *g = &stories[story.index].goals[gi];
+ bool complete = true;
+ if (gi == story.goal)
+ for (int i = 0; i < g->nsub; i++) complete &= story_subgoal_complete(i);
+ const char *s = g->text ? g->text : "";
+ char raw[1100];
+ int o = 0, rsize = (int)sizeof raw < size ? (int)sizeof raw : size;
+ bool adding = true;
+ while (*s && o < rsize - 1) {
+ const char *e = *s == '[' ? strchr(s, ']') : NULL;
+ if (!e) {
+ if (adding) raw[o++] = *s;
+ s++;
+ continue;
+ }
+ int n = (int)(e - s - 1);
+ const char *c = s + 1;
+#define IS(x) (n == (int)strlen(x) && !strncmp(c, x, (size_t)n))
+ if (IS("n")) adding = !complete;
+ else if (IS("c")) adding = complete;
+ else if (IS("mobi")) adding = false;
+ else if (IS("nonmobi")) adding = true;
+ else if (IS("nmobi")) adding = false;
+ else if (IS("nnonmobi")) adding = !complete;
+ else if (IS("/")) adding = true;
+ else if (IS("d")) {
+ /* the time taken: days, hours and minutes */
+ char t[48];
+ int ts = (int)city.timeSinceStart, d = 1 + ts / 1440, h = ts / 60 % 24, m = ts % 60;
+ raw[o] = 0;
+ str_cat(raw, rsize, d == 1 ? L_one_day : lo_1(t, sizeof t, L_n_days, LN(d)));
+ str_cat(raw, rsize, ", ");
+ str_cat(raw, rsize, h == 1 ? L_one_hour : lo_1(t, sizeof t, L_n_hours, LN(h)));
+ str_cat(raw, rsize, ", ");
+ str_cat(raw, rsize, L_and);
+ str_cat(raw, rsize, " ");
+ str_cat(raw, rsize, m == 1 ? L_one_minute : lo_1(t, sizeof t, L_n_minutes, LN(m)));
+ o = (int)strlen(raw);
+ }
+#undef IS
+ s = e + 1;
+ }
+ raw[o] = 0;
+ /* the mouse's and the touch screen's words: the keypad's */
+ static const char *const from[] = {"click on", "Click on", "tap on", "Tap on"};
+ static const char *const to[] = {"press OK on", "Press OK on", "press OK on", "Press OK on"};
+ o = 0;
+ for (const char *r = raw; *r && o < size - 1;) {
+ int k = 0;
+ while (k < 4 && strncmp(r, from[k], strlen(from[k]))) k++;
+ if (k < 4) {
+ buf[o] = 0;
+ str_cat(buf, size, to[k]);
+ o = (int)strlen(buf);
+ r += strlen(from[k]);
+ } else {
+ buf[o++] = *r++;
+ }
+ }
+ buf[o] = 0;
+ return buf;
+}
+
+enum { GW_NEXT = 1, GW_NEW_CITY };
+
+void story_goal_content(WinOut *w) {
+ int gi = w->win->arg;
+ const StoryGoal *g = &stories[story.index].goals[gi];
+ if (g->title && *g->title) win_title(w, g->title);
+ char buf[1100];
+ win_para(w, FONT_STANDARD, goal_text(gi, buf, sizeof buf), 250, C_BLACK);
+ if (!strcmp(g->name, "Win")) {
+ const char *label;
+ int a;
+ if (g->nextStory >= 0 && story_requirements(g->nextStory)) label = L_next_scenario, a = GW_NEXT;
+ else label = L_new_city, a = GW_NEW_CITY;
+ win_bottom(w, &label, &a, 1, L_close, ACT_CLOSE);
+ } else {
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+ }
+}
+
+void story_goal_action(Win *wn, int a) {
+ const StoryGoal *g = &stories[story.index].goals[wn->arg];
+ if (a == GW_NEXT) {
+ win_close_all();
+ menu_new_city(g->nextStory);
+ } else if (a == GW_NEW_CITY) {
+ win_close_all();
+ win_open(WK_SCENARIOS, 0, 0);
+ }
+}
+
+/* ---------------------------------------------------------------- the quick mission (progress.GoalHelp) */
+/* the current tasks: the goal's quick text, then the buildings' missions */
+int goal_help(char *buf, int size, const char **header) {
+ int n = 0;
+ buf[0] = 0;
+ const StoryGoal *g = story_goal();
+ const char *one_cat = NULL, *one_text = NULL;
+ if (g && g->quickText && *g->quickText) {
+ str_cat(buf, size, "- ");
+ str_cat(buf, size, L_main_goal);
+ str_cat(buf, size, "\n");
+ str_cat(buf, size, g->quickText);
+ one_cat = L_main_goal, one_text = g->quickText;
+ n++;
+ }
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || !is_building(p)) continue;
+ const char *cat, *text;
+ if (!bld_global_goal(p, &cat, &text)) continue;
+ if (n) str_cat(buf, size, "\n\n");
+ str_cat(buf, size, "- ");
+ str_cat(buf, size, cat);
+ str_cat(buf, size, "\n");
+ str_cat(buf, size, text);
+ one_cat = cat, one_text = text;
+ n++;
+ }
+ if (n == 1) {
+ /* one task: its text, with "Current Task" (or its category) as the header */
+ buf[0] = 0;
+ str_cat(buf, size, one_text);
+ if (header) *header = one_cat == L_main_goal ? L_current_task : one_cat;
+ } else if (header) {
+ *header = L_current_tasks;
+ }
+ return n;
+}
+
+bool story_has_quick_text(void) {
+ char buf[8];
+ (void)buf;
+ const StoryGoal *g = story_goal();
+ if (g && g->quickText && *g->quickText) return true;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const char *cat, *text;
+ if ((perms[i].flags & PF_USED) && is_building(&perms[i]) && bld_global_goal(&perms[i], &cat, &text)) return true;
+ }
+ return false;
+}
+
+void story_missions_content(WinOut *w) {
+ char buf[800];
+ const char *header = NULL;
+ int n = goal_help(buf, sizeof buf, &header);
+ win_title(w, n == 1 ? L_current_task : L_current_tasks);
+ if (n == 1) {
+ /* CurrentMissionsWindow always lists them as "- category\ntext" */
+ const StoryGoal *g = story_goal();
+ char b2[800] = "- ";
+ str_cat(b2, sizeof b2, header == L_current_task ? L_main_goal : header);
+ str_cat(b2, sizeof b2, "\n");
+ str_cat(b2, sizeof b2, buf);
+ (void)g;
+ win_para(w, FONT_STANDARD, b2, 250, C_BLACK);
+ } else {
+ win_para(w, FONT_STANDARD, n ? buf : "---", 250, C_BLACK);
+ }
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+/* ---------------------------------------------------------------- the story's hooks */
+void ui_show_goal_text(int goal) {
+ if (ui.title && !ui.setup) return; /* a free play's welcome waits under its options window */
+ win_close_all();
+ win_open(WK_GOAL, (uint16_t)goal, 0);
+ win_pause();
+}
+
+void ui_show_tutorial(int t) {
+ if (ui.title) return;
+ tutorial = (uint16_t)t;
+ arrow_time = 0;
+ circle1 = circle2 = (float)M_PI / 2;
+ tut_flags = 0;
+ tut_fix_builder = t == 1;
+ if (t == 2 || t == 101) tut_close_warning = 120;
+}
+
+void ui_show_simple(const char *text) {
+ win_close_all();
+ win_open_text(NULL, text);
+}
+
+void ui_show_message(const char *text) {
+ if (ui.title) return;
+ pending_message = text;
+}
+
+bool ui_story_window_open(void) {
+ for (int i = 0; i < nwins; i++)
+ if (wins[i].kind == WK_GOAL) return true;
+ return false;
+}
+
+/* GUI.notify: a TopScreenNotification (time in the original's frames) */
+void notify_top(const char *text, const char *title, int time) {
+ note_text = text;
+ note_title = title;
+ note_time = (int16_t)time;
+ note_fade = 1;
+}
+
+/* Happiness: the very unhappy citizens' warning (showSimpleWindow + pauseForWindow) */
+void ui_pause_for_window(void) {
+ if (ui.title) return;
+ const char *a = story_is("cityofthekey") ? L_citizens_unhappy_key : city.materials.m[M_FOOD] == 0 ? L_citizens_unhappy_food
+ : L_citizens_unhappy;
+ ui_text_buf[0] = 0;
+ str_cat(str_cat(str_cat(ui_text_buf, sizeof ui_text_buf, a), sizeof ui_text_buf, " "), sizeof ui_text_buf, L_more_happiness_info);
+ win_close_all();
+ win_open_text(L_citizens_unhappy_title, ui_text_buf);
+ win_pause();
+}
+
+void story_ui_tick(void) {
+ arrow_time += TIMEMOD;
+ if (pending_message && !nwins) {
+ win_open_text(NULL, pending_message);
+ pending_message = NULL;
+ }
+ if (note_text || note_title) {
+ if (note_time > 0) note_time = (int16_t)(note_time - (int)TIMEMOD);
+ else if ((note_fade -= 0.05f * TIMEMOD) < 0) note_text = note_title = NULL;
+ }
+ if (tut_close_warning > 0) tut_close_warning = (int16_t)(tut_close_warning - (int)TIMEMOD);
+ if (!nwins) tut_flags |= TF_WINDOW_CLOSED;
+}
+
+/* ---------------------------------------------------------------- HelpArrow */
+enum { HA_DOWN, HA_LEFT, HA_DOWN_HINT };
+/* an arrow at r (x, y, w, h), and maybe a text in a green box */
+static void help_arrow_ex(const int16_t r[4], int dir, const char *text, float *circle) {
+ float wob = sinf(arrow_time / 10) * 2;
+ int cx = r[0] + r[2] / 2, cy = r[1] + r[3] / 2;
+ int ax = 0, ay = 0, aw = 0, ah = 0;
+ if (dir == HA_DOWN) {
+ ax = cx - 10, ay = r[1] - 2 - (int)wob - 30, aw = 20, ah = 30;
+ uint8_t alpha = 255;
+ if (circle && *circle > 0) {
+ float c = *circle, px = (float)cx, py = (float)(ay + 30);
+ *circle -= (0.015f + 0.04f * (c / ((float)M_PI / 2))) * TIMEMOD;
+ px = cosf(c) * (px - SCREEN_W / 2) + SCREEN_W / 2;
+ py = sinf(c) * (SCREEN_H / 2 - py) + py;
+ ax = (int)px - 10, ay = (int)py - 30;
+ alpha = (uint8_t)(255 * fmaxf(0, cosf(c)));
+ }
+ ui_spr_ex(SPR_TUTORIALARROWDOWN, 0, 0, spr_w(SPR_TUTORIALARROWDOWN), spr_h(SPR_TUTORIALARROWDOWN), ax, ay, 0, alpha,
+ GFX_NO_TINT);
+ } else if (dir == HA_LEFT) {
+ ax = r[0] + r[2] + 2 + (int)wob, ay = cy - 10, aw = 30, ah = 20;
+ ui_spr(SPR_TUTORIALARROWLEFT, ax, ay);
+ } else {
+ ax = cx - 5, ay = r[1] - 2 - 6, aw = 10, ah = 6;
+ ui_spr(SPR_HINTINFO_ARROW, ax, ay);
+ }
+ if (!text) return;
+ /* HelpArrow.addText: Arial, 133 wide (200 for long ones), in spr_9p_hintinfo */
+ int tw, maxw = strlen(text) < 45 ? 133 : 200;
+ int th = ui_para(FONT_STANDARD, 0, INT16_MIN, maxw, text, C_BLACK, true, &tw);
+ int bw = tw + 6, bh = th + 6, bx, by;
+ if (dir == HA_DOWN) {
+ bx = cx > bw + 5 + 10 ? cx - 10 - 2 - bw : cx + 10 + 2;
+ by = r[1] - 2 - bh;
+ } else if (dir == HA_LEFT) {
+ bx = r[0] + r[2] + bw > SCREEN_W ? SCREEN_W - bw - 5 : r[0] + r[2];
+ by = cy - 2 - 10 - bh;
+ } else {
+ if (cx > bw + 5 + 5) bx = cx - bw + 5;
+ else if (cx - 10 + bw < SCREEN_W) bx = cx - 5;
+ else bx = 5;
+ by = r[1] - 2 - 6 - bh;
+ }
+ if (bx + bw > SCREEN_W) bx = SCREEN_W - bw;
+ if (bx < 0) bx = 0;
+ if (by < 0) by = 0;
+ /* the small screen: a hint for something beside an open window goes beside it, narrower, not over it */
+ int16_t wr[4];
+ if (dir == HA_DOWN_HINT && win_screen_rect(wr) && bx < wr[0] + wr[2] && bx + bw > wr[0] && by < wr[1] + wr[3] &&
+ by + bh > wr[1] && SCREEN_W - (wr[0] + wr[2]) - 2 >= 50) {
+ maxw = SCREEN_W - (wr[0] + wr[2]) - 2 - 6;
+ th = ui_para(FONT_STANDARD, 0, INT16_MIN, maxw, text, C_BLACK, true, &tw);
+ bw = tw + 6, bh = th + 6;
+ bx = SCREEN_W - bw, by = r[1] - 2 - 6 - bh;
+ if (by < 0) by = 0;
+ }
+ ui_box(bx, by, bw, bh, BX_HINTINFO);
+ ui_para(FONT_STANDARD, bx + 3, by + 2, maxw, text, C_BLACK, true, NULL);
+ (void)ax, (void)ay, (void)aw, (void)ah;
+}
+static void help_arrow(const int16_t r[4], int dir, const char *text) { help_arrow_ex(r, dir, text, NULL); }
+
+static bool window_closed(void) { return (tut_flags & TF_WINDOW_CLOSED) && !nwins; }
+
+/* the button a window shows for an action, on screen */
+
+static void tutorial_draw(void) {
+ int16_t r[4];
+ bool none_shown = cu.category < 0;
+ bool builder = cu.build_kind != BK_NONE;
+ /* showWindowCloseWarning: an arrow at the goal window's Close button */
+ if ((tutorial == 1 && arrow_time >= 180) || (tutorial == 2 || tutorial == 101)) {
+ if (win_is_open(WK_GOAL) && (tutorial == 1 || tut_close_warning <= 0) && win_action_rect(ACT_CLOSE, r)) help_arrow(r, HA_LEFT, NULL);
+ }
+ if (nwins && !win_is_open(WK_WORKERS)) return;
+ switch (tutorial) {
+ case 1:
+ if (window_closed() && !builder) {
+ /* the keypad's own hint: which key leads to the build menu */
+ if (none_shown && city_build_rect(BR_FIRST_CATEGORY, r))
+ help_arrow_ex(r, HA_DOWN, cu.zone == Z_BUILD ? NULL : L_keypad_toolbox_hint, &circle1);
+ else if (!none_shown && city_build_rect(BR_LAST_BUILDING, r)) help_arrow(r, HA_LEFT, NULL);
+ }
+ break;
+ case 101:
+ if (window_closed() && city.materials.m[M_WOOD] < 4 && city_panel_rect(PR_MAT0 + M_WOOD, r)) help_arrow(r, HA_DOWN_HINT, L_see_wood_here);
+ if (city.materials.m[M_WOOD] >= 4 && !builder) {
+ if (none_shown && city_build_rect(BR_FIRST_CATEGORY, r)) help_arrow(r, HA_DOWN, L_you_have_enough_wood);
+ else if (!none_shown && city_build_rect(BR_SECOND_LAST_BUILDING, r)) help_arrow(r, HA_LEFT, L_you_have_enough_wood);
+ }
+ break;
+ case 2: {
+ bool prio = tut_flags & TF_PRIO;
+ bool workers_open = win_is_open(WK_WORKERS);
+ /* the second help: enough stone, no woodcutters */
+ bool woodcutters = false;
+ for (int i = 1; i < MAX_PERMS && !woodcutters; i++)
+ woodcutters = (perms[i].flags & PF_USED) && perms[i].cls == CLS_WoodcuttingCentre && perms[i].nworkers > 0;
+ bool second = city.materials.m[M_STONE] > 6 && city.materials.m[M_WOOD] < 6 && !woodcutters;
+ /* (the keypad's hint says which key reaches the panel, unless the second help's arrow is there too) */
+ if (window_closed() && !workers_open && !prio && !second && city_panel_rect(PR_WORK, r))
+ help_arrow_ex(r, HA_DOWN, cu.zone == Z_PANEL ? NULL : L_keypad_var_hint, &circle2);
+ if (workers_open && !prio && win_action_rect(200 + CLS_StoneMine, r)) help_arrow(r, HA_LEFT, NULL);
+ if (prio && (!nwins || workers_open) && city_panel_rect(PR_MAT0 + M_WOOD, r)) help_arrow(r, HA_DOWN_HINT, L_great_gather_stone);
+ if (second) {
+ extern int priority_jobs[64];
+ bool on_stone = priority_jobs[CLS_StoneMine] >= 3;
+ if (!workers_open && city_panel_rect(PR_WORK, r)) help_arrow(r, HA_DOWN, L_you_have_enough_stone);
+ if (workers_open && on_stone && win_action_rect(300 + CLS_StoneMine, r)) help_arrow(r, HA_LEFT, L_reduce_stone_mining_priority);
+ if (workers_open && !on_stone && win_action_rect(200 + CLS_WoodcuttingCentre, r)) help_arrow(r, HA_LEFT, L_increase_woodcutting_priority);
+ }
+ break;
+ }
+ case 3:
+ if (!(tut_flags & TF_HELP_USED) && !nwins && city_panel_rect(PR_HELP, r)) help_arrow(r, HA_DOWN_HINT, L_hint_hint);
+ break;
+ case 4:
+ if (!(tut_flags & TF_SPEED_USED) && !nwins && cu.speed == 0 && city_panel_rect(PR_SPEED, r)) help_arrow(r, HA_DOWN_HINT, L_speedup_hint);
+ break;
+ case 4001:
+ if (!win_is_open(WK_INVITE)) {
+ if (city_build_rect(BR_INVITE, r)) help_arrow(r, HA_LEFT, NULL);
+ else if (city_build_rect(BR_MANAGEMENT, r)) help_arrow(r, HA_DOWN, NULL);
+ }
+ break;
+ }
+}
+
+/* TopScreenNotification: header and text, the screen's width, at the top */
+static void notification_draw(void) {
+ if (!note_text && !note_title) return;
+ int y = 0, hh = 0, th = 0, w = SCREEN_W;
+ uint8_t a = (uint8_t)(255 * (note_fade < 0 ? 0 : note_fade > 1 ? 1 : note_fade));
+ if (note_title && *note_title) y--, hh = ui_para(FONT_16, 0, INT16_MIN, w - 10, note_title, C_BLACK, true, NULL), y += hh + 2;
+ int ty = y;
+ if (note_text && *note_text) y++, ty = y, th = ui_para(FONT_STANDARD, 0, INT16_MIN, w - 10, note_text, C_BLACK, true, NULL), y += th;
+ y += 2;
+ ui_noclip();
+ if (a < 255) {
+ ui_rect(0, 0, w, y, boxes[BX_TOOLTIP].fill, (uint8_t)(a * 230 / 255));
+ } else {
+ ui_box(0, 0, w, y, BX_TOOLTIP);
+ }
+ if (hh) ui_para(FONT_16, 2, -1, w - 10, note_title, C_BLACK, true, NULL);
+ if (th) ui_para(FONT_STANDARD, 3, ty, w - 10, note_text, C_BLACK, true, NULL);
+}
+
+void story_ui_draw_help(void) {
+ if (!ui.title) tutorial_draw();
+}
+void story_ui_draw_notes(void) { notification_draw(); }
+
+/* MetaGame.winScenario */
+void meta_win_scenario(int s, float time) {
+ if (s < 0 || s >= 4) return;
+ bool had = meta.won >> s & 1;
+ if (!had || (int32_t)time < meta.best[s]) meta.best[s] = (int32_t)time;
+ meta.won |= (uint8_t)(1 << s);
+ extern void meta_save(void);
+ meta_save();
+}
+
+/* tl;dr and other notes of the original that the calculator has no use for are left out */
+void story_notify(const char *text) { (void)text; (void)note_buf; }
diff --git a/games/finalearth2/src/ui_win.c b/games/finalearth2/src/ui_win.c
new file mode 100644
index 00000000..2f00a0c3
--- /dev/null
+++ b/games/finalearth2/src/ui_win.c
@@ -0,0 +1,972 @@
+/* The Final Earth 2: windows (the original's GUI.createWindow and its
+ * window parts: gui.TextElement, gui.TextButton, gui.ContainerButton,
+ * gui.ContainerWithScrollbar, gui.UpgradeWindowParts...).
+ *
+ * A window is kept as its kind and subject only. Each frame its contents
+ * function runs with a WinOut that lays the elements out from the top and
+ * draws those that show; the same function, run without drawing, finds the
+ * buttons for the arrows and OK. */
+#include "uii.h"
+
+Win wins[WIN_STACK];
+int nwins;
+char ui_text_buf[200];
+
+/* GUI.get_windowHeight: the screen less spaceAboveBelowWindow; at 320x240 the window may use nearly all of it, so
+ * that what fits the screen needs no scrolling (a taller one scrolls) */
+#define WIN_MAX_H (SCREEN_H - TITLE_H - 2 - 4)
+#define TITLE_H 17 /* the title row: spr_button_windowheader's height */
+#define CLOSE_W 23
+
+/* ---------------------------------------------------------------- the stack */
+static void win_init(Win *wn, int kind, uint16_t arg, uint16_t arg2) {
+ memset(wn, 0, sizeof *wn);
+ wn->kind = (uint8_t)kind;
+ wn->arg = arg;
+ wn->arg2 = arg2;
+ wn->focus = 0;
+ wn->flags = WF2_NEW;
+ /* backspace on a building: its window asks "Really Destroy?" at once */
+ if (kind == WK_BUILDING && (arg2 & WF2_CONFIRM)) wn->flags |= WF2_CONFIRM;
+ if (windefs[kind].flags & WD_PAUSE) win_pause();
+}
+
+/* GUI.createWindow + addWindowToStack */
+void win_open(int kind, uint16_t arg, uint16_t arg2) {
+ if (nwins == WIN_STACK) {
+ memmove(wins, wins + 1, sizeof(Win) * (WIN_STACK - 1));
+ nwins--;
+ }
+ win_init(&wins[nwins++], kind, arg, arg2);
+}
+
+void win_open_only(int kind, uint16_t arg, uint16_t arg2) {
+ win_close_all();
+ win_open(kind, arg, arg2);
+}
+
+void win_replace(int kind, uint16_t arg, uint16_t arg2) {
+ if (!nwins) {
+ win_open(kind, arg, arg2);
+ return;
+ }
+ win_init(&wins[nwins - 1], kind, arg, arg2);
+}
+
+/* CityGUI.closeWindow: the game goes on if it was paused for the window */
+static void unpause_for_window(void) {
+ if (city.paused && ui.paused_for_window) {
+ city.paused = false;
+ ui.paused_for_window = false;
+ }
+}
+
+void win_close(void) {
+ if (!nwins) return;
+ Win *wn = &wins[nwins - 1];
+ if (wn->kind == WK_BUILDING || wn->kind == WK_FOLLOW_LIST) cu.selected = 0;
+ if (nwins >= 2 && (wins[nwins - 2].kind == WK_BUILDING || wins[nwins - 2].kind == WK_FOLLOW_LIST)) cu.selected = wins[nwins - 2].arg;
+ if (wn->kind == WK_CITIZEN) cu.following = 0;
+ if (wn->kind == WK_FIND) cu.highlight_cls = 0;
+ if (wn->kind == WK_GOAL || wn->kind == WK_TEXT) tut_flags |= TF_WINDOW_CLOSED;
+ if (wn->kind == WK_TEXT) ui.home_unsaved = false;
+ nwins--;
+ if (!nwins) unpause_for_window();
+}
+
+void win_close_all(void) {
+ while (nwins) win_close();
+}
+
+void win_pause(void) {
+ bool was_paused = city.paused, was_for_window = ui.paused_for_window;
+ city.paused = true;
+ if (was_for_window || !was_paused) ui.paused_for_window = true;
+}
+
+bool win_is_open(int kind) { return nwins && wins[nwins - 1].kind == kind; }
+
+static const char *text_win_title, *text_win_text;
+void text_content(WinOut *w) {
+ if (text_win_title && *text_win_title) win_title(w, text_win_title);
+ win_para(w, FONT_STANDARD, text_win_text, 250, C_BLACK);
+ win_bottom(w, NULL, NULL, 0, L_close, ACT_CLOSE);
+}
+
+/* GUI.showSimpleWindow: a text (and a title) that last */
+void win_open_text(const char *title, const char *text) {
+ text_win_title = title;
+ text_win_text = text;
+ win_open(WK_TEXT, 0, 0);
+}
+
+/* ---------------------------------------------------------------- laying out */
+static int win_title_x, win_title_y, content_clip[4];
+static int vis(WinOut *w, int y, int h) { return y + h > w->vis0 && y < w->vis1; }
+
+/* the focused element, framed so that the keypad's focus can't be missed (the original only lightens a hovered
+ * button's border) */
+static void focus_ring(WinOut *w, int x, int y, int wd, int h) {
+ w->ring[0] = (int16_t)x, w->ring[1] = (int16_t)y, w->ring[2] = (int16_t)wd, w->ring[3] = (int16_t)h;
+ w->ring_on = true;
+}
+
+/* a focusable element at content (x, y), w x h: whether it is focused */
+static bool focusable(WinOut *w, int x, int y, int wd, int h, int action) {
+ int i = w->nfocus++;
+ if (w->mode == WO_NAV && w->nav && w->nnav < 48) {
+ NavRect *r = &w->nav[w->nnav++];
+ r->x = (int16_t)x, r->y = (int16_t)y, r->w = (int16_t)wd, r->h = (int16_t)h, r->action = (int16_t)action;
+ }
+ bool f = w->win && i == w->win->focus;
+ w->last_focus = f;
+ if (f) {
+ w->focus_y0 = y, w->focus_y1 = y + h;
+ w->tip_x = w->x0 + x + wd / 2, w->tip_y = w->y0 + y;
+ if (w->mode == WO_PRESS) w->pressed = action;
+ focus_ring(w, x, y, wd, h);
+ }
+ return f;
+}
+
+/* (copied: the texts may be in the caller's buffers, gone before the tooltip is drawn) */
+void win_tip(WinOut *w, const char *header, const char *text) {
+ if (!w->last_focus || w->mode != WO_DRAW) return;
+ w->tip_head[0] = 0;
+ if (header) str_cat(w->tip_head, sizeof w->tip_head, header);
+ if (text && text != w->tip_buf) w->tip_buf[0] = 0, str_cat(w->tip_buf, sizeof w->tip_buf, text);
+ w->tip_header = header ? w->tip_head : NULL;
+ w->tip_text = text ? w->tip_buf : NULL;
+}
+
+static bool drawing(WinOut *w) { return w->mode == WO_DRAW; }
+static int sx(WinOut *w, int x) { return w->x0 + x; }
+static int sy(WinOut *w, int y) { return w->y0 + y; }
+static void grow(WinOut *w, int width) {
+ if (width > w->maxw) w->maxw = width;
+}
+
+static void close_pending(WinOut *w);
+static void pending_body(WinOut *w);
+
+/* TextElement: font, its padding (addToPadding), wrapped at max_w */
+static const int8_t pad_top[FONT_COUNT] = {[FONT_STANDARD] = -2, [FONT_10] = -3, [FONT_15] = -3, [FONT_16] = -2, [FONT_18] = -3};
+static const int8_t pad_bottom[FONT_COUNT] = {[FONT_STANDARD] = 2, [FONT_10] = 3, [FONT_15] = 2, [FONT_16] = 4, [FONT_18] = 2};
+
+static int para_at(WinOut *w, int x, uint8_t font, const char *s, int max_w, uint16_t color, int *width) {
+ if (!s || !*s) {
+ if (width) *width = 0;
+ return 0;
+ }
+ uint16_t col = color;
+ s = ui_color_prefix(s, &col);
+ int wd, h = ui_para(font, 0, INT16_MIN, max_w, s, col, false, &wd);
+ int eh = h + pad_top[font] + pad_bottom[font];
+ if (drawing(w) && vis(w, w->y, eh)) ui_para(font, sx(w, x), sy(w, w->y) + pad_top[font], max_w, s, col, false, NULL);
+ if (width) *width = wd;
+ return eh;
+}
+
+void win_para(WinOut *w, uint8_t font, const char *s, int max_w, uint16_t color) {
+ if (w->muted) return;
+ close_pending(w);
+ int wd;
+ w->y += para_at(w, 0, font, s, max_w, color, &wd);
+ grow(w, wd);
+}
+
+void win_space(WinOut *w, int h) {
+ if (w->muted) return;
+ close_pending(w);
+ w->y += h;
+}
+
+/* windowAddTitleText: Arial16 after 3 pixels (and an icon: 1, the icon 4 lower, 2), the close button at the right */
+void win_title_icon(WinOut *w, const char *s, uint16_t icon) { win_title_tint(w, s, icon, GFX_NO_TINT); }
+void win_title_tint(WinOut *w, const char *s, uint16_t icon, uint16_t tint) {
+ if (w->muted) return;
+ if (w->title_w) {
+ /* a window has one title: a second one is a heading in the text (as AlienRuins' "Findings") */
+ win_space(w, 3);
+ win_header(w, s);
+ return;
+ }
+ int iw = icon ? 1 + spr_w(icon) + 2 : 0;
+ w->title_w = 3 + iw + ui_text_w(FONT_16, s) + 3 + CLOSE_W; /* a small gap before the close button */
+ if (w->win) w->win->tw = (int16_t)w->title_w;
+ if (drawing(w) && s) {
+ /* the title row is not scrolled: drawn at the window's top, outside the contents' clip */
+ ui_noclip();
+ if (icon) ui_spr_ex(icon, 0, 0, spr_w(icon), spr_h(icon), win_title_x + 3 + 1, win_title_y + 4, 0, 255, tint);
+ ui_text(FONT_16, win_title_x + 3 + iw, win_title_y + 1, s, C_BLACK);
+ ui_clip(content_clip[0], content_clip[1], content_clip[2], content_clip[3]);
+ }
+}
+void win_title(WinOut *w, const char *s) { win_title_icon(w, s, 0); }
+
+void win_text(WinOut *w, const char *s) {
+ if (w->muted) return;
+ if (w->pending) {
+ /* a button's description (createActivatableButton): Arial10 inside its box */
+ pending_body(w);
+ int wd;
+ w->y += para_at(w, 3, FONT_10, s, 250, C_BLACK, &wd);
+ grow(w, wd + 6);
+ return;
+ }
+ win_para(w, FONT_STANDARD, s, 250, C_BLACK);
+}
+
+void win_info(WinOut *w, uint16_t icon, const char *s) {
+ if (w->muted) return;
+ if (!icon) {
+ win_para(w, FONT_STANDARD, s, 250, C_BLACK);
+ return;
+ }
+ close_pending(w);
+ int iw = spr_w(icon);
+ if (drawing(w) && vis(w, w->y, 12)) ui_spr(icon, sx(w, 0), sy(w, w->y) + 1);
+ int wd;
+ int h = para_at(w, iw + 2, FONT_STANDARD, s, 250 - iw - 2, C_BLACK, &wd);
+ w->y += h > 12 ? h : 12;
+ grow(w, iw + 2 + wd);
+}
+
+void win_cost(WinOut *w, const float cost[M_COUNT]) {
+ if (w->muted) return;
+ bool inside = w->pending;
+ if (inside) {
+ pending_body(w);
+ w->pend.cost = true;
+ } else {
+ close_pending(w);
+ }
+ int x = inside ? 3 : 0;
+ int wd = ui_cost(0, INT16_MIN, cost, "", " to research", true);
+ if (drawing(w) && vis(w, w->y, 12)) {
+ char after[24] = " ";
+ ui_cost(sx(w, x), sy(w, w->y), cost, "", str_cat(after, sizeof after, L_to_research), true);
+ }
+ w->y += 12;
+ grow(w, wd + x * 2);
+}
+
+/* ---------------------------------------------------------------- buttons */
+/* the box of a button in its state: normal, focused (hover) or down (pressed or on) */
+/* BXF_ACTIVE: TextButton's isActive (it is on), shown pressed */
+static int state_box(int box, bool focused, bool down) {
+ if (box & BXF_ACTIVE) box &= ~BXF_ACTIVE, down = true;
+ return box + (down ? 2 : focused ? 1 : 0);
+}
+
+bool win_text_button(WinOut *w, const char *label, int action, int box, bool fill_width, bool centred) {
+ close_pending(w);
+ int tw = ui_text_w(FONT_STANDARD, label), bw = tw + 6, bh = 15;
+ int x = w->row ? w->rx : 0;
+ if (fill_width && w->cw > bw) bw = w->cw;
+ bool f = focusable(w, x, w->y, bw, bh, action);
+ if (drawing(w) && vis(w, w->y, bh)) {
+ bool down = f && key_held(K_OK);
+ ui_box(sx(w, x), sy(w, w->y), bw, bh, state_box(box, f, down));
+ int tx = centred ? (bw - tw) / 2 : 3;
+ ui_text(FONT_STANDARD, sx(w, x) + tx, sy(w, w->y) + 1, label, C_BLACK);
+ }
+ if (w->row) {
+ w->rx += bw;
+ if (bh > w->rh) w->rh = bh;
+ grow(w, w->rx);
+ } else {
+ w->y += bh;
+ grow(w, tw + 6);
+ }
+ return f;
+}
+
+void win_row_begin(WinOut *w) {
+ close_pending(w);
+ w->row = true;
+ w->rx = 0;
+ w->rh = 0;
+}
+void win_row_end(WinOut *w) {
+ w->row = false;
+ w->y += w->rh;
+}
+
+/* windowAddBottomButtons: extra buttons (2 apart) on the left, the close button on the right */
+void win_bottom(WinOut *w, const char *const *labels, const int *actions, int n, const char *close_label,
+ int close_action) {
+ win_bottom_ex(w, labels, actions, NULL, NULL, n, close_label, close_action);
+}
+void win_bottom_tips(WinOut *w, const char *const *labels, const int *actions, const char *const *tips, int n,
+ const char *close_label, int close_action) {
+ win_bottom_ex(w, labels, actions, NULL, tips, n, close_label, close_action);
+}
+void win_bottom_ex(WinOut *w, const char *const *labels, const int *actions, const char *const *tip_headers,
+ const char *const *tips, int n, const char *close_label, int close_action) {
+ close_pending(w);
+ int x = 0;
+ for (int i = 0; i < n; i++) {
+ int bw = ui_text_w(FONT_STANDARD, labels[i]) + 6;
+ bool f = focusable(w, x, w->y, bw, 15, actions[i]);
+ if ((tips && tips[i]) || (tip_headers && tip_headers[i])) win_tip(w, tip_headers ? tip_headers[i] : NULL, tips ? tips[i] : NULL);
+ if (drawing(w) && vis(w, w->y, 15)) {
+ ui_box(sx(w, x), sy(w, w->y), bw, 15, state_box(BX_BUTTON, f, f && key_held(K_OK)));
+ ui_text(FONT_STANDARD, sx(w, x) + 3, sy(w, w->y) + 1, labels[i], C_BLACK);
+ }
+ x += bw + 2;
+ }
+ if (close_label) {
+ int bw = ui_text_w(FONT_STANDARD, close_label) + 6;
+ int cx = w->cw - bw;
+ if (cx < x) cx = x;
+ bool f = focusable(w, cx, w->y, bw, 15, close_action);
+ if (drawing(w) && vis(w, w->y, 15)) {
+ ui_box(sx(w, cx), sy(w, w->y), bw, 15, state_box(BX_BUTTON, f, f && key_held(K_OK)));
+ ui_text(FONT_STANDARD, sx(w, cx) + 3, sy(w, w->y) + 1, close_label, C_BLACK);
+ }
+ x += bw;
+ }
+ grow(w, x);
+ w->y += 15;
+}
+
+/* a class's button for the bottom row, left of Close (the building's window adds the row) */
+void win_bottom_button(WinOut *w, const char *label, int action, const char *tip_header, const char *tip) {
+ if (w->muted) return;
+ if (w->nbottom >= 2) return;
+ w->bottom[w->nbottom].label = label;
+ w->bottom[w->nbottom].action = (int16_t)action;
+ w->bottom[w->nbottom].tip_header = tip_header;
+ w->bottom[w->nbottom].tip = tip;
+ w->nbottom++;
+}
+
+/* UpgradeWindowParts.createHeader, and with one_action >= 0 addOneAndMaxButtons on its row: One (on unless all)
+ * and All (Max when max), right of the heading, with their tooltips */
+void win_heading(WinOut *w, const char *title, int one_action, int all_action, bool all, bool max, const char *one_tip,
+ const char *all_tip) {
+ if (w->muted) return;
+ close_pending(w); /* (a button before it ends first: the One and All buttons go on the heading's row) */
+ int y0 = w->y;
+ win_header(w, title);
+ if (one_action < 0) return;
+ int one_w = ui_text_w(FONT_STANDARD, L_one) + 6;
+ const char *all_label = max ? L_max : L_all;
+ int all_w = ui_text_w(FONT_STANDARD, all_label) + 6;
+ /* the buttons sit on the header's row, at the right (after a filler) */
+ int save_y = w->y;
+ w->y = y0;
+ win_row_begin(w);
+ w->rx = w->cw - one_w - 2 - all_w;
+ if (w->rx < ui_text_w(FONT_15, title) + 2) w->rx = ui_text_w(FONT_15, title) + 2;
+ /* (the one in use shows pressed: TextButton's isActive) */
+ win_text_button(w, L_one, one_action, BX_BUTTON | (all ? 0 : BXF_ACTIVE), false, false);
+ win_tip(w, NULL, one_tip);
+ w->rx += 2;
+ win_text_button(w, all_label, all_action, BX_BUTTON | (all ? BXF_ACTIVE : 0), false, false);
+ win_tip(w, NULL, all_tip);
+ win_row_end(w);
+ if (w->y < save_y) w->y = save_y;
+}
+
+/* a class's button (win_button): CycleValueButton / FullSizeTextButton, or with a description and a cost
+ * following it, UpgradeWindowParts.createActivatableButton */
+void win_button(WinOut *w, uint16_t icon, const char *label, int action, bool enabled) {
+ if (w->muted) return;
+ close_pending(w);
+ (void)icon;
+ w->pend.label[0] = 0;
+ str_cat(w->pend.label, sizeof w->pend.label, label);
+ w->pend.action = action;
+ w->pend.enabled = enabled;
+ w->pend.body = false;
+ w->pend.cost = false;
+ w->pend.y = w->y;
+ w->pend.focus_index = w->nfocus++;
+ w->pend.focused = w->win && w->pend.focus_index == w->win->focus;
+ w->pending = true;
+ w->pending_box = drawing(w) ? ui_box_later(sx(w, 0), sy(w, w->y), w->cw, BX_BUTTON) : NULL;
+ w->y += 3;
+}
+
+/* the first description or cost after a button: its name goes at the top left */
+static void pending_body(WinOut *w) {
+ if (w->pend.body) return;
+ w->pend.body = true;
+ int tw;
+ w->y += para_at(w, 3, FONT_STANDARD, w->pend.label, 250, C_BLACK, &tw);
+ grow(w, tw + 6);
+}
+
+static void close_pending(WinOut *w) {
+ if (!w->pending) return;
+ w->pending = false;
+ UiPrim *box = w->pending_box;
+ w->pending_box = NULL;
+ int y0 = w->pend.y, h;
+ if (!w->pend.body) {
+ /* FullSizeTextButton: the label centred, 3 above and 0 below */
+ int tw = ui_text_w(FONT_STANDARD, w->pend.label);
+ h = 15;
+ if (drawing(w) && vis(w, y0, h))
+ ui_text(FONT_STANDARD, sx(w, (w->cw - tw) / 2), sy(w, y0) + 1, w->pend.label, w->pend.enabled ? C_BLACK : 0x8410);
+ grow(w, tw + 6);
+ w->y = y0 + h;
+ } else {
+ w->y += 1;
+ h = w->y - y0;
+ }
+ /* the option chosen (a description, no cost, not enabled) is a box, not a button: nothing to focus */
+ bool chosen = !w->pend.enabled && w->pend.body && !w->pend.cost;
+ if (chosen) {
+ if (w->nfocus == w->pend.focus_index + 1) w->nfocus--;
+ w->pend.focused = false;
+ }
+ /* the button's rectangle for the arrows and OK */
+ if (!chosen && w->mode == WO_NAV && w->nav && w->nnav < 48) {
+ NavRect *r = &w->nav[w->nnav++];
+ r->x = 0, r->y = (int16_t)y0, r->w = (int16_t)w->cw, r->h = (int16_t)h, r->action = (int16_t)w->pend.action;
+ }
+ if (w->pend.focused) {
+ w->focus_y0 = y0, w->focus_y1 = y0 + h;
+ if (w->mode == WO_PRESS && w->pend.enabled) w->pressed = w->pend.action;
+ focus_ring(w, 0, y0, w->cw, h);
+ }
+ if (box) {
+ box->h = (int16_t)h;
+ bool f = w->pend.focused;
+ /* not enabled: with a cost, one the city can't pay (a button all the same); with a description only,
+ * the option chosen (createActivatableButton's active box); alone, greyed */
+ int style = w->pend.enabled || w->pend.cost ? state_box(BX_BUTTON, f, f && key_held(K_OK))
+ : w->pend.body ? BX_ACTIVE : state_box(BX_GRAY, f, false);
+ const Box *b = &boxes[style];
+ box->c1 = b->border, box->c2 = b->fill, box->a1 = b->ba, box->a2 = b->fa;
+ /* a box wholly outside the view is not drawn */
+ if (sy(w, y0) + h <= uf->cy0 || sy(w, y0) >= uf->cy1) box->h = 0;
+ }
+ w->y += w->pend.body ? 2 : 4; /* the spacing after it */
+}
+
+/* createActivatableButton: name, description (Arial10) and cost; active ones are green boxes, not buttons */
+bool win_activatable(WinOut *w, bool active, int action, const char *name, const char *desc, const float *cost,
+ const char *before_k) {
+ close_pending(w);
+ int y0 = w->y, tw, h = 3;
+ bool f = false;
+ int nf = active ? -1 : w->nfocus++;
+ if (!active) f = w->win && nf == w->win->focus;
+ UiPrim *box = drawing(w) ? ui_box_later(sx(w, 0), sy(w, y0), w->cw, BX_BUTTON) : NULL;
+ w->y += 3;
+ w->y += para_at(w, 3, FONT_STANDARD, name, 250, C_BLACK, &tw);
+ grow(w, tw + 6);
+ if (desc && *desc) {
+ w->y += para_at(w, 3, FONT_10, desc, 250, C_BLACK, &tw);
+ grow(w, tw + 6);
+ }
+ if (cost) {
+ bool any = false;
+ for (int m = 0; m < M_COUNT; m++) any |= cost[m] > 0;
+ if (any) {
+ int cw = ui_cost(0, INT16_MIN, cost, before_k, L_to_research, true);
+ if (drawing(w) && vis(w, w->y, 12)) {
+ char after[24] = " ";
+ str_cat(after, sizeof after, L_to_research);
+ ui_cost(sx(w, 3), sy(w, w->y), cost, before_k, after, true);
+ }
+ w->y += 12;
+ grow(w, cw + 6);
+ }
+ }
+ w->y += 1;
+ h = w->y - y0;
+ if (!active) {
+ if (w->mode == WO_NAV && w->nav && w->nnav < 48) {
+ NavRect *r = &w->nav[w->nnav++];
+ r->x = 0, r->y = (int16_t)y0, r->w = (int16_t)w->cw, r->h = (int16_t)h, r->action = (int16_t)action;
+ }
+ if (f) {
+ w->focus_y0 = y0, w->focus_y1 = y0 + h;
+ if (w->mode == WO_PRESS) w->pressed = action;
+ focus_ring(w, 0, y0, w->cw, h);
+ }
+ }
+ if (box) {
+ box->h = (int16_t)h;
+ const Box *b = &boxes[active ? BX_ACTIVE : state_box(BX_BUTTON, f, f && key_held(K_OK))];
+ box->c1 = b->border, box->c2 = b->fill, box->a1 = b->ba, box->a2 = b->fa;
+ if (sy(w, y0) + h <= uf->cy0 || sy(w, y0) >= uf->cy1) box->h = 0;
+ }
+ w->y += 2;
+ return f;
+}
+
+/* gui.CheckboxButton (createCheckboxButton): a checkbox and the name, then the description */
+bool win_checkbox(WinOut *w, bool checked, int action, const char *name, const char *desc, const float *cost) {
+ close_pending(w);
+ (void)cost;
+ int y0 = w->y, tw;
+ int nf = w->nfocus++;
+ bool f = w->win && nf == w->win->focus;
+ UiPrim *box = drawing(w) ? ui_box_later(sx(w, 0), sy(w, y0), w->cw, BX_BUTTON) : NULL;
+ w->y += 3;
+ if (drawing(w) && vis(w, w->y, 12)) ui_frame(SPR_CHECKBOX, 8, checked ? 0 : 1, sx(w, 3), sy(w, w->y), 0, 255);
+ int h1 = para_at(w, 3 + 8 + 3, FONT_STANDARD, name, 250, C_BLACK, &tw);
+ w->y += h1 > 8 ? h1 : 8;
+ grow(w, tw + 6 + 11);
+ w->y += para_at(w, 3, FONT_10, desc, 250, C_BLACK, &tw);
+ grow(w, tw + 6);
+ w->y += 1;
+ int h = w->y - y0;
+ if (w->mode == WO_NAV && w->nav && w->nnav < 48) {
+ NavRect *r = &w->nav[w->nnav++];
+ r->x = 0, r->y = (int16_t)y0, r->w = (int16_t)w->cw, r->h = (int16_t)h, r->action = (int16_t)action;
+ }
+ if (f) {
+ w->focus_y0 = y0, w->focus_y1 = y0 + h;
+ if (w->mode == WO_PRESS) w->pressed = action;
+ focus_ring(w, 0, y0, w->cw, h);
+ }
+ if (box) {
+ box->h = (int16_t)h;
+ const Box *b = &boxes[state_box(checked ? BX_CHECKED : BX_BUTTON, f, f && key_held(K_OK))];
+ box->c1 = b->border, box->c2 = b->fill, box->a1 = b->ba, box->a2 = b->fa;
+ if (sy(w, y0) + h <= uf->cy0 || sy(w, y0) >= uf->cy1) box->h = 0;
+ }
+ w->y += 2;
+ return f;
+}
+
+void win_setting(WinOut *w, bool checked, int action, const char *text) {
+ if (w->muted) return;
+ win_checkbox(w, checked, action, text, "", NULL);
+}
+
+void win_later(WinOut *w) {
+ close_pending(w);
+ w->muted = !w->later;
+}
+
+/* windowAddSimpleButton: [icon text] in a small button; several go side by side (4 apart) */
+bool win_simple_button(WinOut *w, uint16_t icon, const char *text, int action) {
+ close_pending(w);
+ int iw = spr_w(icon), ih = spr_h(icon);
+ int tw = ui_text_w(FONT_STANDARD, text);
+ int bw = 2 + iw + 1 + tw + 3, bh = 2 + (ih > 13 ? ih : 13) - 1;
+ int x = w->row ? w->rx : 0;
+ bool f = focusable(w, x, w->y, bw, bh, action);
+ if (drawing(w) && vis(w, w->y, bh)) {
+ ui_box(sx(w, x), sy(w, w->y), bw, bh, state_box(BX_BUTTON, f, f && key_held(K_OK)));
+ ui_spr(icon, sx(w, x) + 2, sy(w, w->y) + 2);
+ ui_text(FONT_STANDARD, sx(w, x) + 2 + iw + 1, sy(w, w->y) + 1, text, C_BLACK);
+ }
+ if (w->row) {
+ w->rx += bw + 4;
+ if (bh > w->rh) w->rh = bh;
+ grow(w, w->rx - 4);
+ } else {
+ w->y += bh;
+ grow(w, bw);
+ }
+ return f;
+}
+
+/* a focusable spot of the content at (x, w->y), wd x h, drawn by the caller: whether it is focused */
+bool win_small_button(WinOut *w, int x, int wd, int h, int action) {
+ close_pending(w);
+ return focusable(w, x, w->y, wd, h, action);
+}
+
+/* UpgradeWindowParts.createHeader: Arial15 (its padding top 3 cancels the font's -3; bottom 0 + 2), then 2 */
+void win_header(WinOut *w, const char *s) {
+ close_pending(w);
+ int tw, h = ui_para(FONT_15, 0, INT16_MIN, 250, s, C_BLACK, true, &tw);
+ if (drawing(w) && vis(w, w->y, h + 2)) ui_para(FONT_15, sx(w, 0), sy(w, w->y), 250, s, C_BLACK, false, NULL);
+ w->y += h + 2;
+ grow(w, tw + 2);
+ w->y += 2;
+}
+
+bool win_area(WinOut *w, int width, int height, int *x, int *y) {
+ close_pending(w);
+ bool v = drawing(w) && vis(w, w->y, height);
+ *x = sx(w, 0);
+ *y = sy(w, w->y);
+ w->y += height;
+ grow(w, width);
+ return v;
+}
+
+/* ---------------------------------------------------------------- drawing the window */
+static bool win_has_title(Win *wn) { return wn->tw > 0; }
+
+static void run_content(WinOut *w) {
+ w->y = 0;
+ w->maxw = 0;
+ w->nfocus = 0;
+ w->pressed = -1;
+ w->focus_y0 = w->focus_y1 = -1;
+ w->pending_box = NULL;
+ w->pending = false;
+ w->row = false;
+ Win *wn = w->win;
+ w->perm = wn->kind == WK_BUILDING ? P(wn->arg) : NULL;
+ windefs[wn->kind].content(w);
+ close_pending(w);
+ if (w->row) win_row_end(w);
+}
+
+/* the window's outer size from its content's (last measured) */
+static void win_geometry(Win *wn, int *wx, int *wy, int *ww, int *wh, int *sh, bool *scroll) {
+ int th = win_has_title(wn) ? TITLE_H : 0;
+ int cw = wn->cw;
+ if (wn->tw - 6 > cw) cw = wn->tw - 6;
+ int inner_h = wn->ch + 4;
+ *sh = inner_h < WIN_MAX_H ? inner_h : WIN_MAX_H;
+ *scroll = inner_h > WIN_MAX_H;
+ *ww = cw + 4 + 2 + (*scroll ? 10 : 0);
+ if (*ww < wn->tw) *ww = wn->tw;
+ *wh = th + 1 + *sh + 1;
+ *wx = SCREEN_W / 2 - *ww / 2;
+ *wy = (windefs[wn->kind].flags & WD_TOP) ? 10 : SCREEN_H / 2 - *wh / 2; /* WindowPosition.Top or Center */
+ if (*wy + *wh > SCREEN_H) *wy = SCREEN_H - *wh;
+}
+
+/* sets up a WinOut for the top window (its layout from last frame's size) */
+static void win_setup(WinOut *w, Win *wn, int mode) {
+ memset(w, 0, sizeof *w);
+ w->mode = (uint8_t)mode;
+ w->win = wn;
+ int wx, wy, ww, wh, sh;
+ bool scroll;
+ win_geometry(wn, &wx, &wy, &ww, &wh, &sh, &scroll);
+ int th = win_has_title(wn) ? TITLE_H : 0;
+ w->cw = ww - 6 - (scroll ? 10 : 0);
+ w->x0 = wx + 3;
+ w->y0 = wy + th + 3 - wn->scroll;
+ w->vis0 = wn->scroll - 2;
+ w->vis1 = wn->scroll + sh - 2;
+ win_title_x = wx;
+ win_title_y = wy;
+}
+
+/* measures a window's contents (when opened, so its first frame is the right size) */
+static void win_measure(Win *wn) {
+ WinOut w;
+ UiFrame *keep = uf;
+ uf = NULL;
+ for (int pass = 0; pass < 2; pass++) {
+ win_setup(&w, wn, WO_NAV);
+ run_content(&w);
+ wn->cw = (int16_t)w.maxw;
+ wn->ch = (int16_t)w.y;
+ }
+ uf = keep;
+}
+
+static void win_scroll_by(Win *wn, int dy) {
+ int wx, wy, ww, wh, sh;
+ bool scroll;
+ win_geometry(wn, &wx, &wy, &ww, &wh, &sh, &scroll);
+ int max_scroll = wn->ch + 4 - sh;
+ int s = wn->scroll + dy;
+ if (s > max_scroll) s = max_scroll;
+ if (s < 0) s = 0;
+ wn->scroll = (int16_t)s;
+}
+
+/* a window just opened: its size measured and its first button that shows focused */
+static void win_ready(Win *wn) {
+ if (wn->flags & WF2_NEW) {
+ win_measure(wn);
+ wn->flags &= (uint8_t)~WF2_NEW;
+ /* the first button that shows is focused */
+ WinOut w;
+ NavRect nav[48];
+ win_setup(&w, wn, WO_NAV);
+ w.nav = nav;
+ UiFrame *keep = uf;
+ uf = NULL;
+ run_content(&w);
+ uf = keep;
+ wn->focus = 255;
+ for (int i = 0; i < w.nnav; i++)
+ if (nav[i].y + nav[i].h <= WIN_MAX_H - 4) {
+ wn->focus = (uint8_t)i;
+ break;
+ }
+ /* asking to destroy: the destroy button focused (scrolled to) */
+ if (wn->flags & WF2_CONFIRM)
+ for (int i = 0; i < w.nnav; i++)
+ if (nav[i].action == ACT_DESTROY) {
+ wn->focus = (uint8_t)i;
+ win_scroll_by(wn, nav[i].y + nav[i].h);
+ }
+ }
+}
+
+/* the window drawn with the size its content had last; false if the content came out another size (it is then
+ * drawn again: what this pass added to the frame is taken back first) */
+static bool win_draw_pass(Win *wn) {
+ int wx, wy, ww, wh, sh;
+ bool scroll;
+ win_geometry(wn, &wx, &wy, &ww, &wh, &sh, &scroll);
+ int th = win_has_title(wn) ? TITLE_H : 0;
+ ui_noclip();
+ ui_box(wx, wy, ww, wh, (windefs[wn->kind].flags & WD_OPAQUE) ? BX_WINDOW_OPAQUE : BX_WINDOW);
+ if (th && !(windefs[wn->kind].flags & WD_NO_CLOSE_BUTTON)) {
+ /* the close button (spr_button_windowheader, spr_icon_close) */
+ ui_frame(SPR_BUTTON_WINDOWHEADER, 23, key_held(K_BACK) ? 2 : 0, wx + ww - CLOSE_W, wy, 0, 255);
+ ui_spr(SPR_ICON_CLOSE, wx + ww - CLOSE_W + 1, wy + 1);
+ }
+ /* the contents, clipped to the scrollable area */
+ WinOut w;
+ win_setup(&w, wn, WO_DRAW);
+ content_clip[0] = wx + 1, content_clip[1] = wy + th + 1, content_clip[2] = ww - 2 - (scroll ? 10 : 0);
+ content_clip[3] = sh;
+ ui_clip(content_clip[0], content_clip[1], content_clip[2], content_clip[3]);
+ run_content(&w);
+ if (w.ring_on) ui_ring(sx(&w, w.ring[0]), sy(&w, w.ring[1]), w.ring[2], w.ring[3], 2, FOCUS_RING);
+ ui_noclip();
+ if (w.title_w == 0) wn->tw = 0;
+ wn->cw = (int16_t)w.maxw;
+ wn->ch = (int16_t)w.y;
+ /* the scroll can't pass the end (the contents may have shrunk) */
+ int nx, ny, nw, nh, nsh;
+ bool nscroll;
+ win_geometry(wn, &nx, &ny, &nw, &nh, &nsh, &nscroll);
+ int max_scroll = wn->ch + 4 - nsh;
+ if (wn->scroll > max_scroll) wn->scroll = (int16_t)(max_scroll > 0 ? max_scroll : 0);
+ if (nx != wx || ny != wy || nw != ww || nh != wh || nscroll != scroll) return false;
+ /* a focused button's tooltip, once the player has moved the focus (the original shows it on hover): kept for
+ * win_draw_tip */
+ if ((w.tip_header || w.tip_text) && (wn->flags & WF2_TIP) && uf) {
+ uf->tip.header[0] = uf->tip.text[0] = 0;
+ if (w.tip_header) str_cat(uf->tip.header, sizeof uf->tip.header, w.tip_header);
+ if (w.tip_text) str_cat(uf->tip.text, sizeof uf->tip.text, w.tip_text);
+ uf->tip.x = (int16_t)w.tip_x, uf->tip.y = (int16_t)w.tip_y;
+ uf->tip.on = true;
+ }
+ if (scroll) {
+ /* gui.ScrollBar: its background and handle (spr_windowparts) */
+ int inner_h = wn->ch + 4, bx = wx + ww - 10, by = wy + th, bh = sh + 2;
+ ui_box(bx, by, 10, bh, BX_SCROLL);
+ int hh = (sh * bh + inner_h / 2) / inner_h, hy = (wn->scroll * bh + inner_h / 2) / inner_h;
+ ui_box(bx, by + hy, 10, hh, BX_HANDLE);
+ }
+ return true;
+}
+
+void win_draw_tip(void) {
+ if (!uf || !uf->tip.on) return;
+ Tip t = {0};
+ t.header = uf->tip.header, t.text = uf->tip.text;
+ ui_tooltip(&t, uf->tip.x, uf->tip.y, false);
+}
+
+/* the top window: laid out before it shows, so that no frame draws it at an old size (clipped) */
+void win_draw(void) {
+ Win *wn = win_top();
+ if (!wn) return;
+ win_ready(wn);
+ int n = uf ? uf->n : 0, ntext = uf ? uf->ntext : 0, dropped = uf ? uf->dropped : 0;
+ int16_t clip[4] = {0};
+ if (uf) clip[0] = uf->cx0, clip[1] = uf->cy0, clip[2] = uf->cx1, clip[3] = uf->cy1;
+ int top = nwins;
+ extern int ui_redraws;
+ for (int pass = 0; pass < 3; pass++) {
+ if (win_draw_pass(wn) || nwins != top || win_top() != wn || pass == 2) break;
+ ui_redraws++;
+ if (uf) {
+ uf->n = n, uf->ntext = ntext, uf->dropped = dropped, uf->tip.on = false;
+ uf->cx0 = clip[0], uf->cy0 = clip[1], uf->cx1 = clip[2], uf->cy1 = clip[3];
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- keys */
+
+/* moves the focus to the nearest button that way, scrolling to show it (or scrolls if none is near) */
+static void win_nav(Win *wn, int dx, int dy) {
+ wn->flags |= WF2_TIP;
+ WinOut w;
+ NavRect nav[48];
+ win_setup(&w, wn, WO_NAV);
+ w.nav = nav;
+ UiFrame *keep = uf;
+ uf = NULL;
+ run_content(&w);
+ uf = keep;
+ int wx, wy, ww, wh, sh;
+ bool scroll;
+ win_geometry(wn, &wx, &wy, &ww, &wh, &sh, &scroll);
+ int view0 = wn->scroll, view1 = wn->scroll + sh - 4;
+ int cur = wn->focus < w.nnav ? wn->focus : -1;
+ /* where the focus is (or the view's edge) */
+ int cx, cy0, cy1;
+ if (cur >= 0) {
+ cx = nav[cur].x + nav[cur].w / 2, cy0 = nav[cur].y, cy1 = nav[cur].y + nav[cur].h;
+ } else {
+ cx = w.cw / 2;
+ cy0 = dy > 0 ? view0 - 1 : view1 + 1;
+ cy1 = cy0;
+ if (dy == 0) cy0 = view0, cy1 = view1;
+ }
+ int best = -1, best_score = 1 << 30;
+ for (int i = 0; i < w.nnav; i++) {
+ if (i == cur) continue;
+ NavRect *r = &nav[i];
+ int score;
+ if (dy) {
+ int ry0 = r->y, ry1 = r->y + r->h;
+ int gap = dy > 0 ? ry0 - cy1 : cy0 - ry1;
+ if (gap < -3) continue; /* not that way */
+ if (dy > 0 && ry0 <= cy0) continue;
+ if (dy < 0 && ry1 >= cy1) continue;
+ int rcx = r->x + r->w / 2;
+ score = (gap > 0 ? gap : 0) * 4 + (rcx > cx ? rcx - cx : cx - rcx);
+ } else {
+ /* the same row: overlapping rows, that side */
+ if (r->y + r->h <= cy0 || r->y >= cy1) continue;
+ int rcx = r->x + r->w / 2;
+ if (dx > 0 ? rcx <= cx : rcx >= cx) continue;
+ score = dx > 0 ? rcx - cx : cx - rcx;
+ }
+ if (score < best_score) best_score = score, best = i;
+ }
+ if (best < 0) {
+ if (dy) win_scroll_by(wn, dy * 24);
+ } else {
+ NavRect *r = &nav[best];
+ /* far out of view: scroll toward it first (so the text before it can be read) */
+ if (dy > 0 && r->y > view1 + 24 && r->y + r->h - view1 > sh / 2) {
+ win_scroll_by(wn, 40);
+ } else if (dy < 0 && r->y + r->h < view0 - 24 && view0 - r->y > sh / 2) {
+ win_scroll_by(wn, -40);
+ } else {
+ wn->focus = (uint8_t)best;
+ if (r->y < view0) win_scroll_by(wn, r->y - view0 - 2);
+ else if (r->y + r->h > view1) win_scroll_by(wn, r->y + r->h - view1 + 2);
+ }
+ }
+ /* a focused button scrolled out of view is no longer focused */
+ if (wn->focus < w.nnav) {
+ NavRect *r = &nav[wn->focus];
+ int v0 = wn->scroll, v1 = wn->scroll + sh - 4;
+ if (r->y + r->h <= v0 || r->y >= v1) wn->focus = 255;
+ }
+}
+
+/* GUI.goPreviousWindow, or the window's own action */
+static void win_do(Win *wn, int action) {
+ if ((action == ACT_CLOSE || action == ACT_BACK) && !(windefs[wn->kind].flags & WD_OWN_CLOSE)) {
+ win_close();
+ return;
+ }
+ if (windefs[wn->kind].action) windefs[wn->kind].action(wn, action);
+}
+
+void win_input(void) {
+ Win *wn = win_top();
+ if (!wn) return;
+ win_ready(wn);
+ if (key_pressed(K_BACK)) {
+ if (!(wn->flags & WF2_NO_CLOSE)) win_do(wn, ACT_BACK);
+ return;
+ }
+ if (pick_keys(wn)) return;
+ if (wn->kind == WK_CITIZEN && (wn->flags & WF2_CONFIRM)) {
+ /* ChangeCitizenVitalBuildings: the cursor goes over the city; OK on a building makes it the citizen's. var
+ * gives the arrows to the window's buttons (centre on the home, on the job) and back */
+ if (key_pressed(K_VAR)) {
+ wn->flags ^= WF2_KEYS;
+ wn->focus = (wn->flags & WF2_KEYS) ? 0 : 255;
+ if (wn->flags & WF2_KEYS) wn->flags |= WF2_TIP;
+ return;
+ }
+ if (!(wn->flags & WF2_KEYS)) {
+ extern bool city_cursor_keys(void);
+ extern bool change_vital_building(uint16_t citizen, uint16_t id);
+ wn->focus = 255;
+ city_cursor_keys();
+ if (input.released & K_OK) {
+ int col, row;
+ int wo = cursor_cell(&col, &row);
+ uint16_t id = wo >= 0 ? perm_at(wo, col, row) : 0;
+ if (is_building(P(id))) change_vital_building(wn->arg, id);
+ }
+ return;
+ }
+ }
+ if ((windefs[wn->kind].flags & WD_TOP) && key_held(K_SHIFT)) {
+ /* windows at the top leave the city in view: shift and the arrows move it */
+ extern bool city_cursor_keys(void);
+ city_cursor_keys();
+ return;
+ }
+ if (key_held(K_SHIFT)) {
+ if (key_repeat(K_UP)) win_scroll_by(wn, -60);
+ if (key_repeat(K_DOWN)) win_scroll_by(wn, 60);
+ return;
+ }
+ if (key_repeat(K_UP)) win_nav(wn, 0, -1);
+ if (key_repeat(K_DOWN)) win_nav(wn, 0, 1);
+ if (key_repeat(K_LEFT)) win_nav(wn, -1, 0);
+ if (key_repeat(K_RIGHT)) win_nav(wn, 1, 0);
+ if (input.released & K_OK) {
+ WinOut w;
+ win_setup(&w, wn, WO_PRESS);
+ UiFrame *keep = uf;
+ uf = NULL;
+ run_content(&w);
+ uf = keep;
+ if (w.pressed >= 0) {
+ win_do(wn, w.pressed);
+ } else if (wn->focus == 255 && !(wn->flags & WF2_NO_CLOSE)) {
+ /* nothing focused (a long text): OK closes it, as its Close button would */
+ bool has_close = false;
+ NavRect nav[48];
+ win_setup(&w, wn, WO_NAV);
+ w.nav = nav;
+ uf = NULL;
+ run_content(&w);
+ uf = keep;
+ for (int i = 0; i < w.nnav; i++) has_close |= nav[i].action == ACT_CLOSE;
+ if (has_close) win_do(wn, ACT_CLOSE);
+ }
+ }
+}
+
+/* the top window's button for an action, on screen (the tutorial arrows point at it) */
+bool win_screen_rect(int16_t r[4]) {
+ Win *wn = win_top();
+ if (!wn) return false;
+ win_ready(wn);
+ int wx, wy, ww, wh, sh;
+ bool scroll;
+ win_geometry(wn, &wx, &wy, &ww, &wh, &sh, &scroll);
+ r[0] = (int16_t)wx, r[1] = (int16_t)wy, r[2] = (int16_t)ww, r[3] = (int16_t)wh;
+ return true;
+}
+
+bool win_action_rect(int action, int16_t r[4]) {
+ Win *wn = win_top();
+ if (!wn) return false;
+ win_ready(wn);
+ WinOut w;
+ NavRect nav[48];
+ win_setup(&w, wn, WO_NAV);
+ w.nav = nav;
+ UiFrame *keep = uf;
+ uf = NULL;
+ run_content(&w);
+ uf = keep;
+ for (int i = 0; i < w.nnav; i++) {
+ if (nav[i].action != action) continue;
+ int y = w.y0 + nav[i].y;
+ if (nav[i].y + nav[i].h <= w.vis0 || nav[i].y >= w.vis1) return false;
+ r[0] = (int16_t)(w.x0 + nav[i].x), r[1] = (int16_t)y, r[2] = nav[i].w, r[3] = nav[i].h;
+ return true;
+ }
+ return false;
+}
diff --git a/games/finalearth2/src/uii.h b/games/finalearth2/src/uii.h
new file mode 100644
index 00000000..59b237ca
--- /dev/null
+++ b/games/finalearth2/src/uii.h
@@ -0,0 +1,406 @@
+/* The Final Earth 2: what the user interface's files (ui*.c) share.
+ *
+ * The interface is drawn immediate-mode: each frame, the city's panel, the
+ * build menu, the open window and the overlays are laid out again from the
+ * game's state and turned into a list of primitives (boxes, sprites, text) on
+ * game_draw's stack, which one band function draws over the city. Nothing a
+ * window shows is kept between frames: only which window is open, its scroll
+ * and the focused button. */
+#ifndef FE_UII_H
+#define FE_UII_H
+#include "bld.h"
+#include "build.h"
+#include "classes.h"
+#include "data.h"
+#include "gfx.h"
+#include "input.h"
+#include "lang_data.h"
+#include "story.h"
+#include "ui.h"
+#include "unlocks.h"
+#include "upgrades.h"
+#include "win.h"
+
+/* ---------------------------------------------------------------- colours */
+#define C_BLACK 0x0000
+#define C_WHITE 0xFFFF
+#define C_RED 0xF800 /* [red] (0xFF0000) */
+#define C_GREEN 0x07E0 /* [green] */
+#define C_BLUE 0x0204 /* [blue] (0x004090) */
+
+/* ---------------------------------------------------------------- the frame's primitives (ui_draw.c) */
+enum { PR_RECT, PR_BOX, PR_SPR, PR_TEXT, PR_TEXTROT, PR_CLIP, PR_SPR_SMALL, PR_KEYS };
+typedef struct {
+ int16_t x, y, w, h; /* text: w is its bytes */
+ uint8_t kind, a1, a2, f; /* alphas (box: border, fill); text: font; sprite: flags */
+ uint16_t c1, c2; /* colours (box: border, fill); sprite: SPR_*, tint */
+ union {
+ const char *s;
+ struct { int16_t sx, sy; } part;
+ } u;
+} UiPrim;
+
+#define UI_PRIMS 200
+#define UI_TEXT 1024 /* the most seen: about 530 */
+struct UiFrame {
+ UiPrim p[UI_PRIMS];
+ char text[UI_TEXT];
+ int n, ntext, dropped;
+ int16_t cx0, cy0, cx1, cy1; /* the clip of what is being added */
+ /* the window's tooltip, drawn after the help arrows (the original's tooltip stage is above them) */
+ struct { char header[64], text[200]; int16_t x, y; bool on; } tip;
+};
+extern UiFrame *uf; /* the frame being made (NULL: nothing is drawn, as when only laying out) */
+
+/* a 9-patch box of the original's (each is a 1-pixel border round a fill) */
+typedef struct { uint16_t border, fill; uint8_t ba, fa; } Box;
+/* the original's 9-patches and buttons: normal, hover (focused) and active (pressed or on) */
+enum { BX_WINDOW, BX_WINDOW_OPAQUE, BX_TOOLTIP, BX_INFO, BX_HINTINFO, BX_ACTIVE, BX_DISABLED,
+ BX_BUTTON, BX_BUTTON_HOVER, BX_BUTTON_DOWN, /* spr_button */
+ BX_TRANS, BX_TRANS_HOVER, BX_TRANS_DOWN, /* spr_transparentbutton_info */
+ BX_BLD, BX_BLD_HOVER, BX_BLD_DOWN, /* spr_buildingbutton */
+ BX_TRANSB, BX_TRANSB_HOVER, BX_TRANSB_DOWN, /* spr_transparentbutton */
+ BX_CHECKED, BX_CHECKED_HOVER, BX_CHECKED_DOWN, /* spr_button_checked */
+ BX_ACTIVABLE, BX_ACTIVABLE_HOVER, BX_ACTIVABLE_DOWN, /* spr_button_activable */
+ BX_GRAY, BX_GRAY_HOVER, BX_GRAY_DOWN, /* spr_button_gray */
+ BX_SCROLL, BX_HANDLE, BX_COUNT };
+extern const Box boxes[BX_COUNT];
+
+void ui_clip(int x, int y, int w, int h);
+void ui_noclip(void);
+void ui_rect(int x, int y, int w, int h, uint16_t c, uint8_t a);
+void ui_box(int x, int y, int w, int h, int box);
+UiPrim *ui_box_later(int x, int y, int w, int box); /* a box whose height is set once known */
+void ui_spr(uint16_t spr, int x, int y);
+void ui_spr_ex(uint16_t spr, int sx, int sy, int w, int h, int x, int y, uint8_t flags, uint8_t alpha, uint16_t tint);
+void ui_frame(uint16_t spr, int fw, int i, int x, int y, uint8_t flags, uint8_t alpha); /* frame of a strip */
+/* a whole sprite at 3/5 of its size (the mobile version's 0.6 scale), each pixel the nearest of the sprite's */
+void ui_spr_small(uint16_t spr, int x, int y);
+void ui_ring(int x, int y, int w, int h, int t, uint16_t c);
+#define FOCUS_RING 0x4CA0 /* the keypad focus: the hint boxes' green (0x4D9600) */ /* a frame t pixels thick round (x, y, w, h) */
+/* a row of keys, each a button cw x h with one character of chars (n of them): focused (255 none) is hovered,
+ * or pressed when down (one primitive for the row) */
+void ui_keys(int x, int y, int cw, int h, const char *chars, int n, int focused, bool down);
+/* one line of text (n bytes, -1: all); copied into the frame unless keep (a string that lasts) */
+int ui_text_n(uint8_t font, int x, int y, const char *s, int n, uint16_t color, uint8_t alpha, bool keep);
+static inline int ui_text(uint8_t font, int x, int y, const char *s, uint16_t color) {
+ return ui_text_n(font, x, y, s, -1, color, 255, false);
+}
+void ui_text_rot(uint8_t font, int x, int y, const char *s, uint16_t color); /* turned a quarter clockwise */
+/* a paragraph wrapped at max_w (PIXI's BitmapText): draws it if y is given (INT16_MIN: measure only);
+ * returns its height (lines x line height), sets its widest line */
+int ui_para(uint8_t font, int x, int y, int max_w, const char *s, uint16_t color, bool keep, int *width);
+/* the colour prefix of the original's texts ("[red]..."): the text after it and its colour */
+const char *ui_color_prefix(const char *s, uint16_t *color);
+void ui_frame_begin(UiFrame *f);
+void ui_frame_end(void); /* adds the band function that draws the frame */
+static inline int ui_line_h(uint8_t font) { return gfx_font_height(font); }
+int ui_text_w(uint8_t font, const char *s);
+
+/* ---------------------------------------------------------------- texts and numbers (ui_draw.c) */
+/* Localize.lo: "[0]", "[1]"... replaced by the arguments (numbers as JavaScript writes them, or strings) */
+typedef struct { const char *s; double v; } LoArg;
+#define LN(v) ((LoArg){NULL, (double)(v)})
+#define LS(s) ((LoArg){(s), 0})
+const char *lo(char *buf, int size, const char *text, int n, const LoArg *args);
+const char *lo_1(char *buf, int size, const char *text, LoArg a);
+const char *lo_2(char *buf, int size, const char *text, LoArg a, LoArg b);
+const char *lo_3(char *buf, int size, const char *text, LoArg a, LoArg b, LoArg c);
+int fmt_num(char *out, int size, double v); /* String(v) */
+int fmt_int(char *out, int size, long v);
+char *str_cat(char *dst, int size, const char *src); /* appends, returns dst */
+/* common.MathExtensions.largeNumberFormat: 12345 as "12.3k" etc. (the axis of the materials graph) */
+int fmt_large(char *out, int size, double v, bool alt);
+int ui_float_fmt(char *out, int size, double v, int decimals); /* MathExtensions.floatFormat */
+
+/* ---------------------------------------------------------------- materials (ui_draw.c) */
+extern const uint16_t mat_icon[M_COUNT];
+extern const char *const mat_lname[M_COUNT]; /* "food", "wood"... as lo(name) */
+const char *mat_title(int m, char *buf, int size); /* "Food", "Wood"... (firstToUpper(lo(name))) */
+/* MaterialsCostDisplay: the icons and amounts of a cost (red where the city has too little), and
+ * before_k / after_k around knowledge; returns its displayWidth (measures only when y is INT16_MIN) */
+int ui_cost(int x, int y, const float cost[M_COUNT], const char *before_k, const char *after_k, bool city_red);
+/* IconListDisplay */
+typedef struct { uint16_t spr; const char *text; } IconText;
+int ui_icon_list(int x, int y, const IconText *it, int n);
+void type_image(int x, int y, int cls); /* a building type's picture: its button back and first 20x20 (ui_info.c) */
+
+/* ---------------------------------------------------------------- the tooltip (ui_city.c) */
+typedef struct {
+ const char *header, *text;
+ const float *cost; /* MaterialsCostDisplay, or NULL */
+ const IconText *extra; /* icons right of the header */
+ int nextra;
+ const IconText *extra2; /* a row of icons under the text */
+ int nextra2;
+ const float *cost2; /* operating cost, after cost2_text */
+ const char *cost2_text;
+} Tip;
+/* Tooltip.setTextDisplay, next to (ax, ay) (a hover position) or at the top-left (continuous) */
+void ui_tooltip(const Tip *t, int ax, int ay, bool continuous);
+
+/* ---------------------------------------------------------------- windows (ui_win.c) */
+enum {
+ WK_NONE, WK_TEXT, WK_BUILDING, WK_CITIZEN, WK_FOLLOW_LIST, WK_MATERIAL, WK_POPULATION, WK_HAPPINESS, WK_HOUSES,
+ WK_WORKERS, WK_BIRTH, WK_ENTERTAINMENT, WK_FIND, WK_UPGRADES, WK_INVITE, WK_GOAL, WK_MISSIONS, WK_GAME_MENU,
+ WK_RESTART, WK_SCENARIOS, WK_FREE_PLAY, WK_CREDITS, WK_DESTROY, WK_REPLACE, WK_REPLACE_TO, WK_CITY_NAME, WK_COLOR,
+ WK_COUNT
+};
+typedef struct {
+ uint8_t kind;
+ uint8_t flags; /* WF2_* */
+ uint16_t arg, arg2; /* its subject: a permanent, a citizen, a material... */
+ int16_t scroll; /* content pixels scrolled */
+ uint8_t focus; /* the focused button */
+ int16_t cw, ch; /* its content's size, measured last frame */
+ int16_t tw; /* its title's width */
+} Win;
+/* WF2_KEYS: the window's buttons have the arrows (not the city's cursor); WF2_TIP: the player has moved the
+ * focus, so the focused button's tooltip shows */
+enum { WF2_PAUSED = 1, WF2_CONFIRM = 2, WF2_ALL = 4, WF2_NO_CLOSE = 8, WF2_OPAQUE = 16, WF2_NEW = 32, WF2_KEYS = 64,
+ WF2_TIP = 128 };
+#define WIN_STACK 5
+extern Win wins[WIN_STACK];
+extern int nwins;
+static inline Win *win_top(void) { return nwins ? &wins[nwins - 1] : NULL; }
+
+/* the layout of a window's contents (win.h's WinOut) */
+enum { WO_DRAW, WO_NAV, WO_PRESS };
+typedef struct { int16_t x, y, w, h; int16_t action; } NavRect;
+struct WinOut {
+ uint8_t mode;
+ Win *win;
+ Perm *perm; /* a building's window: its permanent (win_button's actions go to it) */
+ int x0, y0; /* the content's top-left on screen (scrolled) */
+ int cw; /* the content's width (last frame's) */
+ int y; /* where the next element goes (content coordinates) */
+ int maxw, vis0, vis1; /* widest element; the content rows shown */
+ int nfocus; /* focusables so far */
+ int pressed; /* WO_PRESS: the focused button's action (-1 none) */
+ int focus_y0, focus_y1; /* the focused button's rows */
+ bool row; /* buttons go side by side (win_row_begin) */
+ int rx, rh;
+ UiPrim *pending_box; /* a button box that grows with what follows (win_button's description) */
+ bool pending;
+ struct { /* win_button's label and action, until its box is closed */
+ char label[72];
+ int action, y, focus_index;
+ bool enabled, body, focused, cost;
+ } pend;
+ NavRect *nav; /* WO_NAV: the focusables' rectangles */
+ int nnav;
+ int title_w;
+ int last_focus; /* the last focusable added was the focused one (win_tip) */
+ int tip_x, tip_y; /* the focused button's tooltip: where, and what */
+ const char *tip_header, *tip_text;
+ char tip_buf[200], tip_head[64];
+ int16_t ring[4]; /* the focused element (content x, y, w, h), drawn framed when ring_on */
+ bool ring_on;
+ struct { const char *label, *tip_header, *tip; int16_t action; } bottom[2]; /* win_bottom_button's */
+ int nbottom;
+ bool later, muted; /* a building window's second run of its class (win_later), its elements left out */
+};
+/* the tooltip of the button just added, shown while it is focused (gui.Tooltip on hover) */
+void win_tip(WinOut *w, const char *header, const char *text);
+/* elements a window's contents is made of (and win.h's win_title, win_text, win_info, win_button, win_cost) */
+void win_title_icon(WinOut *w, const char *s, uint16_t icon); /* a title with an icon */
+void win_title_tint(WinOut *w, const char *s, uint16_t icon, uint16_t tint); /* (its icon tinted) */
+void win_header(WinOut *w, const char *s); /* UpgradeWindowParts.createHeader (Arial15) */
+/* a button: a box of the given style (BX_BUTTON..., | BXF_ACTIVE when on) round a label; returns true if focused */
+#define BXF_ACTIVE 0x80
+bool win_text_button(WinOut *w, const char *label, int action, int box, bool fill_width, bool centred);
+/* UpgradeWindowParts.createActivatableButton: a name, a description (Arial10) and a cost in a box
+ * (green when active, a button otherwise); returns true if focused */
+bool win_activatable(WinOut *w, bool active, int action, const char *name, const char *desc, const float *cost,
+ const char *before_k);
+/* gui.CheckboxButton (policies): checked or not */
+bool win_checkbox(WinOut *w, bool checked, int action, const char *name, const char *desc, const float *cost);
+/* windowAddSimpleButton: an icon and a text in a small button (residents, workers...) */
+bool win_simple_button(WinOut *w, uint16_t icon, const char *text, int action);
+bool win_small_button(WinOut *w, int x, int wd, int h, int action); /* focusable, drawn by the caller */
+void win_row_begin(WinOut *w);
+void win_row_end(WinOut *w);
+/* the bottom row: extra buttons on the left, Close (or another) on the right */
+void win_bottom(WinOut *w, const char *const *labels, const int *actions, int n, const char *close_label, int close_action);
+void win_bottom_tips(WinOut *w, const char *const *labels, const int *actions, const char *const *tips, int n,
+ const char *close_label, int close_action);
+void win_bottom_ex(WinOut *w, const char *const *labels, const int *actions, const char *const *tip_headers,
+ const char *const *tips, int n, const char *close_label, int close_action);
+#define ACT_CLOSE 900
+#define ACT_BACK 901
+#define ACT_DESTROY 902 /* a building window's Destroy (focused when it opens asking "Really Destroy?") */
+/* reserves an area of the content (graphs); returns its top-left on screen or false if not visible */
+bool win_area(WinOut *w, int width, int height, int *sx, int *sy);
+
+void win_open(int kind, uint16_t arg, uint16_t arg2); /* on top of the stack */
+void win_open_only(int kind, uint16_t arg, uint16_t arg2); /* clearWindowStack, then open */
+void win_close(void); /* goPreviousWindow */
+void win_close_all(void);
+bool win_action_rect(int action, int16_t r[4]); /* a button of the top window on screen (for the tutorial's arrows) */
+bool win_screen_rect(int16_t r[4]); /* the top window on screen */
+void win_replace(int kind, uint16_t arg, uint16_t arg2); /* in place of the top one */
+void win_pause(void); /* CityGUI.pauseForWindow */
+bool win_is_open(int kind);
+void win_draw(void);
+void win_draw_tip(void); /* the top window's tooltip (after the help arrows) */
+void win_input(void); /* keys while a window is open */
+const char *win_kind_title(Win *wn, char *buf, int size);
+
+/* the windows' contents and actions, by kind (ui_bwin.c, ui_info.c, ui_story.c, ui_menu.c) */
+typedef struct {
+ void (*content)(WinOut *w);
+ void (*action)(Win *wn, int action);
+ uint8_t flags; /* WD_* */
+} WinDef;
+/* WD_TOP: WindowPosition.Top; WD_OWN_CLOSE: closing goes to the window's action (as ACT_CLOSE or ACT_BACK) */
+enum { WD_OPAQUE = 1, WD_PAUSE = 2, WD_NO_CLOSE_BUTTON = 4, WD_TOP = 8, WD_OWN_CLOSE = 16 };
+extern const WinDef windefs[WK_COUNT];
+void bwin_content(WinOut *w);
+void bwin_action(Win *wn, int a);
+void cwin_content(WinOut *w);
+void cwin_action(Win *wn, int a);
+void flist_content(WinOut *w);
+void flist_action(Win *wn, int a);
+void destroy_content(WinOut *w);
+void destroy_action(Win *wn, int a);
+void replace_content(WinOut *w);
+void replace_action(Win *wn, int a);
+void replace_to_content(WinOut *w);
+void replace_to_action(Win *wn, int a);
+void city_name_content(WinOut *w);
+void city_name_action(Win *wn, int a);
+void color_content(WinOut *w);
+void color_action(Win *wn, int a);
+void info_material(WinOut *w);
+void info_population(WinOut *w);
+void info_population_action(Win *wn, int a);
+void info_happiness(WinOut *w);
+void info_happiness_action(Win *wn, int a);
+void info_houses(WinOut *w);
+void info_houses_action(Win *wn, int a);
+void info_workers(WinOut *w);
+void info_workers_action(Win *wn, int a);
+void info_birth(WinOut *w);
+void info_birth_action(Win *wn, int a);
+void info_entertainment(WinOut *w);
+void info_find(WinOut *w);
+void info_find_action(Win *wn, int a);
+void info_upgrades(WinOut *w);
+void info_upgrades_action(Win *wn, int a);
+void info_invite(WinOut *w);
+void info_invite_action(Win *wn, int a);
+void story_goal_content(WinOut *w);
+void story_goal_action(Win *wn, int a);
+void story_missions_content(WinOut *w);
+void menu_game_content(WinOut *w);
+void menu_game_action(Win *wn, int a);
+void menu_restart_content(WinOut *w);
+void menu_restart_action(Win *wn, int a);
+void menu_scenarios_content(WinOut *w);
+void menu_scenarios_action(Win *wn, int a);
+void menu_free_play_content(WinOut *w);
+void menu_free_play_action(Win *wn, int a);
+void menu_credits_content(WinOut *w);
+void text_content(WinOut *w);
+/* the colour picker and typing (ui_pick.c): the picker for a decoration (arg: its permanent) or for the build
+ * menu's any-colour look (arg: the class); typing a text (TX_*: the city's name, a colour code) */
+enum { COLOR_FOR_BUILDING, COLOR_FOR_BUILDER };
+enum { TX_CITY_NAME, TX_COLOR_CODE };
+extern int32_t color_picked, color_picked_on_menu_open;
+void color_picker_open(int target, uint16_t arg);
+void text_window_open(int which);
+bool pick_keys(Win *wn);
+/* WK_TEXT windows: a title and a text that last (flash, or ui_text_buf) */
+void win_open_text(const char *title, const char *text);
+extern char ui_text_buf[200]; /* a text made at run time for a simple window or a notification */
+
+/* ---------------------------------------------------------------- the city screen (ui_city.c) */
+enum { Z_CITY, Z_BUILD, Z_PANEL };
+typedef struct {
+ int16_t cx, cy; /* the cursor: its cell's top-left (city pixels) */
+ uint8_t zone; /* Z_* where the arrows go when no window is open */
+ int8_t category; /* the build menu's shown category, -1 none */
+ int8_t bfocus; /* build menu focus: -1 the category row, else the shown buttons' index */
+ int8_t cfocus; /* the focused category button */
+ int8_t pfocus; /* the panel's focused button */
+ bool panel_hidden; /* the hide-UI toggle */
+ bool modes_open; /* all the building modes shown */
+ bool mgmt_open; /* the management options shown */
+ /* the builder */
+ int8_t build_kind; /* BK_* */
+ uint8_t build_cls; /* a class, a decoration or a world resource */
+ uint8_t build_decor; /* a decoration's look (as_multi_decor) */
+ bool build_mirror; /* the builder's mirroring (Builder.mirrored) */
+ int32_t build_color; /* the builder's colour (decorationAppearanceColor), -1 none */
+ bool mirrored;
+ uint8_t speed; /* simulationSpeedChosen */
+ uint16_t highlight_cls; /* FindBuildingsOfType: the class highlighted + 1 */
+ uint16_t following; /* the citizen followed (FollowingCitizen), 0 none */
+ uint16_t selected; /* the permanent whose window is open (spr_selectedbuilding) */
+ float gui_timer; /* GUI.guiTimer */
+} CityUi;
+extern CityUi cu;
+enum { BK_NONE, BK_BUILDING, BK_DECORATION, BK_RESOURCE, BK_MOVE }; /* BK_MOVE: explored alien ruins (moving_resource) */
+extern uint16_t moving_resource;
+void city_ui_reset(void);
+void city_input(void);
+void city_draw_overlay(void); /* in the city's layer: cursor, builder, highlights */
+void city_draw_ui(void); /* panel and build menu */
+void city_draw_tips(void); /* their tooltips, and the builder's */
+void builder_start(int kind, int index, int decor);
+void builder_start_ex(int kind, int index, int decor, bool mirror, int32_t color);
+void builder_stop(void);
+void camera_follow(float x, float y); /* centre the view there (FollowingCitizen) */
+void camera_clamp_view(void);
+/* the cursor's cell: its world, column and row (-1 when on no world) */
+int cursor_cell(int *col, int *row);
+void cursor_to(int x, int y);
+bool city_panel_rect(int which, int16_t r[4]); /* tutorial arrows: a panel button's rectangle */
+bool city_build_rect(int which, int16_t r[4]); /* tutorial arrows: a build menu button's rectangle */
+enum { PR_HELP, PR_PAUSE, PR_SPEED, PR_MENU, PR_HIDE, PR_POP, PR_HAPPY, PR_HOUSES, PR_WORK, PR_MAT0 };
+enum { BR_FIRST_CATEGORY, BR_LAST_BUILDING, BR_SECOND_LAST_BUILDING, BR_INVITE, BR_MANAGEMENT };
+extern const float simulation_speeds[5];
+
+/* ---------------------------------------------------------------- story overlays (ui_story.c) */
+void story_ui_reset(void);
+void story_ui_tick(void);
+void story_ui_draw_help(void); /* the tutorial's help arrows (gameHelpStage) */
+void story_ui_draw_notes(void); /* the top notification (notificationStage, over everything) */
+bool story_has_quick_text(void);
+void notify_top(const char *text, const char *title, int time); /* GUI.notify (TopScreenNotification) */
+/* the goal text with the inline commands handled ([n], [c], [mobi]...): into buf */
+const char *goal_text(int goal, char *buf, int size);
+extern uint8_t tut_flags; /* tutorial arrows' remembered steps (TF_*) */
+enum { TF_HELP_USED = 1, TF_SPEED_USED = 2, TF_PRIO = 4, TF_WINDOW_CLOSED = 8, TF_EVER_PRIO = 16 };
+extern int16_t tut_close_warning; /* showWindowCloseWarning's countdown */
+
+/* ---------------------------------------------------------------- menus and saves (ui_menu.c) */
+typedef struct {
+ uint8_t won; /* bits: scenarios won */
+ int32_t best[4]; /* their best times (minutes) */
+} Meta;
+extern Meta meta;
+void meta_load(void);
+void title_open(void); /* the title screen (the display city, the title, its buttons) */
+void title_input(void);
+void title_draw(void);
+void menu_new_city(int story); /* createNewGameState */
+bool ui_save(bool tell); /* save_game; tells the player when it fails */
+bool ui_home(void); /* Home: saves; true when the game may quit */
+void autosave_tick(void);
+bool story_requirements(int s); /* progress.StoryLoader.hasCompletedRequirements */
+
+/* ---------------------------------------------------------------- shared state (ui.c) */
+typedef struct {
+ bool title; /* the title screen is shown */
+ bool setup; /* a free play city is being set up (its options window over it) */
+ bool paused_for_window;
+ float autosave_timer; /* seconds since the last save (handleAutoSave) */
+ float seconds_since_save;
+ uint8_t save_failed; /* the last save failed: a window says so */
+ bool home_unsaved; /* Home's save failed: its window is open (Home again quits) */
+} UiState;
+extern UiState ui;
+/* the class's texts and look in the build menu (lang_data.c) */
+static inline const char *cls_title(int c) { return cls_text[c].name; }
+#endif
diff --git a/games/finalearth2/src/unlocks.c b/games/finalearth2/src/unlocks.c
new file mode 100644
index 00000000..a2fbf02b
--- /dev/null
+++ b/games/finalearth2/src/unlocks.c
@@ -0,0 +1,216 @@
+/* The Final Earth 2: what can be built and bought (progress.Unlocks).
+ *
+ * Every building, world resource, building upgrade, city upgrade and policy
+ * is Locked, Unlocked (shown, may need a hint's condition, or research),
+ * Createable (its condition met) or Researched (its knowledge price paid, or
+ * none). Building more of some buildings, and reaching some numbers, unlocks
+ * others. */
+#include "bld.h"
+#include "build.h"
+#include "unlocks.h"
+#include "upgrades.h"
+
+Unlocks unlocks;
+
+/* the unified number of a class (its pcls index) or an upgrade (after the classes) */
+static int uid_of_name(const char *name) {
+ int c = pcls_find(name);
+ if (c >= 0) return c;
+ int u = upgrade_find(name);
+ return u >= 0 ? npcls + u : -1;
+}
+static uint8_t info_flags(int uid) { return uid < npcls ? pcls[uid].unlockFlags : upgrade_info[uid - npcls].unlockFlags; }
+static float info_knowledge(int uid) { return uid < npcls ? pcls[uid].cost[M_KNOWLEDGE] : upgrade_info[uid - npcls].cost[M_KNOWLEDGE]; }
+static bool is_building_uid(int uid) { return uid < npcls && pcls[uid].kind == KIND_BUILDING; }
+
+void unlocks_init(void) {
+ memset(&unlocks, 0, sizeof unlocks);
+ unlocks.unlockedManagementOptions = unlocks.unlockedBuildingModeButton = unlocks.unlockedDecorationTab = true;
+ for (int i = 0; i < npcls; i++) {
+ bool def = pcls[i].unlockFlags & UF_DEFAULT;
+ if (pcls[i].kind == KIND_RESOURCE) unlocks.state[i] = def ? UNLOCK_UNLOCKED : UNLOCK_LOCKED;
+ else unlocks.state[i] = def && pcls[i].cost[M_KNOWLEDGE] == 0 ? UNLOCK_RESEARCHED : def ? UNLOCK_UNLOCKED : UNLOCK_LOCKED;
+ }
+ for (int i = 0; i < nupgrades; i++) {
+ const UpgradeInfo *u = &upgrade_info[i];
+ bool def = u->unlockFlags & UF_DEFAULT;
+ if (u->kind == UK_BUILDING_UPGRADE || u->kind == UK_BUILDING_MODE)
+ unlocks.state[npcls + i] = def && u->cost[M_KNOWLEDGE] == 0 ? UNLOCK_RESEARCHED : def ? UNLOCK_UNLOCKED : UNLOCK_LOCKED;
+ else
+ unlocks.state[npcls + i] = def ? UNLOCK_UNLOCKED : UNLOCK_LOCKED;
+ }
+}
+
+int unlock_state_uid(int uid) { return uid >= 0 ? unlocks.state[uid] : UNLOCK_LOCKED; }
+int unlock_state(int cls) { return unlocks.state[cls]; }
+int unlock_state_name(const char *name) { return unlock_state_uid(uid_of_name(name)); }
+
+static void notify(int uid) {
+ unlocks.notify[uid >> 3] |= (uint8_t)(1 << (uid & 7));
+ if (uid < npcls) unlocks.notifyCategory |= (uint16_t)(1 << pcls[uid].category);
+}
+
+void unlocks_lock_uid(int uid) {
+ if (uid < 0) return;
+ unlocks.state[uid] = UNLOCK_LOCKED;
+ unlocks.explicitlyLocked[uid >> 3] |= (uint8_t)(1 << (uid & 7));
+}
+/* unlock: true if it was locked */
+bool unlocks_unlock_uid(int uid) {
+ if (uid < 0 || unlocks.state[uid] != UNLOCK_LOCKED) return false;
+ uint8_t f = info_flags(uid);
+ bool researched = info_knowledge(uid) == 0 && (!is_building_uid(uid) || !(f & UF_HINT));
+ unlocks.state[uid] = researched ? UNLOCK_RESEARCHED : UNLOCK_UNLOCKED;
+ if (!(f & UF_HINT)) notify(uid);
+ unlocks_check_build_related();
+ return true;
+}
+void unlocks_remove_uid(int uid) {
+ if (uid >= 0) unlocks.state[uid] = UNLOCK_LOCKED;
+}
+void unlocks_fully_unlock_uid(int uid) {
+ if (uid >= 0 && unlocks.state[uid] == UNLOCK_UNLOCKED) {
+ unlocks.state[uid] = UNLOCK_CREATEABLE;
+ notify(uid);
+ }
+}
+void unlocks_research_uid(int uid) {
+ if (uid >= 0) unlocks.state[uid] = UNLOCK_RESEARCHED;
+}
+void unlocks_research(int cls) { unlocks_research_uid(cls); }
+bool unlocks_unlock(const char *name) { return unlocks_unlock_uid(uid_of_name(name)); }
+void unlocks_fully_unlock(const char *name) { unlocks_fully_unlock_uid(uid_of_name(name)); }
+void unlocks_lock(const char *name) { unlocks_lock_uid(uid_of_name(name)); }
+
+bool unlocks_should_notify(int uid) { return uid >= 0 && (unlocks.notify[uid >> 3] >> (uid & 7) & 1); }
+void unlocks_stop_notify(int uid) {
+ if (uid >= 0) unlocks.notify[uid >> 3] &= (uint8_t)~(1 << (uid & 7));
+}
+void unlocks_stop_all_notify(void) {
+ memset(unlocks.notify, 0, sizeof unlocks.notify);
+ unlocks.notifyCategory = 0;
+}
+
+void unlocks_check_build_related_soon(void) {
+ if (unlocks.checkIn <= 0) unlocks.checkIn = 60;
+}
+void unlocks_update(float timeMod) {
+ if (unlocks.checkIn > 0) {
+ unlocks.checkIn -= timeMod;
+ if (unlocks.checkIn <= 0) unlocks_check_build_related();
+ }
+}
+
+/* city.getAmountOfPermanentsPerType */
+static int count(const char *name) {
+ int c = pcls_find(name), n = 0;
+ if (c < 0) return 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == c) n++;
+ return n;
+}
+static bool researched_or_createable(const char *name) {
+ int s = unlock_state_name(name);
+ return s == UNLOCK_RESEARCHED || s == UNLOCK_CREATEABLE;
+}
+
+/* checkBuildRelatedUnlocks (the paid versions' and holidays' rules are left out) */
+void unlocks_check_build_related(void) {
+ if (unlocks.checking >= 4) return; /* an unlock in here checks again, as in the original (a few levels are plenty) */
+ unlocks.checking++;
+ int parks = count("Park"), labs = count("Laboratory"), gardens = count("BotanicalGardens");
+ if (parks >= 5) {
+ unlocks_unlock("BotanicalGardens");
+ if (parks >= 10 && labs >= 5) unlocks_fully_unlock("BotanicalGardens");
+ }
+ if (count("ModernArtMuseum") >= 3) unlocks_fully_unlock("ArtColony");
+ if (researched_or_createable("BotanicalGardens")) {
+ unlocks_unlock("EcoFarm");
+ if (gardens >= 10 && count("ExperimentalFarm") >= 1) unlocks_fully_unlock("EcoFarm");
+ if (gardens >= 50 && count("RefinedMetalFactory") >= 1) unlocks_unlock("BotanicalGardensDome");
+ }
+ int rmf = count("RefinedMetalFactory"), ccf = count("ComputerChipFactory");
+ if (labs >= 5 && rmf >= 1) unlocks_fully_unlock("ComputerResearchCenter");
+ if (count("ComputerResearchCenter") >= 1) unlocks_unlock("ComputerChipFactory");
+ if (count("MachinePartsFactory") >= 3) unlocks_fully_unlock("MechanicalHouse");
+ if (count("LivingResearchCenter") >= 1) {
+ unlocks_fully_unlock("CuttingEdgeHome");
+ unlocks_unlock("ParkPod");
+ unlocks_unlock("ComfortableCouch");
+ unlocks_unlock("SmartSpeaker");
+ }
+ if (ccf >= 1) {
+ unlocks_unlock("HackerHQ");
+ if (count("Arcade") >= 3) unlocks_fully_unlock("HackerHQ");
+ }
+ int pubs = count("Pub");
+ if (pubs >= 2) {
+ unlocks_unlock("Restaurant");
+ if (pubs >= 5) {
+ unlocks_fully_unlock("Restaurant");
+ unlocks_unlock("HerbGarden");
+ }
+ }
+ if (count("Restaurant") >= 2) unlocks_fully_unlock("HerbGarden");
+ int blossom = count("BlossomRestaurant");
+ if (blossom >= 2) {
+ unlocks_unlock("BlossomHut");
+ if (blossom >= 10) unlocks_fully_unlock("BlossomHut");
+ }
+ if (count("FarmByProductProcessor") >= 10 && gardens >= 200 && count("BlossomHut") >= 50) unlocks_unlock("TreeHuggerBase");
+ if (rmf >= 1 && count("StoneMine") >= 15 && count("StoneTeleporter") >= 3) unlocks_fully_unlock("StoneResearchCenter");
+ int mh = count("MechanicalHouse");
+ if ((mh >= 4 && rmf >= 3 && ccf >= 1) || count("ComputerResearchCenter") >= 1) {
+ unlocks_unlock("ExperimentationLab");
+ if ((mh >= 12 && rmf >= 10 && ccf >= 3) || count("ComputerResearchCenter") >= 1) unlocks_fully_unlock("ExperimentationLab");
+ }
+ if (count("TheMachine") >= 1 && count("FestivalHQ") >= 1) unlocks_unlock("FlowerPenthouse");
+ int fh = count("FarmHouse");
+ if (fh >= 20) {
+ unlocks_unlock("RedwoodTree");
+ if (fh >= 40) unlocks_fully_unlock("RedwoodTree");
+ }
+ if (count("School") >= 5) unlocks_unlock("Library");
+ if (count("StatueOfHappiness") >= 1) unlocks_unlock("Beacon");
+ if (unlock_state_name("BlossomHippieHQ") == UNLOCK_UNLOCKED && gardens >= 20) {
+ /* a stack of 20 botanical gardens */
+ int g = pcls_find("BotanicalGardens");
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED) || p->cls != g || (p->bottom && P(p->bottom)->cls == g)) continue;
+ int n = 1;
+ for (Perm *t = P(p->top); t && t->cls == g; t = P(t->top)) n++;
+ if (n >= 20) {
+ unlocks_fully_unlock("BlossomHippieHQ");
+ break;
+ }
+ }
+ }
+ if (count("LivingResearchCenter") >= 1 && count("ArtColony") >= 1 && count("ModernArtMuseum") >= 10) unlocks_unlock("Loft");
+ unlocks.checking--;
+}
+
+/* checkStatRelatedUnlocks (each time the stats are counted) */
+void unlocks_check_stat_related(void) {
+ if (stats.peopleWithHome >= 200) unlocks_fully_unlock("LivingResearchCenter");
+ if (ncits >= 200) unlocks_fully_unlock("HyperElevator");
+ if (happiness.happiness >= 99.99f) unlocks_unlock("StatueOfHappiness");
+ int tps = 0, works = 0;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ if (!(perms[i].flags & PF_USED)) continue;
+ if (is_a(&perms[i], B_TELEPORTER)) tps++;
+ if (is_a(&perms[i], B_WORK)) works++;
+ }
+ if (ncits >= 500 && tps > 1) unlocks_unlock("SecretSocietyHouse");
+ if (bonuses.fossilsCollected >= 5) unlocks_unlock("FossilMuseum");
+ if (ncits >= 750) unlocks_unlock("BlossomHippieHQ");
+ if (unlock_state_name("Beacon") == UNLOCK_UNLOCKED && happiness.fullHappinessTime >= 20160) unlocks_fully_unlock("Beacon");
+ if (ncits >= 100 && works > 1) unlocks_unlock("CityHall");
+}
+
+/* the materials shown once they matter (cacao, chocolate, graphene and rocket fuel are paid-version materials) */
+bool unlocks_material_shown(int m) {
+ return m == M_FOOD || m == M_WOOD || m == M_STONE || m == M_KNOWLEDGE || m == M_MACHINEPARTS || m == M_REFINEDMETAL ||
+ m == M_COMPUTERCHIPS || (unlocks.materials >> m & 1);
+}
+void unlocks_material(int m) { unlocks.materials |= (uint16_t)(1 << m); }
diff --git a/games/finalearth2/src/unlocks.h b/games/finalearth2/src/unlocks.h
new file mode 100644
index 00000000..58a96d09
--- /dev/null
+++ b/games/finalearth2/src/unlocks.h
@@ -0,0 +1,45 @@
+/* The Final Earth 2: unlocks (unlocks.c). A thing is a class (its pcls
+ * index) or an upgrade (npcls + its upgrade_info index). */
+#ifndef FE_UNLOCKS_H
+#define FE_UNLOCKS_H
+#include "fe.h"
+
+enum { UNLOCK_CREATEABLE = 3 }; /* after UNLOCK_LOCKED, UNLOCK_UNLOCKED, UNLOCK_RESEARCHED (build.h) */
+typedef struct {
+ uint8_t state[256];
+ uint8_t explicitlyLocked[32], notify[32]; /* bits */
+ uint16_t notifyCategory; /* bits of categories with something new */
+ uint16_t materials; /* bits of materials unlocked (unlockMaterial) */
+ float checkIn;
+ uint8_t checking;
+ bool unlockedManagementOptions, unlockedBuildingModeButton, unlockedDecorationTab;
+} Unlocks;
+extern Unlocks unlocks;
+
+typedef struct {
+ int fossilsCollected;
+ bool waldoFound;
+ /* simulation.BonusResults (bld_new_city sets them) */
+ float extraFoodFromFarms, machinePartsFactorySpeed, labSpeed, indoorFarmSpeed, ecoFarmSpeed;
+} Bonuses;
+extern Bonuses bonuses;
+
+void unlocks_init(void);
+int unlock_state_uid(int uid);
+int unlock_state_name(const char *name);
+bool unlocks_unlock(const char *name);
+void unlocks_fully_unlock(const char *name);
+void unlocks_lock(const char *name);
+bool unlocks_unlock_uid(int uid);
+void unlocks_fully_unlock_uid(int uid);
+void unlocks_lock_uid(int uid);
+void unlocks_remove_uid(int uid);
+void unlocks_research_uid(int uid);
+bool unlocks_should_notify(int uid);
+void unlocks_stop_notify(int uid);
+void unlocks_stop_all_notify(void);
+void unlocks_check_build_related_soon(void);
+void unlocks_update(float timeMod);
+bool unlocks_material_shown(int m);
+void unlocks_material(int m);
+#endif
diff --git a/games/finalearth2/src/upgrades.c b/games/finalearth2/src/upgrades.c
new file mode 100644
index 00000000..ca037eed
--- /dev/null
+++ b/games/finalearth2/src/upgrades.c
@@ -0,0 +1,409 @@
+/* The Final Earth 2: buying building upgrades and modes, research (city
+ * upgrades) and policies (BuildingUpgrade.js, gui.CreateBuildingUpgrades,
+ * gui.CreateCityUpgrades, gui.CreatePolicies, cityUpgrades.*, policies.*).
+ * A building keeps its upgrades as bits and its mode as a number (Perm.upgrades
+ * and Perm.mode, in its class's lists); the city keeps a bit per city upgrade
+ * bought and per policy on. What they change is read where it is used. */
+#include "bldi.h"
+
+CityUpgradesState city_upgrades;
+
+static inline int uid(int u) { return npcls + u; }
+static int ustate(int u) { return unlock_state_uid(uid(u)); }
+static bool bit(int u) { return city_upgrades.bought[u >> 5] >> (u & 31) & 1; }
+static void set_bit(int u, bool on) {
+ if (on) city_upgrades.bought[u >> 5] |= 1u << (u & 31);
+ else city_upgrades.bought[u >> 5] &= ~(1u << (u & 31));
+}
+bool city_upgrade_bought(int u) { return u >= 0 && u < U_COUNT && upgrade_info[u].kind == UK_CITY_UPGRADE && bit(u); }
+bool policy_on(int u) { return u >= 0 && u < U_COUNT && upgrade_info[u].kind == UK_POLICY && bit(u); }
+
+/* the place of upgrade u in p's class lists, -1 if not there */
+static int up_index(int cls, int u) {
+ for (int k = 0; k < 3; k++)
+ if (class_upgrades[cls].up[k] == u + 1) return k;
+ return -1;
+}
+static int mode_index(int cls, int u) {
+ for (int k = 0; k < 4; k++)
+ if (class_upgrades[cls].mode[k] == u + 1) return k;
+ return -1;
+}
+static bool has_modes(int cls) { return class_upgrades[cls].mode[0] != 0; }
+static int mode_upgrade(const Perm *p) {
+ return has_modes(p->cls) && p->mode < 4 && class_upgrades[p->cls].mode[p->mode] ? class_upgrades[p->cls].mode[p->mode] - 1 : -1;
+}
+bool upgrade_has(const Perm *p, int u) {
+ int k = up_index(p->cls, u);
+ if (k >= 0) return p->upgrades >> k & 1;
+ return mode_upgrade(p) == u;
+}
+static bool in_upgrades(const Perm *p, int u) {
+ int k = up_index(p->cls, u);
+ return k >= 0 && (p->upgrades >> k & 1);
+}
+
+/* Materials.fromBuildingUpgradesInfo, without knowledge once researched */
+static void price_of(int u, float out[M_COUNT]) {
+ memcpy(out, upgrade_info[u].cost, sizeof(float) * M_COUNT);
+ if (upgrade_info[u].kind <= UK_BUILDING_MODE && ustate(u) == UNLOCK_RESEARCHED) out[M_KNOWLEDGE] = 0;
+}
+static bool can_pay(const float m[M_COUNT]) { return mat_can_afford(m); }
+static void pay(const float m[M_COUNT]) { mat_pay(m); }
+
+/* availableTextures: the frames the player may see (the last ones only with the secret code "orchid") */
+static int available_looks(int u) {
+ const UpgradeInfo *ui = &upgrade_info[u];
+ return ui->frames - (bld_secret_orchid ? 0 : ui->lockedFrames);
+}
+
+/* ---------------------------------------------------------------- a building's upgrades and modes */
+/* the BuildingUpgrade constructor (and the upgrade's own) */
+void upgrade_add(Perm *p, int u) {
+ int k = up_index(p->cls, u);
+ if (k < 0 || (p->upgrades >> k & 1)) return;
+ p->upgrades |= (uint8_t)(1 << k);
+ p->bonusAttractiveness = (int8_t)(p->bonusAttractiveness + upgrade_info[u].bonusAttractiveness);
+ if (upgrade_info[u].sprite) {
+ int n = available_looks(u);
+ upgrade_set_look(p, u, n > 0 ? rnd_int(n) : 0);
+ }
+ if (u == U_FossilScanner) upgrades.stoneResearchCenterWithFossils = pid(p);
+ if (u == U_HeatedBed && PC(p)->ops && PC(p)->ops->on_city_change) PC(p)->ops->on_city_change(p);
+}
+void herb_garden_mode(Perm *p);
+void farmhouse_mode_set(Perm *p, int old_type, int type);
+static int farm_type(int mode) {
+ return mode == MODE_FarmHouse_CHProduceStone ? 0 : mode == MODE_FarmHouse_CHProduceWood ? 1 : 2;
+}
+/* the old mode's destroy, then the new one's constructor */
+void upgrade_set_mode(Perm *p, int u) {
+ int k = mode_index(p->cls, u);
+ if (k < 0) return;
+ int old = p->mode;
+ p->mode = (uint8_t)k;
+ if (p->cls == CLS_FarmHouse) farmhouse_mode_set(p, farm_type(old), farm_type(k));
+ else if (p->cls == CLS_HerbGarden) herb_garden_mode(p);
+ else if (u == U_RefinedMetalsFactoryHack && PC(p)->ops && PC(p)->ops->on_city_change) PC(p)->ops->on_city_change(p);
+}
+void upgrade_first_mode(Perm *p) { p->mode = 0; }
+
+void upgrade_change_look(Perm *p, int u) {
+ if (!upgrade_has(p, u) || upgrade_info[u].frames <= 1) return;
+ int n = available_looks(u), l = upgrade_look(p, u) + 1;
+ upgrade_set_look(p, u, l >= n ? 0 : l);
+}
+
+/* what a press does to one building (onUpgrade) */
+static void apply(Perm *p, int u) {
+ if (upgrade_info[u].kind == UK_BUILDING_MODE) upgrade_set_mode(p, u);
+ else upgrade_add(p, u);
+}
+/* CreateBuildingUpgrades.upgradeAll: every building of the exact class without it, while the city can pay */
+static void upgrade_all(const Perm *p, int u, const float price[M_COUNT]) {
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *q = &perms[i];
+ if (!(q->flags & PF_USED) || !is_building(q) || q->cls != p->cls) continue;
+ if (!in_upgrades(q, u) && mode_upgrade(q) != u && can_pay(price)) {
+ pay(price);
+ apply(q, u);
+ }
+ }
+}
+int upgrade_all_count(const Perm *p, int u, float total[M_COUNT], bool *can_afford_all) {
+ float price[M_COUNT], each[M_COUNT];
+ price_of(u, price);
+ memcpy(each, price, sizeof each);
+ each[M_KNOWLEDGE] = 0;
+ double have[M_COUNT];
+ for (int m = 0; m < M_COUNT; m++) have[m] = city.materials.m[m];
+ int num = 0;
+ bool all = true;
+ for (int i = 1; i < MAX_PERMS; i++) {
+ const Perm *q = &perms[i];
+ if (!(q->flags & PF_USED) || !is_building(q) || q->cls != p->cls || in_upgrades(q, u)) continue;
+ bool ok = true;
+ for (int m = 0; m < M_COUNT; m++)
+ if (have[m] < each[m]) ok = false;
+ if (ok) {
+ for (int m = 0; m < M_COUNT; m++) have[m] -= each[m];
+ num++;
+ } else {
+ all = false;
+ }
+ }
+ if (!all && num == 0) num = 1;
+ if (can_afford_all) *can_afford_all = all;
+ if (total) {
+ for (int m = 0; m < M_COUNT; m++) total[m] = num <= 1 ? price[m] : each[m] * num;
+ if (num > 1) total[M_KNOWLEDGE] = price[M_KNOWLEDGE];
+ }
+ return num;
+}
+
+/* ---------------------------------------------------------------- city upgrades (addToCity) and policies */
+static void city_upgrade_effect(int u, bool loading) {
+ switch (u) {
+ case U_BirthControl: upgrades.hasBirthControl = true; break;
+ case U_BuildingRecycling:
+ recycling_amount = upgrades.recyclingAmount = fmaxf(upgrades.recyclingAmount, 0.5f);
+ unlocks_unlock("BuildingRecycling2");
+ break;
+ case U_BuildingRecycling2:
+ recycling_amount = upgrades.recyclingAmount = fmaxf(upgrades.recyclingAmount, 0.75f);
+ unlocks_unlock("BuildingRecycling3");
+ break;
+ case U_BuildingRecycling3: recycling_amount = upgrades.recyclingAmount = fmaxf(upgrades.recyclingAmount, 0.9f); break;
+ case U_ChipBinning: upgrades.computerChipFactorySpeed *= 1.2f; break;
+ case U_OptimizedChipLayouts: upgrades.computerChipFactorySpeed *= 1.33f; break;
+ case U_EcoFarmUpgrade:
+ /* every eco farm standing gets the second plot's bonus (on load too: all of them then) */
+ upgrades.extraEcoFarmFoodToPlot1 = 4;
+ eco_farms_upgrade();
+ break;
+ case U_SlimyLiving: unlocks_unlock("LivingComputer"); break;
+ case U_UniverseMapping:
+ upgrades.stoneTeleporterChanceForRefinedMetals = 0.04f;
+ upgrades.stoneTeleporterHasBigStones = true;
+ upgrades.starDatabaseIsMoreEffective = true;
+ break;
+ case U_MedicalMachineLearning: upgrades.extendAgeBy += 0.05f; break;
+ case U_GeneEditing:
+ upgrades.hasGeneEditing = true;
+ unlocks_unlock("RedForest");
+ unlocks_unlock("PurpleForest");
+ break;
+ case U_LibraryAllowDuplicates: upgrades.hasGalacticLibrary = true; break;
+ case U_ConnectedMachines: upgrades.hasConnectedMachines = true; break;
+ default: break; /* the Living ones change their classes' quality and residents: upgrades_*_bonus */
+ }
+ (void)loading;
+}
+/* buildingInfo's quality and residents, as the city upgrades bought change them */
+int upgrades_quality_bonus(int cls) {
+ switch (cls) {
+ case CLS_ComfortableHouse: return bit(U_WoodenLiving) ? 10 : 0;
+ case CLS_SpaciousHouse: return bit(U_SpaciousLiving) ? 15 : 0;
+ case CLS_AlienHouse: return bit(U_SlimyLiving) ? 25 : 0;
+ case CLS_SecretSocietyHouse: return bit(U_SecretiveLiving) ? 25 : 0;
+ default: return 0;
+ }
+}
+int upgrades_residents_bonus(int cls) {
+ switch (cls) {
+ case CLS_MechanicalHouse: case CLS_TinkerersHome: return bit(U_MechanicalLiving) ? 1 : 0;
+ case CLS_SpaciousHouse: return bit(U_SuperSpaciousLiving) ? 1 : 0;
+ default: return 0;
+ }
+}
+/* SmallerClasses: the students beyond a school's new capacity leave, the last ones first */
+static void schools_trim(void) {
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *s = &perms[i];
+ if (!(s->flags & PF_USED) || !is_a(s, B_SCHOOL)) continue;
+ for (int c = MAX_CITS - 1; c >= 1 && s->nstudents > bld_student_capacity(s); c--)
+ if ((cits[c].flags & CF_ALIVE) && cits[c].school == i) cit_leave_school(&cits[c]);
+ }
+}
+static void policy_effect(int u, bool on) {
+ switch (u) {
+ case U_FoodRationing: eating.foodRationing = on; break;
+ case U_SmallerClasses:
+ policies.schoolClassSizeMod = on ? 0.6666667f : 1;
+ policies.schoolMaxEdu = on ? 1.15f : 1;
+ sim_flags |= SIM_SCHOOLS_CHANGED;
+ if (on) schools_trim();
+ break;
+ case U_MandatoryOvertime: policies.workTimeChange = on ? 2 : 0; break;
+ }
+}
+
+/* ---------------------------------------------------------------- pressing a window's button */
+bool upgrade_press(Perm *p, int u, bool all) {
+ if (u < 0 || u >= U_COUNT) return false;
+ const UpgradeInfo *ui = &upgrade_info[u];
+ float price[M_COUNT];
+ if (ui->kind == UK_CITY_UPGRADE) {
+ if (bit(u) || ustate(u) != UNLOCK_UNLOCKED || !can_pay(ui->cost)) return false;
+ pay(ui->cost);
+ set_bit(u, true);
+ city_upgrade_effect(u, false);
+ sim_flags |= SIM_HOUSES_CHANGED;
+ return true;
+ }
+ if (ui->kind == UK_POLICY) {
+ if (bit(u)) {
+ set_bit(u, false);
+ policy_effect(u, false);
+ sim_flags |= SIM_HOUSES_CHANGED;
+ return true;
+ }
+ if (!can_pay(ui->cost)) return false;
+ pay(ui->cost);
+ set_bit(u, true);
+ policy_effect(u, true);
+ return true;
+ }
+ /* a building upgrade or mode (addUpgradeButton) */
+ if (!p || (up_index(p->cls, u) < 0 && mode_index(p->cls, u) < 0)) return false;
+ price_of(u, price);
+ if (!can_pay(price)) return false;
+ if (!upgrade_has(p, u)) {
+ pay(price);
+ apply(p, u);
+ }
+ sim_flags |= SIM_HOUSES_CHANGED;
+ unlocks_research_uid(uid(u));
+ price[M_KNOWLEDGE] = 0;
+ if (all) upgrade_all(p, u, price);
+ return true;
+}
+/* the modes' "all" chosen: this building's mode for all of its class (onAllButtonSelect) */
+void upgrade_mode_to_all(Perm *p) {
+ int u = mode_upgrade(p);
+ if (u < 0) return;
+ float price[M_COUNT];
+ memcpy(price, upgrade_info[u].cost, sizeof price);
+ price[M_KNOWLEDGE] = 0;
+ upgrade_all(p, u, price);
+}
+
+/* ---------------------------------------------------------------- what the window lists */
+static void option(UpgradeOption *o, int kind, int u, bool owned) {
+ const UpgradeInfo *ui = &upgrade_info[u];
+ o->kind = (uint8_t)kind;
+ o->upgrade = (uint8_t)u;
+ o->owned = owned;
+ o->title = ui->title;
+ o->text = ui->text;
+ if (kind == UO_CITY || kind == UO_POLICY) memcpy(o->price, ui->cost, sizeof o->price);
+ else price_of(u, o->price);
+ o->affordable = can_pay(o->price);
+ o->canChangeLook = false;
+}
+int upgrade_options(const Perm *p, UpgradeOption *out, int max) {
+ if (!p || p->cls >= CLS_COUNT) return 0;
+ const ClassUpgrades *cu = &class_upgrades[p->cls];
+ int n = 0;
+ for (int k = 0; k < 3 && cu->up[k] && n < max; k++) {
+ int u = cu->up[k] - 1;
+ if (ustate(u) == UNLOCK_LOCKED) continue;
+ bool owned = p->upgrades >> k & 1;
+ option(&out[n], UO_UPGRADE, u, owned);
+ out[n].canChangeLook = owned && upgrade_info[u].frames > 1;
+ n++;
+ }
+ for (int k = 0; k < 4 && cu->mode[k] && n < max; k++) {
+ int u = cu->mode[k] - 1;
+ if (ustate(u) == UNLOCK_LOCKED) continue;
+ option(&out[n++], UO_MODE, u, p->mode == k);
+ }
+ /* city upgrades: those exactly Unlocked; a chain shows only its newest step */
+ for (int k = 0; k < 6 && cu->city[k] && n < max; k++) {
+ int u = cu->city[k] - 1;
+ const UpgradeInfo *ui = &upgrade_info[u];
+ if (ustate(u) != UNLOCK_UNLOCKED) continue;
+ if (ui->next != 0xFF && ustate(ui->next) != UNLOCK_LOCKED) continue;
+ option(&out[n], UO_CITY, u, bit(u));
+ if (bit(u) && ui->next == 0xFF) {
+ if (ui->titleDone) out[n].title = ui->titleDone;
+ if (ui->textDone) out[n].text = ui->textDone;
+ }
+ n++;
+ }
+ for (int k = 0; k < 3 && cu->pol[k] && n < max; k++) {
+ int u = cu->pol[k] - 1;
+ if (ustate(u) != UNLOCK_UNLOCKED) continue;
+ option(&out[n++], UO_POLICY, u, bit(u));
+ }
+ return n;
+}
+
+/* ---------------------------------------------------------------- the labs' smart upgrade */
+static bool next_to_plantation(const Perm *p) {
+ const uint16_t nb[4] = {p->left, p->right, p->top, p->bottom};
+ for (int i = 0; i < 4; i++)
+ if (P(nb[i]) && P(nb[i])->cls == CLS_TreePlantation) return true;
+ return false;
+}
+static bool lab_wants(const Perm *p, int which) {
+ if (!(p->flags & PF_USED) || p->cls != CLS_Laboratory) return false;
+ if (which == 0) return adj_effect(p, EF_FARM) > 0 && !(p->upgrades >> UB_Laboratory_FarmingResearch & 1);
+ return next_to_plantation(p) && !(p->upgrades >> UB_Laboratory_TreePlantationResearch & 1);
+}
+bool upgrade_smart_labs_price(float price[M_COUNT]) {
+ int n[2] = {0, 0};
+ for (int i = 1; i < MAX_PERMS; i++)
+ for (int w = 0; w < 2; w++)
+ if (lab_wants(&perms[i], w)) n[w]++;
+ memset(price, 0, sizeof(float) * M_COUNT);
+ const int us[2] = {U_FarmingResearch, U_TreePlantationResearch};
+ for (int w = 0; w < 2; w++) {
+ const float *c = upgrade_info[us[w]].cost;
+ for (int m = 0; m < M_COUNT; m++) {
+ float v = c[m] * n[w];
+ if (m == M_KNOWLEDGE) v = ustate(us[w]) == UNLOCK_RESEARCHED ? 0 : fminf(v, c[m]);
+ price[m] += v;
+ }
+ }
+ return n[0] + n[1] > 0;
+}
+bool upgrade_smart_labs_buy(void) {
+ float price[M_COUNT];
+ if (!upgrade_smart_labs_price(price) || !can_pay(price)) return false;
+ pay(price);
+ /* (the lists are made before any lab changes) */
+ uint8_t want[(MAX_PERMS + 7) / 8 * 2];
+ memset(want, 0, sizeof want);
+ for (int i = 1; i < MAX_PERMS; i++)
+ for (int w = 0; w < 2; w++)
+ if (lab_wants(&perms[i], w)) want[w * ((MAX_PERMS + 7) / 8) + (i >> 3)] |= (uint8_t)(1 << (i & 7));
+ for (int w = 0; w < 2; w++)
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (want[w * ((MAX_PERMS + 7) / 8) + (i >> 3)] >> (i & 7) & 1) upgrade_add(&perms[i], w ? U_TreePlantationResearch : U_FarmingResearch);
+ unlocks_research_uid(uid(U_FarmingResearch));
+ unlocks_research_uid(uid(U_TreePlantationResearch));
+ return true;
+}
+
+/* ---------------------------------------------------------------- the building's recycle reward and the story */
+/* each owned upgrade's info cost (not modes); give_recycle_reward drops knowledge and scales it */
+void building_upgrades_cost_sum(const Perm *p, Materials *m) {
+ if (!p || p->cls >= CLS_COUNT) return;
+ const ClassUpgrades *cu = &class_upgrades[p->cls];
+ for (int k = 0; k < 3 && cu->up[k]; k++)
+ if (p->upgrades >> k & 1)
+ for (int i = 0; i < M_COUNT; i++) m->m[i] += upgrade_info[cu->up[k] - 1].cost[i];
+}
+/* the story's questions: buildings that have a building upgrade, and whether a city upgrade was bought */
+int upgrades_buildings_with(const char *name) {
+ int u = upgrade_find(name), n = 0;
+ if (u < 0) return 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_building(&perms[i]) && in_upgrades(&perms[i], u)) n++;
+ return n;
+}
+bool upgrades_city_bought(const char *name) {
+ int u = upgrade_find(name);
+ return u >= 0 && bit(u);
+}
+
+/* ---------------------------------------------------------------- start and load */
+void upgrades_new_city(void) { memset(&city_upgrades, 0, sizeof city_upgrades); }
+/* CityUpgrades.load and Policies.load add each one again on fresh variables: the city upgrades' variables go
+ * back to their defaults and each effect is made again (the old saves' SlimyLiving fix is for version 11
+ * saves, never ours) */
+void upgrades_after_load(void) {
+ upgrades.computerChipFactorySpeed = 1;
+ upgrades.recyclingAmount = 0;
+ upgrades.hasBirthControl = upgrades.starDatabaseIsMoreEffective = upgrades.stoneTeleporterHasBigStones = false;
+ upgrades.hasGalacticLibrary = upgrades.hasConnectedMachines = upgrades.hasGeneEditing = false;
+ upgrades.stoneTeleporterChanceForRefinedMetals = upgrades.extraEcoFarmFoodToPlot1 = upgrades.extraEcoFarmFoodToPlot2 = 0;
+ upgrades.extendAgeBy = 0;
+ recycling_amount = 0;
+ for (int u = 0; u < U_COUNT; u++) {
+ if (!bit(u)) continue;
+ if (upgrade_info[u].kind == UK_CITY_UPGRADE) city_upgrade_effect(u, true);
+ else if (upgrade_info[u].kind == UK_POLICY) policy_effect(u, true);
+ }
+}
diff --git a/games/finalearth2/src/upgrades.h b/games/finalearth2/src/upgrades.h
new file mode 100644
index 00000000..a6e6e84e
--- /dev/null
+++ b/games/finalearth2/src/upgrades.h
@@ -0,0 +1,86 @@
+/* The Final Earth 2: building upgrades and modes, city upgrades (research)
+ * and policies: their table (upgrades_data.c, made by tools/gen_upgrades.py
+ * from buildingUpgradesInfo.json, cityUpgradesInfo.json and policiesInfo.json)
+ * and buying them (upgrades.c). What they do is in the buildings' own code
+ * (bld_*.c), which reads the bits and modes kept in each building. */
+#ifndef FE_UPGRADES_H
+#define FE_UPGRADES_H
+#include "fe.h"
+#include "upgrades_data.h"
+
+enum { UK_BUILDING_UPGRADE, UK_BUILDING_MODE, UK_CITY_UPGRADE, UK_POLICY };
+typedef struct {
+ const char *name; /* the original's class name */
+ const char *title, *text; /* its name and description (lang_en.csv) */
+ const char *titleDone, *textDone; /* city upgrades: shown instead once bought (nameIfNotDone...) */
+ uint8_t kind; /* UK_* */
+ uint8_t unlockFlags; /* UF_* (pcls.h) */
+ int8_t layer; /* the layer its sprite is drawn on (LAYER_*), -1 none */
+ uint8_t frames; /* frames of its sprite (the player may pick one), 0 none */
+ uint8_t lockedFrames; /* the last frames, shown only after the secret code "orchid" */
+ int8_t bonusAttractiveness;
+ uint8_t noCache; /* drawn after the building's other sprites of its layer */
+ uint8_t next; /* city upgrades: the next step of its chain, 0xFF none */
+ uint16_t sprite; /* SPR_* */
+ float cost[M_COUNT]; /* knowledge only until researched */
+} UpgradeInfo;
+
+extern const UpgradeInfo upgrade_info[];
+extern const int nupgrades;
+int upgrade_find(const char *name); /* -1 if unknown */
+
+/* what a class offers in its window: upgrade_info indexes + 1, 0 ends the list */
+typedef struct { uint8_t up[3], mode[4], city[6], pol[3]; } ClassUpgrades;
+extern const ClassUpgrades class_upgrades[];
+
+/* ---------------------------------------------------------------- the user interface's view (upgrades.c)
+ * A building's window lists, in this order, its upgrades, its modes, the
+ * city upgrades it offers, then the policies it offers. Each entry: */
+enum { UO_UPGRADE, UO_MODE, UO_CITY, UO_POLICY };
+typedef struct {
+ uint8_t kind; /* UO_* */
+ uint8_t upgrade; /* index in upgrade_info */
+ bool owned; /* bought (an upgrade, a city upgrade), the current mode, or the policy is on */
+ bool affordable; /* the city can pay price now */
+ bool canChangeLook; /* owned and with several sprites: "change_variant" (upgrade_change_look) */
+ const char *title, *text; /* in the original's words (a bought chain step shows its titleDone) */
+ float price[M_COUNT]; /* for this building (knowledge only while not researched) */
+} UpgradeOption;
+/* the options of p's window (at most max); returns how many */
+int upgrade_options(const Perm *p, UpgradeOption *out, int max);
+/* the "all" button: how many buildings of p's class the option would be bought for, and its total price
+ * (gui.CreateBuildingUpgrades.getUpgradeAllNumberAndCanAfford) */
+int upgrade_all_count(const Perm *p, int upgrade, float total[M_COUNT], bool *can_afford_all);
+/* presses an option's button: buys it (or switches the mode, buys the research, toggles the policy);
+ * all: the window's "all" button is on, so every building of its class gets it too. False if it could not
+ * be paid */
+bool upgrade_press(Perm *p, int upgrade, bool all);
+/* the "all" button pressed while the modes' "all" is selected: p's mode for every building of its class */
+void upgrade_mode_to_all(Perm *p);
+void upgrade_change_look(Perm *p, int upgrade); /* the next frame of an owned upgrade's sprite */
+/* the labs' smart upgrade (gui.GlobalUpgradeWindow.addSmartUpgradeForLabs): what it would cost, whether there
+ * is anything to buy, and buying it */
+bool upgrade_smart_labs_price(float price[M_COUNT]);
+bool upgrade_smart_labs_buy(void);
+
+/* ---------------------------------------------------------------- state */
+bool upgrade_has(const Perm *p, int upgrade); /* a building's upgrade or current mode */
+bool city_upgrade_bought(int upgrade);
+bool policy_on(int upgrade);
+/* buys a building upgrade for p without paying (story actions, the load quirk) */
+void upgrade_add(Perm *p, int upgrade);
+/* p's mode becomes upgrade (its old one goes first) */
+void upgrade_set_mode(Perm *p, int upgrade);
+void upgrade_first_mode(Perm *p); /* the Building constructor's first mode */
+/* each class's per-city changes (city upgrades on buildingInfo): quality and residents */
+int upgrades_quality_bonus(int cls);
+int upgrades_residents_bonus(int cls);
+/* city upgrades bought and policies on, as bits of upgrade_info indexes (saved) */
+#define UPG_WORDS ((U_COUNT + 31) / 32)
+typedef struct {
+ uint32_t bought[UPG_WORDS];
+} CityUpgradesState;
+extern CityUpgradesState city_upgrades;
+void upgrades_new_city(void);
+void upgrades_after_load(void); /* CityUpgrades.load: their effects again (and its quirk) */
+#endif
diff --git a/games/finalearth2/src/upgrades_data.c b/games/finalearth2/src/upgrades_data.c
new file mode 100644
index 00000000..f1e69f41
--- /dev/null
+++ b/games/finalearth2/src/upgrades_data.c
@@ -0,0 +1,126 @@
+/* The Final Earth 2: building upgrades and modes, city upgrades and policies, made by tools/gen_upgrades.py
+ * from the original's buildingUpgradesInfo.json, cityUpgradesInfo.json, policiesInfo.json, classes and
+ * lang_en.csv. Don't edit: edit the generator. */
+#include "upgrades.h"
+#include "classes.h"
+#include "data.h"
+#include "pcls.h"
+
+const UpgradeInfo upgrade_info[] = {
+ {.name = "Flowers", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Flowers", .text = "Flowers improve the happiness of residents. Improves housing quality by 5.", .cost = {[M_FOOD] = 1, [M_WOOD] = 2}, .layer = LAYER_MID, .sprite = SPR_UPGRADE_FLOWERS, .frames = 3, .bonusAttractiveness = 5, .next = 255},
+ {.name = "MachinePartsFactoryEfficiency", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Scrap Metal Recycling", .text = "Two stone is now used to make a machine part instead of three.", .cost = {[M_STONE] = 5, [M_MACHINEPARTS] = 10, [M_KNOWLEDGE] = 20}, .layer = -1, .next = 255},
+ {.name = "StoneUsingFactoryDisabled", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Disable Factory", .text = "The factory will fully halt production and not use any stone.", .layer = -1, .next = 255},
+ {.name = "RefinedStoneUsingFactoryDisabled", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Disable Factory", .text = "The factory will fully halt production and not use any refined metals.", .layer = -1, .next = 255},
+ {.name = "MachinePartsFactoryTurbo", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Turbo Boost", .text = "The factory will work twice as fast, but also use two more stone per machine part.", .cost = {[M_KNOWLEDGE] = 10}, .layer = -1, .next = 255},
+ {.name = "CensusData", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Census Data", .text = "Workers produce a small amount of knowledge based on the number of citizens.", .layer = -1, .next = 255},
+ {.name = "NightMayor", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Night Mayor", .text = "Nightclubs have 2 more capacity per worker here.", .layer = -1, .next = 255},
+ {.name = "RefinedMetalsFactoryHack", .kind = UK_BUILDING_MODE, .unlockFlags = 0, .title = "Firmware Modding", .text = "The factory will work 50% faster, but also use one more stone per unit of refined metal produced.", .cost = {[M_KNOWLEDGE] = 1337}, .layer = -1, .next = 255},
+ {.name = "FactoryWorking", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Enable Factory", .text = "The factory will work normally.", .layer = -1, .next = 255},
+ {.name = "LabWorking", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Enable Lab", .text = "The lab will work normally.", .layer = -1, .next = 255},
+ {.name = "LabDisabled", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Disable Lab", .text = "The lab will not use any machine parts nor produce knowledge. It can still boost Refined Metal Factories.", .layer = -1, .next = 255},
+ {.name = "FarmingResearch", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Genetic Crop Engineering", .text = "Crops of adjacent farms produce 7 more food per harvest.", .cost = {[M_WOOD] = 30, [M_MACHINEPARTS] = 10, [M_KNOWLEDGE] = 30}, .layer = LAYER_MID, .sprite = SPR_UPGRADE_FARMBOOST, .frames = 1, .next = 255},
+ {.name = "TreePlantationResearch", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Tree Growth Gas", .text = "Trees in adjacent tree plantations grow 20% faster.", .cost = {[M_WOOD] = 10, [M_MACHINEPARTS] = 20, [M_KNOWLEDGE] = 70}, .layer = LAYER_MAIN, .sprite = SPR_TREEGROWTHBOOST, .frames = 1, .next = 255},
+ {.name = "BetterPickaxes", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Better Pickaxes", .text = "Use better pickaxes to improve mining speed by 20%.", .cost = {[M_WOOD] = 3, [M_STONE] = 3, [M_KNOWLEDGE] = 3}, .layer = LAYER_BG, .sprite = SPR_IMPROVEDPICKAXES, .frames = 1, .next = 255},
+ {.name = "AIMining", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "AI-assisted Mining", .text = "Use a computer system to improve mining speed by 30%.", .cost = {[M_COMPUTERCHIPS] = 10, [M_KNOWLEDGE] = 1500}, .layer = LAYER_BG, .sprite = SPR_AIMINING, .frames = 1, .next = 255},
+ {.name = "DieShrink", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Die Shrink", .text = "The factory will work 50% faster and use two less units of refined metals per computer chip.", .cost = {[M_MACHINEPARTS] = 50, [M_REFINEDMETAL] = 10, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 1000}, .layer = LAYER_MID, .sprite = SPR_DIESHRINK, .frames = 1, .next = 255},
+ {.name = "BetterLightShow", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Better Light Show", .text = "The entertainment capacity of the building will be doubled.", .cost = {[M_MACHINEPARTS] = 20, [M_COMPUTERCHIPS] = 2, [M_KNOWLEDGE] = 100}, .layer = -1, .next = 255},
+ {.name = "MedicalEducation", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Improved Medical Education", .text = "The quality of this building will be increased by 25% of the education happiness.", .cost = {[M_FOOD] = 100, [M_WOOD] = 10, [M_KNOWLEDGE] = 100}, .layer = -1, .next = 255},
+ {.name = "AIAssistedDiagnosis", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Computer-Aided Diagnosis", .text = "The quality of this building will be increased by 25 and its capacity will be doubled.", .cost = {[M_STONE] = 20, [M_MACHINEPARTS] = 50, [M_COMPUTERCHIPS] = 25, [M_KNOWLEDGE] = 1000}, .layer = LAYER_BG, .sprite = SPR_SMARTDIAGNOSE, .frames = 1, .next = 255},
+ {.name = "StoneTeleporterRemote", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Remote Control", .text = "The worker of the rock teleporter can teleport stone even if they're somewhere else. This allows them to help mine stone as well.", .cost = {[M_MACHINEPARTS] = 2, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 500}, .layer = LAYER_BG, .sprite = SPR_STONETELEPORTER_REMOTE, .frames = 1, .next = 255},
+ {.name = "BiggerTV", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Bigger TV", .text = "Improves housing quality by 5. Adds capacity for one resident.", .cost = {[M_STONE] = 2, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 100}, .layer = LAYER_BG, .sprite = SPR_BIGGERTV, .frames = 1, .bonusAttractiveness = 5, .next = 255},
+ {.name = "ModernHomePlant", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Air-Cleaning Plant", .text = "A plant that's been cultivated to be extremely good at cleaning the air. Improves housing quality by 10 and makes residents live longer.", .cost = {[M_FOOD] = 20, [M_WOOD] = 10, [M_KNOWLEDGE] = 500}, .layer = LAYER_BG, .sprite = SPR_MODERNHOMEPLANT, .frames = 10, .lockedFrames = 3, .bonusAttractiveness = 10, .next = 255},
+ {.name = "HeatedBed", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Heated Bed", .text = "Improves housing quality by 20.", .cost = {[M_WOOD] = 10, [M_MACHINEPARTS] = 5, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 750}, .layer = -1, .bonusAttractiveness = 20, .next = 255},
+ {.name = "SmartChairs", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Smart Chairs", .text = "Improves housing quality by 10.", .cost = {[M_WOOD] = 4, [M_MACHINEPARTS] = 4, [M_COMPUTERCHIPS] = 4, [M_KNOWLEDGE] = 1000}, .layer = LAYER_BG, .sprite = SPR_SMARTCHAIRS, .frames = 1, .bonusAttractiveness = 10, .next = 255},
+ {.name = "ModernConveniences", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Modern Conveniences", .text = "Improves housing quality by 15.", .cost = {[M_WOOD] = 5, [M_MACHINEPARTS] = 5, [M_REFINEDMETAL] = 2, [M_KNOWLEDGE] = 100}, .layer = LAYER_BG, .sprite = SPR_MODERNCONVENIENCES, .frames = 1, .bonusAttractiveness = 15, .next = 255},
+ {.name = "WorkshopKnowledge", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Pet Projects", .text = "Gather knowledge.", .layer = LAYER_BG, .sprite = SPR_WORKSHOP_PETPROJECTS, .frames = 1, .next = 255},
+ {.name = "WorkshopMachineParts", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Craft Machine Parts", .text = "Create machine parts from wood.", .layer = LAYER_BG, .sprite = SPR_WORKSHOP_MAKEMACHINEPARTS, .frames = 1, .next = 255},
+ {.name = "StarDatabase", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Star Database", .text = "This building produces 50% more knowledge. If the Precise Universe Mapping upgrade from the Supercomputer has been researched, it produces 500% more knowledge instead.", .cost = {[M_STONE] = 5, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 100}, .layer = LAYER_BG, .sprite = SPR_COMPUTER_OBSERVATORY, .frames = 1, .next = 255},
+ {.name = "SofterBeds", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Extremely Soft Beds", .text = "Improves housing quality by 10.", .cost = {[M_FOOD] = 12, [M_WOOD] = 6, [M_KNOWLEDGE] = 50}, .layer = LAYER_BG, .sprite = SPR_SOFTERBEDS, .frames = 1, .bonusAttractiveness = 10, .next = 255},
+ {.name = "SmartLights", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Smart Lights", .text = "Improves housing quality by 15.", .cost = {[M_REFINEDMETAL] = 5, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 200}, .layer = LAYER_BG, .sprite = SPR_SMARTLIGHTS, .frames = 1, .bonusAttractiveness = 15, .noCache = 1, .next = 255},
+ {.name = "LivingComputer", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Living Computer", .text = "Improves housing quality by 20.", .cost = {[M_FOOD] = 25, [M_WOOD] = 50, [M_COMPUTERCHIPS] = 1, [M_KNOWLEDGE] = 2000}, .layer = LAYER_BG, .sprite = SPR_ALIENHOUSE_LIVINGCOMPUTER, .frames = 7, .bonusAttractiveness = 20, .next = 255},
+ {.name = "BetterTools", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Better Tools", .text = "Improves housing quality by 20.", .cost = {[M_MACHINEPARTS] = 10, [M_REFINEDMETAL] = 6, [M_COMPUTERCHIPS] = 2, [M_KNOWLEDGE] = 3000}, .layer = LAYER_BG, .sprite = SPR_TINKERERSHOUSE_BETTERTOOLS, .frames = 4, .bonusAttractiveness = 20, .next = 255},
+ {.name = "MisdirectorNormal", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Enable", .text = "The Misdirector is predictably unpredictable.", .layer = -1, .next = 255},
+ {.name = "MisdirectorAlways", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Overclock", .text = "Any attempt at teleportation will bring people here. Perfect to stop excess productivity.\\nThe knowledge gain per misdirection is reduced by 90% because the device is overloaded.", .cost = {[M_KNOWLEDGE] = 5000}, .layer = -1, .next = 255},
+ {.name = "MisdirectorMostlyDisabled", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Mostly Disable", .text = "There's an OFF button. It mostly works.", .layer = -1, .next = 255},
+ {.name = "MisdirectorDisabled", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Disable", .text = "With some effort, the Misdirector can be tamed.", .cost = {[M_KNOWLEDGE] = 50000}, .layer = -1, .next = 255},
+ {.name = "IndoorPond", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Indoor Pond", .text = "Improves housing quality by 15.", .cost = {[M_FOOD] = 20, [M_STONE] = 100, [M_KNOWLEDGE] = 10000}, .layer = LAYER_BG, .sprite = SPR_COMMUNITYHOUSE_INDOORPOND, .frames = 1, .bonusAttractiveness = 15, .next = 255},
+ {.name = "CHProduceStone", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Rock", .text = "Produce stone.", .layer = -1, .next = 255},
+ {.name = "CHProduceWood", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Tree", .text = "Produce wood.", .layer = -1, .next = 255},
+ {.name = "CHProduceFood", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Crops", .text = "Produce food.", .layer = -1, .next = 255},
+ {.name = "PickaxeTech", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Peer-Reviewed Pickaxe Part Papers", .text = "The boost to stone production is increased and scales faster with knowledge production.", .cost = {[M_COMPUTERCHIPS] = 25, [M_KNOWLEDGE] = 2500}, .layer = LAYER_BG, .sprite = SPR_STONERESEARCHCENTRE_PICKAXETECH, .frames = 1, .next = 255},
+ {.name = "FossilScanner", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Fossil Detector", .text = "Whenever a rock teleporter teleports a meteoroid, there is a tiny chance that a fossil is detected in it. When this happens, you gain 10000 knowledge.", .cost = {[M_COMPUTERCHIPS] = 2000, [M_KNOWLEDGE] = 150000}, .layer = LAYER_BG, .sprite = SPR_STONERESEARCHCENTRE_COMPUTER, .frames = 1, .next = 255},
+ {.name = "UltimateScrewdriver", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Ultra-High-Tech Screwdriver", .text = "You gain two more knowledge for each machine part used.", .cost = {[M_STONE] = 1, [M_MACHINEPARTS] = 1, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 10000}, .layer = LAYER_BG, .sprite = SPR_EXPERIMENTATIONLAB_SCREWDRIVER, .frames = 1, .noCache = 1, .next = 255},
+ {.name = "AutomaticWaterManagement", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Automatic Water Management", .text = "The passive growth speed of these trees is tripled.", .cost = {[M_MACHINEPARTS] = 5, [M_COMPUTERCHIPS] = 5, [M_KNOWLEDGE] = 5000}, .layer = -1, .next = 255},
+ {.name = "CulinaryHerbs", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Culinary Herbs", .text = "Increases the capacity of restaurants to the left and right of the garden.", .layer = -1, .next = 255},
+ {.name = "MedicalHerbs", .kind = UK_BUILDING_MODE, .unlockFlags = UF_DEFAULT, .title = "Medicinal Herbs", .text = "Improves the medical happiness. Herb gardens can't provide more than 20% of the medical happiness in total.", .cost = {[M_KNOWLEDGE] = 25}, .layer = -1, .next = 255},
+ {.name = "ComfortableCouch", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Comfortable Couch", .text = "Improves housing quality by 15.", .cost = {[M_FOOD] = 20, [M_WOOD] = 5, [M_KNOWLEDGE] = 200}, .layer = LAYER_BG, .sprite = SPR_COMFORTABLECOUCH, .frames = 1, .bonusAttractiveness = 15, .next = 255},
+ {.name = "SmartSpeaker", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Somewhat Smart Speaker", .text = "Improves housing quality by 10.", .cost = {[M_WOOD] = 2, [M_MACHINEPARTS] = 2, [M_COMPUTERCHIPS] = 2, [M_KNOWLEDGE] = 1000}, .layer = LAYER_BG, .sprite = SPR_SMARTSPEAKER, .frames = 1, .bonusAttractiveness = 10, .next = 255},
+ {.name = "SoundProofing", .kind = UK_BUILDING_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Soundproofing", .text = "Improves housing quality by 12.", .cost = {[M_WOOD] = 20, [M_STONE] = 10, [M_KNOWLEDGE] = 3000}, .layer = -1, .bonusAttractiveness = 12, .next = 255},
+ {.name = "RefinedMetalFactoryEfficiency", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Optimized Temperature Curve", .text = "The factory works faster and uses one less stone per unit of refined metal produced.", .cost = {[M_MACHINEPARTS] = 20, [M_COMPUTERCHIPS] = 3, [M_KNOWLEDGE] = 10000}, .layer = -1, .next = 255},
+ {.name = "TheMachineUpgrade", .kind = UK_BUILDING_UPGRADE, .unlockFlags = 0, .title = "Machine Tuning", .text = "The Machine produces 50% more materials and it sometimes also produces graphene and rocket fuel. If it's ever destroyed, Secret Society of the Key members stay alive longer. Members of the Feather Alliance live longer.", .cost = {[M_COMPUTERCHIPS] = 5000, [M_GRAPHENE] = 1000, [M_ROCKETFUEL] = 20000, [M_KNOWLEDGE] = 50000}, .layer = -1, .next = 255},
+ {.name = "UniverseMapping", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Precise Universe Mapping", .text = "Rock Teleporters teleport bigger meteoroids.", .cost = {[M_KNOWLEDGE] = 25000}, .layer = -1, .next = 255},
+ {.name = "OptimizedChipLayouts", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Optimized Chip Layouts", .text = "Computer Chip Factories work 33% faster.", .cost = {[M_KNOWLEDGE] = 50000}, .layer = -1, .next = 255},
+ {.name = "MedicalMachineLearning", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Medical Machine Learning", .text = "Makes your citizens live longer.", .cost = {[M_KNOWLEDGE] = 100000}, .layer = -1, .next = 255},
+ {.name = "WoodenLiving", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Wooden Living", .text = "Improves the house quality of all Wooden Houses by 10.", .cost = {[M_KNOWLEDGE] = 200}, .layer = -1, .next = 255},
+ {.name = "SpaciousLiving", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Spacious Living", .text = "Improves the house quality of all Spacious Houses by 15.", .cost = {[M_KNOWLEDGE] = 250}, .layer = -1, .next = 255},
+ {.name = "SlimyLiving", .kind = UK_CITY_UPGRADE, .unlockFlags = 0, .title = "Slimy Living", .text = "Improves the house quality of all Alien Houses by 25. Also unlocks a building upgrade for them.", .cost = {[M_KNOWLEDGE] = 500}, .layer = -1, .next = 255},
+ {.name = "SecretiveLiving", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_NOT_WITH_ALL, .title = "Secretive Living", .text = "Improves the house quality of the Secret Society of the Key by 25.", .cost = {[M_KNOWLEDGE] = 200}, .layer = -1, .next = 255},
+ {.name = "MechanicalLiving", .kind = UK_CITY_UPGRADE, .unlockFlags = 0, .title = "Mechanical Living", .text = "Adds capacity for one more resident in all Mechanical Houses and Tinkerers' Houses.", .cost = {[M_KNOWLEDGE] = 8000}, .layer = -1, .next = 255},
+ {.name = "SuperSpaciousLiving", .kind = UK_CITY_UPGRADE, .unlockFlags = 0, .title = "Societal Living", .text = "Adds capacity for one more resident in all Spacious Houses.", .cost = {[M_KNOWLEDGE] = 9500}, .layer = -1, .next = 255},
+ {.name = "BirthControl", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Birth Control", .text = "Allows you to decrease or increase the population growth.", .cost = {[M_KNOWLEDGE] = 100}, .layer = -1, .next = 255},
+ {.name = "BuildingRecycling", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Building Recycling", .text = "When you destroy a building, you get back half its cost.", .cost = {[M_KNOWLEDGE] = 25}, .layer = -1, .next = 62},
+ {.name = "BuildingRecycling2", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_NOT_WITH_ALL, .title = "Smart Demolition (Currently: Building Recycling)", .text = "When you destroy a building, you get back 75% of its cost (currently 50%).", .cost = {[M_KNOWLEDGE] = 125}, .layer = -1, .next = 63},
+ {.name = "BuildingRecycling3", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_NOT_WITH_ALL, .title = "Sustainable Building (Currently: Smart Demolition)", .text = "When you destroy a building, you get back 90% of its cost (currently 75%).", .titleDone = "Sustainable Building", .textDone = "When you destroy a building, you get back 90% of its cost.", .cost = {[M_KNOWLEDGE] = 500}, .layer = -1, .next = 255},
+ {.name = "ChipBinning", .kind = UK_CITY_UPGRADE, .unlockFlags = 0, .title = "Chip Binning", .text = "Computer Chip Factories work 20% faster.", .cost = {[M_KNOWLEDGE] = 5000}, .layer = -1, .next = 255},
+ {.name = "EcoFarmUpgrade", .kind = UK_CITY_UPGRADE, .unlockFlags = 0, .title = "Permaculture", .text = "Eco farms produce more food.", .cost = {[M_KNOWLEDGE] = 1250}, .layer = -1, .next = 255},
+ {.name = "GeneEditing", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Gene Editing", .text = "Allows you to plant the purple and red forests and grass from Wooded Worlds, and the blue flowers from Bridge Worlds.", .cost = {[M_KNOWLEDGE] = 5000}, .layer = -1, .next = 255},
+ {.name = "LibraryAllowDuplicates", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Metropolis", .text = "Allows you to build the following unique buildings a second time: Workshop, Experimental Farm, Observatory, Art Colony, Computing Research Center, Living Research Center, Lab Escape Room, and Supercomputer. Their city upgrades are still available only once.", .cost = {[M_KNOWLEDGE] = 200000}, .layer = -1, .next = 255},
+ {.name = "ConnectedMachines", .kind = UK_CITY_UPGRADE, .unlockFlags = UF_DEFAULT, .title = "Connected Machines", .text = "The production of The Machine is increased by 50% for each Machine in an associated city.", .cost = {[M_KNOWLEDGE] = 500000}, .layer = -1, .next = 255},
+ {.name = "FoodRationing", .kind = UK_POLICY, .unlockFlags = UF_DEFAULT, .title = "Food Rationing", .text = "Your citizens consume half as much food. However, their happiness is reduced by a third if it's above 10.", .layer = -1, .next = 255},
+ {.name = "SmallerClasses", .kind = UK_POLICY, .unlockFlags = UF_DEFAULT, .title = "Smaller Class Sizes", .text = "Schools give a 15% better education, but their capacity is reduced by a third.", .layer = -1, .next = 255},
+ {.name = "MandatoryOvertime", .kind = UK_POLICY, .unlockFlags = UF_DEFAULT, .title = "Mandatory Overtime", .text = "Your citizens work two hours per day longer. Their happiness goes down gradually while this policy is implemented. After you end it, happiness starts to restore again slowly after a day.", .layer = -1, .next = 255},
+};
+const int nupgrades = sizeof upgrade_info / sizeof upgrade_info[0];
+
+/* what each class offers in its window: upgrade_info indexes + 1 (0: none) */
+const ClassUpgrades class_upgrades[CLS_COUNT] = {
+ [CLS_NormalHouse] = {.up = {U_Flowers + 1}},
+ [CLS_AlienHouse] = {.up = {U_LivingComputer + 1}},
+ [CLS_ModernRusticHome] = {.up = {U_ModernConveniences + 1}},
+ [CLS_ComfortableHouse] = {.up = {U_ComfortableCouch + 1, U_SmartSpeaker + 1}},
+ [CLS_MechanicalHouse] = {.up = {U_HeatedBed + 1}},
+ [CLS_SpaciousHouse] = {.up = {U_SmartLights + 1, U_SofterBeds + 1}},
+ [CLS_CuttingEdgeHome] = {.up = {U_BiggerTV + 1, U_ModernHomePlant + 1, U_SmartChairs + 1}},
+ [CLS_Loft] = {.up = {U_SoundProofing + 1}},
+ [CLS_TinkerersHome] = {.up = {U_BetterTools + 1}},
+ [CLS_FarmHouse] = {.up = {U_IndoorPond + 1}, .mode = {U_CHProduceFood + 1, U_CHProduceStone + 1, U_CHProduceWood + 1}},
+ [CLS_StoneMine] = {.up = {U_BetterPickaxes + 1, U_AIMining + 1}},
+ [CLS_MachinePartsFactory] = {.up = {U_MachinePartsFactoryEfficiency + 1}, .mode = {U_FactoryWorking + 1, U_MachinePartsFactoryTurbo + 1, U_StoneUsingFactoryDisabled + 1}},
+ [CLS_Laboratory] = {.up = {U_FarmingResearch + 1, U_TreePlantationResearch + 1}},
+ [CLS_TreePlantation] = {.up = {U_AutomaticWaterManagement + 1}},
+ [CLS_StoneTeleporter] = {.up = {U_StoneTeleporterRemote + 1}},
+ [CLS_RefinedMetalFactory] = {.up = {U_RefinedMetalFactoryEfficiency + 1}, .mode = {U_FactoryWorking + 1, U_RefinedMetalsFactoryHack + 1, U_StoneUsingFactoryDisabled + 1}},
+ [CLS_ComputerChipFactory] = {.up = {U_DieShrink + 1}, .mode = {U_FactoryWorking + 1, U_RefinedStoneUsingFactoryDisabled + 1}},
+ [CLS_ExperimentationLab] = {.up = {U_UltimateScrewdriver + 1}, .mode = {U_LabWorking + 1, U_LabDisabled + 1}},
+ [CLS_HerbGarden] = {.mode = {U_CulinaryHerbs + 1, U_MedicalHerbs + 1}},
+ [CLS_MedicalClinic] = {.up = {U_MedicalEducation + 1, U_AIAssistedDiagnosis + 1}, .city = {U_BirthControl + 1}},
+ [CLS_FactoryPub] = {.up = {U_RefinedMetalFactoryEfficiency + 1}, .mode = {U_FactoryWorking + 1, U_RefinedMetalsFactoryHack + 1, U_StoneUsingFactoryDisabled + 1}},
+ [CLS_NightClub] = {.up = {U_BetterLightShow + 1}},
+ [CLS_Workshop] = {.mode = {U_WorkshopMachineParts + 1, U_WorkshopKnowledge + 1}, .city = {U_BuildingRecycling + 1, U_BuildingRecycling2 + 1, U_BuildingRecycling3 + 1}},
+ [CLS_ExperimentalFarm] = {.city = {U_EcoFarmUpgrade + 1}},
+ [CLS_Observatory] = {.up = {U_StarDatabase + 1}},
+ [CLS_CityHall] = {.mode = {U_CensusData + 1, U_NightMayor + 1}, .pol = {U_FoodRationing + 1, U_SmallerClasses + 1, U_MandatoryOvertime + 1}},
+ [CLS_StoneResearchCenter] = {.up = {U_PickaxeTech + 1, U_FossilScanner + 1}},
+ [CLS_ComputerResearchCenter] = {.city = {U_ChipBinning + 1}},
+ [CLS_LivingResearchCenter] = {.city = {U_WoodenLiving + 1, U_SpaciousLiving + 1, U_SlimyLiving + 1, U_SecretiveLiving + 1, U_MechanicalLiving + 1, U_SuperSpaciousLiving + 1}},
+ [CLS_Misdirector] = {.mode = {U_MisdirectorNormal + 1, U_MisdirectorAlways + 1, U_MisdirectorMostlyDisabled + 1, U_MisdirectorDisabled + 1}},
+ [CLS_TheMachine] = {.up = {U_TheMachineUpgrade + 1}},
+ [CLS_IntergalacticLibrary] = {.city = {U_GeneEditing + 1, U_LibraryAllowDuplicates + 1, U_ConnectedMachines + 1}},
+ [CLS_Supercomputer] = {.city = {U_UniverseMapping + 1, U_OptimizedChipLayouts + 1, U_MedicalMachineLearning + 1}},
+};
+
+int upgrade_find(const char *name) {
+ for (int i = 0; i < nupgrades; i++)
+ if (!strcmp(upgrade_info[i].name, name)) return i;
+ return -1;
+}
diff --git a/games/finalearth2/src/upgrades_data.h b/games/finalearth2/src/upgrades_data.h
new file mode 100644
index 00000000..d9461a73
--- /dev/null
+++ b/games/finalearth2/src/upgrades_data.h
@@ -0,0 +1,139 @@
+/* The Final Earth 2: upgrade numbers and the classes' lists (made by tools/gen_upgrades.py). */
+#ifndef FE_UPGRADES_DATA_H
+#define FE_UPGRADES_DATA_H
+enum {
+ U_Flowers = 0,
+ U_MachinePartsFactoryEfficiency = 1,
+ U_StoneUsingFactoryDisabled = 2,
+ U_RefinedStoneUsingFactoryDisabled = 3,
+ U_MachinePartsFactoryTurbo = 4,
+ U_CensusData = 5,
+ U_NightMayor = 6,
+ U_RefinedMetalsFactoryHack = 7,
+ U_FactoryWorking = 8,
+ U_LabWorking = 9,
+ U_LabDisabled = 10,
+ U_FarmingResearch = 11,
+ U_TreePlantationResearch = 12,
+ U_BetterPickaxes = 13,
+ U_AIMining = 14,
+ U_DieShrink = 15,
+ U_BetterLightShow = 16,
+ U_MedicalEducation = 17,
+ U_AIAssistedDiagnosis = 18,
+ U_StoneTeleporterRemote = 19,
+ U_BiggerTV = 20,
+ U_ModernHomePlant = 21,
+ U_HeatedBed = 22,
+ U_SmartChairs = 23,
+ U_ModernConveniences = 24,
+ U_WorkshopKnowledge = 25,
+ U_WorkshopMachineParts = 26,
+ U_StarDatabase = 27,
+ U_SofterBeds = 28,
+ U_SmartLights = 29,
+ U_LivingComputer = 30,
+ U_BetterTools = 31,
+ U_MisdirectorNormal = 32,
+ U_MisdirectorAlways = 33,
+ U_MisdirectorMostlyDisabled = 34,
+ U_MisdirectorDisabled = 35,
+ U_IndoorPond = 36,
+ U_CHProduceStone = 37,
+ U_CHProduceWood = 38,
+ U_CHProduceFood = 39,
+ U_PickaxeTech = 40,
+ U_FossilScanner = 41,
+ U_UltimateScrewdriver = 42,
+ U_AutomaticWaterManagement = 43,
+ U_CulinaryHerbs = 44,
+ U_MedicalHerbs = 45,
+ U_ComfortableCouch = 46,
+ U_SmartSpeaker = 47,
+ U_SoundProofing = 48,
+ U_RefinedMetalFactoryEfficiency = 49,
+ U_TheMachineUpgrade = 50,
+ U_UniverseMapping = 51,
+ U_OptimizedChipLayouts = 52,
+ U_MedicalMachineLearning = 53,
+ U_WoodenLiving = 54,
+ U_SpaciousLiving = 55,
+ U_SlimyLiving = 56,
+ U_SecretiveLiving = 57,
+ U_MechanicalLiving = 58,
+ U_SuperSpaciousLiving = 59,
+ U_BirthControl = 60,
+ U_BuildingRecycling = 61,
+ U_BuildingRecycling2 = 62,
+ U_BuildingRecycling3 = 63,
+ U_ChipBinning = 64,
+ U_EcoFarmUpgrade = 65,
+ U_GeneEditing = 66,
+ U_LibraryAllowDuplicates = 67,
+ U_ConnectedMachines = 68,
+ U_FoodRationing = 69,
+ U_SmallerClasses = 70,
+ U_MandatoryOvertime = 71,
+ U_COUNT = 72
+};
+
+/* a class's upgrade's bit in Perm.upgrades, and its modes' numbers (Perm.mode) */
+#define UB_NormalHouse_Flowers 0
+#define UB_AlienHouse_LivingComputer 0
+#define UB_ModernRusticHome_ModernConveniences 0
+#define UB_ComfortableHouse_ComfortableCouch 0
+#define UB_ComfortableHouse_SmartSpeaker 1
+#define UB_MechanicalHouse_HeatedBed 0
+#define UB_SpaciousHouse_SmartLights 0
+#define UB_SpaciousHouse_SofterBeds 1
+#define UB_CuttingEdgeHome_BiggerTV 0
+#define UB_CuttingEdgeHome_ModernHomePlant 1
+#define UB_CuttingEdgeHome_SmartChairs 2
+#define UB_Loft_SoundProofing 0
+#define UB_TinkerersHome_BetterTools 0
+#define UB_FarmHouse_IndoorPond 0
+#define MODE_FarmHouse_CHProduceFood 0
+#define MODE_FarmHouse_CHProduceStone 1
+#define MODE_FarmHouse_CHProduceWood 2
+#define UB_StoneMine_BetterPickaxes 0
+#define UB_StoneMine_AIMining 1
+#define UB_MachinePartsFactory_MachinePartsFactoryEfficiency 0
+#define MODE_MachinePartsFactory_FactoryWorking 0
+#define MODE_MachinePartsFactory_MachinePartsFactoryTurbo 1
+#define MODE_MachinePartsFactory_StoneUsingFactoryDisabled 2
+#define UB_Laboratory_FarmingResearch 0
+#define UB_Laboratory_TreePlantationResearch 1
+#define UB_TreePlantation_AutomaticWaterManagement 0
+#define UB_StoneTeleporter_StoneTeleporterRemote 0
+#define UB_RefinedMetalFactory_RefinedMetalFactoryEfficiency 0
+#define MODE_RefinedMetalFactory_FactoryWorking 0
+#define MODE_RefinedMetalFactory_RefinedMetalsFactoryHack 1
+#define MODE_RefinedMetalFactory_StoneUsingFactoryDisabled 2
+#define UB_ComputerChipFactory_DieShrink 0
+#define MODE_ComputerChipFactory_FactoryWorking 0
+#define MODE_ComputerChipFactory_RefinedStoneUsingFactoryDisabled 1
+#define UB_ExperimentationLab_UltimateScrewdriver 0
+#define MODE_ExperimentationLab_LabWorking 0
+#define MODE_ExperimentationLab_LabDisabled 1
+#define MODE_HerbGarden_CulinaryHerbs 0
+#define MODE_HerbGarden_MedicalHerbs 1
+#define UB_MedicalClinic_MedicalEducation 0
+#define UB_MedicalClinic_AIAssistedDiagnosis 1
+#define UB_FactoryPub_RefinedMetalFactoryEfficiency 0
+#define MODE_FactoryPub_FactoryWorking 0
+#define MODE_FactoryPub_RefinedMetalsFactoryHack 1
+#define MODE_FactoryPub_StoneUsingFactoryDisabled 2
+#define UB_NightClub_BetterLightShow 0
+#define MODE_Workshop_WorkshopMachineParts 0
+#define MODE_Workshop_WorkshopKnowledge 1
+#define UB_Observatory_StarDatabase 0
+#define MODE_CityHall_CensusData 0
+#define MODE_CityHall_NightMayor 1
+#define UB_StoneResearchCenter_PickaxeTech 0
+#define UB_StoneResearchCenter_FossilScanner 1
+#define MODE_Misdirector_MisdirectorNormal 0
+#define MODE_Misdirector_MisdirectorAlways 1
+#define MODE_Misdirector_MisdirectorMostlyDisabled 2
+#define MODE_Misdirector_MisdirectorDisabled 3
+#define UB_TheMachine_TheMachineUpgrade 0
+#endif
diff --git a/games/finalearth2/src/view.c b/games/finalearth2/src/view.c
new file mode 100644
index 00000000..64bf888f
--- /dev/null
+++ b/games/finalearth2/src/view.c
@@ -0,0 +1,134 @@
+/* The Final Earth 2: drawing the city (the original's City stages, back to
+ * front): the sky, the buildings' backs, the citizens inside them, upgrade
+ * sprites, the buildings' fronts and the worlds' islands, what is above them,
+ * the citizens outside, and the foreground. Each layer is drawn band by band
+ * (gfx_call), over the permanents on screen. */
+#include "bld.h"
+#include "bg.h"
+#include "data.h"
+#include "view.h"
+
+BgCamera camera = {0, 0, 1};
+extern BgWorld bgworlds[MAX_WORLDS];
+
+#define MAX_VISIBLE 384
+static uint16_t visible[MAX_VISIBLE];
+static int16_t vis_x[MAX_VISIBLE], vis_y[MAX_VISIBLE]; /* screen positions of their top-left */
+static int nvisible;
+
+/* the permanents on screen this frame */
+static void find_visible(void) {
+ nvisible = 0;
+ int z = camera.zoom;
+ float x0 = camera.x - 20, y0 = camera.y - 20;
+ float x1 = camera.x + (float)SCREEN_W / z, y1 = camera.y + (float)SCREEN_H / z;
+ for (int w = 0; w < nworlds; w++) {
+ World *wd = &worlds[w];
+ if (wd->x + wd->w < x0 || wd->x > x1 || wd->y < y0) continue;
+ int c0 = (int)((x0 - wd->x) / 20), c1 = (int)((x1 - wd->x) / 20) + 1;
+ if (c0 < 0) c0 = 0;
+ if (c1 > wd->ncols) c1 = wd->ncols;
+ for (int c = c0; c < c1; c++) {
+ int h = col_stack_height(w, c);
+ for (int r = 0; r < h; r++) {
+ int py = wd->y - 20 * (r + 1);
+ if (py > y1) continue;
+ if (py + 20 < y0) break;
+ uint16_t id = perm_at(w, c, r);
+ if (!id || nvisible >= MAX_VISIBLE) continue;
+ visible[nvisible] = id;
+ vis_x[nvisible] = (int16_t)bg_screen_x(&camera, (float)(wd->x + 20 * c));
+ vis_y[nvisible] = (int16_t)bg_screen_y(&camera, (float)py);
+ nvisible++;
+ }
+ }
+ }
+}
+
+static void band_layer(const GfxBand *b, void *ctx) {
+ int layer = (int)(intptr_t)ctx;
+ int size = 20 * camera.zoom;
+ for (int i = 0; i < nvisible; i++) {
+ if (vis_y[i] >= b->y1 || vis_y[i] + size + 20 * camera.zoom <= b->y0) continue; /* (some draw a little above themselves) */
+ bld_draw(b, P(visible[i]), layer, vis_x[i], vis_y[i]);
+ }
+ bld_draw_free(b, layer);
+}
+
+/* a citizen's sprite: children and adults have 51 looks each, then Dracula and Waldo */
+static void draw_citizen(const GfxBand *b, const Cit *c, float cx, float cy, uint8_t alpha) {
+ bool child = cit_age(c) < 16;
+ uint16_t spr;
+ int frame = 0;
+ if (c->spriteIndex == NCITIZEN_SPRITES - 1) spr = child ? SPR_WALDO_CHILD : SPR_WALDO_ADULT;
+ else if (c->spriteIndex == NCITIZEN_SPRITES - 2) spr = child ? SPR_DRACULA_CHILD : SPR_DRACULA_ADULT;
+ else spr = child ? SPR_CHILDREN : SPR_HUMANS, frame = c->spriteIndex;
+ int h = spr_h(spr);
+ int x = bg_screen_x(&camera, cx), y = bg_screen_y(&camera, cy - h); /* the sprite's bottom at cy */
+ gfx_band_sprite(b, spr, frame * 4, 0, 2, h, x, y, 0, alpha, GFX_NO_TINT);
+}
+
+/* citizens inside buildings (inside != 0) or outside them */
+static void band_citizens(const GfxBand *b, void *ctx) {
+ bool inside = ctx != NULL;
+ int z = camera.zoom;
+ float x0 = camera.x - 4, x1 = camera.x + (float)SCREEN_W / z + 4;
+ float y0 = camera.y + (float)b->y0 / z - 1, y1 = camera.y + (float)b->y1 / z + 6;
+ for (int i = 1; i < MAX_CITS; i++) {
+ const Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || (c->flags & CF_CONTROLLED)) continue;
+ const Perm *in = P(c->inPermanent);
+ bool in_building = is_building(in);
+ if (in_building != inside) continue;
+ float x, y;
+ uint8_t alpha = 255;
+ if (in) {
+ x = (float)perm_city_x(in) + c->relativeX;
+ y = (float)perm_city_y(in) + 20 - c->relativeY - (in_building ? 1 : 0);
+ if (in_building) {
+ if (!(c->flags & CF_CAN_VIEW_SELF) || (c->flags & CF_DELAY_CAN_VIEW_SELF)) continue;
+ if (c->currentPathAction == 7 && cit_timer(c) > 0 && cit_timer(c) < 1)
+ alpha = (uint8_t)(cit_timer(c) * 255);
+ }
+ } else {
+ x = worlds[c->onWorld].x + c->relativeX;
+ y = worlds[c->onWorld].y - c->relativeY;
+ }
+ if (x < x0 || x > x1 || y < y0 || y > y1) continue;
+ draw_citizen(b, c, x, y, alpha);
+ }
+}
+
+void view_draw(void) {
+ find_visible();
+ bg_draw_sky(&camera, city.timeSinceStart);
+ gfx_zoom(camera.zoom);
+ gfx_call(band_layer, (void *)(intptr_t)LAYER_BG, 0, SCREEN_H);
+ gfx_call(band_citizens, (void *)1, 0, SCREEN_H);
+ gfx_call(band_layer, (void *)(intptr_t)LAYER_MID, 0, SCREEN_H);
+ gfx_call(band_layer, (void *)(intptr_t)LAYER_MAIN, 0, SCREEN_H);
+ for (int w = 0; w < nworlds; w++)
+ if (worlds[w].h > 0) bg_draw_world(&bgworlds[w], col_deco + worlds[w].col0, &camera);
+ gfx_call(band_layer, (void *)(intptr_t)LAYER_ABOVE, 0, SCREEN_H);
+ gfx_call(band_citizens, NULL, 0, SCREEN_H);
+ gfx_call(band_layer, (void *)(intptr_t)LAYER_FRONT, 0, SCREEN_H);
+ gfx_zoom(1);
+}
+
+/* the city's edges (City.getCityEdges), for the clouds and the camera's limits */
+void view_edges(BgEdges *e) {
+ e->minX = 1 << 30, e->maxX = -(1 << 30), e->minY = 1 << 30, e->maxY = -(1 << 30);
+ for (int w = 0; w < nworlds; w++) {
+ World *wd = &worlds[w];
+ if (wd->h == 0) continue;
+ int top = wd->y;
+ for (int c = 0; c < wd->ncols; c++) {
+ int t = wd->y - 20 * col_stack_height(w, c);
+ if (t < top) top = t;
+ }
+ if (wd->x < e->minX) e->minX = wd->x;
+ if (wd->x + wd->w > e->maxX) e->maxX = wd->x + wd->w;
+ if (top < e->minY) e->minY = top;
+ if (wd->y + wd->h > e->maxY) e->maxY = wd->y + wd->h;
+ }
+}
diff --git a/games/finalearth2/src/view.h b/games/finalearth2/src/view.h
new file mode 100644
index 00000000..dac2a797
--- /dev/null
+++ b/games/finalearth2/src/view.h
@@ -0,0 +1,12 @@
+/* The Final Earth 2: drawing the city (view.c). */
+#ifndef FE_VIEW_H
+#define FE_VIEW_H
+#include "bg.h"
+#include "fe.h"
+
+extern BgCamera camera;
+void view_draw(void);
+void view_edges(BgEdges *e);
+/* bld*.c: one layer (LAYER_*) of a permanent, its top-left at screen (x, y) */
+void bld_draw(const GfxBand *b, const Perm *p, int layer, int x, int y);
+#endif
diff --git a/games/finalearth2/src/win.h b/games/finalearth2/src/win.h
new file mode 100644
index 00000000..c920fb5d
--- /dev/null
+++ b/games/finalearth2/src/win.h
@@ -0,0 +1,34 @@
+/* The Final Earth 2: what a window shows, said by the code that knows it
+ * (a building's class, a citizen, the city's menus) and laid out by the
+ * user interface (ui*.c). Texts are UTF-8, in the original's words. */
+#ifndef FE_WIN_H
+#define FE_WIN_H
+#include "fe.h"
+
+typedef struct WinOut WinOut;
+void win_title(WinOut *w, const char *s);
+void win_text(WinOut *w, const char *s); /* a paragraph, wrapped */
+void win_info(WinOut *w, uint16_t icon, const char *s); /* a line with an icon (SPR_*, 0 none) */
+void win_space(WinOut *w, int h); /* GUISpacing: h pixels */
+/* a button of the window's owner: pressing it calls its window_action(action). Alone it is a FullSizeTextButton;
+ * followed by win_text (a description) and win_cost, it is UpgradeWindowParts.createActivatableButton. Not
+ * enabled: with a description and no cost, the option chosen (the active box, not a button); with a cost, one
+ * the city can't pay (a button all the same, its cost in red, that does nothing); alone, greyed out */
+void win_button(WinOut *w, uint16_t icon, const char *label, int action, bool enabled);
+/* materials, as the original's cost lines (icons and amounts) */
+void win_cost(WinOut *w, const float cost[M_COUNT]);
+/* UpgradeWindowParts.createHeader (Arial15); with one_action >= 0 also addOneAndMaxButtons on its row: One
+ * (pressed unless all) and All (Max when max), with their tooltips */
+void win_heading(WinOut *w, const char *title, int one_action, int all_action, bool all, bool max, const char *one_tip,
+ const char *all_tip);
+/* a button of the window's bottom row, left of its Close (windowAddBottomButtons' extra buttons, at most two),
+ * with its tooltip */
+void win_bottom_button(WinOut *w, const char *label, int action, const char *tip_header, const char *tip);
+/* a paragraph in one of the original's fonts (FONT_*, data.h), wrapped at max_w */
+void win_para(WinOut *w, uint8_t font, const char *s, int max_w, uint16_t color);
+/* gui.CheckboxButton.createSettingButton: a checkbox and its text in a button */
+void win_setting(WinOut *w, bool checked, int action, const char *text);
+/* what a building's window shows after its upgrades, modes and policies (the original's createMainWindowPart after
+ * the Building's, and createWindowAddBottomButtons): what follows this call goes there */
+void win_later(WinOut *w);
+#endif
diff --git a/games/finalearth2/tests/bldtest.c b/games/finalearth2/tests/bldtest.c
new file mode 100644
index 00000000..dee92ff3
--- /dev/null
+++ b/games/finalearth2/tests/bldtest.c
@@ -0,0 +1,514 @@
+/* Runs the buildings without a screen. First a city with every class of
+ * building and world resource: many days, every window and button, every
+ * upgrade, mode, research and policy, every drawer at both zooms, then a save
+ * and a load. Then small cities, one per kind of production, whose output is
+ * measured against the original's formulas.
+ *
+ * Built like the other tests but without the user interface (it has its own
+ * windows and stand-ins here): every src file but plat_eadk.c, game.c and
+ * ui*.c, with -DHOST and the address and undefined behaviour sanitizers. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include "../src/bldi.h"
+#include "../src/save.h"
+#include "../src/scratch.h"
+#include "../src/view.h"
+
+void story_set_name(const char *n);
+void game_reset(void);
+void host_save_dir(const char *d);
+extern int bld_bad_draws;
+
+/* ---------------------------------------------------------------- windows: counted, and their buttons kept */
+struct WinOut {
+ int lines, buttons;
+ int actions[24], nactions;
+ bool print;
+};
+static void show(WinOut *w, const char *kind, const char *s) {
+ w->lines++;
+ if (w->print) printf(" %s %s\n", kind, s);
+}
+void win_title(WinOut *w, const char *s) { show(w, "#", s); }
+void win_text(WinOut *w, const char *s) { show(w, "|", s); }
+void win_info(WinOut *w, uint16_t icon, const char *s) { (void)icon, show(w, "i", s); }
+void win_button(WinOut *w, uint16_t icon, const char *label, int action, bool enabled) {
+ (void)icon;
+ w->buttons++;
+ if (w->print) printf(" [%s]%s\n", label, enabled ? "" : " (off)");
+ if (enabled && w->nactions < 24) w->actions[w->nactions++] = action;
+}
+void win_cost(WinOut *w, const float cost[M_COUNT]) {
+ w->lines++;
+ if (w->print) {
+ printf(" $");
+ for (int m = 0; m < M_COUNT; m++)
+ if (cost[m]) printf(" %d:%g", m, cost[m]);
+ printf("\n");
+ }
+}
+
+void win_para(WinOut *w, uint8_t font, const char *s, int max_w, uint16_t color) {
+ (void)font, (void)max_w, (void)color;
+ show(w, "|", s);
+}
+void win_setting(WinOut *w, bool checked, int action, const char *text) {
+ w->buttons++;
+ if (w->print) printf(" [%s] %s\n", checked ? "x" : " ", text);
+ if (w->nactions < 24) w->actions[w->nactions++] = action;
+}
+void win_later(WinOut *w) { (void)w; }
+void win_space(WinOut *w, int h) { (void)w, (void)h; }
+void win_heading(WinOut *w, const char *title, int one_action, int all_action, bool all, bool max, const char *one_tip,
+ const char *all_tip) {
+ (void)all, (void)max, (void)one_tip, (void)all_tip;
+ show(w, "##", title);
+ if (one_action >= 0 && w->nactions + 2 <= 24) w->actions[w->nactions++] = one_action, w->actions[w->nactions++] = all_action;
+}
+void win_bottom_button(WinOut *w, const char *label, int action, const char *tip_header, const char *tip) {
+ (void)tip_header, (void)tip;
+ w->buttons++;
+ if (w->print) printf(" [%s] (bottom)\n", label);
+ if (w->nactions < 24) w->actions[w->nactions++] = action;
+}
+
+/* the interface's part the city calls (the interface itself is not linked here) */
+void ui_show_goal_text(int goal) { (void)goal; }
+void ui_show_tutorial(int tutorial) { (void)tutorial; }
+void ui_show_message(const char *text) { (void)text; }
+void ui_show_simple(const char *text) { (void)text; }
+bool ui_story_window_open(void) { return false; }
+void meta_win_scenario(int s, float time) { (void)s, (void)time; }
+void ui_pause_for_window(void) {}
+
+static int failures;
+#define CHECK(c, ...) do { if (!(c)) { failures++; printf("FAIL: " __VA_ARGS__); printf("\n"); } } while (0)
+
+static Scratch scr;
+static void new_city(const char *story) {
+ game_reset();
+ unlocks_init();
+ story_set_name(story);
+}
+static uint16_t build(int w, int col, int row, const char *name) {
+ int cls = pcls_find(name);
+ if (cls < 0) {
+ printf("no class %s\n", name);
+ failures++;
+ return 0;
+ }
+ return bld_build_at(w, col, row, cls, false);
+}
+static void people(int w, int n, float amin, float amax) {
+ for (int i = 0; i < n; i++) cit_create(w, rnd_range(amin, amax), NONE, -1);
+}
+static void plenty(void) {
+ for (int m = 0; m < M_COUNT; m++) city.materials.m[m] = 1e7;
+}
+/* production of material m, summed over the days (the stats' today, which starts again at midnight) */
+typedef struct { double last, total; } Meter;
+static void meter(Meter *mt, int m) {
+ double cur = stats.materialProduction[m][0];
+ mt->total += cur >= mt->last ? cur - mt->last : cur;
+ mt->last = cur;
+}
+#define TICK_TIMEMOD (city.simulationSpeed * 0.6666667f * 2) /* timeMod of one sim_tick */
+#define TICKS_PER_DAY ((int)(1440 / (city.minutesPerTick * TICK_TIMEMOD)))
+
+/* ---------------------------------------------------------------- drawing: every permanent, every layer, both zooms */
+static uint16_t band_px[SCREEN_W * GFX_BAND];
+static uint8_t bad_shown[256];
+static int draw_all(void) {
+ /* nothing a drawer reaches may touch the search memory (the band lives there while a frame is drawn) */
+ memset(&scr, 0xA5, sizeof scr);
+ int n = 0;
+ for (int z = 1; z <= 2; z++) {
+ GfxBand b = {band_px, 0, GFX_BAND, 0, 0, SCREEN_W, GFX_BAND, z};
+ camera.zoom = z;
+ for (int layer = 0; layer < LAYER_COUNT; layer++) {
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (perms[i].flags & PF_USED) {
+ int bad = bld_bad_draws;
+ for (int dy = -20 * z; dy < GFX_BAND; dy += 7) bld_draw(&b, &perms[i], layer, 100, dy);
+ if (bld_bad_draws != bad && !bad_shown[perms[i].cls]) {
+ bad_shown[perms[i].cls] = 1;
+ printf(" bad drawing: %s layer %d\n", pcls[perms[i].cls].name, layer);
+ }
+ n++;
+ }
+ int bad = bld_bad_draws;
+ bld_draw_free(&b, layer);
+ if (bld_bad_draws != bad) printf(" bad free drawing on layer %d\n", layer);
+ }
+ }
+ camera.zoom = 1;
+ const uint8_t *s = (const uint8_t *)&scr;
+ for (size_t k = 0; k < sizeof scr; k++)
+ if (s[k] != 0xA5) {
+ failures++;
+ printf("FAIL: drawing wrote into the search memory at byte %zu\n", k);
+ break;
+ }
+ return n;
+}
+
+/* ---------------------------------------------------------------- windows, buttons and upgrades of one permanent */
+static int windows_shown, buttons_pressed, upgrades_bought, options_seen;
+static void exercise(uint16_t id, bool press) {
+ Perm *p = P(id);
+ if (!(p->flags & PF_USED)) return;
+ const PermOps *o = PC(p)->ops;
+ WinOut w = {0};
+ if (o && o->window) {
+ o->window(p, &w);
+ windows_shown++;
+ }
+ if (press && o && o->window_action)
+ for (int a = 0; a < w.nactions && (p->flags & PF_USED); a++)
+ if (w.actions[a] < WA_UI_BIRTH_CONTROL) {
+ o->window_action(p, w.actions[a]);
+ buttons_pressed++;
+ }
+ if (!(p->flags & PF_USED) || !is_building(p)) return;
+ UpgradeOption opt[16];
+ int n = upgrade_options(p, opt, 16);
+ options_seen += n;
+ if (!press) return;
+ for (int k = 0; k < n; k++) {
+ if (opt[k].kind == UO_POLICY) continue;
+ if (!opt[k].owned && upgrade_press(p, opt[k].upgrade, k & 1)) upgrades_bought++;
+ if (opt[k].canChangeLook) upgrade_change_look(p, opt[k].upgrade);
+ }
+}
+
+/* ---------------------------------------------------------------- 1: every class */
+static unsigned long city_sum(void) {
+ unsigned long h = (unsigned long)ncits * 31 + (unsigned long)perm_count() * 7;
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) h = h * 131 + cits[i].home * 3 + cits[i].job * 5 + cits[i].inPermanent + cits[i].hobby;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if (perms[i].flags & PF_USED) h = h * 7 + perms[i].cls + perms[i].upgrades * 3 + perms[i].mode;
+ return h;
+}
+static void every_class(int days) {
+ printf("== every class\n");
+ rnd_seed(1234);
+ new_city("FreePlayEmptyCanvas");
+ int ncls = 0;
+ for (int c = 0; c < npcls; c++)
+ if (pcls[c].kind == KIND_BUILDING) ncls++;
+ int cols = ncls + 24;
+ int wa = world_add(0, 400, cols * 20, 120, 11, 0);
+ int wb = world_add(cols * 20 + 200, 300, 400, 100, 12, 0);
+ world_add(-20, 600, cols * 20 + 640, 0, 0, 0); /* (the bottom world) */
+ plenty();
+ for (int u = 0; u < U_COUNT; u++) unlocks_unlock_uid(npcls + u);
+ int col = 0, built = 0;
+ for (int c = 0; c < npcls; c++) {
+ if (pcls[c].kind != KIND_BUILDING) continue;
+ if (pcls[c].base & B_ROOFTOP) {
+ bld_build_at(wa, col, 0, pcls_find("NormalHouse"), false);
+ built += bld_build_at(wa, col, 1, c, false) != 0;
+ } else {
+ built += bld_build_at(wa, col, 0, c, false) != 0;
+ }
+ col++;
+ }
+ /* neighbours that merge, stacks, trees, flying and teleporting */
+ for (int k = 0; k < 3; k++) build(wa, col + k, 0, "BotanicalGardens"), build(wa, col + k, 1, "BotanicalGardens");
+ col += 3;
+ for (int k = 0; k < 3; k++) build(wa, col, k, "RedwoodTree");
+ col++;
+ build(wa, col, 0, "HyperElevator"), build(wa, col, 1, "HyperElevator"), build(wa, col, 2, "Library");
+ col++;
+ build(wa, col++, 0, "Teleporter");
+ build(wa, col, 0, "NormalHouse"), build(wa, col++, 1, "LandingSite");
+ build(wa, col++, 0, "ScrapyardNightClub"), build(wa, col++, 0, "ScrapyardNightClub");
+ build(wa, col++, 0, "HoloGameHall");
+ build(wa, col++, 0, "Pub");
+ const char *res[] = {"Forest", "PineForest", "BranchyForest", "RedForest", "PurpleForest", "BirchForest", "Rock", "Boulder",
+ "AlienRuins", "AlienRuins", "ComputerAlienRuins"};
+ for (int k = 0; k < (int)(sizeof res / sizeof res[0]) && col < cols; k++) perm_new(pcls_find(res[k]), wa, col++, 0);
+ for (int k = 0; k < 6; k++) build(wb, k, 0, "NormalHouse");
+ build(wb, 6, 0, "Teleporter");
+ build(wb, 7, 0, "NormalHouse"), build(wb, 7, 1, "LandingSite");
+ for (int k = 8; k < 12; k++) perm_new(pcls_find("Forest"), wb, k, 0);
+ city_update_connections();
+ sim_update_pathfinder(true, 0);
+ people(wa, 260, 0, 70);
+ people(wb, 30, 18, 50);
+ saucer_spawn(wb, 4, 20, 30, -1);
+ printf(" %d of %d building classes built, %d permanents, %d citizens\n", built, ncls, perm_count(), ncits);
+ CHECK(built == ncls, "not every class was built");
+
+ /* the decorations' looks, as the story makes them */
+ for (int i = 1; i < MAX_PERMS; i++) {
+ Perm *p = &perms[i];
+ if (!(p->flags & PF_USED)) continue;
+ if (p->cls == CLS_RooftopDecoration) bld_customize(p, 9, true), bld_customize_color(p, 0x3080FF);
+ if (p->cls == CLS_ColoredBlock) bld_customize(p, 19, false), bld_customize_color(p, 0xFF0000);
+ if (p->cls == CLS_Loft || p->cls == CLS_LandedExplorationShip) bld_customize(p, -1, true);
+ }
+ CHECK(bld_door_x(P(perm_at(wa, 0, 0))) >= 0, "door");
+
+ int ticks = days * TICKS_PER_DAY, drawn = 0, k = 0;
+ for (int t = 0; t < ticks; t++) {
+ sim_tick(1.0f);
+ if (t % 37 == 0) {
+ /* a few windows and their buttons */
+ for (int j = 0; j < 4; j++) {
+ k = k % (MAX_PERMS - 1) + 1;
+ if (perms[k].flags & PF_USED) exercise((uint16_t)k, (t / 37) % 3 != 0);
+ }
+ }
+ if (t % 211 == 0) drawn += draw_all();
+ if (t == ticks / 3) {
+ /* research every city upgrade, turn every policy on, start a festival */
+ for (int u = 0; u < U_COUNT; u++)
+ if (upgrade_info[u].kind >= UK_CITY_UPGRADE) upgrade_press(NULL, u, false);
+ upgrade_smart_labs_buy();
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == CLS_FestivalHQ) PC(&perms[i])->ops->window_action(&perms[i], WA_SPECIAL);
+ printf(" a third of the way: festival %s\n", festival_running() ? "running" : "not running");
+ }
+ if (t == 2 * ticks / 3)
+ for (int u = 0; u < U_COUNT; u++)
+ if (upgrade_info[u].kind == UK_POLICY && policy_on(u)) upgrade_press(NULL, u, false);
+ plenty();
+ }
+ printf(" %d days: %d citizens, %d permanents; %d windows, %d buttons pressed, %d upgrade options seen, %d bought\n", days,
+ ncits, perm_count(), windows_shown, buttons_pressed, options_seen, upgrades_bought);
+ printf(" %d permanent drawings, %d parts outside their sprites\n", drawn, bld_bad_draws);
+ CHECK(bld_bad_draws == 0, "drawings outside their sprites");
+ int with_hobby = 0;
+ for (int i = 1; i < MAX_CITS; i++)
+ if ((cits[i].flags & CF_ALIVE) && cits[i].hobby) with_hobby++;
+ printf(" citizens with a hobby: %d; story questions: ruins %.2f, research craft %.0f, hackers %.0f, decryptor %.0f\n",
+ with_hobby, bld_alien_ruins_explored(), bld_research_bot_time(), bld_hacker_mission(), bld_decryptor_time());
+ {
+ int jobs = 0, workers = 0;
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && is_a(&perms[i], B_WORK)) jobs += bld_jobs(&perms[i]), workers += perms[i].nworkers;
+ printf(" jobs %d, workers %d, unemployed adults %d\n", jobs, workers, stats.laborForce - stats.peopleWithAJob);
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == CLS_ResearchBot) {
+ Cit *c = worker_at(&perms[i], 0);
+ printf(" research craft %d (row %d): %d workers", i, perms[i].row, perms[i].nworkers);
+ if (c) printf(", its pilot: action %d in %d at %.1f,%.1f flags %x", c->currentAction, c->inPermanent, c->relativeX, c->relativeY, c->flags);
+ printf("\n");
+ }
+ }
+ printf(" upgrades: SmartLights on %d buildings; BuildingRecycling bought %d; recycling %.2f\n",
+ upgrades_buildings_with("SmartLights"), upgrades_city_bought("BuildingRecycling"), recycling_amount);
+ CHECK(upgrades_city_bought("BirthControl") && upgrades.hasBirthControl, "research");
+
+ /* a save and a load: the same city */
+ mkdir("build", 0755);
+ mkdir("build/bldtest-saves", 0755);
+ host_save_dir("build/bldtest-saves");
+ unsigned long before = city_sum();
+ float speed = upgrades.computerChipFactorySpeed;
+ CHECK(save_game(), "save");
+ new_city("theLostShip");
+ CHECK(load_game(), "load");
+ unsigned long after = city_sum();
+ printf(" save and load: %s (chip factory speed %.3f, then %.3f)\n", before == after ? "same city" : "DIFFERENT", speed,
+ upgrades.computerChipFactorySpeed);
+ CHECK(before == after && fabsf(speed - upgrades.computerChipFactorySpeed) < 1e-4f, "save and load");
+ for (int t = 0; t < TICKS_PER_DAY / 2; t++) sim_tick(1.0f);
+ draw_all();
+
+ /* the windows' words, for a few */
+ const char *show_classes[] = {"Laboratory", "Forest", "AlienRuins", "HackerHQ", "TheMachine", "FestivalHQ", "MachinePartsFactory"};
+ for (int s = 0; s < (int)(sizeof show_classes / sizeof show_classes[0]); s++) {
+ int cls = pcls_find(show_classes[s]);
+ for (int i = 1; i < MAX_PERMS; i++)
+ if ((perms[i].flags & PF_USED) && perms[i].cls == cls) {
+ printf(" window of %s:\n", show_classes[s]);
+ WinOut w = {.print = true};
+ PC(&perms[i])->ops->window(&perms[i], &w);
+ break;
+ }
+ }
+}
+
+/* ---------------------------------------------------------------- 2: production rates */
+/* a small city on one world: houses for n workers, the buildings given, and n adults */
+static int small_city(int cols) {
+ new_city("FreePlayEmptyCanvas");
+ rnd_seed(77);
+ int w = world_add(0, 300, cols * 20, 100, 5, 0);
+ world_add(-20, 500, cols * 20 + 40, 0, 0, 0);
+ return w;
+}
+static void settle(int w, int n) {
+ plenty();
+ city_update_connections();
+ sim_update_pathfinder(true, 0);
+ people(w, n, 25, 35);
+}
+/* workers of class cls at work inside a permanent passing test, this tick */
+typedef bool (*Where)(const Perm *in, const Cit *c);
+static bool any_path; /* gatherers and farmers work along scripted paths: count them too */
+static int at_work(int cls, Where where, float *edu_sum) {
+ int n = 0;
+ if (edu_sum) *edu_sum = 0;
+ for (int i = 1; i < MAX_CITS; i++) {
+ const Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE) || !c->job || P(c->job)->cls != cls || c->currentAction != 0) continue;
+ if (!any_path && (c->flags & (CF_HAS_PATH | CF_REQUESTING_PATH))) continue;
+ const Perm *in = P(c->inPermanent);
+ if (!in || !where(in, c)) continue;
+ n++;
+ if (edu_sum) *edu_sum += cit_education_speed_modifier(c);
+ }
+ return n;
+}
+static bool in_lab(const Perm *in, const Cit *c) { return in->cls == CLS_Laboratory && !cit_is_at_ground_level(c); }
+static bool in_observatory(const Perm *in, const Cit *c) { (void)c; return in->cls == CLS_Observatory; }
+static bool in_forest(const Perm *in, const Cit *c) { (void)c; return is_a(in, B_FOREST); }
+static bool in_rock(const Perm *in, const Cit *c) { (void)c; return is_a(in, B_ROCK); }
+static bool in_farm(const Perm *in, const Cit *c) { (void)c; return in->cls == CLS_IndoorFarm; }
+static bool in_mpf(const Perm *in, const Cit *c) { (void)c; return in->cls == CLS_MachinePartsFactory; }
+
+static void report(const char *what, double measured, double expected, int days, int units, const char *unit, double tol) {
+ double per = measured / days / units, exp_per = expected / days / units;
+ double ratio = expected > 0 ? measured / expected : 0;
+ printf(" %-34s %8.3f %s/day each; formula %8.3f (ratio %.3f)\n", what, per, unit, exp_per, ratio);
+ if (tol > 0) CHECK(fabs(ratio - 1) <= tol, "%s off by more than %.0f%%", what, tol * 100);
+}
+
+static void rates(int days) {
+ printf("== production over %d days (formula: the original's, over the time the workers were at it)\n", days);
+ /* Laboratory: 0.00125 x timeMod x speed x labSpeed x education per tick, upstairs */
+ {
+ int w = small_city(8);
+ build(w, 0, 0, "NormalHouse"), build(w, 1, 0, "NormalHouse");
+ build(w, 3, 0, "Laboratory"), build(w, 4, 0, "Laboratory");
+ settle(w, 4);
+ Meter m = {0};
+ double exp = 0;
+ for (int t = 0; t < days * TICKS_PER_DAY; t++) {
+ float e;
+ at_work(CLS_Laboratory, in_lab, &e);
+ exp += 0.00125 * TICK_TIMEMOD * happiness.actionSpeedModifier * bonuses.labSpeed * e;
+ sim_tick(1.0f);
+ meter(&m, M_KNOWLEDGE);
+ }
+ report("knowledge per lab", m.total, exp, days, 2, "", 0.05);
+ }
+ /* Observatory: 0.002 x timeMod x speed x labSpeed x education per tick */
+ {
+ int w = small_city(8);
+ build(w, 0, 0, "NormalHouse"), build(w, 1, 0, "NormalHouse");
+ build(w, 3, 0, "Observatory");
+ settle(w, 4);
+ Meter m = {0};
+ double exp = 0;
+ for (int t = 0; t < days * TICKS_PER_DAY; t++) {
+ float e;
+ at_work(CLS_Observatory, in_observatory, &e);
+ exp += 0.002 * TICK_TIMEMOD * happiness.actionSpeedModifier * bonuses.labSpeed * e;
+ sim_tick(1.0f);
+ meter(&m, M_KNOWLEDGE);
+ }
+ report("knowledge per observatory", m.total, exp, days, 1, "", 0.05);
+ }
+ /* MachinePartsFactory: 0.0015 x timeMod x workers x speed x bonus per tick, 3 stone each */
+ {
+ int w = small_city(8);
+ build(w, 0, 0, "NormalHouse"), build(w, 1, 0, "NormalHouse");
+ uint16_t f = build(w, 3, 0, "MachinePartsFactory");
+ settle(w, 4);
+ city.materials.m[M_STONE] = 1e6;
+ Meter m = {0};
+ double exp = 0, stone0 = city.materials.m[M_STONE];
+ for (int t = 0; t < days * TICKS_PER_DAY; t++) {
+ int n = at_work(CLS_MachinePartsFactory, in_mpf, NULL);
+ exp += 0.0015 * TICK_TIMEMOD * n * happiness.actionSpeedModifier * bonuses.machinePartsFactorySpeed;
+ sim_tick(1.0f);
+ meter(&m, M_MACHINEPARTS);
+ }
+ report("machine parts per factory", m.total, exp, days, 1, "", 0.05);
+ double used = stone0 - city.materials.m[M_STONE];
+ printf(" %-34s %8.3f (formula 3)\n", "stone per machine part", m.total > 0 ? used / m.total : 0);
+ CHECK(m.total > 0 && fabs(used / m.total - 3) < 0.01, "stone per part");
+ /* its upgrade: two stone per part */
+ upgrade_press(P(f), U_MachinePartsFactoryEfficiency, false);
+ stone0 = city.materials.m[M_STONE];
+ Meter m2 = {stats.materialProduction[M_MACHINEPARTS][0], 0};
+ for (int t = 0; t < TICKS_PER_DAY; t++) sim_tick(1.0f), meter(&m2, M_MACHINEPARTS);
+ used = stone0 - city.materials.m[M_STONE];
+ printf(" %-34s %8.3f (formula 2)\n", " with Scrap Metal Recycling", m2.total > 0 ? used / m2.total : 0);
+ CHECK(m2.total > 0 && fabs(used / m2.total - 2) < 0.01, "upgrade efficiency");
+ }
+ any_path = true;
+ /* WoodcuttingCentre: 0.2 x earlyFix wood per cut, a cut every getInt(60, 90) / speed ticks at the forest
+ * (the bound counts no walking inside the forest) */
+ {
+ int w = small_city(12);
+ build(w, 0, 0, "NormalHouse"), build(w, 1, 0, "NormalHouse");
+ build(w, 2, 0, "WoodcuttingCentre");
+ for (int k = 4; k < 10; k++) perm_new(pcls_find("Forest"), w, k, 0);
+ settle(w, 4);
+ Meter m = {0};
+ double exp = 0, ticks_at = 0;
+ for (int t = 0; t < days * TICKS_PER_DAY; t++) {
+ int n = at_work(CLS_WoodcuttingCentre, in_forest, NULL);
+ ticks_at += n * TICK_TIMEMOD;
+ exp += n * TICK_TIMEMOD * 0.2 * early_fix() * happiness.actionSpeedModifier / 74.5;
+ sim_tick(1.0f);
+ meter(&m, M_WOOD);
+ }
+ report("wood per woodcutter", m.total, exp, days, 2, "", 0);
+ printf(" %-34s %8.1f ticks a day at the forest (of %d working)\n", "", ticks_at / days / 2, (int)(13 * 60 / city.minutesPerTick));
+ CHECK(m.total > 0 && m.total <= exp * 1.02, "wood above the bound");
+ }
+ /* StoneMine: 0.2 x stoneMiningSpeed x earlyFix stone per blow, a blow every getInt(90, 120) / speed ticks */
+ {
+ int w = small_city(12);
+ build(w, 0, 0, "NormalHouse"), build(w, 1, 0, "NormalHouse");
+ uint16_t mine = build(w, 2, 0, "StoneMine");
+ for (int k = 4; k < 8; k++) perm_new(pcls_find("Rock"), w, k, 0);
+ settle(w, 4);
+ upgrade_press(P(mine), U_BetterPickaxes, false);
+ Meter m = {0};
+ double exp = 0;
+ for (int t = 0; t < days * TICKS_PER_DAY; t++) {
+ int n = at_work(CLS_StoneMine, in_rock, NULL);
+ exp += n * TICK_TIMEMOD * 0.2 * 1.2 * upgrades.stoneMiningSpeed * early_fix() * happiness.actionSpeedModifier / 104.5;
+ sim_tick(1.0f);
+ meter(&m, M_STONE);
+ }
+ report("stone per miner (Better Pickaxes)", m.total, exp, days, 2, "", 0);
+ CHECK(m.total > 0 && m.total <= exp * 1.02, "stone above the bound");
+ }
+ /* IndoorFarm: 25 food a harvest; a cycle is about 74 growing (45 ticks), 100 harvesting (22.5) and 20 cleaning
+ * actions (45), plus the crops' own growth in day light */
+ {
+ int w = small_city(8);
+ build(w, 0, 0, "NormalHouse"), build(w, 1, 0, "NormalHouse");
+ build(w, 3, 0, "IndoorFarm"), build(w, 4, 0, "IndoorFarm");
+ settle(w, 4);
+ Meter m = {0};
+ double exp = 0;
+ for (int t = 0; t < days * TICKS_PER_DAY; t++) {
+ int n = at_work(CLS_IndoorFarm, in_farm, NULL);
+ exp += n * TICK_TIMEMOD * happiness.actionSpeedModifier * 25.0 / (74 * 45 + 100 * 22.5 + 20 * 45);
+ sim_tick(1.0f);
+ meter(&m, M_FOOD);
+ }
+ report("food per indoor farm", m.total, exp, days, 2, "", 0);
+ }
+}
+
+int main(int argc, char **argv) {
+ scratch = &scr;
+ int days = argc > 1 ? atoi(argv[1]) : 6;
+ every_class(days);
+ rates(days);
+ printf("%s (%d failures)\n", failures ? "FAIL" : "all good", failures);
+ return failures != 0;
+}
diff --git a/games/finalearth2/tests/noui.c b/games/finalearth2/tests/noui.c
new file mode 100644
index 00000000..4acdc1e1
--- /dev/null
+++ b/games/finalearth2/tests/noui.c
@@ -0,0 +1,32 @@
+/* The Final Earth 2: the interface's hooks, doing nothing, for the tests that run the game without it
+ * (simtest, storytest, savetest). */
+#include "../src/story.h"
+#include "../src/win.h"
+
+void win_title(WinOut *w, const char *s) { (void)w, (void)s; }
+void win_text(WinOut *w, const char *s) { (void)w, (void)s; }
+void win_info(WinOut *w, uint16_t icon, const char *s) { (void)w, (void)icon, (void)s; }
+void win_button(WinOut *w, uint16_t icon, const char *label, int action, bool enabled) {
+ (void)w, (void)icon, (void)label, (void)action, (void)enabled;
+}
+void win_cost(WinOut *w, const float cost[M_COUNT]) { (void)w, (void)cost; }
+void win_para(WinOut *w, uint8_t font, const char *s, int max_w, uint16_t color) {
+ (void)w, (void)font, (void)s, (void)max_w, (void)color;
+}
+void win_setting(WinOut *w, bool checked, int action, const char *text) { (void)w, (void)checked, (void)action, (void)text; }
+void win_later(WinOut *w) { (void)w; }
+void win_space(WinOut *w, int h) { (void)w, (void)h; }
+void win_heading(WinOut *w, const char *title, int one_action, int all_action, bool all, bool max, const char *one_tip,
+ const char *all_tip) {
+ (void)w, (void)title, (void)one_action, (void)all_action, (void)all, (void)max, (void)one_tip, (void)all_tip;
+}
+void win_bottom_button(WinOut *w, const char *label, int action, const char *tip_header, const char *tip) {
+ (void)w, (void)label, (void)action, (void)tip_header, (void)tip;
+}
+void ui_show_goal_text(int goal) { (void)goal; }
+void ui_show_tutorial(int tutorial) { (void)tutorial; }
+void ui_show_message(const char *text) { (void)text; }
+void ui_show_simple(const char *text) { (void)text; }
+bool ui_story_window_open(void) { return false; }
+void meta_win_scenario(int s, float time) { (void)s, (void)time; }
+void ui_pause_for_window(void) {}
diff --git a/games/finalearth2/tests/play.c b/games/finalearth2/tests/play.c
new file mode 100644
index 00000000..f91990b1
--- /dev/null
+++ b/games/finalearth2/tests/play.c
@@ -0,0 +1,223 @@
+/* Plays The Final Earth 2 on a computer, with scripted keys, and saves frames.
+ *
+ * play [--story N] [--frames N] [--keys "10-40:right,50:ok,..."] [--shots 30,60] [--out DIR] [--saves DIR]
+ * [--speed X] [--zoom Z] [--at X,Y] [--title] [--draw-all] [--cursor X,Y] [--materials N]
+ * [--building Class[:arg2]] [--move Class] [--open kind,arg,arg2] [--open-frame N] [--tutorial N] [--trace]
+ * [--add Class:world:col[:rgb]]... [--boost] [--explore N] [--storage-full]
+ *
+ * --title starts at the title screen (as the calculator does); otherwise the story's city is made and
+ * played. --draw-all draws every frame (to find the frames' peak use of the draw list). --cursor puts the
+ * city's cursor on a city position; --materials gives the city N of each material. --add builds a class on top
+ * of a world's column (a decoration tinted 0xRRGGBB); --boost starts a music festival's happiness boost;
+ * --explore explores every alien ruins N percent. --storage-full leaves no room for saves.
+ *
+ * Keys: left right up down ok back home toolbox var shift alpha plus minus backspace, and the typing keys as
+ * tkN (N: the key's number on the NumWorks keyboard, plat.h's TK_*: tk18 is exp, "a" with alpha). "a-b:key"
+ * holds the key from frame a to b, "a:key" for one frame. Screenshots are DIR/shot_<frame>.ppm. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include "../src/bld.h"
+#include "../src/game.h"
+#include "../src/scratch.h"
+#include "../src/story.h"
+#include "../src/view.h"
+#include "../src/ui.h"
+#include "../src/uii.h"
+#include "../src/classes.h"
+extern int ui_peak_prims, ui_peak_text, ui_dropped_total, ui_redraws;
+uint16_t bld_build_at(int w, int col, int row, int cls, bool replace);
+void ruins_explore(Perm *p, float amount);
+
+extern uint32_t host_keys, host_time;
+extern int host_text_key;
+extern bool host_storage_full;
+void host_shot(const char *path);
+void host_save_dir(const char *d);
+
+typedef struct { int a, b; uint32_t k; int tk; } Hold;
+static Hold holds[1024];
+static int nholds;
+
+static uint32_t key_bit(const char *s) {
+ if (!strncmp(s, "tk", 2)) return 0;
+ static const struct { const char *n; uint32_t k; } keys[] = {
+ {"left", K_LEFT}, {"right", K_RIGHT}, {"up", K_UP}, {"down", K_DOWN}, {"ok", K_OK}, {"back", K_BACK},
+ {"home", K_HOME}, {"toolbox", K_TOOLBOX}, {"var", K_VAR}, {"shift", K_SHIFT}, {"alpha", K_ALPHA},
+ {"plus", K_PLUS}, {"minus", K_MINUS}, {"backspace", K_BACKSPACE}};
+ for (size_t i = 0; i < sizeof keys / sizeof keys[0]; i++)
+ if (!strcmp(s, keys[i].n)) return keys[i].k;
+ fprintf(stderr, "unknown key %s\n", s);
+ return 0;
+}
+
+int main(int argc, char **argv) {
+ static Scratch scr;
+ scratch = &scr;
+ const char *out = "build/play", *saves = "build/play/saves", *shots = "";
+ int frames = 300, story_index = 0, zoom = 1;
+ float speed = 1, at_x = 0, at_y = 0;
+ bool at = false, title = false, draw_all = false, cursor = false, trace = false;
+ float cur_x = 0, cur_y = 0, materials = -1;
+ int open_kind = -1, open_arg = 0, open_arg2 = 0, open_frame = 1;
+ const char *building = NULL, *move = NULL;
+ int tutorial = 0, nadds = 0;
+ const char *adds[16];
+ bool boost = false;
+ float explore = 0;
+ for (int i = 1; i < argc; i++) {
+ if (!strcmp(argv[i], "--frames") && i + 1 < argc) frames = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--story") && i + 1 < argc) story_index = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i];
+ else if (!strcmp(argv[i], "--saves") && i + 1 < argc) saves = argv[++i];
+ else if (!strcmp(argv[i], "--shots") && i + 1 < argc) shots = argv[++i];
+ else if (!strcmp(argv[i], "--speed") && i + 1 < argc) speed = (float)atof(argv[++i]);
+ else if (!strcmp(argv[i], "--zoom") && i + 1 < argc) zoom = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--at") && i + 1 < argc) at = sscanf(argv[++i], "%f,%f", &at_x, &at_y) == 2;
+ else if (!strcmp(argv[i], "--cursor") && i + 1 < argc) cursor = sscanf(argv[++i], "%f,%f", &cur_x, &cur_y) == 2;
+ else if (!strcmp(argv[i], "--materials") && i + 1 < argc) materials = (float)atof(argv[++i]);
+ else if (!strcmp(argv[i], "--title")) title = true;
+ else if (!strcmp(argv[i], "--draw-all")) draw_all = true;
+ else if (!strcmp(argv[i], "--trace")) trace = true;
+ else if (!strcmp(argv[i], "--open") && i + 1 < argc) sscanf(argv[++i], "%d,%d,%d", &open_kind, &open_arg, &open_arg2);
+ else if (!strcmp(argv[i], "--open-frame") && i + 1 < argc) open_frame = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--building") && i + 1 < argc) building = argv[++i];
+ else if (!strcmp(argv[i], "--move") && i + 1 < argc) move = argv[++i];
+ else if (!strcmp(argv[i], "--tutorial") && i + 1 < argc) tutorial = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--add") && i + 1 < argc && nadds < 16) adds[nadds++] = argv[++i];
+ else if (!strcmp(argv[i], "--boost")) boost = true;
+ else if (!strcmp(argv[i], "--storage-full")) host_storage_full = true;
+ else if (!strcmp(argv[i], "--explore") && i + 1 < argc) explore = (float)atof(argv[++i]);
+ else if (!strcmp(argv[i], "--keys") && i + 1 < argc) {
+ char *s = strdup(argv[++i]);
+ for (char *t = strtok(s, ","); t && nholds < 1024; t = strtok(NULL, ",")) {
+ int a, b;
+ char k[16];
+ if (sscanf(t, "%d-%d:%15s", &a, &b, k) == 3) holds[nholds++] = (Hold){a, b, key_bit(k), -1};
+ else if (sscanf(t, "%d:%15s", &a, k) == 2) holds[nholds++] = (Hold){a, a, key_bit(k), -1};
+ else continue;
+ if (!strncmp(k, "tk", 2)) holds[nholds - 1].tk = atoi(k + 2);
+ }
+ }
+ }
+ mkdir(out, 0755);
+ mkdir(saves, 0755);
+ host_save_dir(saves);
+ rnd_seed(12345);
+ bg_init(777);
+ if (title) {
+ ui_init();
+ } else {
+ ui_before_city();
+ game_start(story_index, NULL);
+ ui_after_load();
+ city.simulationSpeed = speed;
+ if (zoom == 2) camera.zoom = 2;
+ if (at) camera.x = at_x, camera.y = at_y;
+ if (cursor) cursor_to((int)cur_x, (int)cur_y);
+ if (materials >= 0)
+ for (int m = 0; m < M_COUNT; m++) city.materials.m[m] = materials;
+ for (int a = 0; a < nadds; a++) {
+ char name[48];
+ int w = 0, col = 0;
+ unsigned rgb = 0;
+ snprintf(name, sizeof name, "%s", adds[a]);
+ char *c1 = strchr(name, ':');
+ if (!c1) continue;
+ *c1 = 0;
+ int n = sscanf(c1 + 1, "%d:%d:%x", &w, &col, &rgb);
+ int cls = pcls_find(name);
+ if (cls < 0 || n < 2 || w >= nworlds) continue;
+ uint16_t id = bld_build_at(w, col, col_stack_height(w, col), cls, false);
+ if (id && n == 3) bld_customize_color(P(id), (int32_t)rgb);
+ }
+ if (boost) happiness_add_boost(city.timeSinceStart + 10080, 25, true, HB_MUSIC_FESTIVAL);
+ for (int k = 1; explore > 0 && k < MAX_PERMS; k++)
+ if ((perms[k].flags & PF_USED) && is_a(&perms[k], B_RUINS)) ruins_explore(&perms[k], explore);
+ }
+ int peak_items = 0, peak_dropped = 0;
+ for (int f = 0; f < frames && game_running; f++) {
+ host_keys = 0;
+ host_text_key = -1;
+ for (int i = 0; i < nholds; i++)
+ if (f >= holds[i].a && f <= holds[i].b) {
+ host_keys |= holds[i].k;
+ if (holds[i].tk >= 0) host_text_key = holds[i].tk;
+ }
+ if (f == open_frame) {
+ /* a window opened straight away (for screenshots): --open kind,arg,arg2 or --building Class */
+ if (building) {
+ /* "Class" or "Class:arg2" */
+ char name[48];
+ int arg2 = 0;
+ snprintf(name, sizeof name, "%s", building);
+ char *colon = strchr(name, ':');
+ if (colon) *colon = 0, arg2 = atoi(colon + 1);
+ int c = pcls_find(name);
+ for (int k = 1; k < MAX_PERMS; k++)
+ if (c >= 0 && (perms[k].flags & PF_USED) && perms[k].cls == c) {
+ win_close_all();
+ cu.selected = (uint16_t)k;
+ win_open(WK_BUILDING, (uint16_t)k, (uint16_t)arg2);
+ break;
+ }
+ }
+ if (tutorial) {
+ /* a tutorial's arrows (as the story's goal starts them), its window already closed */
+ win_close_all();
+ ui_show_tutorial(tutorial);
+ tut_flags |= TF_WINDOW_CLOSED;
+ }
+ if (move) {
+ /* a world resource being moved (as explored alien ruins' Move button does) */
+ int c = pcls_find(move);
+ for (int k = 1; k < MAX_PERMS; k++)
+ if (c >= 0 && (perms[k].flags & PF_USED) && perms[k].cls == c) {
+ moving_resource = (uint16_t)k;
+ cu.selected = (uint16_t)k;
+ builder_start(BK_MOVE, 0, 0);
+ break;
+ }
+ }
+ if (open_kind >= 0) {
+ win_close_all();
+ win_open(open_kind, (uint16_t)open_arg, (uint16_t)open_arg2);
+ }
+ }
+ game_tick();
+ host_time += 33;
+ if (trace)
+ printf("%d: keys %x zone %d windows %d (top %d focus %d) category %d focus %d builder %d cursor %d,%d camera %.0f,%.0f panel %d\n", f,
+ host_keys, cu.zone, nwins, nwins ? wins[nwins - 1].kind : -1, nwins ? wins[nwins - 1].focus : -1, cu.category, cu.bfocus,
+ cu.build_kind, cu.cx, cu.cy, camera.x, camera.y, cu.pfocus);
+ char tag[16];
+ snprintf(tag, sizeof tag, ",%d,", f);
+ char list[1024];
+ snprintf(list, sizeof list, ",%s,", shots);
+ bool shot = strstr(list, tag) || f == frames - 1;
+ if (shot || draw_all) {
+ game_draw();
+ if (gfx_items() > peak_items) peak_items = gfx_items();
+ if (gfx_dropped() > peak_dropped) peak_dropped = gfx_dropped();
+ }
+ if (shot) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/shot_%d.ppm", out, f);
+ host_shot(p);
+ }
+ }
+ printf("story %d (goal %d): day %d %.1fh citizens %d permanents %d food %.1f wood %.1f stone %.1f happiness %.1f gfx items %d dropped %d\n",
+ story.index, story.goal, city_day(), city_hour(), ncits, perm_count(), city.materials.m[M_FOOD], city.materials.m[M_WOOD],
+ city.materials.m[M_STONE], happiness.happiness, gfx_items(), gfx_dropped());
+ if (trace) {
+ int counts[CLS_COUNT] = {0};
+ for (int k = 1; k < MAX_PERMS; k++)
+ if (perms[k].flags & PF_USED) counts[perms[k].cls]++;
+ for (int c = 0; c < CLS_COUNT; c++)
+ if (counts[c]) printf("%s x%d\n", pcls[c].name, counts[c]);
+ }
+ printf("peak: gfx items %d, gfx dropped %d, ui prims %d/%d, ui text %d/%d, ui dropped %d, windows laid out again %d\n",
+ peak_items, peak_dropped, ui_peak_prims, UI_PRIMS, ui_peak_text, UI_TEXT, ui_dropped_total, ui_redraws);
+ return 0;
+}
diff --git a/games/finalearth2/tests/render.c b/games/finalearth2/tests/render.c
new file mode 100644
index 00000000..7f5dc1b1
--- /dev/null
+++ b/games/finalearth2/tests/render.c
@@ -0,0 +1,288 @@
+/* Drawing tests: renders scenes with gfx.c and bg.c and saves them as images.
+ *
+ * render [DIR] (default build/shots)
+ *
+ * Writes DIR/a_title_night, b_title_midday, c_city, d_fonts and e_city_zoom2, each as .ppm and
+ * .png, and prints what each frame took on this computer. Scenes follow the
+ * original's stories/displayCity.json (the title screen's city: theLostShip's
+ * island, seed 1000) with a few buildings added for the city. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <time.h>
+#include "../src/bg.h"
+#include "../src/data.h"
+#include "../src/gfx.h"
+
+extern uint16_t host_fb[SCREEN_W * SCREEN_H];
+void host_shot(const char *path);
+
+/* ---------------------------------------------------------------- PNG (stored, no compression) */
+static uint32_t crc_table[256];
+static uint32_t crc(uint32_t c, const uint8_t *p, size_t n) {
+ if (!crc_table[1])
+ for (uint32_t i = 0; i < 256; i++) {
+ uint32_t v = i;
+ for (int k = 0; k < 8; k++) v = v & 1 ? 0xEDB88320u ^ (v >> 1) : v >> 1;
+ crc_table[i] = v;
+ }
+ c = ~c;
+ while (n--) c = crc_table[(c ^ *p++) & 255] ^ (c >> 8);
+ return ~c;
+}
+static void be32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)(v >> 24), p[1] = (uint8_t)(v >> 16), p[2] = (uint8_t)(v >> 8), p[3] = (uint8_t)v; }
+static void chunk(FILE *f, const char *type, const uint8_t *data, uint32_t n) {
+ uint8_t h[8];
+ be32(h, n);
+ memcpy(h + 4, type, 4);
+ fwrite(h, 1, 8, f);
+ if (n) fwrite(data, 1, n, f);
+ uint32_t c = crc(crc(0, (const uint8_t *)type, 4), data, n);
+ be32(h, c);
+ fwrite(h, 1, 4, f);
+}
+static void save_png(const char *path) {
+ enum { ROW = 1 + SCREEN_W * 3, RAW = ROW * SCREEN_H };
+ static uint8_t raw[RAW], z[RAW + RAW / 65535 * 5 + 64];
+ for (int y = 0; y < SCREEN_H; y++) {
+ uint8_t *r = raw + y * ROW;
+ r[0] = 0;
+ for (int x = 0; x < SCREEN_W; x++) {
+ uint16_t c = host_fb[y * SCREEN_W + x];
+ r[1 + 3 * x] = (uint8_t)((c >> 11) * 255 / 31);
+ r[2 + 3 * x] = (uint8_t)(((c >> 5) & 63) * 255 / 63);
+ r[3 + 3 * x] = (uint8_t)((c & 31) * 255 / 31);
+ }
+ }
+ /* zlib with stored blocks */
+ size_t n = 0;
+ z[n++] = 0x78, z[n++] = 1;
+ uint32_t a = 1, b = 0;
+ for (size_t at = 0; at < RAW;) {
+ size_t len = RAW - at > 65535 ? 65535 : RAW - at;
+ z[n++] = at + len == RAW;
+ z[n++] = (uint8_t)len, z[n++] = (uint8_t)(len >> 8), z[n++] = (uint8_t)~len, z[n++] = (uint8_t)(~len >> 8);
+ memcpy(z + n, raw + at, len);
+ for (size_t i = 0; i < len; i++) a = (a + raw[at + i]) % 65521, b = (b + a) % 65521;
+ n += len;
+ at += len;
+ }
+ be32(z + n, b << 16 | a);
+ n += 4;
+ FILE *f = fopen(path, "wb");
+ if (!f) return;
+ fwrite("\x89PNG\r\n\x1a\n", 1, 8, f);
+ uint8_t ihdr[13];
+ be32(ihdr, SCREEN_W);
+ be32(ihdr + 4, SCREEN_H);
+ ihdr[8] = 8, ihdr[9] = 2, ihdr[10] = ihdr[11] = ihdr[12] = 0;
+ chunk(f, "IHDR", ihdr, 13);
+ chunk(f, "IDAT", z, (uint32_t)n);
+ chunk(f, "IEND", NULL, 0);
+ fclose(f);
+}
+
+static const char *out_dir = "build/shots";
+static void save(const char *name) {
+ char p[512];
+ snprintf(p, sizeof p, "%s/%s.ppm", out_dir, name);
+ host_shot(p);
+ snprintf(p, sizeof p, "%s/%s.png", out_dir, name);
+ save_png(p);
+ printf("render: %s/%s.ppm, .png (%d commands, %d dropped)\n", out_dir, name, gfx_items(), gfx_dropped());
+}
+
+/* ---------------------------------------------------------------- the scene */
+/* displayCity.json's planets and moons */
+static const BgPlanet planets[] = {
+ {SPR_PLANETS_SMALL, 40, 2, 120, -80, 0.5f}, {SPR_PLANETS_MEDIUM, 80, 1, 300, -200, 1},
+ {SPR_PLANETS_SMALL, 40, 0, 40, -500, 0.2f}, {SPR_PLANETS_BIG, 100, 1, 900, 0, 1.3f},
+ {SPR_PLANETS_BIG, 100, 3, -900, 400, 1.5f}, {SPR_PLANETS_MEDIUM, 80, 3, -400, 100, 0.1f}};
+
+static BgWorld world = {0, 160, 440, 100, 1000, BG_LOOK_NORMAL, 0};
+#define COLS 22
+static uint8_t decos[COLS];
+
+/* what stands on each column: world resources (displayCity.json) and buildings, bottom first */
+enum { NONE_, FOREST, ROCK, RUINS, RUINS2, SHIP, NORMALHOUSE, WOODCUTTING, STONEMINE, INDOORFARM };
+static uint8_t stack[COLS][4];
+static const uint16_t building_spr[] = {[SHIP] = SPR_EXPLORATIONSHIP, [NORMALHOUSE] = SPR_NORMALHOUSE,
+ [WOODCUTTING] = SPR_WOODCUTTINGCENTRE, [STONEMINE] = SPR_STONEMINE,
+ [INDOORFARM] = SPR_INDOORFARM};
+
+static void set_title_world(bool city) {
+ memset(stack, 0, sizeof stack);
+ static const struct { int col, what; } res[] = {{0, FOREST}, {6, ROCK}, {7, FOREST}, {9, ROCK}, {12, RUINS},
+ {14, FOREST}, {17, RUINS2}, {18, ROCK}, {19, FOREST},
+ {20, ROCK}, {21, FOREST}};
+ bg_world_decorate(&world, decos);
+ for (size_t i = 0; i < sizeof res / sizeof res[0]; i++) {
+ stack[res[i].col][0] = (uint8_t)res[i].what;
+ decos[res[i].col] = 0; /* World.createWorldResource removes the decoration */
+ }
+ stack[3][0] = SHIP;
+ decos[3] = 0;
+ if (city) {
+ static const struct { int col; uint8_t s[4]; } b[] = {
+ {4, {NORMALHOUSE, NORMALHOUSE}}, {5, {WOODCUTTING, NORMALHOUSE, NORMALHOUSE}}, {8, {STONEMINE}},
+ {10, {INDOORFARM, INDOORFARM, NORMALHOUSE}}, {11, {NORMALHOUSE, WOODCUTTING}}};
+ for (size_t i = 0; i < sizeof b / sizeof b[0]; i++) {
+ memcpy(stack[b[i].col], b[i].s, 4);
+ decos[b[i].col] = 0;
+ }
+ }
+}
+
+/* a citizen: spr_humans frame (2 x 5, anchor at its bottom) */
+typedef struct { float x, y; int sprite; } Walker;
+
+static void draw_citizen(const BgCamera *cam, const Walker *w) {
+ int z = cam->zoom;
+ gfx_zoom(z);
+ gfx_frame(SPR_HUMANS, 2, w->sprite, bg_screen_x(cam, w->x), bg_screen_y(cam, w->y - 5), 0, 255);
+}
+
+static void draw_city(const BgCamera *cam, double time, bool city) {
+ int z = cam->zoom;
+ bg_draw_sky(cam, time);
+ gfx_zoom(z);
+ /* buildings' backs (cityBgStage), then the farms' crops in front of them */
+ for (int c = 0; c < COLS; c++)
+ for (int r = 0; r < 4 && stack[c][r]; r++) {
+ int k = stack[c][r];
+ if (k < SHIP) continue;
+ int x = bg_screen_x(cam, (float)(world.x + 20 * c)), y = bg_screen_y(cam, (float)(world.y - 20 * (1 + r)));
+ gfx_sprite_part(building_spr[k], 44, 0, 20, 20, x, y, 0, 255);
+ }
+ for (int c = 0; c < COLS; c++)
+ for (int r = 0; r < 4 && stack[c][r]; r++)
+ if (stack[c][r] == INDOORFARM)
+ gfx_frame(SPR_INDOORFARM_CROPS, 20, r ? 7 : 4, bg_screen_x(cam, (float)(world.x + 20 * c)),
+ bg_screen_y(cam, (float)(world.y - 20 * (1 + r))), 0, 255);
+ /* citizens inside buildings */
+ if (city) {
+ /* (a citizen inside stands 1 pixel above its floor's bottom: Citizen.updateDisplay) */
+ static const Walker inside[] = {{4 * 20 + 6, 159, 3}, {5 * 20 + 12, 139, 17}, {10 * 20 + 9, 159, 25},
+ {11 * 20 + 14, 139, 40}, {5 * 20 + 4, 119, 8}};
+ for (size_t i = 0; i < sizeof inside / sizeof inside[0]; i++) draw_citizen(cam, &inside[i]);
+ }
+ /* the island and its decorations, buildings' fronts, world resources (cityStage) */
+ bg_draw_world(&world, decos, cam);
+ gfx_zoom(z);
+ for (int c = 0; c < COLS; c++)
+ for (int r = 0; r < 4 && stack[c][r]; r++) {
+ int k = stack[c][r];
+ int x = bg_screen_x(cam, (float)(world.x + 20 * c)), y = bg_screen_y(cam, (float)(world.y - 20 * (1 + r)));
+ switch (k) {
+ case FOREST: gfx_frame(SPR_FOREST, 20, 0, x, y, 0, 255); break;
+ case ROCK: gfx_frame(SPR_ROCK, 20, 0, x, y, 0, 255); break;
+ case RUINS: gfx_sprite(SPR_ALIENRUINS, x, y, 0, 255); break;
+ case RUINS2: gfx_sprite(SPR_ALIENRUINS_2, x, y, 0, 255); break;
+ default:
+ /* NormalBuildingDrawer: the ground floor's frame is the second */
+ gfx_sprite_part(building_spr[k], r == 0 ? 22 : 0, 0, 20, 20, x, y, 0, 255);
+ if (k == NORMALHOUSE && r == 0) gfx_frame(SPR_COLOREDDOORS, 20, c % 6, x, y, 0, 255);
+ }
+ }
+ /* citizens outside (displayCity: five, between x 60 and 80) */
+ static const Walker outside[] = {{61, 160, 0}, {66, 160, 12}, {70, 160, 30}, {74, 160, 7}, {79, 160, 21},
+ {130, 160, 44}, {150, 160, 2}, {205, 160, 15}};
+ for (size_t i = 0; i < (city ? 8u : 5u); i++) draw_citizen(cam, &outside[i]);
+}
+
+static double frame_ms(void (*fn)(void *), void *arg) {
+ struct timespec a, b;
+ clock_gettime(CLOCK_MONOTONIC, &a);
+ int n = 20;
+ for (int i = 0; i < n; i++) fn(arg);
+ clock_gettime(CLOCK_MONOTONIC, &b);
+ return ((double)(b.tv_sec - a.tv_sec) * 1e3 + (double)(b.tv_nsec - a.tv_nsec) / 1e6) / n;
+}
+
+typedef struct { BgCamera cam; double time; bool city, title; } Scene;
+
+static void scene(void *p) {
+ const Scene *s = p;
+ gfx_begin();
+ draw_city(&s->cam, s->time, s->city);
+ if (s->title) { /* MainMenu's logo, centred 10 pixels from the top */
+ gfx_zoom(1);
+ gfx_sprite(SPR_TITLE, SCREEN_W / 2 - (SPR_TITLE_W + 1) / 2, 10, 0, 255);
+ }
+ gfx_end();
+}
+
+static void fonts(void *p) {
+ (void)p;
+ static const char *names[FONT_COUNT] = {"standard", "standard10", "standard15", "standard16", "standard18"};
+ gfx_begin();
+ gfx_fill(rgb565_near(0x281460));
+ gfx_zoom(1);
+ /* a window as the original's GUI draws its back (spr_9p_window's middle, see-through) */
+ gfx_rect(4, 4, SCREEN_W - 8, SCREEN_H - 8, rgb565_near(0x000000), 96);
+ int y = 8;
+ char line[128];
+ for (int f = 0; f < FONT_COUNT; f++) {
+ snprintf(line, sizeof line, "%s: The Final Earth 2", names[f]);
+ gfx_text(f, 8, y, line, 0xFFFF);
+ y += gfx_font_height(f) + 1;
+ snprintf(line, sizeof line, "0123456789 %d px, ABC xyz +-/%%() Straße é ë ü", gfx_text_width(f, line));
+ gfx_text(f, 8, y, line, rgb565_near(0xFFE08A));
+ y += gfx_font_height(f) + 3;
+ }
+ /* kerning (standard16 has pairs such as " A"), alpha and a clipped line */
+ gfx_text(FONT_16, 8, y, "A A AV To kerning", rgb565_near(0xA0FFA0));
+ gfx_text_ex(FONT_STANDARD, 180, y, "half see-through", 0xFFFF, 128);
+ y += gfx_font_height(FONT_16) + 2;
+ gfx_clip(8, y, 100, 6);
+ gfx_text(FONT_STANDARD, 8, y, "clipped to a 100 x 6 box: cut", rgb565_near(0xFF8080));
+ gfx_clip(0, 0, SCREEN_W, SCREEN_H);
+ gfx_zoom(2);
+ gfx_text(FONT_10, 120, y, "zoom 2", 0xFFFF);
+ gfx_end();
+}
+
+int main(int argc, char **argv) {
+ if (argc > 1) out_dir = argv[1];
+ mkdir("build", 0777);
+ mkdir(out_dir, 0777);
+ bg_init(1);
+ bg_set_planets(planets, (int)(sizeof planets / sizeof planets[0]));
+ /* City.getCityEdges for displayCity: its world (the stacks on it are lower than y 0) */
+ BgEdges edges = {0, 440, 0, 260};
+ bg_clouds_start(&edges);
+ for (int i = 0; i < 120; i++) bg_clouds_update(2, &edges);
+ printf("render: %d clouds\n", bg_cloud_count());
+
+ /* the title screen's view: viewPos (225, 150) (displayCity's viewYFromBottom 270), zoom 1 */
+ Scene s = {{225 - SCREEN_W / 2, 150 - SCREEN_H / 2, 1}, 0, false, true};
+ set_title_world(false);
+ double ms = frame_ms(scene, &s);
+ save("a_title_night");
+ printf("render: %.2f ms a frame (this computer, sanitizers on)\n", ms);
+ s.time = 12 * 60;
+ ms = frame_ms(scene, &s);
+ save("b_title_midday");
+ printf("render: %.2f ms a frame\n", ms);
+ set_title_world(true);
+ s = (Scene){{170 - SCREEN_W / 2, 120 - SCREEN_H / 2, 1}, 16.5 * 60, true, false};
+ ms = frame_ms(scene, &s);
+ save("c_city");
+ printf("render: %.2f ms a frame\n", ms);
+ fonts(NULL);
+ save("d_fonts");
+ s.cam = (BgCamera){170 - SCREEN_W / 4, 120 - SCREEN_H / 4, 2};
+ ms = frame_ms(scene, &s);
+ save("e_city_zoom2");
+ printf("render: %.2f ms a frame\n", ms);
+
+ /* the islands' collision mask, as WorldImage's */
+ printf("render: mask of the island (20 x 20 cells):\n");
+ for (int cy = 0; cy < world.h / 20; cy++) {
+ printf(" ");
+ for (int cx = 0; cx < world.w / 20; cx++) putchar(bg_world_mask(&world, cx, cy) ? '#' : '.');
+ putchar('\n');
+ }
+ return 0;
+}
diff --git a/games/finalearth2/tests/savetest.c b/games/finalearth2/tests/savetest.c
new file mode 100644
index 00000000..8bbf27dd
--- /dev/null
+++ b/games/finalearth2/tests/savetest.c
@@ -0,0 +1,56 @@
+/* Saves cities and loads them back: the same city, which then runs on. */
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include "../src/bld.h"
+#include "../src/save.h"
+#include "../src/scratch.h"
+#include "../src/story.h"
+
+void host_save_dir(const char *d);
+
+static unsigned long city_sum(void) {
+ unsigned long h = (unsigned long)ncits * 31 + (unsigned long)perm_count() * 7 + (unsigned long)city.timeSinceStart;
+ for (int i = 1; i < MAX_CITS; i++)
+ if (cits[i].flags & CF_ALIVE) h = h * 131 + cits[i].home * 3 + cits[i].job * 5 + cits[i].inPermanent;
+ return h;
+}
+
+int main(int argc, char **argv) {
+ static Scratch scr;
+ scratch = &scr;
+ const char *dir = argc > 1 ? argv[1] : "build/savetest_out";
+ mkdir(dir, 0755);
+ host_save_dir(dir);
+ int bad = 0;
+ for (int s = 0; s < nstories; s++) {
+ rnd_seed(99 + s);
+ story_new_city(s, NULL);
+ for (int t = 0; t < 2000; t++) sim_tick(1.0f);
+ unsigned long before = city_sum();
+ double food = city.materials.m[M_FOOD];
+ if (!save_game()) { printf("%s: save failed\n", stories[s].link); bad++; continue; }
+ char p[512];
+ snprintf(p, sizeof p, "%s/finalearth2.sav", dir);
+ FILE *f = fopen(p, "rb");
+ fseek(f, 0, SEEK_END);
+ long size = ftell(f);
+ fclose(f);
+ story_new_city((s + 1) % nstories, NULL); /* something else in between */
+ /* every other city: the save gone, as after installing the app again; it comes back from the script's copy */
+ bool restored = s % 2 == 1;
+ if (restored) {
+ remove(p);
+ save_restore();
+ }
+ if (!load_game()) { printf("%s: load failed\n", stories[s].link); bad++; continue; }
+ unsigned long after = city_sum();
+ printf("%-26s save %5ld bytes, citizens %3d permanents %3d: %s%s\n", stories[s].link, size, ncits, perm_count(),
+ before == after && food == city.materials.m[M_FOOD] ? "same city" : "DIFFERENT",
+ restored ? " (from the copy)" : "");
+ if (before != after) bad++;
+ for (int t = 0; t < 1000; t++) sim_tick(1.0f);
+ }
+ printf("%s\n", bad ? "FAIL" : "all good");
+ return bad != 0;
+}
diff --git a/games/finalearth2/tests/simtest.c b/games/finalearth2/tests/simtest.c
new file mode 100644
index 00000000..434beeeb
--- /dev/null
+++ b/games/finalearth2/tests/simtest.c
@@ -0,0 +1,51 @@
+/* Runs the simulation without drawing: a world, some buildings and
+ * citizens, for many ticks, and prints what the citizens are doing. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "../src/bld.h"
+#include "../src/scratch.h"
+
+void story_set_name(const char *n);
+
+static const char *action_name(const Cit *c) {
+ static char b[64];
+ snprintf(b, sizeof b, "act %d path %d step %d", c->currentAction, c->currentPathAction, c->pathPos);
+ return b;
+}
+
+int main(int argc, char **argv) {
+ int ticks = argc > 1 ? atoi(argv[1]) : 3000;
+ static Scratch scr;
+ scratch = &scr;
+ game_reset();
+ story_set_name("theLostShip");
+ int w = world_add(0, 160, 440, 100, 1000, 0);
+ perm_new(pcls_find("Forest"), w, 0, 0);
+ perm_new(pcls_find("Rock"), w, 6, 0);
+ perm_new(pcls_find("Forest"), w, 7, 0);
+ uint16_t ship = perm_new(pcls_find("LandedExplorationShip"), w, 10, 0);
+ uint16_t wc = perm_new(pcls_find("WoodcuttingCentre"), w, 3, 0);
+ uint16_t h1 = perm_new(pcls_find("NormalHouse"), w, 4, 0);
+ uint16_t h2 = perm_new(pcls_find("NormalHouse"), w, 4, 1);
+ uint16_t sm = perm_new(pcls_find("StoneMine"), w, 5, 0);
+ uint16_t farm = perm_new(pcls_find("IndoorFarm"), w, 5, 1);
+ city_update_connections();
+ for (int i = 0; i < 8; i++) cit_new(w, (float)(220 + i * 3), 20 + i, ship);
+ cit_new(w, 100, 5, NONE);
+ printf("perms %d citizens %d (ship %u wc %u houses %u %u mine %u farm %u)\n", perm_count(), ncits, ship, wc, h1, h2, sm, farm);
+ for (int t = 0; t < ticks; t++) {
+ sim_tick(1.0f);
+ if (t % 600 == 0 || t == ticks - 1) {
+ printf("--- tick %d day %d %.1fh\n", t, city_day(), city_hour());
+ for (int i = 1; i < MAX_CITS; i++) {
+ Cit *c = &cits[i];
+ if (!(c->flags & CF_ALIVE)) continue;
+ float x, y;
+ cit_city_position(c, &x, &y);
+ printf(" cit %d age %.1f home %u job %u school %u in %u at %.0f,%.0f %s\n", i, cit_age(c), c->home, c->job, c->school,
+ c->inPermanent, x, y, action_name(c));
+ }
+ }
+ }
+ return 0;
+}
diff --git a/games/finalearth2/tests/storytest.c b/games/finalearth2/tests/storytest.c
new file mode 100644
index 00000000..c684e559
--- /dev/null
+++ b/games/finalearth2/tests/storytest.c
@@ -0,0 +1,26 @@
+/* Starts every scenario and free play map without drawing, runs it a while,
+ * and prints its worlds, permanents, citizens and current goal. */
+#include <stdio.h>
+#include <stdlib.h>
+#include "../src/bld.h"
+#include "../src/scratch.h"
+#include "../src/story.h"
+
+int main(int argc, char **argv) {
+ static Scratch scr;
+ scratch = &scr;
+ int ticks = argc > 1 ? atoi(argv[1]) : 2000;
+ for (int s = 0; s < nstories; s++) {
+ rnd_seed(1234 + s);
+ story_new_city(s, NULL);
+ int cols = 0;
+ for (int w = 0; w < nworlds; w++) cols += worlds[w].ncols;
+ printf("%-26s worlds %2d cols %3d perms %3d citizens %3d goal %s\n", stories[s].link, nworlds, cols, perm_count(), ncits,
+ story_goal() ? story_goal()->name : "-");
+ for (int t = 0; t < ticks; t++) sim_tick(1.0f);
+ printf("%-26s after %d ticks: day %d citizens %d food %.1f wood %.1f stone %.1f goal %s happiness %.1f\n", "", ticks,
+ city_day(), ncits, city.materials.m[M_FOOD], city.materials.m[M_WOOD], city.materials.m[M_STONE],
+ story_goal() ? story_goal()->name : "-", happiness.happiness);
+ }
+ return 0;
+}
diff --git a/games/finalearth2/tools/gen_classes.py b/games/finalearth2/tools/gen_classes.py
new file mode 100644
index 00000000..1d5c88e8
--- /dev/null
+++ b/games/finalearth2/tools/gen_classes.py
@@ -0,0 +1,265 @@
+#!/usr/bin/env python3
+"""Makes src/classes.c and src/classes.h, the table of permanents' classes,
+from the original's data (buildinginfo.json, buildableWorldResourcesInfo.json)
+and its classes' code (the split/ folder of game_js.js): each class's base
+classes, the numbers its constructor sets and the constants its getters
+return, inherited from its ancestors.
+
+A class's behaviour is a PermOps `ops_<Class>` defined in a src/bld_*.c file;
+a class without one uses its nearest ancestor's (ops_Work, ops_House...).
+
+ python3 -I tools/gen_classes.py [REFERENCE_DIR]
+"""
+import json
+import os
+import re
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+GAME = os.path.dirname(HERE)
+REF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("FE2_REF", os.path.expanduser("~/Documents/Assets/gamesrc/finalearth2/web14"))
+SPLIT = os.path.join(REF, "split")
+
+MATS = ["food", "wood", "stone", "machineParts", "refinedMetal", "computerChips", "cacao", "chocolate", "graphene",
+ "rocketFuel", "knowledge"]
+M_ENUM = ["M_FOOD", "M_WOOD", "M_STONE", "M_MACHINEPARTS", "M_REFINEDMETAL", "M_COMPUTERCHIPS", "M_CACAO",
+ "M_CHOCOLATE", "M_GRAPHENE", "M_ROCKETFUEL", "M_KNOWLEDGE"]
+# out of scope: paid versions, holidays, snow
+EXCLUDE_FLAGS = {"premium", "halloween"}
+EXCLUDE = {"ChristmasTree", "ChristmasMarket", "UnknownBuilding", "ForestSnow",
+ "CacaoFarm", "ChocolateFactory", "BoardGameStore", "ShadyHome", "TheContraption"} # scrapped in the original
+CATEGORIES = ["Houses", "Production", "Services", "Entertainment", "Transportation", "Unique Buildings",
+ "Decoration & Nature", "Hidden", "None"]
+
+static = open(os.path.join(SPLIT, "_static_init.js"), encoding="utf-8").read()
+lang = open(os.path.join(REF, "lang_en.csv"), encoding="utf-8").read()
+HINTS = set(re.findall(r'buildinginfo\.json/(\w+)\.showUnlockHint', lang))
+
+
+def read_class(prefix, name):
+ p = os.path.join(SPLIT, f"{prefix}.{name}.js")
+ return open(p, encoding="utf-8").read() if os.path.exists(p) else ""
+
+
+def class_file(name):
+ for prefix in ("buildings", "worldResources", ""):
+ p = os.path.join(SPLIT, f"{prefix}.{name}.js" if prefix else f"{name}.js")
+ if os.path.exists(p):
+ return open(p, encoding="utf-8").read()
+ return ""
+
+
+def parse(name):
+ """super class, interfaces, constructor numbers, constant getters"""
+ src = class_file(name)
+ info = {"super": None, "ifaces": [], "ctor": {}, "get": {}}
+ m = re.search(r'__super__ = (\w+);', src)
+ if m:
+ sup = m.group(1)
+ info["super"] = sup.split("_", 1)[1] if sup.startswith(("buildings_", "worldResources_")) else sup
+ m = re.search(r'__interfaces__ = \[([^\]]*)\]', src)
+ if m:
+ info["ifaces"] = [i.strip().split("_")[-1] for i in m.group(1).split(",") if i.strip()]
+ ctor = src.split("$hxClasses", 1)[0]
+ for k, v in re.findall(r'this\.(\w+) = (-?[\d.]+|true|false);', ctor):
+ info["ctor"].setdefault(k, v)
+ for k, v in re.findall(r'get_(\w+): function\(\) \{\n\t\treturn (-?[\d.]+|true|false|[\w.]+);\n\t\}', src):
+ info["get"].setdefault(k, v)
+ return info
+
+
+def chain(prefix, name):
+ """the class and its ancestors, nearest first"""
+ out = []
+ while name and name != "Permanent" and len(out) < 12:
+ info = parse(name)
+ out.append((name, info))
+ name = info["super"]
+ return out
+
+
+def inherited(ch, kind, key, default=None):
+ for _, info in ch:
+ if key in info[kind]:
+ return info[kind][key]
+ return default
+
+
+def flit(v):
+ """a C float literal"""
+ t = f"{v:g}"
+ if "." not in t and "e" not in t:
+ t += ".0"
+ return t + "f"
+
+
+def num(v, default=0):
+ try:
+ return float(v)
+ except (TypeError, ValueError):
+ return default
+
+
+ops_defined = set()
+for f in os.listdir(os.path.join(GAME, "src")):
+ if f.startswith("bld") and f.endswith(".c"):
+ ops_defined |= set(re.findall(r'^const PermOps ops_(\w+)\b', open(os.path.join(GAME, "src", f)).read(), re.M))
+
+spr_known = set()
+data_h = os.path.join(GAME, "src", "data.h")
+if os.path.exists(data_h):
+ spr_known = set(re.findall(r'\b(SPR_\w+)\b', open(data_h).read()))
+
+
+def spr_id(name):
+ if not name:
+ return "0"
+ s = "SPR_" + re.sub(r'[^A-Z0-9]', '_', name.replace("spr_", "", 1).upper())
+ return s if (not spr_known or s in spr_known) else "0"
+
+
+rows = []
+binfo = json.load(open(os.path.join(REF, "buildinginfo.json")))
+winfo = json.load(open(os.path.join(REF, "buildableWorldResourcesInfo.json")))
+for r in ["Forest", "PineForest", "BranchyForest", "RedForest", "PurpleForest", "BirchForest", "Rock", "Boulder",
+ "AlienRuins", "ComputerAlienRuins"]:
+ info = next((w for w in winfo if w["className"] == r), {"className": r})
+ ch = chain("worldResources", r)
+ names = [n for n, _ in ch]
+ base = []
+ if any("Forest" in n for n in names):
+ base.append("B_FOREST")
+ if "Rock" in names or "Boulder" in names:
+ base.append("B_ROCK")
+ if "AlienRuins" in names:
+ base.append("B_RUINS")
+ rows.append({"name": r, "kind": "KIND_RESOURCE", "base": base, "info": info, "chain": ch, "category": "Decoration & Nature",
+ "sprite": (info.get("textureName") or "").split("@")[0]})
+
+for b in binfo:
+ n = b["className"]
+ flags = set(b.get("specialInfo", []))
+ if n in EXCLUDE or flags & EXCLUDE_FLAGS:
+ continue
+ ch = chain("buildings", n)
+ names = [c for c, _ in ch]
+ ifaces = [i for _, info in ch for i in info["ifaces"]]
+ base = []
+ if "House" in names or "IHousing" in ifaces:
+ base.append("B_HOUSE")
+ if "Work" in names:
+ base.append("B_WORK")
+ if "IEntertainmentBuilding" in ifaces or inherited(ch, "ctor", "isEntertainment") == "true":
+ base.append("B_ENTERTAINMENT")
+ if "IMedicalBuilding" in ifaces or inherited(ch, "ctor", "isMedical") == "true":
+ base.append("B_MEDICAL")
+ if "School" in names:
+ base.append("B_SCHOOL")
+ if "Teleporter" in names:
+ base.append("B_TELEPORTER")
+ if "LandingSite" in names:
+ base.append("B_LANDINGSITE")
+ if "HyperElevator" in names:
+ base.append("B_ELEVATOR")
+ if "unique" in flags:
+ base.append("B_UNIQUE")
+ if "rooftop" in flags:
+ base.append("B_ROOFTOP")
+ if "disableInsertReplaceOrBuildOnTop" in flags:
+ base += ["B_NO_INSERT", "B_NO_BUILD_ON_TOP"]
+ if "buildOnGround" in flags:
+ base.append("B_BUILD_ON_GROUND")
+ if "cityTop" in flags:
+ base.append("B_CITY_TOP")
+ if inherited(ch, "get", "walkThroughCanViewSelfInThisBuilding") == "false":
+ base.append("B_HIDE_WALKERS")
+ m = re.search(r'buildings_%s\.spriteName = "([^"]*)"' % n, static)
+ rows.append({"name": n, "kind": "KIND_BUILDING", "base": base, "info": b, "chain": ch,
+ "category": "Decoration & Nature" if b["category"].startswith("Decoration & Nature") else b["category"],
+ "sprite": m.group(1) if m else ""})
+
+out = []
+out.append("/* The Final Earth 2: the classes of permanents, made by tools/gen_classes.py from the original's\n"
+ " * buildinginfo.json, buildableWorldResourcesInfo.json and classes. Don't edit: edit the generator. */")
+out.append('#include "classes.h"')
+out.append('#include "data.h"' if spr_known else "")
+ops_used = set()
+for r in rows:
+ for c, _ in r["chain"]:
+ if c in ops_defined:
+ ops_used.add(c)
+ break
+for o in sorted(ops_used):
+ out.append(f"extern const PermOps ops_{o};")
+out.append("const PermClass pcls[] = {")
+for r in rows:
+ b, ch = r["info"], r["chain"]
+ cost = ", ".join(f"[{M_ENUM[i]}] = {num(b.get(m)):g}" for i, m in enumerate(MATS) if num(b.get(m)) or
+ (m == "refinedMetal" and num(b.get("refinedMetals"))))
+ if num(b.get("refinedMetals")) and not num(b.get("refinedMetal")):
+ cost = cost.replace(f"[M_REFINEDMETAL] = 0", f"[M_REFINEDMETAL] = {num(b.get('refinedMetals')):g}")
+ fields = [f'.name = "{r["name"]}"', f'.kind = {r["kind"]}', f'.base = {" | ".join(r["base"]) or "0"}',
+ f'.category = {CATEGORIES.index(r["category"]) if r["category"] in CATEGORIES else 8}']
+ if cost:
+ fields.append(f".cost = {{{cost}}}")
+ if b.get("residents"):
+ fields.append(f".residents = {int(b['residents'])}")
+ if b.get("jobs"):
+ fields.append(f".jobs = {int(b['jobs'])}")
+ if b.get("quality") is not None:
+ fields.append(f".quality = {int(b['quality'])}")
+ fields.append(f".startTime = {num(inherited(ch, 'ctor', 'startTime', 6), 6):g}")
+ fields.append(f".endTime = {num(inherited(ch, 'ctor', 'endTime', 19), 19):g}")
+ fields.append(f".doorX = {int(num(inherited(ch, 'ctor', 'doorX', 13), 13))}")
+ fields.append(f".workTimePreferenceMod = {num(inherited(ch, 'ctor', 'workTimePreferenceMod', 1), 1):g}")
+ et = inherited(ch, "get", "entertainmentType")
+ fields.append(f".entType = {int(num(et, -1)) if et is not None else -1}")
+ for k, f in (("minimumNormalTimeToSpend", "entMinTime"), ("maximumNormalTimeToSpend", "entMaxTime"),
+ ("minimumEntertainmentGroupSatisfy", "entMinSatisfy"), ("maximumEntertainmentGroupSatisfy", "entMaxSatisfy")):
+ v = inherited(ch, "get", k)
+ if v is not None and re.match(r'^-?[\d.]+$', v):
+ fields.append(f".{f} = {flit(num(v))}")
+ v = inherited(ch, "get", "entertainmentQuality")
+ if v is not None and re.match(r'^-?[\d.]+$', v):
+ fields.append(f".entQuality = {int(num(v))}")
+ v = inherited(ch, "get", "medicalTypeID")
+ fields.append(f".medicalTypeID = {int(num(v, 0)) if v is not None and re.match(r'^-?[0-9]+$', v) else 0}")
+ v = inherited(ch, "get", "medicalTypeLimit")
+ if v is not None and re.match(r'^-?[\d.]+$', v):
+ fields.append(f".medicalTypeLimit = {flit(num(v))}")
+ if b.get("teleporterOperatingCost"):
+ fields.append(f".teleporterOperatingCost = {flit(num(b['teleporterOperatingCost']))}")
+ for s in b.get("specialInfo", []):
+ m = re.match(r'limitedToCitizens:(\d+)', s)
+ if m:
+ fields.append(f".limitedPerCitizens = {int(m.group(1))}")
+ uf = []
+ if b.get("unlockedByDefault", r["kind"] == "KIND_RESOURCE"):
+ uf.append("UF_DEFAULT")
+ if r["name"] in HINTS:
+ uf.append("UF_HINT")
+ if b.get("notUnlockedWithAll"):
+ uf.append("UF_NOT_WITH_ALL")
+ if uf:
+ fields.append(f".unlockFlags = {' | '.join(uf)}")
+ names_in_table = [x["name"] for x in rows]
+ parent = next((names_in_table.index(c) for c, _ in ch[1:] if c in names_in_table), -1)
+ fields.append(f".parent = {parent}")
+ fields.append(f".sprite = {spr_id(r['sprite'])}")
+ for c, _ in ch:
+ if c in ops_defined:
+ fields.append(f".ops = &ops_{c}")
+ break
+ out.append(" {" + ", ".join(fields) + "},")
+out.append("};")
+out.append("const int npcls = sizeof pcls / sizeof pcls[0];")
+out.append("int pcls_find(const char *name) {\n for (int i = 0; i < npcls; i++)\n if (!strcmp(pcls[i].name, name)) return i;\n return -1;\n}")
+open(os.path.join(GAME, "src", "classes.c"), "w").write("\n".join(l for l in out if l is not None) + "\n")
+
+h = ["/* The Final Earth 2: class numbers (made by tools/gen_classes.py). */", "#ifndef FE_CLASSES_H", "#define FE_CLASSES_H",
+ '#include "pcls.h"', "enum {"]
+for i, r in enumerate(rows):
+ h.append(f" CLS_{r['name']} = {i},")
+h += [f" CLS_COUNT = {len(rows)}", "};", "#endif"]
+open(os.path.join(GAME, "src", "classes.h"), "w").write("\n".join(h) + "\n")
+print(f"{len(rows)} classes ({sum(1 for r in rows if r['kind'] == 'KIND_BUILDING')} buildings), ops for {len(ops_used)}")
diff --git a/games/finalearth2/tools/gen_lang.py b/games/finalearth2/tools/gen_lang.py
new file mode 100644
index 00000000..5bb1405e
--- /dev/null
+++ b/games/finalearth2/tools/gen_lang.py
@@ -0,0 +1,330 @@
+#!/usr/bin/env python3
+"""Makes src/lang_data.c and src/lang_data.h: the texts the user interface
+shows (the original's lang_en.csv) and its tables of the build menu (the
+buildings' names, descriptions, unlock hints and button art, the categories,
+the decorations and the world resources one can build).
+
+Only the texts the game shows go in: every `L_<key>` in src/ui*.c and
+src/bld*.c is the text of lang_en.csv's <key>. Texts written for a mouse or a touch screen get
+the keypad's words (KEYPAD below).
+
+ python3 -I tools/gen_lang.py [REFERENCE_DIR]
+"""
+import json
+import os
+import re
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+GAME = os.path.dirname(HERE)
+SRC = os.path.join(GAME, "src")
+REF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("FE2_REF", os.path.expanduser("~/Documents/Assets/gamesrc/finalearth2/web14"))
+
+lang = {}
+for line in open(os.path.join(REF, "lang_en.csv"), encoding="utf-8"):
+ line = line.rstrip("\n")
+ if "|" not in line:
+ continue
+ k, v = line.split("|", 1)
+ # (a key given twice: the later one, as the original's LocalizeLoader keeps it)
+ lang[k] = v.replace("\\n", "\n")
+
+# texts that speak of clicking, tapping or keys of a computer: the calculator's words instead
+KEYPAD = {
+ "tap_for_age_distribution": "Press OK for the age distribution.",
+ "tap_for_age_distribution_or_pop_limit": "Press OK for the age distribution or to change the population limit.",
+ "change_game_speed_mobile": "Press OK to change the game speed.",
+ "change_game_speed_pc": "Press OK to change the game speed.\nPress shift and OK to select an advanced speed.",
+ "to_pause": "to pause the game.",
+ "to_unpause": "to unpause the game.",
+ "destroy_tip": "",
+ "ctrl_to_highlight": "",
+ "follow_hint": "",
+ "click_here_to_play": "Press OK to Play",
+ "hint_hint": "Tip! If you ever forget what to do, just press OK on the ? here (press var to reach it).",
+ "tap_near_citizen_to_follow": "Press OK near a citizen to follow them.",
+ "build_mode_multi_explanation": "Hold OK and move the cursor to quickly build multiple buildings of the same type.",
+ "build_mode_multi_replace_explanation": "Hold OK and move the cursor to quickly build or replace buildings.",
+}
+# the start of the pause button's tooltip: "Click (or press Space)" / "Tap"
+EXTRA = {
+ "ok_or_alpha": "Press OK (or alpha)",
+ "keypad_credits_1": "Inspired by The Final Earth 2 by Florian van Strien.",
+ "keypad_credits_2": "Not affiliated with him.",
+ "keypad_credits_3": "The sprites, fonts and texts are his, from the original game.",
+ "keypad_credits_4": "Made by Mason Chen as part of NumPlay.",
+ "keypad_save_failed": "The city could not be saved: there is not enough room on the calculator.",
+ "keypad_save_failed_title": "Not Saved",
+ "keypad_saved": "The city was saved.",
+ "keypad_home_quit": "Press Home again to quit without saving.",
+ "keypad_hold": "Press OK again to confirm.",
+ "save": "Save",
+ "priority_text": " priority.",
+ "keypad_load_failed": "The saved city could not be loaded.",
+ "keypad_toolbox_hint": "Press toolbox to open the build menu.",
+ "keypad_typing_hint": "Type with alpha and the keys' letters (shift, alpha: capitals), or pick them here:",
+ "keypad_caps": "Caps",
+ "keypad_space": "Space",
+ "keypad_delete": "Delete",
+ "keypad_var_hint": "Press var to reach these buttons.",
+ "keypad_builder_hint": "Arrows move, OK builds here, Back picks another building.",
+ "keypad_menu_hint": "Left and right: buildings. Up and down: categories. OK: pick.",
+}
+
+
+def adapt(key, text):
+ if key in KEYPAD:
+ return KEYPAD[key]
+ text = text.replace("[Tap]", "Press OK").replace("[tap]", "press OK")
+ return text
+
+
+def cname(key):
+ return "L_" + re.sub(r"[^A-Za-z0-9_]", "_", key)
+
+
+def cstr(s):
+ if s is None:
+ return "NULL"
+ out = []
+ for ch in s:
+ if ch == "\\":
+ out.append("\\\\")
+ elif ch == '"':
+ out.append('\\"')
+ elif ch == "\n":
+ out.append("\\n")
+ elif ord(ch) < 128:
+ out.append(ch)
+ else:
+ out.append("".join("\\%03o" % b for b in ch.encode("utf-8")))
+ return '"' + "".join(out) + '"'
+
+
+# the keys the interface uses
+used = set()
+for f in sorted(os.listdir(SRC)):
+ if (f.startswith("ui") or f.startswith("bld")) and f.endswith(".c"):
+ used |= set(re.findall(r"\bL_([A-Za-z0-9_]+)\b", open(os.path.join(SRC, f), encoding="utf-8").read()))
+
+# the sprites packed (data.h) and the classes (classes.h)
+sprites = set(re.findall(r"^\s+SPR_([A-Z0-9_]+),", open(os.path.join(SRC, "data.h"), encoding="utf-8").read(), re.M))
+classes = re.findall(r"CLS_(\w+) = (\d+),", open(os.path.join(SRC, "classes.h"), encoding="utf-8").read())
+cls_index = {n: int(i) for n, i in classes}
+ncls = len(classes)
+
+
+def spr(name):
+ if not name or name == "none":
+ return "0"
+ n = name[4:].upper() if name.startswith("spr_") else name.upper()
+ n = n.split("@")[0]
+ if n not in sprites:
+ raise SystemExit(f"gen_lang.py: no sprite {name}")
+ return "SPR_" + n
+
+
+info = json.load(open(os.path.join(REF, "buildinginfo.json"), encoding="utf-8"))
+by_class = {b["className"]: b for b in info}
+res_info = json.load(open(os.path.join(REF, "buildableWorldResourcesInfo.json"), encoding="utf-8"))
+deco_info = json.load(open(os.path.join(REF, "decorationsInfo.json"), encoding="utf-8"))
+cats = json.load(open(os.path.join(REF, "buildingCategoriesInfo.json"), encoding="utf-8"))
+SUBS = ["coloredBlocks", "slantedroofs", "slantedrooftops", "roofbottom", "domeroofs"]
+SUB_TEXT = {"coloredBlocks": ("colored_blocks", "spr_coloredblock"), "slantedroofs": ("slanted_roofs", "spr_slantedroof"),
+ "slantedrooftops": ("slanted_rooftops", "spr_slantedrooftop"), "roofbottom": ("roof_bottoms", "spr_roofbottom"),
+ "domeroofs": ("domeroofs", "spr_domeroof")}
+CAT_NAMES = [c["name"] for c in cats]
+
+h = ["/* The Final Earth 2: the user interface's texts and build menu tables (made by tools/gen_lang.py",
+ " * from the original's lang_en.csv and data). Don't edit: edit the generator. */",
+ "#ifndef FE_LANG_DATA_H", "#define FE_LANG_DATA_H", "#include <stdint.h>", ""]
+c = ["/* The Final Earth 2: the user interface's texts and build menu tables (made by tools/gen_lang.py",
+ " * from the original's lang_en.csv and data). Don't edit: edit the generator. */",
+ '#include "lang_data.h"', '#include "classes.h"', '#include "data.h"', ""]
+
+missing = []
+for k in sorted(used):
+ if k in EXTRA:
+ text = EXTRA[k]
+ elif k in lang:
+ text = adapt(k, lang[k])
+ else:
+ missing.append(k)
+ continue
+ h.append(f"extern const char {cname(k)}[];")
+ c.append(f"const char {cname(k)}[] = {cstr(text)};")
+if missing:
+ raise SystemExit("gen_lang.py: no text for " + ", ".join(missing))
+
+# ---------------------------------------------------------------- the classes
+h += ["", "/* a class's texts and look in the build menu */",
+ "typedef struct {",
+ " const char *name, *desc, *hint; /* hint: showUnlockHint, NULL none */",
+ " uint16_t back; /* its button's background (buttonBack; BACK_OWN: its sprite's at 44,0), 0 none */",
+ " uint16_t on_build; /* onBuildSprite, 0: the class's sprite */",
+ " uint16_t tip_icon; /* tooltipBottomIconInfo, 0 none */",
+ " uint8_t flags; /* CT_* */",
+ " uint8_t sub; /* its decoration subcategory + 1 (SUB_*), 0 none */",
+ " uint16_t limited; /* limitedToCitizens: one per that many citizens, 0 none */",
+ "} ClsText;",
+ "#define BACK_OWN 0xFFFF",
+ "enum { CT_MULTI_DECOR = 1, CT_ANYCOLOR = 2, CT_MIRRORABLE = 4, CT_MULTI_SPEC = 8, CT_NOT_UNIQUE_GL = 16,",
+ " CT_UNIQUE = 32, CT_LIMITED = 64 };",
+ "extern const ClsText cls_text[];",
+ "/* the buildings in the original's order (buildinginfo.json), for the build menu */",
+ "extern const uint8_t build_order[];",
+ "extern const int nbuild_order;"]
+c.append("const ClsText cls_text[] = {")
+
+
+def resource_name(name):
+ """A world resource's get_name (its window's title), following its superclasses"""
+ while name:
+ p = os.path.join(REF, "split", f"worldResources.{name}.js")
+ if not os.path.exists(p):
+ return None
+ js = open(p, encoding="utf-8").read()
+ m = re.search(r'get_name: function\(\) \{\s*return (?:common_Localize\.lo\("([^"]+)"\)|"([^"]*)")', js)
+ if m:
+ return lang.get(m.group(1)) if m.group(1) else m.group(2)
+ m = re.search(r'__super__ = worldResources_(\w+);', js)
+ name = m.group(1) if m else None
+ return None
+
+
+rows = []
+for name, i in sorted(cls_index.items(), key=lambda x: x[1]):
+ b = by_class.get(name)
+ key = f"buildinginfo.json/{name}."
+ rkey = f"buildableWorldResourcesInfo.json/{name}."
+ nm = lang.get(key + "name") or resource_name(name) or lang.get(rkey + "name") or (b or {}).get("name") or name
+ desc = lang.get(key + "description") or lang.get(rkey + "description") or (b or {}).get("description") or ""
+ hint = lang.get(key + "showUnlockHint")
+ si = (b or {}).get("specialInfo", [])
+ flags = []
+ if "as_multi_decor" in si: flags.append("CT_MULTI_DECOR")
+ if "as_multi_decor_anycolor" in si: flags.append("CT_ANYCOLOR")
+ if "mirrorable" in si: flags.append("CT_MIRRORABLE")
+ if "has_multi_decor_spec" in si: flags.append("CT_MULTI_SPEC")
+ if "notUniqueIfGalacticLibrary" in si: flags.append("CT_NOT_UNIQUE_GL")
+ if "unique" in si: flags.append("CT_UNIQUE")
+ if "limited" in si: flags.append("CT_LIMITED")
+ limited = 0
+ for s in si:
+ if s.startswith("limitedToCitizens:"):
+ limited = int(s.split(":")[1])
+ back = "0"
+ if b is not None:
+ bb = b.get("buttonBack")
+ if bb == "none":
+ back = "0"
+ elif bb:
+ back = spr(bb)
+ else:
+ back = "BACK_OWN" # the class's own sprite at 44,0
+ tips = (b or {}).get("tooltipBottomIconInfo") or []
+ tip = spr(tips[0]["texture"]) if tips else "0"
+ cat = (b or {}).get("category", "")
+ sub = 0
+ if "_" in cat:
+ sub = SUBS.index(cat.split("_", 1)[1]) + 1
+ rows.append(f" {{{cstr(nm)}, {cstr(desc)}, {cstr(hint)}, {back}, {spr((b or {}).get('onBuildSprite'))}, {tip}, "
+ f"{' | '.join(flags) or '0'}, {sub}, {limited}}}")
+c.append(",\n".join(rows) + "};")
+order = [cls_index[b["className"]] for b in info if b["className"] in cls_index]
+c.append("const uint8_t build_order[] = {" + ", ".join(str(x) for x in order) + "};")
+c.append(f"const int nbuild_order = {len(order)};")
+
+# ---------------------------------------------------------------- categories
+h += ["", "/* buildingCategoriesInfo.json, and the decorations' subcategories */",
+ "typedef struct { const char *name, *desc; uint16_t icon; } CatText;",
+ f"#define NCATEGORIES {len(cats)}",
+ "extern const CatText cat_text[NCATEGORIES];",
+ f"#define NSUBCATEGORIES {len(SUBS)}",
+ "extern const CatText sub_text[NSUBCATEGORIES];"]
+c.append("const CatText cat_text[NCATEGORIES] = {" + ", ".join(
+ f"{{{cstr(lang.get('categories/' + x['name'] + '.name', x['name']))}, "
+ f"{cstr(lang.get('categories/' + x['name'] + '.description', x['description']))}, {spr(x['image'])}}}" for x in cats) + "};")
+c.append("const CatText sub_text[NSUBCATEGORIES] = {" + ", ".join(
+ f"{{{cstr(lang[SUB_TEXT[s][0]])}, NULL, {spr(SUB_TEXT[s][1])}}}" for s in SUBS) + "};")
+
+# ---------------------------------------------------------------- decorations and world resources
+h += ["", "/* decorationsInfo.json (snow left out): what one places on a world's ground */",
+ "typedef struct { uint16_t spr; uint8_t flags; uint8_t food, wood, stone; const char *name, *desc; } DecoText;",
+ "enum { DT_GENE_EDITING = 1, DT_REMOVE = 2 };",
+ "extern const DecoText deco_text[];",
+ "extern const int ndeco_text;",
+ "/* buildableWorldResourcesInfo.json: forests and rocks one can place */",
+ "typedef struct { uint8_t cls; int16_t grow, resources; float wood, stone; const char *name, *desc; } ResText;",
+ "extern const ResText res_text[];",
+ "extern const int nres_text;"]
+drows = []
+for d in deco_info:
+ si = d.get("specialInfo") or []
+ if "snow" in si:
+ continue
+ fl = []
+ if "geneEditingReq" in si: fl.append("DT_GENE_EDITING")
+ if d.get("isRemoveDecoration"): fl.append("DT_REMOVE")
+ key = f"decorationsInfo.json/{d['textureName']}."
+ drows.append(f" {{{spr(d['textureName'])}, {' | '.join(fl) or '0'}, {d['food']}, {d['wood']}, {d['stone']}, "
+ f"{cstr(lang.get(key + 'name', d['textureName']))}, {cstr(lang.get(key + 'description'))}}}")
+c.append("const DecoText deco_text[] = {\n" + ",\n".join(drows) + "};")
+c.append(f"const int ndeco_text = {len(drows)};")
+rrows = []
+for r in res_info:
+ if r["className"] not in cls_index:
+ continue
+ key = f"buildableWorldResourcesInfo.json/{r['className']}."
+ rrows.append(f" {{CLS_{r['className']}, {r.get('initialGrow', -1)}, {r.get('initialResources', -1)}, {r['wood']}, "
+ f"{r['stone']}, {cstr(lang.get(key + 'name', r['className']))}, {cstr(lang.get(key + 'description'))}}}")
+c.append("const ResText res_text[] = {\n" + ",\n".join(rrows) + "};")
+c.append(f"const int nres_text = {len(rrows)};")
+
+# ---------------------------------------------------------------- citizens' names (Resources.citizenNames)
+names = open(os.path.join(REF, "citizenNames.txt"), encoding="utf-8").read().replace("\r\n", "\n").split("\n")
+names = names[names.index("START") + 1:]
+# front-coded: each name is the length it shares with the one before, then the rest and a 0; every 32nd
+# shares nothing and has its offset in the index
+blob = bytearray()
+index = []
+prev = b""
+for i, n in enumerate(names):
+ b = n.encode("utf-8")
+ if i % 32 == 0:
+ index.append(len(blob))
+ shared = 0
+ else:
+ shared = 0
+ while shared < min(len(prev), len(b), 255) and prev[shared] == b[shared]:
+ shared += 1
+ blob += bytes([shared]) + b[shared:] + b"\0"
+ prev = b
+h += ["", "/* the citizens' names (citizenNames.txt): name i, front-coded */",
+ "extern const int ncitizen_names;",
+ "const char *citizen_name(int i, char *buf, int size);"]
+c.append(f"const int ncitizen_names = {len(names)};")
+c.append("static const uint8_t names_blob[] = {" + ",".join(str(x) for x in blob) + "};")
+c.append("static const uint32_t names_index[] = {" + ",".join(str(x) for x in index) + "};")
+c.append("""const char *citizen_name(int i, char *buf, int size) {
+ buf[0] = 0;
+ if (i < 0 || i >= ncitizen_names || size < 2) return buf;
+ const uint8_t *p = names_blob + names_index[i / 32];
+ int len = 0;
+ for (int k = i - i % 32; k <= i; k++) {
+ int shared = *p++;
+ if (shared > len) shared = len;
+ len = shared;
+ while (*p) {
+ if (len < size - 1) buf[len++] = (char)*p;
+ p++;
+ }
+ p++;
+ buf[len] = 0;
+ }
+ return buf;
+}""")
+h += ["#endif", ""]
+open(os.path.join(SRC, "lang_data.h"), "w", encoding="utf-8").write("\n".join(h))
+open(os.path.join(SRC, "lang_data.c"), "w", encoding="utf-8").write("\n".join(c) + "\n")
+print(f"gen_lang.py: {len(used)} texts, {ncls} classes, {len(drows)} decorations, {len(rrows)} world resources")
diff --git a/games/finalearth2/tools/gen_stories.py b/games/finalearth2/tools/gen_stories.py
new file mode 100644
index 00000000..f9bc721e
--- /dev/null
+++ b/games/finalearth2/tools/gen_stories.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+"""Makes src/stories_data.c, the scenarios and free play maps, from the
+original's stories.json, stories/*.json and lang_en.csv (their texts).
+
+ python3 -I tools/gen_stories.py [REFERENCE_DIR]
+"""
+import json
+import os
+import re
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+GAME = os.path.dirname(HERE)
+REF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("FE2_REF", os.path.expanduser("~/Documents/Assets/gamesrc/finalearth2/web14"))
+
+STORIES = ["theLostShip", "multipleWorlds", "hackersandaliens", "cityofthekey", "FreePlayMegaWorld",
+ "FreePlayManyWorldsRandom", "FreePlayEmptyCanvas", "FreePlayDivided", "FreePlayRandomMiniWorlds",
+ "FreePlayManyWorlds"]
+MATS = ["food", "wood", "stone", "machineParts", "refinedMetal", "computerChips", "cacao", "chocolate", "graphene",
+ "rocketFuel", "knowledge"]
+M_ENUM = ["M_FOOD", "M_WOOD", "M_STONE", "M_MACHINEPARTS", "M_REFINEDMETAL", "M_COMPUTERCHIPS", "M_CACAO",
+ "M_CHOCOLATE", "M_GRAPHENE", "M_ROCKETFUEL", "M_KNOWLEDGE"]
+SUBGOALS = ["BuildPermanents", "GatherMaterials", "ProductionGoal", "PerformBuildingUpgrades", "PerformCityUpgrade",
+ "MinimumHappiness", "MinimumCitizens", "HousingCapacity", "Wait", "InvitePeople", "ExploreAlienRuins",
+ "ExploredWithResearchSpacecraft", "CompleteHackerMissions", "WaitForDecryption", "GloryGoal"]
+FLAGS = ["disableDying", "disableDestroy", "hiddenBoost", "setBuildableAliens"]
+APPEARANCES = {None: 0, "": 0, "key": 1, "key2": 2}
+
+lang = {}
+for line in open(os.path.join(REF, "lang_en.csv"), encoding="utf-8"):
+ if "|" in line:
+ k, v = line.rstrip("\n").split("|", 1)
+ lang[k] = v.replace("\\n", "\n")
+classes = re.findall(r'CLS_(\w+) = ', open(os.path.join(GAME, "src", "classes.h")).read())
+
+
+def cstr(s):
+ if s is None:
+ return "NULL"
+ return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
+
+
+def mats(d):
+ if not d:
+ return "{0}"
+ return "{" + ", ".join(f"[{M_ENUM[MATS.index(k)]}] = {v}" for k, v in d.items() if k in MATS) + "}"
+
+
+def cls(name):
+ name = name.split(".")[-1]
+ if name not in classes:
+ raise SystemExit(f"unknown class {name}")
+ return f"CLS_{name}"
+
+
+out = ['/* The Final Earth 2: the scenarios and free play maps, made by tools/gen_stories.py from the',
+ " * original's stories and texts. Don't edit: edit the generator. */",
+ '#include "story.h"', '#include "classes.h"', '#include "data.h"', ""]
+table = []
+for si, name in enumerate(STORIES):
+ d = json.load(open(os.path.join(REF, "stories", name + ".json")))
+ p = f"s{si}"
+ free = bool(d.get("isFreePlay"))
+ tkey = "FreePlay" if free else name + ".json"
+ # worlds
+ wrows = []
+ for wi, w in enumerate(d.get("worlds", [])):
+ q = f"{p}w{wi}"
+ res = w.get("worldResources", [])
+ if res:
+ out.append(f"static const StoryRes {q}r[] = {{" + ", ".join(f"{{{r['position']}, {cls(r['className'])}}}" for r in res) + "};")
+ stacks = w.get("buildingStacks", [])
+ for k, s in enumerate(stacks):
+ items = []
+ for c in s["classNames"]:
+ if c == "NULL":
+ items.append("STACK_NULL")
+ continue
+ m = re.match(r'^(\w+)\*(true|false)\.(\d+)$', c)
+ if m:
+ items.append(f"{cls(m.group(1))} | STACK_DECOR({int(m.group(3))})" + (" | STACK_MIRROR" if m.group(2) == "true" else ""))
+ elif c.endswith("_mirrored"):
+ items.append(f"{cls(c[:-9])} | STACK_MIRROR")
+ else:
+ items.append(cls(c))
+ out.append(f"static const uint16_t {q}s{k}[] = {{{', '.join(items)}}};")
+ if stacks:
+ out.append(f"static const StoryStack {q}s[] = {{" + ", ".join(
+ f"{{{s['position']}, {len(s['classNames'])}, {q}s{k}}}" for k, s in enumerate(stacks)) + "};")
+ cits = w.get("citizens", [])
+ if cits:
+ out.append(f"static const StoryCitizens {q}c[] = {{" + ", ".join(
+ f"{{{c['amount']}, {c['ageRangeMin']}, {c['ageRangeMax']}, {c.get('minX', -1)}, {c.get('maxX', -1)}}}" for c in cits) + "};")
+ decos = w.get("decorations", [])
+ if decos:
+ out.append(f"static const StoryDeco {q}d[] = {{" + ", ".join(
+ f"{{{x['position']}, SPR_{x['spriteName'][4:].upper()}}}" for x in decos) + "};")
+ flags = []
+ if w.get("unbuildableAliens"):
+ flags.append("WF_UNBUILDABLE_ALIENS")
+ if w.get("protectedKey"):
+ flags.append("WF_PROTECTED_KEY")
+ r = w["rect"]
+ deco = w.get("decoration")
+ wrows.append("{" + ", ".join([str(r["x"]), str(r["y"]), str(r["width"]), str(r["height"]), str(w.get("seed", 0)) + "u",
+ str(APPEARANCES[w.get("appearance")]), " | ".join(flags) or "0",
+ f"SPR_{deco[4:].upper()}" if deco else "0",
+ str(len(res)), f"{q}r" if res else "NULL", str(len(stacks)), f"{q}s" if stacks else "NULL",
+ str(len(cits)), f"{q}c" if cits else "NULL", str(len(decos)), f"{q}d" if decos else "NULL"]) + "}")
+ out.append(f"static const StoryWorld {p}w[] = {{\n " + ",\n ".join(wrows) + "};")
+ # goals
+ grows = []
+ for gi, g in enumerate(d["goals"]):
+ q = f"{p}g{gi}"
+ subs = []
+ for s in g.get("subGoals", []):
+ t = s["type"]
+ if t not in SUBGOALS:
+ raise SystemExit(f"{name}: unknown subgoal {t}")
+ f = [f".type = SG_{t.upper()}"]
+ if t == "BuildPermanents":
+ f.append(f".cls = {cls(s['permanentToBuildClass'])}")
+ f.append(f".amount = {s['amount']}")
+ f.append(f".world = {s.get('onWorld', -1)}")
+ f.append(f".notWorld = {s.get('notOnWorld', -1)}")
+ elif t in ("GatherMaterials", "ProductionGoal"):
+ f.append(f".mats = {mats(s['materials'])}")
+ elif t in ("PerformBuildingUpgrades", "PerformCityUpgrade"):
+ f.append(f'.name = "{s["upgradeClass"]}"')
+ f.append(f".amount = {s.get('amount', 1)}")
+ elif t == "MinimumHappiness":
+ f.append(f".value = {s['happiness']}")
+ elif t == "MinimumCitizens":
+ f.append(f".amount = {s['number']}")
+ elif t in ("HousingCapacity", "CompleteHackerMissions"):
+ f.append(f".amount = {s['amount']}")
+ elif t == "Wait":
+ f.append(f".value = {s['waitTime']}")
+ subs.append("{" + ", ".join(f) + "}")
+ if subs:
+ out.append(f"static const SubGoal {q}sub[] = {{" + ", ".join(subs) + "};")
+ for key in ("unlocks", "researches"):
+ if g.get(key):
+ out.append(f"static const char *const {q}{key[0]}[] = {{" + ", ".join(cstr(x) for x in g[key]) + "};")
+ plans = []
+ for e in g.get("planning", []):
+ t = e["type"]
+ if t == "SpawnCitizensFlyingSaucer":
+ plans.append(f"{{.type = EV_SAUCER, .time = {e['time']}, .amount = {e['amount']}, .ageMin = {e['ageRangeMin']}, "
+ f".ageMax = {e['ageRangeMax']}, .world = {e['world']}}}")
+ elif t == "ScriptedStoryPart" and e["className"] == "SpawnCitizensRegularly":
+ after = e.get("afterDoneMessage")
+ if after is not None:
+ after = lang.get(f"{tkey}.FreePlayStart.planning.afterDoneMessage" if free else "", after)
+ plans.append(f"{{.type = EV_REGULARLY, .time = {e['time']}, .amount = {e['spawnNumber']}, .ageMin = {e['ageRangeMin']}, "
+ f".ageMax = {e['ageRangeMax']}, .world = {e['world']}, .groupMin = {e['groupSizeMin']}, "
+ f".groupMax = {e['groupSizeMax']}, .betweenMin = {e['timeBetweenMin']}, .betweenMax = {e['timeBetweenMax']}, "
+ f".afterDone = {cstr(after)}}}")
+ else:
+ raise SystemExit(f"{name}: unknown planning {t}")
+ if plans:
+ out.append(f"static const StoryEvent {q}e[] = {{" + ", ".join(plans) + "};")
+ fl = g.get("flags", {})
+ fset = [f"GF_{k.upper()}" for k in FLAGS if k in fl]
+ fval = [f"GF_{k.upper()}" for k in FLAGS if fl.get(k)]
+ gname = g["name"]
+ # (lang_en.csv's keys: "theLostShip.json/Start.text", and "FreePlay.FreePlayStart.text")
+ tsep = "." if free else "/"
+ text = lang.get(f"{tkey}{tsep}{gname}.text", g.get("text"))
+ quick = lang.get(f"{tkey}{tsep}{gname}.quickText", g.get("quickText") or "")
+ title = lang.get(f"{tkey}{tsep}{gname}.title", g.get("title"))
+ nxt = g.get("nextGoal", "")
+ nxt_i = next((i for i, x in enumerate(d["goals"]) if x["name"] == nxt), -1) if nxt else -1
+ nstory = STORIES.index(g["nextStory"]) if g.get("nextStory") in STORIES else -1
+ grows.append("{" + ", ".join([cstr(gname), str(nxt_i), str(nstory), str(len(subs)), f"{q}sub" if subs else "NULL",
+ str(len(g.get("unlocks", []))), f"{q}u" if g.get("unlocks") else "NULL",
+ str(len(g.get("researches", []))), f"{q}r" if g.get("researches") else "NULL",
+ str(len(plans)), f"{q}e" if plans else "NULL", " | ".join(fset) or "0", " | ".join(fval) or "0",
+ str(g.get("showTutorial", 0)), cstr(text), cstr(quick), cstr(title)]) + "}")
+ out.append(f"static const StoryGoal {p}g[] = {{\n " + ",\n ".join(grows) + "};")
+ gens = []
+ for gi, gs in enumerate(d.get("generatorScripts", [])):
+ a = gs["args"]
+ items = [(x["className"], x["numberMin"], x["numberMax"], 1) for x in a.get("initialBuildings", [])] + \
+ [(x["className"], x["numberMin"], x["numberMax"], 0) for x in a.get("initialWorldResources", [])]
+ out.append(f"static const GenItem {p}x{gi}[] = {{" + ", ".join(f"{{{cls(c)}, {lo}, {hi}, {b}}}" for c, lo, hi, b in items) + "};")
+ gens.append("{" + ", ".join(str(a[k]) for k in ("numberOfWorldsMin", "numberOfWorldsMax", "minX", "minY", "maxX", "maxY",
+ "minWidth", "maxWidth", "minHeight", "maxHeight", "heightVariation")) +
+ f", {len(items)}, {p}x{gi}, " + ", ".join("true" if a.get(k) else "false" for k in (
+ "spreadBuildingsEvenlyBetweenWorlds", "spreadWorldResourcesEvenlyBetweenWorlds",
+ "rememberWorldSpreadBetweenBuildingsAndWorldResources", "avoidGeneratingOverfullWorlds")) + "}")
+ if gens:
+ out.append(f"static const WorldGenerator {p}x[] = {{" + ", ".join(gens) + "};")
+ bgs = d.get("backgroundSprites", [])
+ if bgs:
+ out.append(f"static const StoryBackground {p}b[] = {{" + ", ".join(
+ f"{{SPR_{b['sprite'][4:].upper()}, {b['width']}, {b['image']}, {b['x']}, {b['y']}, {float(b['velocity'])!r}f}}" for b in bgs) + "};")
+ start = next(i for i, x in enumerate(d["goals"]) if x["name"] == d["startGoal"])
+ sname = lang.get(f"stories.json/{name}.name", name)
+ sdesc = lang.get(f"stories.json/{name}.description", "")
+ flags = [f for f, k in (("ST_FREEPLAY", "isFreePlay"), ("ST_LOCK_ALL", "lockAllPermanents"), ("ST_INVITE", "useInviteCitizens"),
+ ("ST_SPEED_UP_NIGHTS", "speedUpStartNights"), ("ST_NO_EXTRA_RESOURCES", "extraResourcesDisabled")) if d.get(k)]
+ locks = d.get("lockPermanents", [])
+ if locks:
+ out.append(f"static const char *const {p}l[] = {{" + ", ".join(cstr(x) for x in locks) + "};")
+ table.append("{" + ", ".join([cstr(name), cstr(sname), cstr(sdesc), " | ".join(flags) or "0", mats(d.get("initialMaterials")),
+ str(len(d.get("worlds", []))), f"{p}w", str(len(d["goals"])), f"{p}g", str(start),
+ str(len(gens)), f"{p}x" if gens else "NULL", str(len(locks)), f"{p}l" if locks else "NULL",
+ str(d.get("viewYFromBottom", 0)), str(d.get("viewStartX", d.get("mobileViewStartX", 0))),
+ str(len(bgs)), f"{p}b" if bgs else "NULL"]) + "}")
+ out.append("")
+out.append("const Story stories[] = {\n " + ",\n ".join(table) + "};")
+out.append(f"const int nstories = {len(STORIES)};")
+open(os.path.join(GAME, "src", "stories_data.c"), "w").write("\n".join(out) + "\n")
+print(f"{len(STORIES)} stories")
diff --git a/games/finalearth2/tools/gen_upgrades.py b/games/finalearth2/tools/gen_upgrades.py
new file mode 100644
index 00000000..8e04e7eb
--- /dev/null
+++ b/games/finalearth2/tools/gen_upgrades.py
@@ -0,0 +1,233 @@
+#!/usr/bin/env python3
+"""Makes src/upgrades_data.c and src/upgrades_data.h, the table of building
+upgrades, building modes, city upgrades (research) and policies, from the
+original's buildingUpgradesInfo.json, cityUpgradesInfo.json, policiesInfo.json,
+their classes' code (split/buildingUpgrades.*, cityUpgrades.*, policies.*) and
+lang_en.csv: costs, unlock flags, kind, sprite, its layer and frames, the
+quality bonus, texts, and which classes offer each (get_possibleUpgrades and
+friends, inherited from the class's ancestors).
+
+Run it after tools/gen_classes.py (it reads src/classes.h and src/data.h):
+
+ python3 -I tools/gen_upgrades.py [REFERENCE_DIR]
+"""
+import json
+import os
+import re
+import sys
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+GAME = os.path.dirname(HERE)
+REF = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("FE2_REF", os.path.expanduser("~/Documents/Assets/gamesrc/finalearth2/web14"))
+SPLIT = os.path.join(REF, "split")
+
+MATS = ["food", "wood", "stone", "machineParts", "refinedMetal", "computerChips", "cacao", "chocolate", "graphene",
+ "rocketFuel", "knowledge"]
+M_ENUM = ["M_FOOD", "M_WOOD", "M_STONE", "M_MACHINEPARTS", "M_REFINEDMETAL", "M_COMPUTERCHIPS", "M_CACAO",
+ "M_CHOCOLATE", "M_GRAPHENE", "M_ROCKETFUEL", "M_KNOWLEDGE"]
+# out of scope: holidays, the paid versions' buildings and rockets, info entries without a class
+EXCLUDE = {"Pumpkin", "MiniChristmasTree", "RocketFuelFactoryEfficiency", "GrapheneFactoryImprovement",
+ "FactoryUsingFood", "FactoryUsingWood", "FactoryDisabled", "LiteratureReviews", "BoardGameCollection"}
+
+lang = {}
+for line in open(os.path.join(REF, "lang_en.csv"), encoding="utf-8"):
+ k, _, v = line.rstrip("\n").partition("|")
+ lang[k] = v
+
+
+def cstr(s):
+ if s is None:
+ return "NULL"
+ return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def read(name):
+ p = os.path.join(SPLIT, name + ".js")
+ return open(p, encoding="utf-8").read() if os.path.exists(p) else ""
+
+
+# sprites known to the packer
+spr_w = {}
+for m in re.finditer(r'#define (SPR_\w+)_W (\d+)', open(os.path.join(GAME, "src", "data.h")).read()):
+ spr_w[m.group(1)] = int(m.group(2))
+
+
+def spr_id(name):
+ return "SPR_" + re.sub(r'[^A-Z0-9]', '_', name.replace("spr_", "", 1).upper())
+
+
+# the classes, in classes.h's order
+classes = re.findall(r'CLS_(\w+) = \d+,', open(os.path.join(GAME, "src", "classes.h")).read())
+
+
+def class_src(name):
+ for prefix in ("buildings", "worldResources"):
+ s = read(f"{prefix}.{name}")
+ if s:
+ return s
+ return read(name)
+
+
+def parent(name):
+ m = re.search(r'__super__ = (\w+);', class_src(name))
+ if not m:
+ return None
+ s = m.group(1)
+ return s.split("_", 1)[1] if s.startswith(("buildings_", "worldResources_")) else s
+
+
+def possible(name, getter):
+ """the list a class's getter returns, from the nearest ancestor that has one"""
+ n = name
+ while n:
+ m = re.search(r'get_%s: function\(\) \{\n\t\treturn \[([^\]]*)\];' % getter, class_src(n))
+ if m:
+ return [x.strip().split("_", 1)[1] for x in m.group(1).split(",") if x.strip()]
+ n = parent(n)
+ return []
+
+
+per_class = {c: {k: possible(c, g) for k, g in (("up", "possibleUpgrades"), ("mode", "possibleBuildingModes"),
+ ("city", "possibleCityUpgrades"), ("pol", "possiblePolicies"))}
+ for c in classes}
+offered_modes = {m for c in classes for m in per_class[c]["mode"]}
+
+
+def upgrade_class_info(name):
+ """layer, texture, frames lost without a secret code, quality bonus, sprite not cached"""
+ layer, tex, locked, bonus, nocache = None, "", 0, 0, False
+ n = name
+ seen_layer = False
+ while n and n != "BuildingUpgrade":
+ src = read("buildingUpgrades." + n)
+ if not seen_layer:
+ m = re.search(r'BuildingUpgrade\.call\(this,(\w+),building\)', src)
+ if m:
+ layer = {"bgStage": "LAYER_BG", "midStage": "LAYER_MID", "stage": "LAYER_MAIN"}.get(m.group(1))
+ seen_layer = True
+ if not tex:
+ m = re.search(r'get_textureName: function\(\) \{\n\t\treturn "([^"]*)";', src)
+ if m:
+ tex = m.group(1)
+ m = re.search(r'get_bonusAttractiveness: function\(\) \{\n\t\treturn (-?\d+);', src)
+ if m and not bonus:
+ bonus = int(m.group(1))
+ m = re.search(r'get_availableTextures: function\(\) \{\n\t\treturn this\.textures\.length - \(Settings\.hasSecretCode\("orchid"\) \? 0 : (\d+)\)', src)
+ if m:
+ locked = int(m.group(1))
+ if re.search(r'get_canCacheSprite: function\(\) \{\n\t\treturn false;', src):
+ nocache = True
+ m = re.search(r'buildingUpgrades_(\w+)\.call\(this,stage,midStage,bgStage,building\)', src)
+ n = m.group(1) if m else None
+ return layer, tex, locked, bonus, nocache
+
+
+rows = [] # dicts
+binfo = [b for b in json.load(open(os.path.join(REF, "buildingUpgradesInfo.json"))) if b["className"] not in EXCLUDE]
+cinfo = [b for b in json.load(open(os.path.join(REF, "cityUpgradesInfo.json")))
+ if b["className"] not in EXCLUDE and read("cityUpgrades." + b["className"])]
+pinfo = [b for b in json.load(open(os.path.join(REF, "policiesInfo.json")))
+ if b["className"] not in EXCLUDE and read("policies." + b["className"])]
+
+for b in binfo:
+ n = b["className"]
+ if not read("buildingUpgrades." + n):
+ continue
+ layer, tex, locked, bonus, nocache = upgrade_class_info(n)
+ spr = spr_id(tex) if tex else None
+ if spr and spr not in spr_w:
+ print("warning: no sprite", tex, "for", n)
+ spr = None
+ frames = (spr_w[spr] + 2) // 22 if spr else 0
+ rows.append({"name": n, "kind": "UK_BUILDING_MODE" if n in offered_modes else "UK_BUILDING_UPGRADE", "info": b,
+ "layer": layer if spr else None, "sprite": spr, "frames": frames, "locked": locked, "bonus": bonus,
+ "nocache": nocache, "title": lang.get(f"buildingUpgradesInfo.json/{n}.name", n),
+ "text": lang.get(f"buildingUpgradesInfo.json/{n}.description", "")})
+for b in cinfo:
+ n = b["className"]
+ rows.append({"name": n, "kind": "UK_CITY_UPGRADE", "info": b, "layer": None, "sprite": None, "frames": 0,
+ "locked": 0, "bonus": 0, "nocache": False,
+ "title": lang.get(f"cityUpgradesInfo.json/{n}.name", n),
+ "text": lang.get(f"cityUpgradesInfo.json/{n}.description", ""),
+ "titleDone": b.get("nameIfNotDone"), "textDone": b.get("descriptionIfNotDone"),
+ "next": b.get("nextUpgrade")})
+for b in pinfo:
+ n = b["className"]
+ rows.append({"name": n, "kind": "UK_POLICY", "info": b, "layer": None, "sprite": None, "frames": 0, "locked": 0,
+ "bonus": 0, "nocache": False, "title": lang.get(f"policiesInfo.json/{n}.name", n),
+ "text": lang.get(f"policiesInfo.json/{n}.description", "")})
+index = {r["name"]: i for i, r in enumerate(rows)}
+
+h = ["/* The Final Earth 2: upgrade numbers and the classes' lists (made by tools/gen_upgrades.py). */",
+ "#ifndef FE_UPGRADES_DATA_H", "#define FE_UPGRADES_DATA_H", "enum {"]
+for i, r in enumerate(rows):
+ h.append(f" U_{r['name']} = {i},")
+h += [f" U_COUNT = {len(rows)}", "};", "",
+ "/* a class's upgrade's bit in Perm.upgrades, and its modes' numbers (Perm.mode) */"]
+for c in classes:
+ for i, u in enumerate(per_class[c]["up"]):
+ if u in index:
+ h.append(f"#define UB_{c}_{u} {i}")
+ for i, u in enumerate(per_class[c]["mode"]):
+ if u in index:
+ h.append(f"#define MODE_{c}_{u} {i}")
+h += ["#endif"]
+open(os.path.join(GAME, "src", "upgrades_data.h"), "w").write("\n".join(h) + "\n")
+
+out = ["/* The Final Earth 2: building upgrades and modes, city upgrades and policies, made by tools/gen_upgrades.py",
+ " * from the original's buildingUpgradesInfo.json, cityUpgradesInfo.json, policiesInfo.json, classes and",
+ " * lang_en.csv. Don't edit: edit the generator. */",
+ '#include "upgrades.h"', '#include "classes.h"', '#include "data.h"', '#include "pcls.h"', "",
+ "const UpgradeInfo upgrade_info[] = {"]
+for r in rows:
+ b = r["info"]
+ cost = ", ".join(f"[{M_ENUM[i]}] = {b.get(m, 0):g}" for i, m in enumerate(MATS) if b.get(m))
+ uf = []
+ if b.get("unlockedByDefault", True):
+ uf.append("UF_DEFAULT")
+ if b.get("notUnlockedWithAll"):
+ uf.append("UF_NOT_WITH_ALL")
+ f = [f'.name = "{r["name"]}"', f".kind = {r['kind']}", f".unlockFlags = {' | '.join(uf) or '0'}",
+ f".title = {cstr(r['title'])}", f".text = {cstr(r['text'])}"]
+ if r.get("titleDone"):
+ f.append(f".titleDone = {cstr(r['titleDone'])}")
+ if r.get("textDone"):
+ f.append(f".textDone = {cstr(r['textDone'])}")
+ if cost:
+ f.append(f".cost = {{{cost}}}")
+ f.append(f".layer = {r['layer'] or -1}")
+ if r["sprite"]:
+ f.append(f".sprite = {r['sprite']}")
+ f.append(f".frames = {r['frames']}")
+ if r["locked"]:
+ f.append(f".lockedFrames = {r['locked']}")
+ if r["bonus"]:
+ f.append(f".bonusAttractiveness = {r['bonus']}")
+ if r["nocache"]:
+ f.append(".noCache = 1")
+ f.append(f".next = {index[r['next']] if r.get('next') in index else 0xFF}")
+ out.append(" {" + ", ".join(f) + "},")
+out.append("};")
+out.append("const int nupgrades = sizeof upgrade_info / sizeof upgrade_info[0];")
+out.append("")
+out.append("/* what each class offers in its window: upgrade_info indexes + 1 (0: none) */")
+out.append("const ClassUpgrades class_upgrades[CLS_COUNT] = {")
+for c in classes:
+ pc = per_class[c]
+ if not any(u in index for v in pc.values() for u in v):
+ continue
+ parts = []
+ for k, n in (("up", 3), ("mode", 4), ("city", 6), ("pol", 3)):
+ lst = [f"U_{u} + 1" for u in pc[k] if u in index]
+ if len(lst) > n:
+ raise SystemExit(f"{c}: too many {k}")
+ if lst:
+ parts.append(f".{k} = {{{', '.join(lst)}}}")
+ out.append(f" [CLS_{c}] = {{{', '.join(parts)}}},")
+out.append("};")
+out.append("")
+out.append("int upgrade_find(const char *name) {\n for (int i = 0; i < nupgrades; i++)\n"
+ " if (!strcmp(upgrade_info[i].name, name)) return i;\n return -1;\n}")
+open(os.path.join(GAME, "src", "upgrades_data.c"), "w").write("\n".join(out) + "\n")
+print(f"{len(rows)} upgrades ({sum(1 for r in rows if r['kind'] == 'UK_BUILDING_MODE')} modes, "
+ f"{sum(1 for r in rows if r['kind'] == 'UK_CITY_UPGRADE')} city upgrades, {len(pinfo)} policies)")
diff --git a/games/finalearth2/tools/pack.py b/games/finalearth2/tools/pack.py
new file mode 100644
index 00000000..2887e309
--- /dev/null
+++ b/games/finalearth2/tools/pack.py
@@ -0,0 +1,393 @@
+#!/usr/bin/env python3
+"""Packs The Final Earth 2's sprites and fonts for the calculator.
+
+ python3 -I tools/pack.py [REFERENCE]
+
+REFERENCE is the original's web version (default below). Writes src/data.bin
+and src/data.h next to this folder and prints what each part takes.
+
+Sprites: every frame of sprites.json (a frame is often a strip of frames the
+game cuts at run time), cut from sprites.png, except the ones in DROPPED.
+Each sprite has its own palette (RGB565 and the original's 8-bit alpha) and
+its rows are coded as tokens, 4 bits a pixel when it has at most 16 colours,
+8 bits otherwise:
+
+ 0x00-0x3F skip n + 1 clear pixels
+ 0x40-0x7F n + 1 pixels follow (4-bit: two a byte, low nibble first)
+ 0x80-0xEF 4-bit: (t >> 4) - 7 pixels of colour t & 15
+ 0xF0-0xFF 4-bit: the next byte + 8 pixels of colour t & 15
+ 0x80-0xFF 8-bit: (t & 127) + 1 pixels of the colour in the next byte
+
+A row ends where the next one starts (clear pixels at its end are left out).
+Sprites with more than 256 colours (only the colour picker's circle) keep
+RGB565 pixels instead of indexes ("direct"):
+
+ 0x00-0x3F skip, 0x40-0x7F n + 1 opaque pixels (u16 each),
+ 0x80-0xBF n + 1 pixels of one u16 colour, 0xC0-0xFF n + 1 pixels of u16 + alpha byte
+
+Fonts: the five BMFont fonts, 1 bit a pixel, for the characters the game's
+English texts and citizens' names use (ASCII and a few accented letters),
+with their offsets, advances and kerning.
+
+data.bin (little-endian):
+ 0 'FE2D'
+ 4 u16 sprites, u16 fonts
+ 8 u32 offset of the sprite table: per sprite u32 offset of its data, u16 w, u16 h
+ 12 u32 offset of the font table: per font u32 offset of its data
+ sprite data (4-aligned): u8 colours, u8 mode (0 4-bit, 1 8-bit, 2 direct; +4: u32 row offsets),
+ u8 slabs, u8 0, u16 RGB565[colours], u8 alpha[colours], pad to 4, then per slab (columns x0 to
+ x1 - 1, coded on their own): u16 x0, u16 x1, u32 offset of its rows (from the sprite's data);
+ a slab's rows (4-aligned): u16 or u32 row offsets[h + 1] (from the end of the table), row data
+ font data (4-aligned): u8 line height, u8 glyphs, u16 kerning pairs, u32 offset of the bits
+ (from the font's start), glyphs (u16 first bit, i8 x offset, i8 y offset, u8 w, u8 h,
+ u8 advance, u8 0), kerning pairs (u8 first, u8 second, i8 amount, u8 0) sorted by second
+ then first, bits (each glyph's rows, w bits a row, one after the other, low bit first)
+"""
+import json
+import os
+import re
+import struct
+import sys
+
+from PIL import Image
+
+REF = os.environ.get("FE2_REF", os.path.expanduser("~/Documents/Assets/gamesrc/finalearth2/web14"))
+HERE = os.path.dirname(os.path.abspath(__file__))
+SRC = os.path.join(HERE, '..', 'src')
+
+# Sprites left out. Each is used only by content the port leaves out, or by
+# nothing at all in this version of the game.
+DROPPED = {
+ # premium buildings and city elements (paid versions only; bridges need
+ # bridgesInfo.json, which the free version doesn't have)
+ 'spr_alienfarm', 'spr_alienfarm_buttonback', 'spr_alienfarm_crops',
+ 'spr_aliennightclub', 'spr_aliennightclub_alienthing', 'spr_lightbeam_aliennightclub',
+ 'spr_aquarium', 'spr_aquarium_buttonback', # Aquarium, UnderwaterHouse
+ 'spr_underwaterhouse', 'spr_underwaterhouse_buttonback',
+ 'spr_graphenefactory', 'spr_graphenefactory_frames', 'spr_graphenefactory_idle',
+ 'spr_boostrange_onright', 'spr_stoneteleporter_graphenefactory_connection', # GrapheneFactory
+ 'spr_grapheneresearchcenter', # GrapheneLab
+ 'spr_futuristichome', 'spr_futuristichome_interiors',
+ 'spr_landingpad_tunnel', 'spr_landingpadtunnel_bg', 'spr_landingpadtunnel_buttonback',
+ 'spr_dome_treeplantation', 'spr_dome_treeplantation_buttonback',
+ 'spr_treeplantation_dome_trees', 'spr_treeplantation_dome_trees_grow',
+ 'spr_rocketfuelfactory', 'spr_rocketfuelfactory_frames', 'spr_rocketfuelfactory_idle',
+ 'spr_otherworld_plants', 'spr_otherworldlyZoo_buttonback',
+ 'spr_otherworldcreature_1', 'spr_otherworldcreature_2', 'spr_otherworldcreature_3',
+ 'spr_otherworldcreature_4', # the zoo's animals
+ 'spr_oldesttreeintheuniverse',
+ 'spr_techmuseum', 'spr_techmuseum_buttonback', 'spr_techmuseum_majordisplay_1',
+ 'spr_techmuseum_majordisplay_2', 'spr_techmuseum_minordisplay', 'spr_techmuseum_minordisplay_ext',
+ 'spr_wizardhatcafe',
+ 'spr_trainstation_buttonbg',
+ 'spr_bridge', 'spr_bridge_potential', 'spr_woodenbridge', 'spr_woodenbridge_potential',
+ 'spr_reinforcedbridge', 'spr_reinforcedbridge_potential',
+ 'spr_botanicalbridge', 'spr_botanicalbridge_potential',
+ # holiday content: Christmas, Halloween, snow and winter
+ 'spr_christmasmarket', 'spr_christmastree', 'spr_christmastree_bg', 'spr_upgrade_christmastree',
+ 'spr_horrorgamehall', 'spr_horrorgamehall_lightup', 'spr_horrorgamehall_lightup2',
+ 'spr_indoorpark_dark', 'spr_spiderweb', 'spr_ghostlygarden_buttonbg', # GhostlyPark
+ 'spr_hauntedlaboratory', 'spr_hauntedlaboratory_failed',
+ 'spr_upgrade_pumpkin', 'spr_halloween',
+ 'spr_santahat', 'spr_snow', 'spr_snowman', 'spr_lanterns', 'spr_forest_snow', 'spr_forest_snow_grow',
+ # ads, stores, upsells and links to other sites
+ 'app_store_badge', 'discord_badge', 'google_play_badge', 'steam_badge', 'steam_badge2',
+ 'steam_badge_coolmath', 'spr_badge_premium', 'spr_button_upsell', 'spr_button_upsell_ignore',
+ 'spr_twitter', 'spr_mailinglist', 'spr_discord',
+ # the music and sound buttons (no sound on the calculator)
+ 'spr_music', 'spr_sound',
+ # used by no code of this version
+ 'Naamloos', 'elephant', 'src/potential_hacker_symbol', 'spr_apple', 'spr_aquarium_plants',
+ 'spr_bloomrestaurant_alt', 'spr_boardgames', 'spr_divingsuit', 'spr_festival_podium_large',
+ 'spr_floatingplatform_bottom', 'spr_floatingplatform_top', 'spr_herbgarden_altplants',
+ 'spr_highlightedbuilding', 'spr_icon_followcitizen_small', 'spr_icon_play', 'spr_icon_stats',
+ 'spr_icon_traveltime', 'spr_icon_triplespeed', 'spr_inlinebutton', 'spr_inlinebutton_2',
+ 'spr_movingplatform', 'spr_movingplatform_bottom', 'spr_rail', 'spr_railwaybridge', 'spr_rock_2',
+ 'spr_rocket', 'spr_rocket_part1', 'spr_rocket_part1_down', 'spr_rocket_part2', 'spr_rocket_part3',
+ 'spr_rocket_part4', 'spr_rocketlaunchplatform', 'spr_rocketlaunchplatform_whilebuilding',
+ 'spr_rockettrail', 'spr_rockettrail_small', 'spr_statueofmorehappiness', 'spr_swimmingpool',
+ 'spr_thievesden', 'spr_train', 'spr_trainrail', 'spr_trainselectorbutton', 'spr_trainstation',
+ 'spr_trainstation_decoration', 'spr_trainstation_l', 'spr_trainstation_r',
+ 'spr_transparentbutton_mini', 'spr_vr_headset',
+}
+
+FONTS = [('FONT_STANDARD', 'standard'), ('FONT_10', 'standard10'), ('FONT_15', 'standard15'),
+ ('FONT_16', 'standard16'), ('FONT_18', 'standard18')]
+# characters packed: ASCII, then the others the English texts and the names use
+EXTRA_CHARS = [0xDF, 0xE9, 0xEB, 0xFC] # ß é ë ü
+CHARS = list(range(32, 127)) + EXTRA_CHARS
+SLAB = 48
+
+
+def c565(r, g, b):
+ """the nearest RGB565 colour"""
+ return ((r * 31 + 127) // 255) << 11 | ((g * 63 + 127) // 255) << 5 | ((b * 31 + 127) // 255)
+
+
+def enum_name(name):
+ n = name[4:] if name.startswith('spr_') else name
+ return 'SPR_' + re.sub(r'[^A-Z0-9]', '_', n.upper())
+
+
+def encode_row(row, mode):
+ """the tokens of one row (indexes, None for clear; direct: (rgb565, alpha) or None)"""
+ out = bytearray()
+ end = len(row)
+ while end and row[end - 1] is None:
+ end -= 1
+ x = 0
+ if mode == 2:
+ while x < end:
+ s = x
+ if row[x] is None:
+ while x < end and row[x] is None and x - s < 64:
+ x += 1
+ out.append(x - s - 1)
+ continue
+ while x < end and row[x] == row[s] and x - s < 64:
+ x += 1
+ if x - s >= 3:
+ out.append(0x80 | (x - s - 1))
+ out += struct.pack('<H', row[s][0])
+ if row[s][1] != 255: # a run of a see-through colour: as pixels with alpha
+ del out[-3:]
+ out.append(0xC0 | (x - s - 1))
+ for _ in range(x - s):
+ out += struct.pack('<HB', row[s][0], row[s][1])
+ continue
+ x = s
+ semi = row[x][1] != 255
+ while x < end and row[x] is not None and (row[x][1] != 255) == semi and x - s < 64:
+ x += 1
+ out.append((0xC0 if semi else 0x40) | (x - s - 1))
+ for p in row[s:x]:
+ out += struct.pack('<HB', *p) if semi else struct.pack('<H', p[0])
+ return bytes(out)
+ four = mode == 0
+ fill_min = 4 if four else 3
+ fill_max = 263 if four else 128
+ while x < end:
+ s = x
+ if row[x] is None:
+ while x < end and row[x] is None and x - s < 64:
+ x += 1
+ out.append(x - s - 1)
+ continue
+ while x < end and row[x] == row[s] and x - s < fill_max:
+ x += 1
+ if x - s >= fill_min:
+ if four and x - s < 8:
+ out.append((x - s + 7) << 4 | row[s])
+ elif four:
+ out += bytes([0xF0 | row[s], x - s - 8])
+ else:
+ out += bytes([0x80 | (x - s - 1), row[s]])
+ continue
+ # literal pixels, up to the next clear one or a run worth breaking it for
+ x = s + 1
+ while x < end and row[x] is not None and x - s < 64:
+ y = x
+ while y < end and row[y] == row[x]:
+ y += 1
+ if y - x > fill_min:
+ break
+ x += 1
+ out.append(0x40 | (x - s - 1))
+ lit = row[s:x]
+ if four:
+ for i in range(0, len(lit), 2):
+ out.append(lit[i] | (lit[i + 1] << 4 if i + 1 < len(lit) else 0))
+ else:
+ out += bytes(lit)
+ return bytes(out)
+
+
+def pack_sprite(px, f):
+ """the data of one sprite (frame rectangle f of the atlas)"""
+ w, h = f['w'], f['h']
+ keys = [[None] * w for _ in range(h)]
+ pal = {}
+ for y in range(h):
+ for x in range(w):
+ r, g, b, a = px[f['x'] + x, f['y'] + y]
+ if a:
+ k = (c565(r, g, b), a)
+ keys[y][x] = k
+ if k not in pal:
+ pal[k] = len(pal)
+ if len(pal) > 256:
+ # alpha 252 and more blends like 255 (the renderer has 33 levels)
+ rows = [[None if k is None else (k[0], 255 if k[1] >= 252 else k[1]) for k in r] for r in keys]
+ mode, colours = 2, []
+ else:
+ mode = 0 if len(pal) <= 16 else 1
+ rows = [[None if k is None else pal[k] for k in r] for r in keys]
+ colours = sorted(pal, key=pal.get)
+ # wide strips are cut into slabs (at clear columns, at least SLAB pixels wide; every frame
+ # for the small ones such as citizens), each with its own rows, so that a frame far right
+ # is found without walking all the row
+ slabs = [(0, w)]
+ if w > 64:
+ opaque = [any(rows[y][x] is not None for y in range(h)) for x in range(w)]
+ segs, x = [], 0
+ while x < w:
+ if not opaque[x]:
+ x += 1
+ continue
+ s0 = x
+ while x < w and opaque[x]:
+ x += 1
+ if segs and s0 - segs[-1][0] < (SLAB if h > 8 else 1):
+ segs[-1][1] = x
+ else:
+ segs.append([s0, x])
+ if segs:
+ slabs = [(a, b) for a, b in segs]
+ if h <= 8 and len(slabs) == 1:
+ # small strips without clear columns between frames (citizens: frames 2 wide, 4 apart)
+ slabs = [(a, min(a + 4, w)) for a in range(0, w, 4)]
+ assert len(slabs) < 256, 'too many slabs'
+ coded = [[encode_row(r[a:b], mode) for r in rows] for a, b in slabs]
+ big = any(sum(len(c) for c in sl) > 0xFFFF for sl in coded)
+ head = struct.pack('<BBBB', len(colours), mode | (4 if big else 0), len(slabs), 0)
+ head += b''.join(struct.pack('<H', c[0]) for c in colours)
+ head += bytes(c[1] for c in colours)
+ while len(head) & 3:
+ head += b'\0'
+ at = len(head) + 8 * len(slabs)
+ table, body = b'', b''
+ st = {'palette': len(head), 'rows': 8 * len(slabs), 'pixels': 0, 'mode': mode, 'slabs': len(slabs)}
+ for (a, b), sl in zip(slabs, coded):
+ while (at + len(body)) & 3:
+ body += b'\0'
+ table += struct.pack('<HHI', a, b, at + len(body))
+ offs = [0]
+ for c in sl:
+ offs.append(offs[-1] + len(c))
+ body += b''.join(struct.pack('<I' if big else '<H', o) for o in offs) + b''.join(sl)
+ st['rows'] += (4 if big else 2) * len(offs)
+ st['pixels'] += offs[-1]
+ return head + table + body, st
+
+
+def parse_fnt(path):
+ text = open(path, encoding='utf-8').read()
+ def attrs(tag):
+ return {k: v for k, v in re.findall(r'(\w+)="([^"]*)"', tag)}
+ common = attrs(re.search(r'<common [^>]*>', text).group(0))
+ page = attrs(re.search(r'<page [^>]*>', text).group(0))['file']
+ chars = {}
+ for m in re.finditer(r'<char [^>]*>', text):
+ a = attrs(m.group(0))
+ chars[int(a['id'])] = {k: int(a[k]) for k in ('x', 'y', 'width', 'height', 'xoffset', 'yoffset', 'xadvance')}
+ kern = []
+ for m in re.finditer(r'<kerning [^>]*>', text):
+ a = attrs(m.group(0))
+ kern.append((int(a['first']), int(a['second']), int(a['amount'])))
+ return int(common['lineHeight']), page, chars, kern
+
+
+def pack_font(ref, base):
+ line_h, page, chars, kern = parse_fnt(os.path.join(ref, 'fonts', base + '.fnt'))
+ im = Image.open(os.path.join(ref, 'fonts', page)).convert('RGBA')
+ px = im.load()
+ glyphs = bytearray()
+ bits = []
+ for code in CHARS:
+ c = chars.get(code)
+ if c is None: # missing: nothing drawn, no advance (BitmapText skips it)
+ glyphs += struct.pack('<HbbBBBB', 0, 0, 0, 0, 0, 0, 0)
+ continue
+ first = len(bits)
+ for y in range(c['height']):
+ for x in range(c['width']):
+ bits.append(1 if px[c['x'] + x, c['y'] + y][3] >= 128 else 0)
+ glyphs += struct.pack('<HbbBBBB', first, c['xoffset'], c['yoffset'], c['width'], c['height'],
+ c['xadvance'], 0)
+ index = {code: i for i, code in enumerate(CHARS)}
+ pairs = sorted((index[b], index[a], n) for a, b, n in kern if a in index and b in index and n)
+ kerning = b''.join(struct.pack('<BBbB', a, b, n, 0) for b, a, n in pairs)
+ data = bytearray(len(bits) + 7 >> 3)
+ for i, v in enumerate(bits):
+ if v:
+ data[i >> 3] |= 1 << (i & 7)
+ head_len = 8
+ bits_off = head_len + len(glyphs) + len(kerning)
+ head = struct.pack('<BBHI', line_h, len(CHARS), len(pairs), bits_off)
+ return head + bytes(glyphs) + kerning + bytes(data), len(pairs)
+
+
+def main():
+ ref = sys.argv[1] if len(sys.argv) > 1 else REF
+ atlas = json.load(open(os.path.join(ref, 'sprites.json')))
+ im = Image.open(os.path.join(ref, 'sprites.png')).convert('RGBA')
+ px = im.load()
+ names = sorted(k[:-4] for k in atlas['frames'] if k[:-4] not in DROPPED)
+ missing = DROPPED - set(k[:-4] for k in atlas['frames'])
+ if missing:
+ sys.exit('pack.py: dropped sprites not in the atlas: ' + ', '.join(sorted(missing)))
+ enums = [enum_name(n) for n in names]
+ if len(set(enums)) != len(enums):
+ sys.exit('pack.py: two sprites with the same SPR_ name')
+
+ out = bytearray(16)
+ def align(n=4):
+ while len(out) % n:
+ out.append(0)
+ spr_table = len(out)
+ out += bytes(8 * len(names))
+ stats = {'palette': 0, 'rows': 0, 'pixels': 0, 'table': 8 * len(names), 'slabs': 0}
+ modes = [0, 0, 0]
+ sizes = []
+ for i, n in enumerate(names):
+ f = atlas['frames'][n + '.png']['frame']
+ align()
+ blob, st = pack_sprite(px, f)
+ struct.pack_into('<IHH', out, spr_table + 8 * i, len(out), f['w'], f['h'])
+ out += blob
+ for k in ('palette', 'rows', 'pixels', 'slabs'):
+ stats[k] += st[k]
+ modes[st['mode']] += 1
+ sizes.append((f['w'], f['h']))
+ sprite_end = len(out)
+ align()
+ font_table = len(out)
+ out += bytes(4 * len(FONTS))
+ font_sizes = []
+ for i, (_, base) in enumerate(FONTS):
+ align()
+ blob, npairs = pack_font(ref, base)
+ struct.pack_into('<I', out, font_table + 4 * i, len(out))
+ out += blob
+ font_sizes.append((base, len(blob), npairs))
+ align()
+ struct.pack_into('<4sHHII', out, 0, b'FE2D', len(names), len(FONTS), spr_table, font_table)
+ open(os.path.join(SRC, 'data.bin'), 'wb').write(out)
+
+ h = ['/* The Final Earth 2: what tools/pack.py packed in data.bin (made by it: do not edit). */',
+ '#ifndef FE_DATA_H', '#define FE_DATA_H', '#include <stdint.h>', '',
+ 'extern const uint8_t fe_data[]; /* data.bin (data.S) */', '',
+ '/* sprites: each frame of the original\'s atlas (often a strip of frames, 2 pixels apart) */',
+ 'enum {']
+ for e, n, (w, hh) in zip(enums, names, sizes):
+ h.append(' %s,%s/* %s.png, %d x %d */' % (e, ' ' * max(1, 40 - len(e)), n, w, hh))
+ h += [' SPR_COUNT', '};', '', '/* each sprite\'s width and height */']
+ for e, (w, hh) in zip(enums, sizes):
+ h.append('#define %s_W %d' % (e, w))
+ h.append('#define %s_H %d' % (e, hh))
+ h += ['', '/* fonts (the original\'s BMFont fonts) */', 'enum { ' + ', '.join(f[0] for f in FONTS) + ', FONT_COUNT };',
+ '', '#endif', '']
+ open(os.path.join(SRC, 'data.h'), 'w').write('\n'.join(h))
+
+ print('data.bin: %d bytes' % len(out))
+ print(' sprites: %d bytes for %d sprites (%d 4-bit, %d 8-bit, %d direct), %d dropped' %
+ (sprite_end - spr_table, len(names), modes[0], modes[1], modes[2], len(DROPPED)))
+ print(' table %d, palettes and headers %d, slabs (%d) and row offsets %d, pixels %d, padding %d' %
+ (stats['table'], stats['palette'], stats['slabs'], stats['rows'], stats['pixels'],
+ sprite_end - spr_table - stats['table'] - stats['palette'] - stats['rows'] - stats['pixels']))
+ print(' fonts: %d bytes (%s)' % (len(out) - sprite_end,
+ ', '.join('%s %d B, %d kerning pairs' % f for f in font_sizes)))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tests/test_games.py b/tests/test_games.py
index 81ab653d..f832bb9e 100644
--- a/tests/test_games.py
+++ b/tests/test_games.py
@@ -117,6 +117,9 @@ GAMES = {
presses((2500, "ok"), (4500, "ok"), (5500, "ok"), (6500, "ok")) + every(18000, 22000, 600, "right", 400),
25000,
presses((2500, "ok"), (4500, "ok")) + every(9000, 11000, 600, "left", 400), 14000),
+ # Press OK to Play: the first scenario, its first goal closed, the city runs; then Continue
+ "finalearth2": ("FinalEarth2.nwa", "finalearth2.sav", presses((2000, "ok"), (3000, "ok")), 9000,
+ presses((2000, "ok")), 6000),
# a level, its message, then play; then back to the level select
"portal": ("PortalReturns.nwa", "portal.sav",
presses((1500, "ok"), (2500, "ok"), (3500, "ok")) + every(4000, 7000, 400, "right", 300), 8000,
@@ -144,7 +147,7 @@ SEEDS = {
# NumWorks installer keeps): before the second session, as after installing
# the app again, only the scripts are left, and the save must come back
COPIES = {"championisland": "champion_saves.py", "numblocks": "numblocks_saves.py", "celeste": "celeste_saves.py",
- "hollowknight": "hollowknight_saves.py"}
+ "hollowknight": "hollowknight_saves.py", "finalearth2": "finalearth2_saves.py"}
CHECKS = {
# the island remembers where Lucky was; after the reinstall, from the copy
"championisland": (lambda v: v[:3] == b"CI1" and b"PLAYER_LOC" in v,) * 2,
@@ -153,6 +156,8 @@ CHECKS = {
"celeste": (lambda v: v[:4] == b"SLEC" and v[1072] == 1 and struct.unpack_from("<I", v, 1096)[0] > 0,
lambda v: v[:4] == b"SLEC" and v[1072] == 1 and struct.unpack_from("<I", v, 1096)[0] > 60),
"chess": (lambda v: v == SEEDS["chess"],) * 2, # read back and kept
+ # a city saved ("FE2S", version 1); after the reinstall, from the copy, it goes on and is saved again
+ "finalearth2": (lambda v: v[:4] == b"FE2S" and v[4] == 1,) * 2,
# a game saved ("HKSV", then the play time at 152); after the reinstall, from the copy, it goes on
"hollowknight": (lambda v: v[:4] == b"HKSV" and struct.unpack_from("<f", v, 152)[0] > 0,
lambda v: v[:4] == b"HKSV" and struct.unpack_from("<f", v, 152)[0] > 10),
diff --git a/tools/release.py b/tools/release.py
index 51baa56b..0b05e830 100644
--- a/tools/release.py
+++ b/tools/release.py
@@ -29,6 +29,8 @@ ALONE = {
"NumPlay: install it on its own"),
"championisland": ("Champion Island", "the Doodle Champion Island Games. Too big to share the calculator with "
"NumPlay: install it on its own"),
+ "finalearth2": ("The Final Earth 2", "build a city on floating islands in space, every scenario and free play map. "
+ "Too big to share the calculator with NumPlay: install it on its own"),
}
VARIANTS = [
("NumPlay-Invisible.nwa", "The same app, hidden: a blank icon with no name"),