craftos-mcp
A headless CC:Tweaked emulator for AI agents and tests
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 17 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Akkiruk/craftos-mcp with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Akkiruk/craftos-mcp'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/akkiruk--craftos-mcp)HTML
<a href="/listings/akkiruk--craftos-mcp"><img src="/api/listings/akkiruk--craftos-mcp/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
You need Node.js 22 or newer.
From npm (Windows and Linux x64)
npx -y craftos-mcp serve # the MCP server, for any agent claude mcp add craftos -- npx -y craftos-mcp serve npx craftos-mcp test # or window, app, run, info: see the command line below
The package holds no engine or ROM. The first command fetches the engine from this repository's release, builds the ROMs from the real CC:Tweaked jars and the GPU fonts, and keeps them in `%LOCALAPPDATA%\craftos-mcp` or `~/.cache/craftos-mcp` (`CRAFTOS_HOME` moves it); that takes a few seconds to a minute, once per version. `serve` answers its client straight away and lets the tools that run computers wait for it. The workspace is the folder you run it in. `craftos-mcp setup --force` does the setup again.
Quick start from a clone
git clone https://github.com/Akkiruk/craftos-mcp cd craftos-mcp npm run setup
`npm run setup` installs the packages, builds the tools, builds the ROM from the real CC:Tweaked jar (and Tom's Peripherals' fonts), downloads the prebuilt engine for your OS from the latest release, checks everything and prints the line that connects your agent. Run it again any time: finished steps are skipped. If the release has no engine for your OS it tells you how to build one (below).
Claude Code plugin
One install gives Claude Code the `cc-tweaked-dev` skill and the `craftos` MCP server:
/plugin marketplace add Akkiruk/craftos-mcp /plugin install craftos-mcp@craftos-mcp
Claude Code keeps a copy of this repository for the plugin, which has no engine or ROM yet, so the first time the server starts it runs the setup above in the background (a few minutes: it downloads the jar and the engine). If `/mcp` shows the server as failed on that first try, wait a minute and reconnect; setup carries on without it. Progress is in `.cache/setup.log` inside the plugin's folder. The plugin asks which mods your pack has (the addon list below), and the server's workspace is the folder you start Claude Code in.
The command line
`craftos-mcp` runs without an agent, so it works in scripts and CI. Run it from your Lua project folder (`--dir` changes that):
craftos-mcp test # every *.test.lua below here, ccunit harness; exits 1 on a failure craftos-mcp test tests/ --addons create --timescale 10 craftos-mcp run clock.lua --monitor top:2x2 --screenshot shot.png # terminal and monitors as text, PNGs saved craftos-mcp run sort.lua --world worlds/chests.json --timeout 20 -- --verbose craftos-mcp info # engine, ROM and addons status craftos-mcp serve # the MCP server over stdio
Inside a clone use `npx craftos-mcp ...`, or `node apps/cli/dist/index.js ...`. `craftos-mcp help <command>` lists the options. A `--world` is a JSON file or the name of one in `worlds/`; `--addons` is `all`, `none` or ids separated by commas.
Doing it by hand
1. The engine
Download the prebuilt engine for your OS from the [latest release](../../releases/latest) and unzip it over the repository, or build it yourself:
- **Windows**: Visual Studio 2022 (or its Build Tools) with C++, CMake, Ninja and a [vcpkg](https://vcpkg.io) checkout in `VCPKG_ROOT`. Then `engine\build.cmd`. - **Linux**: a C++17 compiler, CMake, Ninja and vcpkg in `VCPKG_ROOT`. Then `engine/build.sh`.
macOS is not supported yet.
2. The ROM
CC:Tweaked's license does not allow its ROM to be redistributed with this project, so you build it on your own machine. This downloads CC:Tweaked 1.101.3 from Modrinth, checks its hash, and builds `rom/cc-1.101.3`:
node scripts/build-rom.mjs --download
If you already have the jar: `node scripts/build-rom.mjs path/to/cc-tweaked-1.18.2-1.101.3.jar rom/cc-1.101.3`.
The same step downloads Tom's Peripherals 1.18.2-1.2.1 (MIT) and builds the GPU's fonts from it, since they are not
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 12 lines
- {
- "name": "craftos-mcp",
- "description": "A headless CC:Tweaked emulator for AI agents and tests",
- "owner": { "name": "craftos-mcp contributors" },
- "plugins": [
- {
- "name": "craftos-mcp",
- "source": "./",
- "description": "Run, test and screenshot ComputerCraft Lua programs without Minecraft: the cc-tweaked-dev skill and the craftos MCP server."
- }
- ]
- }
README.md · README · 390 lines
- # craftos-mcp
- > **Minecraft 1.18.2 is complete. 1.20.1 is partly there:** pick it and you get CC:Tweaked 1.121.0's behaviour and
- > 1.20.1 turtle data, but the mods' peripherals still behave like their 1.18.2 versions for now. 1.21.1 is next. See
- > [Choose your Minecraft version](#choose-your-minecraft-version).
- **Let your coding agent test the ComputerCraft code it writes.** AI agents write CC:Tweaked Lua they have never run,
- and the bugs turn up on your server. craftos-mcp is a CC:Tweaked emulator the agent drives itself over
- [MCP](https://modelcontextprotocol.io): it runs the program, reads the terminal and every monitor, taps buttons,
- changes the world around the computer (a player walks up, a chest fills, a train arrives, a reactor heats up, an hour
- passes), writes and runs tests, and fixes what broke until it works. All without Minecraft.
- ```json
- {
- "mcpServers": {
- "craftos": { "command": "npx", "args": ["-y", "craftos-mcp", "serve"] }
- }
- }
- ```
- That one entry works in Claude Code, Cursor, VS Code and any other MCP client; the first start downloads the engine
- and builds the ROM by itself. In VS Code, Cursor or Windsurf you can install the
- [extension](https://marketplace.visualstudio.com/items?itemName=Rogiedoji.craftos-mcp) instead (also on
- [Open VSX](https://open-vsx.org/extension/Rogiedoji/craftos-mcp)): it sets up the server for Copilot, and adds Run in
- CraftOS for any `.lua` file and your `*.test.lua` files in the Testing view. The world it simulates is what CC programs depend on: several computers on modems with
- real rednet, turtles in a block world, and peripherals from Create, Mekanism, Advanced Peripherals and more.
- No agent? The same emulator works for people too:
- - **In a window**, like CraftOS-PC: `craftos-mcp window` ([Without an AI agent](#without-an-ai-agent)).
- - **In your browser**: `craftos-mcp app` opens computers, monitors and the world side by side.
- - **From the command line and CI**: `craftos-mcp test tests/` runs your `*.test.lua` files.
- The engine passes 1190 of 1191 of CC:Tweaked's own tests at 1.101.3 (and 1362 of 1363 at 1.121.0), and the ROM is
- built from the real CC:Tweaked jar. [How exact is it](docs/accuracy.md) says, area by area, what was measured in game
- and what was written from source.
- 
- _A real Claude Code session, unscripted: asked for a door controller with tests, it ran its program in the emulator,
- caught a monitor that never stopped redrawing and a player at the range edge who could not get in, fixed both, and
- finished with its tests passing. Then the same file went onto a computer in real Minecraft and worked there with no code
- changes, just a player name added to its whitelist ([the diff](docs/media/showcase/ingame-door-diff.txt),
- [the clip](docs/media/showcase/ingame-door.mp4)). The [full transcript](docs/media/showcase/agent-demo-transcript.md)
- is next to the [video](docs/media/showcase/agent-demo.mp4)._
- Some games built and tested with it are **[playable in your browser](https://rogiedoji.com/craftos)**, no install,
- and there's a [highlight reel](docs/media/showcase/sizzle.mp4) of them.
- ## What it does
- - **Run and test**: run a program in a fresh computer and get the terminal and every monitor back as text, PNGs or
- golden snapshots; run `*.test.lua` files with the built-in `ccunit` harness.
- - **Interactive sessions**: type, press keys, touch monitors, send events, wait for text. `craftos_ui` reads every
- screen as buttons and text runs with colours, so an agent can drive a UI without screenshots.
- - **Monitors** at any wall size and text scale, with real touch events.
- - **Several computers at once**: wireless, ender and wired modems with real rednet, ranges and wired names.
- - **Turtles** in a block world built from vanilla 1.18.2 data: the whole turtle API with its tick timing, digging
- with loot-table drops, placing, inventories, refuelling, upgrades and crafting. What a turtle places comes alive:
- computers boot, disk drives take floppies, monitors join into walls.
- - **CC's generic peripherals**: chests, barrels and any modded block as an inventory, fluid tank and energy store,
- with `pushItems`, `pullItems`, `pushFluid` and levels that move over time.
- - **Peripherals from other mods**, written from each mod's source and checked against its jar, each one an addon
- you switch on only if your pack has it (see [Choose your mods](#choose-your-mods)):
- - Advanced Peripherals 0.7.31r: player, energy and environment detectors, chat box, redstone integrator, NBT
- storage, AR controller, ME and RS bridges.
- - Mekanism 10.2.5: QIO, the Quantum Entangloporter, the boiler and induction matrix; with Mekanism Generators, the
- fission reactor, turbine and fusion reactor, running tick by tick (a reactor left alone melts down).
- - Create 0.5.1: train stations with schedules and trains on the clock, gauges, speed controllers, sequenced
- gearshifts and the display link; Create Crafts & Additions 1.0.0's motor, accumulator, relay and digital adapter.
- - Tom's Peripherals 1.2.1: the GPU with its full drawing API, pixel-exact and in screenshots, keyboard, redstone
- port and watchdog.
- - Bigger Reactors 0.6.0 and Extreme Reactors 2.0.71: reactors and turbines with their real heat, fuel and rotor
- physics.
- - **Determinism**: seed `math.random`, run the clock faster, or jump it forward so timers fire instantly.
- - **Your way in**: a desktop window, a browser app (also the MCP server's live viewer at <http://127.0.0.1:7878>),
- a command line, and an in-computer `sim` command to change the world by typing (`sim join Alice`).
- ## Games
- Three game cabinets and an RPG in plain CC:Tweaked Lua, each with a world file and tests that play real games through
- taps on the monitors. They're examples of what you can build and test here, and they use nothing but CC:Tweaked's own
- APIs.
- | Cabinet | Games | Shows off |
- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
- | [Board](workspace/examples/games/board/README.md) | Ultimate Tic-Tac-Toe, Four in a Row, Reversi, Checkers, Dots and Boxes, Mancala, Fleet, Codebreaker; three computer levels | touch monitor walls, two players at one wall |
- | [Action](workspace/examples/games/action/README.md) | Snake, Blocks, Bricks, Lander, Mines | fast redraws, real-time touch |
- | [Versus](workspace/examples/games/versus/README.md) | Paddle, Trails, Artillery | two computers in one match over rednet |
- | [BLIGHTMARE](workspace/examples/games/blightmare/README.md) | a first-person RPG in eleven acts: towns, a world map, turn-based fights, bosses, saves | 2 MB of game packed onto a 1 MB disk |
- 
- BLIGHTMARE, played by touch ([the whole showcase](docs/media/showcase/blightmare.mp4))
- | | |
- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
- |  |  |
- | Blocks, steered by tapping the wall | Paddle across two computers on rednet (3x speed) |
- Each cabinet's README says how to open it. The board games, for example:
- ```sh
- craftos-mcp window workspace/examples/games/board/arcade.world.json --dir workspace --monitor left:6x6 --monitor right:6x6
- # then, in the computer: examples/games/board/arcade
- ```
- `node scripts/make-showcase.mjs` records the videos again from real runs.
- ## Examples
- [`workspace/examples/`](workspace/examples/README.md) also has complete programs for the mods above, each with a world
- and a test that proves it works: a Mekanism reactor controller, a Create train departure board, an energy monitor for
- any modded battery, a Tom's Peripherals GPU demo, an Extreme Reactors rod controller, an Advanced Peripherals player
- greeter and a rednet chat between two computers. These pictures are rendered from real runs (`node
- scripts/make-demo-gif.mjs` makes them again).
- 
- _The [reactor controller](workspace/examples/mekanism/reactor.lua) on a simulated Mekanism reactor, with the clock sped
- up: it scrams the reactor before it is damaged, and RESET restarts it once it has cooled. The
- [test](workspace/examples/mekanism/reactor.test.lua) checks exactly that._
- | | |
- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
- |  |  |
- | Train departure board: platform, train, status and schedule for each station | GPU demo: a spinning cube, a sine ribbon and ripples where you right-click |
- |  |  |
- | Power monitor: any block with an energy store, with rates and a low-power alarm | The reactor controller after it has scrammed on temperature |
- ## Setup
- You need Node.js 22 or newer.
- ### From npm (Windows and Linux x64)
- ```sh
- npx -y craftos-mcp serve # the MCP server, for any agent
- claude mcp add craftos -- npx -y craftos-mcp serve
- npx craftos-mcp test # or window, app, run, info: see the command line below
- ```
- The package holds no engine or ROM. The first command fetches the engine from this repository's release, builds the
- ROMs from the real CC:Tweaked jars and the GPU fonts, and keeps them in `%LOCALAPPDATA%\craftos-mcp` or
- `~/.cache/craftos-mcp` (`CRAFTOS_HOME` moves it); that takes a few seconds to a minute, once per version. `serve`
- answers its client straight away and lets the tools that run computers wait for it. The workspace is the folder you
- run it in. `craftos-mcp setup --force` does the setup again.
- ### Quick start from a clone
- ```sh
- git clone https://github.com/Akkiruk/craftos-mcp
- cd craftos-mcp
- npm run setup
- ```
- `npm run setup` installs the packages, builds the tools, builds the ROM from the real CC:Tweaked jar (and Tom's
- Peripherals' fonts), downloads the prebuilt engine for your OS from the latest release, checks everything and prints
- the line that connects your agent. Run it again any time: finished steps are skipped. If the release has no engine for
- your OS it tells you how to build one (below).
- ### Claude Code plugin
- One install gives Claude Code the `cc-tweaked-dev` skill and the `craftos` MCP server:
- ```text
- /plugin marketplace add Akkiruk/craftos-mcp
- /plugin install craftos-mcp@craftos-mcp
- ```
- Claude Code keeps a copy of this repository for the plugin, which has no engine or ROM yet, so the first time the
- server starts it runs the setup above in the background (a few minutes: it downloads the jar and the engine). If
- `/mcp` shows the server as failed on that first try, wait a minute and reconnect; setup carries on without it. Progress
- is in `.cache/setup.log` inside the plugin's folder. The plugin asks which mods your pack has (the addon list below),
- and the server's workspace is the folder you start Claude Code in.
- ### The command line
- `craftos-mcp` runs without an agent, so it works in scripts and CI. Run it from your Lua project folder (`--dir`
- changes that):
- ```sh
- craftos-mcp test # every *.test.lua below here, ccunit harness; exits 1 on a failure
- craftos-mcp test tests/ --addons create --timescale 10
- craftos-mcp run clock.lua --monitor top:2x2 --screenshot shot.png # terminal and monitors as text, PNGs saved
- craftos-mcp run sort.lua --world worlds/chests.json --timeout 20 -- --verbose
- craftos-mcp info # engine, ROM and addons status
- craftos-mcp serve # the MCP server over stdio
- ```
- Inside a clone use `npx craftos-mcp ...`, or `node apps/cli/dist/index.js ...`. `craftos-mcp help <command>` lists the
- options. A `--world` is a JSON file or the name of one in `worlds/`; `--addons` is `all`, `none` or ids separated by
- commas.
- ### Doing it by hand
- #### 1. The engine
- Download the prebuilt engine for your OS from the
- [latest release](../../releases/latest) and unzip it over the repository, or build it yourself:
- - **Windows**: Visual Studio 2022 (or its Build Tools) with C++, CMake, Ninja and a [vcpkg](https://vcpkg.io)
- checkout in `VCPKG_ROOT`. Then `engine\build.cmd`.
- - **Linux**: a C++17 compiler, CMake, Ninja and vcpkg in `VCPKG_ROOT`. Then `engine/build.sh`.
- macOS is not supported yet.
- #### 2. The ROM
- CC:Tweaked's license does not allow its ROM to be redistributed with this project, so you build it on your own
- machine. This downloads CC:Tweaked 1.101.3 from Modrinth, checks its hash, and builds `rom/cc-1.101.3`:
- ```sh
- node scripts/build-rom.mjs --download
- ```
- If you already have the jar: `node scripts/build-rom.mjs path/to/cc-tweaked-1.18.2-1.101.3.jar rom/cc-1.101.3`.
- The same step downloads Tom's Peripherals 1.18.2-1.2.1 (MIT) and builds the GPU's fonts from it, since they are not
- shipped here either (`node scripts/build-toms-fonts.mjs` does it alone).
- #### 3. The tools
- ```sh
- npm install
- npm run build
- ```
- #### 4. Connect your agent
- Claude Code:
- ```sh
- claude mcp add craftos -- node /path/to/craftos-mcp/apps/mcp-server/dist/index.js
- ```
- VS Code: `.vscode/mcp.json` is already set up for this folder. Other MCP clients: run
- `node apps/mcp-server/dist/index.js` over stdio. Then call `craftos_info`; it lists anything that is missing.
- Point `CRAFTOS_WORKSPACE` at your own Lua project to work on it in place. Other settings: `CRAFTOS_ENGINE`,
- `CRAFTOS_ROM`, `CRAFTOS_RUNTIME_ROOT`, `CRAFTOS_VIEWER_PORT` (`off` turns the viewer off).
- ## Without an AI agent
- `craftos-mcp window` opens the computer in a desktop window, with the same simulated world an agent gets:
- ```sh
- craftos-mcp window worlds/generic-storage-demo.json --monitor top:3x2 # from your Lua project folder
- craftos-mcp window create-demo --dir path/to/project # a world from worlds/ by name
- ```
- The computer's files are your folder (`--dir`, default the current one), live: edit in your own editor, then hold
- Ctrl+R in the window to reboot. Monitors open as windows of their own and a click is a touch; a world can list them
- under `"monitors"`. A world's speakers play real sound. F12 copies a screenshot to the clipboard. Turtle worlds and several computers on
- one network do not open in a window yet.
- Inside the computer, the `sim` program changes the world, as `craftos_sim_command` does for an agent. It is the
- emulator's own: a real CC:Tweaked computer has no `sim`.
- ```text
- sim join Alice sim leave Alice
- sim chat Alice hello sim advance 60 (jump the clock 60 seconds)
- sim item chest_0 1 minecraft:diamond 5
- sim state (players, peripherals, chat)
- sim createTrainArrive station=Create_Station_0 train=Express (any command a mod's simulation knows)
- sim help (all of them)
- ```
- ### In your browser
- `craftos-mcp app` starts a local web page and opens it:
- ```sh
- craftos-mcp app --dir path/to/project # --port 7878 by default; --no-open just prints the address
- ```
- **New computer** makes one: a normal, advanced, pocket or turtle computer, a world from `worlds/` or your own JSON,
- the mods your pack has, monitors and their sizes, and a program to run (or just the shell). Set **Computers** above 1
- for a network, each with a modem. Every computer gets a tab. Its terminal takes the keyboard, paste and mouse; the
- Ctrl+T, Ctrl+R and Ctrl+S buttons hold the keys for a second as CC needs (your browser keeps Ctrl+T for itself).
- Monitors and Tom's Peripherals GPU screens update live, and a click is a touch on that cell or pixel; **UI** outlines
- what the screens show as buttons. On the side: the world (players join, leave and chat, the clock jumps, items go
- into slots, and the whole sim state as a tree), a box for any sim command with the list of the ones this world knows,
- and the computer's files, which you can edit, or copy your project in again, and reboot.
- It listens on 127.0.0.1 only. The MCP server's live viewer (<http://127.0.0.1:7878>) is the same page, so you can
- watch and help while an agent works.
- ## Choose your Minecraft version
- | Version | CC:Tweaked | State |
- | ------------------ | ---------- | ---------------------------------------------------------------------------------------------------- |
- | `1.18.2` (default) | 1.101.3 | Complete: CC itself, turtles, modems and every mod below |
- | `1.20.1` | 1.121.0 | CC itself and turtles (1.20.1 block data) as in 1.121.0; the mods still act as their 1.18.2 versions |
- | `1.21.1` | 1.121.0 | CC itself as in 1.121.0; turtle data and mods not done yet |
- Pick one per world with `"version": "1.20.1"`, for the MCP server with `CRAFTOS_VERSION`, or on the command line with
- `--mc 1.20.1`. Each CC:Tweaked version needs its ROM: `node scripts/build-rom.mjs --download 1.20.1`, or
- `npm run setup -- --mc all` for every version. A mod that does not exist on the chosen version (Bigger Reactors on
- 1.21.1) is refused with a message.
- ## Choose your mods
- Every mod besides CC:Tweaked is an addon. Switch on only the ones your pack has, so a program cannot come to rely on
- a peripheral your server does not have. Set `CRAFTOS_ADDONS` for the MCP server (the `.vscode/mcp.json` here lists
- them all: delete the ones you do not use), or give one world its own list with `addons`:
- ```json
- {
- "addons": ["create", "mekanism"],
- "peripherals": [{ "name": "station_0", "type": "Create_Station" }]
- }
- ```
- | Id | Mod |
- | ---------------------- | ------------------------------------------------ |
- | `advanced-peripherals` | Advanced Peripherals 0.7.31r |
- | `mekanism` | Mekanism 10.2.5 |
- | `mekanism-generators` | Mekanism Generators 10.2.5 (needs `mekanism`) |
- | `create` | Create 0.5.1.i |
- | `create-additions` | Create Crafts & Additions 1.0.0 (needs `create`) |
- | `toms-peripherals` | Tom's Peripherals 1.18.2-1.2.1 |
- | `bigger-reactors` | Bigger Reactors 1.18.2-0.6.0-beta.1.4 |
- | `extreme-reactors` | Extreme Reactors 1.18.2-2.0.71 |
- `"all"` and `"none"` work too. With no setting at all, everything is on. A world that uses a block from an addon that
- is off fails before the computer boots and names the addon; `craftos_info` lists what is on.
- ## Tools
- | Tool | Purpose |
- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
- | `craftos_info` | Engine, ROM and workspace status |
- | `craftos_write_file`, `craftos_read_file`, `craftos_list_files` | Workspace files (copied to the root of each computer) |
- | `craftos_run` | Run a program in a fresh computer: terminal and monitor text, PNGs, golden snapshots |
- | `craftos_test` | Run `*.test.lua` files with the `ccunit` harness |
- | `craftos_session_create`, `craftos_type`, `craftos_key`, `craftos_touch_monitor`, ... | Interactive computers |
- | `craftos_ui`, `craftos_act`, `craftos_settle`, `craftos_expect`, `craftos_script` | Read screens as data, act and wait until the program is done, assert |
- | `craftos_network_create`, `craftos_network_update` | Several computers with modems |
- | `craftos_sim_command`, `craftos_sim_state` | Change and read the simulated world during a session |
- | `craftos_seed`, `craftos_advance`, `craftos_trace`, `craftos_screenshot` | Determinism, the virtual clock, what the program saw, pictures |
- For an agent, `.claude/skills/cc-tweaked-dev/SKILL.md` is a short guide to using these well.
- ## Your own modpack
- The turtle world ships with vanilla Minecraft, Forge and CC:Tweaked data. To give it every block, item, recipe and
- loot table in your modpack, generate the data from your own instance:
- ```sh
- python -I tools/turtledata/extract.py --instance "<your instance>/minecraft"
- ```
- ## Layout
- ```text
- engine/ Forked CraftOS-PC 2 (MIT, see engine/UPSTREAM.md)
- packages/ rawterm (engine protocol, PNG renderer), runner (runs, tests, sessions, networks, browser app), protocol
- apps/ The craftos-mcp command line (window, app, test, run, info, serve) and the MCP server
- rom-overlay/ The simulation layered over the CC:Tweaked ROM (peripherals, modems, turtles)
- web/ The browser build: the engine as WebAssembly and a player for pages (web/README.md)
- scripts/ Setup, ROM builder, CC:Tweaked conformance runner, the video recorder
- tools/ Data extraction for turtles
- worlds/ Example worlds
- docs/ Architecture, security model, peripherals, turtles, conformance
- ```
- ## Known limits
- - Minecraft 1.18.2 is complete; on 1.20.1 and 1.21.1 the mods are still their 1.18.2 versions (see
- [Choose your Minecraft version](#choose-your-minecraft-version)). Older versions (1.16.5, 1.12.2) are not supported.
- - Only the mods listed above are simulated, and each from its source: where a mechanic is too large to copy (Create's
- stress network and track graph, multiblock formation) it is a fixture instead. Each mod's doc ends with what is not
- simulated or not confirmed. Pocket computer upgrades and most of Advanced Peripherals' turtle upgrades are not simulated (the geo scanner and chunky turtle are).
- - A pattern that never finishes inside one C function (a pathological `string.find`) cannot be aborted by the
- engine; the runner's timeout ends the process instead.
- - The virtual clock can run faster, but it is not a fully deterministic scheduler.
- - Lua runs in a scratch directory per run, but the engine is not sandboxed by the OS. Only run code you trust; see
- [docs/security.md](docs/security.md).
- ## Credits
- The engine is a fork of [CraftOS-PC 2](https://github.com/MCJack123/craftos2) by JackMacWindows (MIT).
- [CC:Tweaked](https://tweaked.cc) is by SquidDev and contributors; this project does not include it, and builds its ROM
- on your machine from the official jar. Not affiliated with Mojang or Microsoft.
- ## License
- MIT, see [LICENSE](LICENSE). The engine keeps CraftOS-PC's MIT license ([engine/LICENSE](engine/LICENSE)). See
- [NOTICE.md](NOTICE.md) for third-party parts.
packages/runner/src/versions.integration.test.ts · Bundled script · 173 lines · 2 findings marked
- import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- rmSync,
- writeFileSync,
- } from "node:fs";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import { afterAll, describe, expect, it } from "vitest";
- import {
- type TestRunResult,
- DEFAULT_MC,
- type WorldConfig,
- checkConfig,
- loadConfig,
- resolveVersion,
- romDirFor,
- runTests,
- } from "./index.js";
- const base = loadConfig();
- const scratch = mkdtempSync(join(tmpdir(), "versions-ws-"));
- const config = { ...base, workspaceDir: scratch };
- const ready = checkConfig(config).length === 0;
- // the 1.121.0 ROM: node scripts/build-rom.mjs --download 1.20.1
- const newer = existsSync(
- join(romDirFor(config, resolveVersion("1.20.1", {})), "bios.lua"),
- );
- afterAll(() => rmSync(scratch, { recursive: true, force: true }));
- async function runLua(
- lua: string,
- world: WorldConfig | undefined,
- name: string,
- ): Promise<TestRunResult> {
- const file = join(scratch, name);
- mkdirSync(join(file, ".."), { recursive: true });
- writeFileSync(file, lua);
- return runTests(config, { paths: [name], world, timeoutMs: 20000 }, 1);
- }
- function failures(result: TestRunResult): string[] {
- expect(result.files.map((f) => f.status)).toHaveLength(1);
- return result.files.flatMap((f) =>
- f.status === "passed"
- ? []
- : [
- `${f.status}`,
- ...f.tests
- .filter((t) => !t.passed)
- .map((t) => `${t.name}: ${t.error}`),
- ],
- );
- }
- const worldVersionLua = `
- local function worldVersion()
- local h = fs.open("/results/world.json", "r")
- local world = textutils.unserializeJSON(h.readAll())
- h.close()
- return world.version
- end
- `;
- describe.skipIf(!ready)("the version reaches the engine", () => {
- it("1.18.2: CC:Tweaked 1.101.3's _HOST and file handles", async () => {
- const result = await runLua(
- `${worldVersionLua}
- ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft 1.101.3 ", 1, true), _HOST) end)
- ccunit.test("world.json", function() ccunit.eq(worldVersion().mc, "1.18.2") ccunit.eq(worldVersion().cc, "1.101.3") end)
- ccunit.test("no w+ before 1.109", function() ccunit.raises(function() fs.open("x.txt", "w+") end, "Unsupported mode") end)
- ccunit.test("directory read message", function()
- local h, err = fs.open("rom", "r") ccunit.eq(h, nil) ccunit.eq(err, "/rom: No such file")
- end)
- ccunit.test("1.101.3's private addresses", function()
- ccunit.eq(http.checkURL("http://10.1.2.3"), false)
- ccunit.eq(http.checkURL("http://[::1]"), false)
- ccunit.eq(http.checkURL("http://100.100.100.200"), false)
- ccunit.eq(http.checkURL("http://100.64.1.1"), true)
- ccunit.eq(http.checkURL("http://192.30.255.113"), true)
- Warning: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 82 on GitHub
- end)
- ccunit.test("numbers written as Java doubles", function()
- local w = fs.open("n.txt", "w") w.write(65) w.close()
- local r = fs.open("n.txt", "r") ccunit.eq(r.readAll(), "65.0") r.close()
- end)
- ccunit.finish()
- `,
- { version: "1.18.2" },
- "default.test.lua",
- );
- expect(failures(result)).toEqual([]);
- });
- it(`no version runs the default one (${DEFAULT_MC}, or CRAFTOS_VERSION)`, async () => {
- const want = resolveVersion(undefined);
- const result = await runLua(
- `${worldVersionLua}
- ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft ${want.cc} ", 1, true), _HOST) end)
- ccunit.test("world.json", function() ccunit.eq(worldVersion().mc, "${want.mc}") end)
- ccunit.finish()
- `,
- undefined,
- "no-version.test.lua",
- );
- expect(failures(result)).toEqual([]);
- });
- it.skipIf(!newer)(
- "1.20.1: CC:Tweaked 1.121.0's _HOST, r+/w+ handles and messages",
- async () => {
- const result = await runLua(
- `${worldVersionLua}
- ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft 1.121.0 ", 1, true), _HOST) end)
- ccunit.test("world.json", function()
- local v = worldVersion() ccunit.eq(v.mc, "1.20.1") ccunit.eq(v.cc, "1.121.0") ccunit.eq(v.loader, "forge")
- end)
- ccunit.test("w+ reads back what it wrote", function()
- local h = fs.open("x.txt", "w+") h.write("hello") h.seek("set", 0) ccunit.eq(h.readAll(), "hello") h.close()
- end)
- ccunit.test("directory read message", function()
- local h, err = fs.open("rom", "r") ccunit.eq(h, nil) ccunit.eq(err, "/rom: Not a file")
- end)
- ccunit.test("numbers written as Lua prints them", function()
- local w = fs.open("n.txt", "w") w.write(65) w.close()
- local r = fs.open("n.txt", "r") ccunit.eq(r.readAll(), "65") ccunit.eq(r.readAll(), "") r.close()
- end)
- ccunit.test("raw bytes in text mode", function()
- local w = fs.open("b.txt", "wb") w.write("\\225lo") w.close()
- local r = fs.open("b.txt", "r") ccunit.eq(r.readAll(), "\\225lo") r.close()
- end)
- ccunit.test("queueEvent copies tables", function()
- local t = {} os.queueEvent("copy_me", t) local _, u = os.pullEvent("copy_me") ccunit.truthy(u ~= t)
- end)
- ccunit.test("fs.getDir of ..", function() ccunit.eq(fs.getDir(".."), "../..") end)
- ccunit.test("1.121.0's private addresses", function()
- ccunit.eq(http.checkURL("http://100.64.1.1"), false)
- ccunit.eq(http.checkURL("http://[fc00::1]"), false)
- ccunit.eq(http.checkURL("http://192.30.255.113"), true)
- Warning: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 140 on GitHub
- end)
- ccunit.finish()
- `,
- { version: "1.20.1" },
- "newer.test.lua",
- );
- expect(failures(result)).toEqual([]);
- },
- );
- it.skipIf(!newer)("1.21.1 shares the 1.121.0 ROM, on NeoForge", async () => {
- const result = await runLua(
- `${worldVersionLua}
- ccunit.test("host", function() ccunit.truthy(_HOST:find("ComputerCraft 1.121.0 ", 1, true), _HOST) end)
- ccunit.test("world.json", function() ccunit.eq(worldVersion().mc, "1.21.1") ccunit.eq(worldVersion().loader, "neoforge") end)
- ccunit.finish()
- `,
- { version: "1.21.1" },
- "neoforge.test.lua",
- );
- expect(failures(result)).toEqual([]);
- });
- it("refuses an addon the version lacks before booting", async () => {
- await expect(
- runLua(
- `ccunit.finish()`,
- { version: "1.21.1", addons: ["bigger-reactors"] },
- "refused.test.lua",
- ),
- ).rejects.toThrow(/Bigger Reactors .*no release for Minecraft 1\.21\.1/);
- });
- });
packages/runner/src/versions.ts · Bundled script · 309 lines · 5 findings marked
- /**
- * Which Minecraft / CC:Tweaked version a computer behaves as. One engine binary and one runner serve every version:
- * the version picks the ROM, the engine's `--cc-version` (every behaviour the engine pinned to 1.101.3 is gated on
- * it), the addons' mod versions and the turtle block data.
- *
- * Which version a world runs, first match wins:
- * 1. `world.version`: "1.18.2", "1.20.1", "1.21.1", or { mc, cc?, loader? }.
- * 2. The CRAFTOS_VERSION environment variable: the same forms, the object as JSON.
- * 3. The newest version in VERSIONS (NEWEST_MC): 1.21.1 (CC:Tweaked 1.121.0) today, the next one once it is added.
- *
- * Accuracy on 1.20.1 and 1.21.1 rests on CC:Tweaked's source and its own test suite (docs/conformance), not on a
- * real game: there is no instance of those versions to compare against.
- */
- import { join } from "node:path";
- import type { RunnerConfig } from "./config.js";
- /** A CC:Tweaked jar on Modrinth: build-rom.mjs --download builds the ROM from it after checking the sha512. */
- export interface CcJar {
- readonly loader: string;
- readonly file: string;
- readonly url: string;
- readonly sha512: string;
- }
- export interface McVersionInfo {
- /** Minecraft version, the id used in `world.version` and CRAFTOS_VERSION. */
- readonly mc: string;
- /** The CC:Tweaked version computers behave as (the newest for that Minecraft). */
- readonly cc: string;
- /** Mod loaders it exists for; the first is the default. The ROM is the same for each (byte-identical). */
- readonly loaders: readonly string[];
- /** The jars build-rom.mjs can download; the first one is used. */
- readonly jars: readonly CcJar[];
- /** ROM directory under rom/ (scripts/build-rom.mjs writes it). */
- readonly romDir: string;
- /**
- * Turtle block data in the ROM (rom-overlay/rom/ccsim/turtle/data/, made by tools/turtledata/extract.py --mc): 1.18.2
- * and 1.20.1 have their own sets; 1.21.1 has none yet, and ccsim falls back to 1.18.2's (turtle/data.lua).
- */
- readonly blockDataDir: string;
- }
- /** The CC:Tweaked version the engine behaves as without --cc-version. */
- export const ENGINE_DEFAULT_CC = "1.101.3";
- const CC_121_DIR = "cc-1.121.0";
- export const VERSIONS: readonly McVersionInfo[] = [
- {
- mc: "1.18.2",
- cc: "1.101.3",
- loaders: ["forge"],
- jars: [
- {
- loader: "forge",
- file: "cc-tweaked-1.18.2-1.101.3.jar",
- url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/fmRxKFx2/cc-tweaked-1.18.2-1.101.3.jar",
- Warning: Links to a Windows program from code, which is how droppers fetch their payload
- Line 57 on GitHub
- sha512:
- "dff864e824f111b5901414b633e13ca2ff3685195f1d2992bdf6a3470fb6e1119ba7e995d99575296415fccb00c6cb99939e6a47fdc7983b322f3f65e805a27f",
- },
- ],
- romDir: "cc-1.101.3",
- blockDataDir: "/rom/ccsim/turtle/data/",
- },
- {
- mc: "1.20.1",
- cc: "1.121.0",
- loaders: ["forge", "fabric"],
- jars: [
- {
- loader: "forge",
- file: "cc-tweaked-1.20.1-forge-1.121.0.jar",
- url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/Qm9iIIEY/cc-tweaked-1.20.1-forge-1.121.0.jar",
- Warning: Links to a Windows program from code, which is how droppers fetch their payload
- Line 73 on GitHub
- sha512:
- "6ebe4c1e8e6165cb97f071a5a54acd942c234ae62d36330369fdae4bf720a93e99b84e833385f0f103e8fb03425ed20c9f9122411f0008e8ac9efa24b719522d",
- },
- {
- loader: "fabric",
- file: "cc-tweaked-1.20.1-fabric-1.121.0.jar",
- url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/LFj8qZ7a/cc-tweaked-1.20.1-fabric-1.121.0.jar",
- Warning: Links to a Windows program from code, which is how droppers fetch their payload
- Line 80 on GitHub
- sha512:
- "20d29a7f0c239433fe35d4607ccba8b5a65e30f0bfdeba6f0b5a4307c83dc257b3eff4bc25644009f517b062c54d7d3e54ef58ae63db8ac6e43498d73757557a",
- },
- ],
- romDir: CC_121_DIR,
- blockDataDir: "/rom/ccsim/turtle/data/1.20.1/",
- },
- {
- mc: "1.21.1",
- cc: "1.121.0",
- loaders: ["neoforge", "fabric"],
- jars: [
- {
- // Modrinth names the NeoForge build "forge"
- loader: "neoforge",
- file: "cc-tweaked-1.21.1-forge-1.121.0.jar",
- url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/KNdTEfUA/cc-tweaked-1.21.1-forge-1.121.0.jar",
- Warning: Links to a Windows program from code, which is how droppers fetch their payload
- Line 97 on GitHub
- sha512:
- "042f9c2de7f73f83dbe848c79ddab6383ecef5e6c4a9b51f50fdcae70caa4759d4a2cf5d14e8a3ba4d94ce4a79340c4d2fe0c8b33c33a268e21b164021d25ae3",
- },
- {
- loader: "fabric",
- file: "cc-tweaked-1.21.1-fabric-1.121.0.jar",
- url: "https://cdn.modrinth.com/data/gu7yAYhd/versions/ThbQoK4I/cc-tweaked-1.21.1-fabric-1.121.0.jar",
- Warning: Links to a Windows program from code, which is how droppers fetch their payload
- Line 104 on GitHub
- sha512:
- "7f00c7ed5011d817c8c1405400c1738ddf13971c4a0b7f7a9aa5d98f5e41cc7ac0915c99e36a751e134f009158a1c0078ca354da8395058671d7c40eafc738fd",
- },
- ],
- romDir: CC_121_DIR,
- blockDataDir: "/rom/ccsim/turtle/data/1.21.1/",
- },
- ];
- /** What a world (or CRAFTOS_VERSION) may say. */
- export type VersionSpec =
- | string
- | {
- /** Minecraft version. */
- readonly mc: string;
- /** CC:Tweaked version; must be the one this Minecraft version has. */
- readonly cc?: string;
- /** Mod loader (forge, fabric, neoforge). Default: the version's first. */
- readonly loader?: string;
- };
- /** A version resolved against VERSIONS: what the runner, the engine and ccsim (core.version) get. */
- export interface ResolvedVersion {
- readonly mc: string;
- readonly cc: string;
- readonly loader: string;
- /** rom/<romDir> */
- readonly romDir: string;
- readonly blockDataDir: string;
- }
- const numbers = (mc: string): number[] => mc.split(".").map(Number);
- /** The newest Minecraft version there is a ROM for, by its numbers (1.21.1 over 1.20.1 over 1.18.2). */
- export const NEWEST_MC: string = VERSIONS.map((v) => v.mc).reduce((a, b) => {
- const [x, y] = [numbers(a), numbers(b)];
- for (let i = 0; i < Math.max(x.length, y.length); i++)
- if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0) ? a : b;
- return a;
- });
- /** The version a world runs with none given: the newest there is (NEWEST_MC), so a new version moves it. */
- export const DEFAULT_MC: string = NEWEST_MC;
- /** The versions for a help line: "1.18.2 (CC:Tweaked 1.101.3), 1.20.1 or 1.21.1 (CC:Tweaked 1.121.0); default ...". */
- export function versionChoices(): string {
- const groups: string[] = [];
- for (const cc of new Set(VERSIONS.map((v) => v.cc))) {
- const mcs = VERSIONS.filter((v) => v.cc === cc).map((v) => v.mc);
- groups.push(`${mcs.join(" or ")} (CC:Tweaked ${cc})`);
- }
- return `${groups.join(", ")}; default ${DEFAULT_MC}`;
- }
- const BY_MC = new Map(VERSIONS.map((v) => [v.mc, v]));
- const KNOWN_CC = [...new Set(VERSIONS.map((v) => v.cc))];
- export function versionInfo(mc: string): McVersionInfo | undefined {
- return BY_MC.get(mc);
- }
- function known(): string {
- return VERSIONS.map((v) => `${v.mc} (CC:Tweaked ${v.cc})`).join(", ");
- }
- function parseSpec(spec: VersionSpec, from: string): ResolvedVersion {
- let mc: string;
- let cc: string | undefined;
- let loader: string | undefined;
- if (typeof spec === "string") {
- const text = spec.trim();
- if (text.startsWith("{")) {
- let parsed: unknown;
- try {
- parsed = JSON.parse(text);
- } catch (error) {
- throw new Error(`${from}: not valid JSON: ${(error as Error).message}`);
- }
- return parseSpec(parsed as VersionSpec, from);
- }
- mc = text;
- } else if (spec && typeof spec === "object" && typeof spec.mc === "string") {
- mc = spec.mc.trim();
- if (spec.cc !== undefined) {
- if (typeof spec.cc !== "string")
- throw new Error(`${from}.cc must be a string like "1.121.0"`);
- cc = spec.cc.trim();
- }
- if (spec.loader !== undefined) {
- if (typeof spec.loader !== "string")
- throw new Error(`${from}.loader must be a string like "forge"`);
- loader = spec.loader.trim().toLowerCase();
- }
- } else {
- throw new Error(
- `${from} must be a Minecraft version ("1.20.1") or { mc, cc?, loader? }`,
- );
- }
- const info = BY_MC.get(mc);
- if (!info)
- throw new Error(
- `${from}: unknown Minecraft version ${JSON.stringify(mc)}; known: ${known()}`,
- );
- if (cc !== undefined && !KNOWN_CC.includes(cc))
- throw new Error(
- `${from}: unknown CC:Tweaked version ${JSON.stringify(cc)}; known: ${KNOWN_CC.join(", ")}`,
- );
- if (loader !== undefined && !info.loaders.includes(loader))
- throw new Error(
- `${from}: CC:Tweaked for Minecraft ${mc} has no ${JSON.stringify(loader)} build; loaders: ${info.loaders.join(", ")}`,
- );
- const ccVersion = cc ?? info.cc;
- return {
- mc,
- cc: ccVersion,
- loader: loader ?? info.loaders[0]!,
- // the ROM follows the CC version (one ROM serves every Minecraft on that CC)
- romDir:
- VERSIONS.find((v) => v.cc === ccVersion && v.mc === mc)?.romDir ??
- `cc-${ccVersion}`,
- blockDataDir: info.blockDataDir,
- };
- }
- /** The version a world runs as: world.version, else CRAFTOS_VERSION, else DEFAULT_MC. Unknown versions are refused. */
- export function resolveVersion(
- worldVersion: VersionSpec | undefined,
- env: NodeJS.ProcessEnv = process.env,
- ): ResolvedVersion {
- if (worldVersion !== undefined)
- return parseSpec(worldVersion, "world.version");
- const envSpec = env["CRAFTOS_VERSION"];
- if (envSpec !== undefined && envSpec.trim() !== "")
- return parseSpec(envSpec, "CRAFTOS_VERSION");
- return parseSpec(DEFAULT_MC, "default");
- }
- /** Whether this is the version the emulator behaves as with no version given (no engine flag, the default ROM). */
- export function isDefaultVersion(version: ResolvedVersion): boolean {
- return version.mc === DEFAULT_MC && version.cc === ENGINE_DEFAULT_CC;
- }
- /**
- * The ROM for a version. The default version (DEFAULT_MC) uses config.romDir, as every run did before versions
- * existed; other versions use rom/<romDir>. CRAFTOS_ROM (config.romsDir then unset) names one ROM for every version.
- */
- export function romDirFor(
- config: RunnerConfig,
- version: ResolvedVersion,
- ): string {
- if (!config.romsDir || version.romDir === versionInfo(DEFAULT_MC)!.romDir)
- return config.romDir;
- return join(config.romsDir, version.romDir);
- }
- /** Engine arguments for a version: none for 1.101.3 (the engine's own default), else --cc-version. */
- export function engineVersionArgs(version: ResolvedVersion): string[] {
- return version.cc === ENGINE_DEFAULT_CC ? [] : ["--cc-version", version.cc];
- }
- /** What ccsim reads as core.version (world.json `version`). */
- export function versionForSim(version: ResolvedVersion): {
- mc: string;
- cc: string;
- loader: string;
- blockData: string;
- } {
- return {
- mc: version.mc,
- cc: version.cc,
- loader: version.loader,
- blockData: version.blockDataDir,
- };
- }
- /** For craftos_info and `craftos-mcp info`: the default version and every version there is. */
- export function versionReport(env: NodeJS.ProcessEnv = process.env): {
- source: string;
- default: { mc: string; cc: string; loader: string } | undefined;
- versions: { mc: string; cc: string; loaders: readonly string[] }[];
- } {
- let current: ResolvedVersion | undefined;
- let source: string;
- try {
- current = resolveVersion(undefined, env);
- source =
- env["CRAFTOS_VERSION"] !== undefined && env["CRAFTOS_VERSION"] !== ""
- ? `CRAFTOS_VERSION=${env["CRAFTOS_VERSION"]}`
- : `default: Minecraft ${DEFAULT_MC} (set world.version or CRAFTOS_VERSION for another)`;
- } catch (error) {
- source = `CRAFTOS_VERSION is invalid: ${(error as Error).message}`;
- }
- return {
- source,
- default: current && {
- mc: current.mc,
- cc: current.cc,
- loader: current.loader,
- },
- versions: VERSIONS.map((v) => ({
- mc: v.mc,
- cc: v.cc,
- loaders: v.loaders,
- })),
- };
- }
scripts/compat/projects/games-media.mjs · Bundled script · 555 lines · 2 findings marked
- // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
- import { shellInstall, watchAnimation } from "../helpers.mjs";
- const RAW = "https://raw.githubusercontent.com";
- const SPEAKER = { peripherals: [{ name: "right", type: "speaker" }] };
- /**
- * The installer most PineStore games share: a progress bar, then "Finished installation! Press any key to close...".
- */
- async function pineInstall(t, line, timeoutMs = 180000) {
- if (!t.booted) await t.boot();
- await t.shell(line);
- await t.waitFor(/Finished installation!|Press any key/, timeoutMs);
- t.noCrash();
- await t.key("enter");
- await t.waitForPrompt(15000);
- }
- /** A picture, not a blank or nearly blank screen. */
- function expectPicture(t, what, least = 8) {
- const variety = t.variety();
- if (variety < least)
- t.fail(`${what} drew next to nothing (${variety} kinds of cell)`);
- }
- /** Do something and check the screen is not what it was. */
- async function expectReaction(t, what, act, settleMs = 600) {
- const before = t.frameHash();
- await act();
- await t.sleep(settleMs);
- t.noCrash();
- if (t.frameHash() === before) t.fail(`${what} changed nothing on screen`);
- }
- /** How many audio buffers a speaker has taken. */
- const audioCount = (t, name = "right") =>
- t.speaker(name).raw?.audio?.pushed ?? 0;
- export default [
- {
- id: "chess",
- name: "Chess",
- url: "https://github.com/aTimmYm/Chess",
- category: "program",
- section: "Games",
- // its sha2 library picks CC's `bit` API over bit32 unless _VERSION is "Lua 5.2", and `bit` lacks what it needs
- minCC: "1.109.0",
- async run(t) {
- await t.boot();
- await t.shell(
- `wget run "${RAW}/aTimmYm/Chess/refs/heads/main/installer.lua"`,
- );
- await t.waitFor("success", 120000);
- await t.waitForPrompt(10000);
- t.noCrash();
- if (!t.exists("main.lua")) t.fail(`no main.lua installed: ${t.list()}`);
- // main.lua starts the graphics-mode version when the terminal has CraftOS-PC's setGraphicsMode, and nothing
- // otherwise (its text-mode branch tests a variable that is never set): on CC:Tweaked it returns without a
- // word. So the check starts the text-mode game the way that branch would have.
- await t.shell("main");
- await t.waitForPrompt(10000);
- t.noCrash();
- t.put(
- "textmode.lua",
- `package.path = package.path .. ";/Data/?;/Data/?.lua;/Data/?/init.lua"\nos.run(_ENV, "TM.lua")\n`,
- );
- await t.shell("clear");
- await t.shell("textmode");
- await t.sleep(5000);
- await t.shot("menu");
- t.noCrash();
- if (/> ?$/.test(t.text().trimEnd()))
- t.fail(`TM.lua ended at once:\n${t.text()}`);
- expectPicture(t, "the main menu", 6);
- t.expect("Local Game");
- await expectReaction(
- t,
- "starting a local game",
- () => t.clickText("Local Game"),
- 2500,
- );
- await t.shot("board");
- // a first move: the pawn in front of the king, two squares up (wherever the board is, clicking two cells in
- // its middle column must not break anything)
- const { width, height } = {
- width: t.lines()[0].length,
- height: t.lines().length,
- };
- await t.click(Math.floor(width / 2), height - 4);
- await t.click(Math.floor(width / 2), height - 8);
- await t.sleep(1000);
- await t.shot("moved");
- t.noCrash();
- },
- },
- {
- id: "ccdoom",
- name: "CCDoom",
- url: "https://github.com/Xella37/CCDoom",
- category: "program",
- section: "Games",
- async run(t) {
- await pineInstall(t, "pastebin run xLC8mABU");
- await t.shell("Doom");
- await t.sleep(3000);
- await t.shot("menu");
- t.noCrash();
- expectPicture(t, "the title screen");
- // Play, then "Normal Mode"
- await t.key("enter");
- await t.waitFor("Normal Mode", 15000);
- await t.shot("modes");
- await t.key("enter");
- await t.waitFor(/^(?![\s\S]*Normal Mode)/, 30000);
- await t.sleep(4000);
- await t.shot("level");
- t.noCrash();
- expectPicture(t, "the level", 12);
- await expectReaction(t, "walking and turning", async () => {
- await t.hold("w", 700);
- await t.hold("right", 500);
- });
- await expectReaction(
- t,
- "shooting and walking on",
- async () => {
- await t.key("space");
- await t.hold("s", 600);
- },
- 800,
- );
- await t.shot("played");
- },
- },
- {
- id: "watermelon-game",
- name: "Watermelon Game 3D",
- url: "https://github.com/Xella37/Watermelon-Game-3D",
- category: "program",
- section: "Games",
- async run(t) {
- await t.boot();
- await t.shell("wget run https://pinestore.cc/d/psi/32");
- await t.sleep(4000);
- await t.shot("installer");
- for (let i = 0; i < 60 && !/> ?$/.test(t.text().trimEnd()); i++) {
- if (t.has(/[Pp]ress any key|key to/)) await t.key("enter");
- await t.sleep(2000);
- }
- await t.waitForPrompt(10000);
- t.noCrash();
- await t.shell("WatermelonGame");
- await t.waitFor("Press enter to continue", 15000);
- await t.shot("controls");
- await t.key("enter");
- await t.sleep(3000);
- await t.shot("game");
- t.noCrash();
- expectPicture(t, "the game");
- await expectReaction(t, "moving and dropping a fruit", async () => {
- await t.hold("left", 400);
- await t.key("space");
- await t.sleep(1500);
- await t.hold("right", 600);
- await t.key("space");
- });
- await t.shot("dropped");
- },
- },
- {
- id: "tetracraft",
- name: "Tetracraft",
- url: "https://pastebin.com/2jmN835i",
- Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
- Warning: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 173 on GitHub
- category: "program",
- section: "Games",
- async run(t) {
- await shellInstall(t, "pastebin get 2jmN835i tetracraft");
- t.hash("tetracraft");
- await t.shell("tetracraft");
- await t.sleep(2500);
- await t.shot("start");
- t.noCrash();
- expectPicture(t, "the game", 4);
- await expectReaction(t, "moving a piece", async () => {
- await t.key("left");
- await t.key("left");
- await t.key("up");
- await t.hold("down", 600);
- });
- await t.shot("played");
- await watchAnimation(t, 3000, 2);
- },
- },
- {
- id: "cc-minecraft",
- name: "CC:Minecraft",
- url: "https://github.com/Xella37/CC-Minecraft",
- category: "program",
- section: "Games",
- async run(t) {
- await pineInstall(t, "pastebin run hgm142Pj");
- await t.shell("Minecraft");
- await t.waitFor("Singleplayer", 20000);
- await t.shot("menu");
- await t.clickText("Singleplayer");
- await t.sleep(1500);
- await t.shot("worlds");
- await t.clickText("New World");
- await t.waitFor("World Creation");
- const name = t.find("Name:");
- await t.click(name.x + 12, name.y);
- await t.type("compat");
- await t.shot("creation");
- await t.clickText("Create World");
- // generating the world takes a while
- await t.waitFor(/^(?![\s\S]*World Creation)/, 60000);
- await t.sleep(6000);
- await t.shot("start");
- t.noCrash();
- expectPicture(t, "the world", 10);
- await expectReaction(t, "walking and looking around", async () => {
- await t.hold("w", 800);
- await t.hold("left", 600);
- });
- await t.shot("walked");
- // break the block in front, pick another and place it
- await t.click(26, 10, 1);
- await t.key("two");
- await t.click(26, 10, 2);
- await t.sleep(500);
- await t.shot("built");
- t.noCrash();
- },
- },
- {
- id: "rubiks-cube",
- name: "CC Rubik's Cube",
- url: "https://github.com/MichielP1807/CC-Rubiks-Cube",
- category: "program",
- section: "Games",
- async run(t) {
- await pineInstall(t, "pastebin run A5wTQs2B");
- await t.shell("Cube");
- await t.sleep(3000);
- await t.shot("cube");
- t.noCrash();
- expectPicture(t, "the cube");
- await expectReaction(t, "turning the cube", () => t.hold("left", 600));
- await expectReaction(t, "turning a face", async () => {
- await t.key("e");
- await t.key("space");
- });
- await t.shot("turned");
- },
- },
- {
- id: "the-button",
- name: "The Button",
- url: "https://github.com/MichielP1807/CC-Bored-Button",
- category: "program",
- section: "Games",
- async run(t) {
- await pineInstall(
- t,
- `wget run ${RAW}/MichielP1807/CC-Bored-Button/main/installer.lua`,
- );
- await t.shell("Button");
- await t.sleep(3000);
- await t.shot("button");
- t.noCrash();
- expectPicture(t, "the button");
- await expectReaction(t, "pressing the button", async () => {
- await t.click(26, 10);
- await t.click(26, 10);
- });
- await t.shot("pressed");
- },
- },
- {
- id: "samurai-salad",
- name: "Samurai Salad",
- url: "https://github.com/MichielP1807/CC-Samurai-Salad",
- category: "program",
- section: "Games",
- async run(t) {
- await pineInstall(t, "pastebin run Sxfk57tP");
- await t.shell("SamuraiSalad");
- await t.sleep(3000);
- await t.shot("start");
- t.noCrash();
- expectPicture(t, "the game");
- // slicing is dragging the mouse across the fruit
- await t.drag(10, 14, 40, 5);
- await t.drag(40, 14, 10, 5);
- await watchAnimation(t, 2500, 3);
- await t.shot("sliced");
- },
- },
- {
- id: "spamtons-jump",
- name: "Spamton's Jump",
- url: "https://github.com/simadude/obsi2-pinejam25-game",
- category: "program",
- section: "Games",
- // its installer fetches the sprites as text: before CC:Tweaked 1.109 a text handle decodes UTF-8 and they
- // arrive damaged ("Unknown character (?) ... Make sure your image is valid")
- minCC: "1.109.0",
- world: SPEAKER,
- async run(t) {
- await t.boot();
- await t.shell(
- `wget run ${RAW}/simadude/obsi2-pinejam25-game/refs/heads/main/installer.lua`,
- );
- await t.sleep(5000);
- await t.shot("installer");
- for (let i = 0; i < 60 && !/> ?$/.test(t.text().trimEnd()); i++) {
- if (t.has("Continue")) await t.clickText("Continue");
- await t.sleep(2000);
- }
- await t.waitForPrompt(10000);
- t.noCrash();
- await t.shot("installed");
- await t.shell("main");
- await t.sleep(3000);
- await t.shot("title");
- t.noCrash();
- expectPicture(t, "the title screen", 4);
- await t.key("enter");
- await t.key("space");
- await t.sleep(1500);
- await expectReaction(t, "running and jumping", async () => {
- await t.hold("right", 600);
- await t.key("space");
- await t.key("up");
- });
- await t.shot("played");
- },
- },
- {
- id: "mine-clicker",
- name: "Mine Clicker",
- url: "https://github.com/Sparkwave2/mine-clicker",
- category: "program",
- section: "Games",
- world: SPEAKER,
- async run(t) {
- await shellInstall(t, "pastebin get hgw016VY mineclicker.lua");
- t.hash("mineclicker.lua");
- await t.shell("mineclicker");
- await t.sleep(2500);
- await t.shot("start");
- t.noCrash();
- expectPicture(t, "the game", 4);
- await expectReaction(t, "clicking the block", async () => {
- for (let i = 0; i < 6; i++) await t.click(12, 9, 1, 80);
- });
- await t.shot("clicked");
- },
- },
- {
- id: "crazy-cargo-crusade",
- name: "Crazy Cargo Crusade",
- url: "https://github.com/SammyForReal/CrazyCargoCrusade",
- category: "program",
- section: "Games",
- async run(t) {
- await shellInstall(
- t,
- "wget https://github.com/SammyForReal/CrazyCargoCrusade/releases/download/0.1.0/ccc.lua",
- );
- t.hash("ccc.lua");
- await t.shell("ccc");
- await t.sleep(4000);
- await t.shot("start");
- t.noCrash();
- expectPicture(t, "the game", 4);
- await t.key("enter");
- await t.sleep(1500);
- await expectReaction(t, "driving", async () => {
- await t.hold("w", 800);
- await t.hold("a", 400);
- });
- await t.shot("driving");
- },
- },
- {
- id: "pumpkin-carver",
- name: "Pumpkin Carver",
- url: "https://github.com/Xella37/Pumpkin-Carver",
- category: "program",
- section: "Games",
- async run(t) {
- await t.boot();
- await t.shell("wget run https://pinestore.cc/d/psi/118");
- await t.sleep(4000);
- for (let i = 0; i < 60 && !/> ?$/.test(t.text().trimEnd()); i++) {
- if (t.has(/[Pp]ress any key|key to/)) await t.key("enter");
- await t.sleep(2000);
- }
- await t.waitForPrompt(10000);
- t.noCrash();
- await t.shell("pumpkincarver");
- // its own instructions end with "Press any key to continue..."
- await t.waitFor("Press any key to continue", 15000);
- await t.shot("instructions");
- await t.key("enter");
- await t.sleep(3000);
- await t.shot("pumpkin");
- t.noCrash();
- expectPicture(t, "the pumpkin");
- await expectReaction(t, "carving", () => t.drag(22, 8, 30, 12));
- await t.shot("carved");
- },
- },
- {
- id: "meowsynth",
- name: "MeowSynthCC",
- url: "https://github.com/MichielP1807/MeowSynthCC",
- category: "program",
- section: "Audio and video players",
- world: SPEAKER,
- async run(t) {
- await pineInstall(
- t,
- `wget run ${RAW}/MichielP1807/MeowSynthCC/main/installer.lua`,
- );
- await t.shell("meow");
- await t.sleep(3000);
- await t.shot("synth");
- t.noCrash();
- expectPicture(t, "the synth");
- const before = audioCount(t);
- // the keyboard row plays notes
- for (let round = 0; round < 5 && audioCount(t) <= before; round++) {
- for (const key of ["a", "s", "d", "f"]) await t.hold(key, 250);
- await t.sleep(1000);
- }
- await t.shot("played");
- t.noCrash();
- if (audioCount(t) <= before)
- t.fail(
- `playing four notes sent the speaker no audio: ${JSON.stringify(t.speaker("right").raw).slice(0, 300)}`,
- );
- },
- },
- {
- id: "herobrine",
- name: "Herobrine",
- url: "https://github.com/MCJack123/Herobrine",
- category: "program",
- section: "Demoscene and proof of concept",
- // the release is one file with its data as raw bytes in a string: before CC:Tweaked 1.109 a program is read as
- // UTF-8 text and those bytes do not survive
- minCC: "1.109.0",
- world: SPEAKER,
- timeoutS: 420,
- async run(t) {
- await shellInstall(
- t,
- "wget https://github.com/MCJack123/Herobrine/releases/download/1.0.1/herobrine.lua herobrine.lua",
- 120000,
- );
- t.hash("herobrine.lua");
- await t.shell("herobrine");
- await t.sleep(8000);
- await t.shot("start");
- t.noCrash();
- // the demo is timed to its soundtrack: sample it for a minute and a half
- let frames = 0;
- for (let i = 0; i < 9; i++) {
- frames += await watchAnimation(t, 10000, 1);
- await t.shot(`at-${(i + 1) * 10 + 8}s`);
- if (/> ?$/.test(t.text().trimEnd())) break;
- }
- t.note(`${frames} different frames seen, ${audioCount(t)} audio buffers`);
- if (frames < 40) t.fail(`only ${frames} different frames in the demo`);
- if (audioCount(t) < 10)
- t.fail(`the soundtrack sent the speaker ${audioCount(t)} buffers`);
- },
- },
- {
- id: "4th-dimension",
- name: "4th Dimension",
- url: "https://github.com/MCJack123/4thDimension",
- category: "program",
- section: "Demoscene and proof of concept",
- // Its music is mixed in Lua while it plays. At the 8 times slowdown the other checks use, one mixing pass runs
- // past CC's 7 seconds without yielding; at 4 times it plays, late. It runs here at the engine's own speed, and
- // notes.mjs says so: which of these a real computer is on this workload has not been measured.
- world: { ...SPEAKER, cobaltSpeed: false },
- timeoutS: 420,
- async run(t) {
- const repo = t.clone("https://github.com/MCJack123/4thDimension");
- t.install(repo, ".");
- await t.boot();
- await t.shell("player");
- await t.sleep(8000);
- await t.shot("start");
- t.noCrash();
- let frames = 0;
- for (let i = 0; i < 9; i++) {
- frames += await watchAnimation(t, 10000, 1);
- await t.shot(`at-${(i + 1) * 10 + 8}s`);
- if (/> ?$/.test(t.text().trimEnd())) break;
- }
- t.note(`${frames} different frames seen, ${audioCount(t)} audio buffers`);
- if (frames < 40) t.fail(`only ${frames} different frames in the demo`);
- if (audioCount(t) < 10)
- t.fail(`the soundtrack sent the speaker ${audioCount(t)} buffers`);
- },
- },
- {
- id: "jane-demo",
- name: "Jane Demo",
- url: "https://github.com/piguman3/PineJam2026Demo",
- category: "program",
- section: "Demoscene and proof of concept",
- world: SPEAKER,
- async run(t) {
- const repo = t.clone("https://github.com/piguman3/PineJam2026Demo");
- for (const file of [
- "demo.lua",
- "Pine3D.lua",
- "betterblittle.lua",
- "anim.bin",
- "janecut.dfpwm",
- ])
- t.install(`${repo}/${file}`, file);
- await t.boot();
- const started = Date.now();
- await t.shell("demo");
- await t.sleep(3000);
- await t.shot("start");
- t.noCrash();
- let frames = 0;
- for (let i = 0; i < 4; i++) {
- frames += await watchAnimation(t, 8000, 1);
- await t.shot(`at-${(i + 1) * 8 + 3}s`);
- if (/> ?$/.test(t.text().trimEnd())) break;
- }
- // "a really tiny 38 second demo": it ends on its own
- await t.waitForPrompt(30000);
- const seconds = (Date.now() - started) / 1000;
- t.note(
- `${frames} different frames seen, ${audioCount(t)} audio buffers, ended after ${seconds.toFixed(0)} s`,
- );
- t.noCrash();
- if (frames < 30) t.fail(`only ${frames} different frames in the demo`);
- if (audioCount(t) < 10)
- t.fail(`the soundtrack sent the speaker ${audioCount(t)} buffers`);
- if (seconds < 30 || seconds > 60)
- t.fail(`a 38 second demo took ${seconds.toFixed(0)} s`);
- },
- },
- ];
scripts/compat/projects/libraries-other.mjs · Bundled script · 494 lines · 2 findings marked
- // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
- import { shellInstall } from "../helpers.mjs";
- const RAW = "https://raw.githubusercontent.com";
- const GIST = "https://gist.githubusercontent.com";
- const chest = (n, items = {}) => ({
- name: `minecraft:chest_${n}`,
- type: "minecraft:chest",
- size: 27,
- items,
- });
- /** Chests behind wired modems on one cable, and the computer's own wired modem on it, as a storage room has. */
- const storageRoom = (...chests) => ({
- world: {
- peripherals: [
- { name: "back", type: "modem", kind: "wired", network: "storage" },
- ],
- },
- wired: [{ id: "storage", peripherals: chests }],
- });
- export default [
- {
- id: "ecnet2",
- name: "ECNet2",
- url: "https://github.com/migeyel/ecnet",
- category: "library",
- section: "Networking",
- computers: [
- {
- name: "server",
- world: {
- peripherals: [{ name: "top", type: "modem" }],
- position: { x: 0, y: 64, z: 0 },
- },
- },
- {
- name: "client",
- world: {
- peripherals: [{ name: "top", type: "modem" }],
- position: { x: 5, y: 64, z: 0 },
- },
- },
- ],
- async run(t) {
- const client = t.computer("client");
- const ecnet = t.clone("https://github.com/migeyel/ecnet", "ecnet");
- const crypto = t.clone(
- "https://github.com/migeyel/ccryptolib",
- "ccryptolib",
- );
- for (const c of [t, client]) {
- c.install(`${ecnet}/ecnet2`, "ecnet2");
- c.install(`${crypto}/ccryptolib`, "ccryptolib");
- }
- // its own ping example: the server as it is, the client with the server's real address in place of the
- // author's
- t.install(`${ecnet}/examples/ping/server.lua`, "server.lua");
- t.put(
- "address.lua",
- `local ecnet2 = require "ecnet2"
- require "ccryptolib.random".initWithTiming()
- local h = fs.open("address.txt", "w") h.write(ecnet2.Identity("/.ecnet2").address) h.close()
- `,
- );
- await t.boot();
- await t.shell("address");
- await t.waitForFile("address.txt", 30000);
- await t.waitForPrompt();
- t.noCrash();
- const address = t.read("address.txt");
- if (!/^[A-Za-z0-9_-]{43}=$/.test(address))
- t.fail(`the identity's address is ${address}`);
- const { readFileSync } = await import("node:fs");
- const source = readFileSync(
- `${ecnet}/examples/ping/client.lua`,
- "utf8",
- ).replace(
- /local server = "[^"]*"/,
- `local server = ${JSON.stringify(address)}`,
- );
- client.put("client.lua", source);
- await t.shell("server");
- await t.sleep(1500);
- t.noCrash();
- await client.shell("client");
- await client.waitFor("ping v1.0", 20000);
- await client.shell("hello over ecnet");
- await t.waitFor(/got\s+hello over ecnet\s+on channel/, 15000);
- await client.waitFor(/hello over ecnet\s*\n\s*hello over ecnet/, 15000);
- await t.shot("ping");
- await client.shot("ping");
- // "from 5 blocks away": the modem's distance, through the encrypted tunnel
- t.expect(/from\s+5\s+blocks\s+away/);
- t.noCrash();
- client.noCrash();
- },
- },
- {
- id: "taskmaster",
- name: "Taskmaster",
- url: "https://gist.github.com/MCJack123/1678fb2c240052f1480b07e9053d4537",
- category: "library",
- section: "Threads / multitasking",
- async run(t) {
- await shellInstall(
- t,
- `wget ${GIST}/MCJack123/1678fb2c240052f1480b07e9053d4537/raw taskmaster.lua`,
- );
- t.hash("taskmaster.lua");
- const out = await t.lua(`
- local taskmaster = require("taskmaster")
- local order = {}
- -- three tasks in parallel, as its first example
- taskmaster(
- function() sleep(0.3) order[#order + 1] = "slow" end,
- function() sleep(0.1) order[#order + 1] = "fast" end,
- function() order[#order + 1] = "now" end
- ):waitForAll()
- result(table.concat(order, ","))
- -- event listeners and a timer in one loop, stopped from inside
- local loop = taskmaster()
- local seen = {}
- loop:eventListener("ping", function(ev, n) seen[#seen + 1] = "ping" .. n end)
- loop:addTimer(0.1, function() os.queueEvent("ping", #seen + 1) if #seen >= 3 then loop:stop() end end)
- loop:run()
- result(table.concat(seen, ","))
- -- waitForAny returns when the first finishes
- local started = os.epoch("utc")
- taskmaster(function() sleep(0.2) end, function() sleep(5) end):waitForAny()
- result(os.epoch("utc") - started < 1500)
- `);
- if (out[0] !== "now,fast,slow") t.fail(`task order was ${out[0]}`);
- if (!out[1].startsWith("ping1,ping2,ping3"))
- t.fail(`listeners saw ${out[1]}`);
- if (out[2] !== "true") t.fail("waitForAny waited for the slow task");
- },
- },
- {
- id: "redrun",
- name: "RedRun",
- url: "https://gist.github.com/MCJack123/473475f07b980d57dd2bd818026c97e8",
- category: "library",
- section: "Threads / multitasking",
- async run(t) {
- await shellInstall(
- t,
- `wget ${GIST}/MCJack123/473475f07b980d57dd2bd818026c97e8/raw redrun.lua`,
- );
- t.hash("redrun.lua");
- // RedRun hooks the coroutine rednet.run lives in (through getfenv), so its tasks outlive the program that
- // started them: this one keeps answering events from the shell prompt
- const out = await t.lua(`
- local redrun = require("redrun")
- local id = redrun.start(function()
- while true do
- local _, text = os.pullEvent("compat_note")
- local h = fs.open("heard.txt", "a") h.writeLine(text) h.close()
- end
- end, "listener")
- result(type(id), redrun.getid("listener") == id)
- os.queueEvent("compat_note", "first")
- sleep(0.2)
- result(type(redrun.getstate(id)))
- `);
- if (out[0] !== "number\ttrue") t.fail(`start gave ${out[0]}`);
- if (out[1] !== "table") t.fail(`the task's state is a ${out[1]}`);
- await t.waitForPrompt();
- t.event("compat_note", "second");
- await t.sleep(500);
- const heard = t.read("heard.txt").trim().split(/\r?\n/).join(",");
- if (heard !== "first,second")
- t.fail(
- `the background task heard "${heard}", not first and then second (after its program ended)`,
- );
- const killed = await t.lua(`
- local redrun = require("redrun")
- local id = redrun.getid("listener")
- redrun.kill(id)
- os.queueEvent("compat_note", "third")
- sleep(0.2)
- result(redrun.getstate(id))
- `);
- if (killed[0] !== "nil") t.fail(`after kill its state is ${killed[0]}`);
- if (t.read("heard.txt").includes("third"))
- t.fail("the killed task still ran");
- },
- },
- {
- id: "fatboychummy-thread",
- name: "Thread (Fatboychummy libraries)",
- url: "https://github.com/Fatboychummy-CC/Libraries/blob/main/thread.lua",
- category: "library",
- section: "Threads / multitasking",
- async run(t) {
- const repo = t.clone("https://github.com/Fatboychummy-CC/Libraries");
- t.install(repo, "lib");
- await t.boot();
- const out = await t.lua(`
- package.path = package.path .. ";/lib/?.lua"
- local thread = require("thread")
- local order = {}
- thread.new(function() sleep(0.2) order[#order + 1] = "b" end)
- thread.new(function() order[#order + 1] = "a" end):after(function() order[#order + 1] = "after-a" end)
- thread.new(function() sleep(0.05) error("boom") end):on_error(function() order[#order + 1] = "caught" end)
- thread.new(function() sleep(0.5) thread.stop() end)
- thread.run()
- result(table.concat(order, ","))
- `);
- for (const want of ["a", "after-a", "caught", "b"])
- if (!out[0].split(",").includes(want))
- t.fail(`the threads ran as ${out[0]}; ${want} is missing`);
- },
- },
- {
- id: "aes",
- name: "AES library",
- url: "https://gist.github.com/afonya2/489c3306a7d85f8f9512df321d904dbb",
- category: "library",
- section: "Encryption",
- async run(t) {
- await shellInstall(
- t,
- `wget ${GIST}/afonya2/489c3306a7d85f8f9512df321d904dbb/raw aes.lua`,
- );
- t.hash("aes.lua");
- // FIPS-197 appendix C.1: AES-128 of 00112233445566778899aabbccddeeff under 000102030405060708090a0b0c0d0e0f
- const out = await t.lua(
- `
- local aes = require("aes")
- local function bytes(hex) local t = {} for b in hex:gmatch("%x%x") do t[#t + 1] = tonumber(b, 16) end return t end
- local function hex(t) local s = {} for i = 1, #t do s[i] = ("%02x"):format(t[i]) end return table.concat(s) end
- local key = bytes("000102030405060708090a0b0c0d0e0f")
- local plain = bytes("00112233445566778899aabbccddeeff")
- local cipher = aes.Encrypt(plain, key)
- result(hex(cipher))
- result(hex(aes.Decrypt(cipher, key)))
- local iv = bytes("0f0e0d0c0b0a09080706050403020100")
- local text = aes.StringToTable("the quick brown fox jumps over the lazy dog")
- local back = aes.DecryptCBC(aes.EncryptCBC(text, key, iv), key, iv)
- result(aes.TableToString(back))
- `,
- 60000,
- );
- if (!out[0].startsWith("69c4e0d86a7b0430d8cdb78070b4c55a"))
- t.fail(`AES-128 of the FIPS-197 vector gave ${out[0]}`);
- if (!out[1].startsWith("00112233445566778899aabbccddeeff"))
- t.fail(`decrypting gave ${out[1]}`);
- if (!out[2].startsWith("the quick brown fox jumps over the lazy dog"))
- t.fail(`CBC round trip gave ${out[2]}`);
- },
- },
- {
- id: "sha256",
- name: "SHA256 / HMAC / PBKDF2 (Anavrins)",
- url: "https://pastebin.com/6UV4qfNF",
- Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
- Warning: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 257 on GitHub
- category: "library",
- section: "Encryption",
- async run(t) {
- await shellInstall(t, "pastebin get 6UV4qfNF sha256.lua");
- t.hash("sha256.lua");
- const out = await t.lua(
- `
- local sha = require("sha256")
- result(sha.digest("abc"):toHex())
- result(sha.digest(""):toHex())
- result(sha.digest(("a"):rep(1000)):toHex())
- -- RFC 4231 test case 2
- result(sha.hmac("what do ya want for nothing?", "Jefe"):toHex())
- -- RFC 7914 section 11: PBKDF2-HMAC-SHA256, "passwd" / "salt", 1 iteration, 64 bytes
- result(sha.pbkdf2("passwd", "salt", 1, 64):toHex())
- `,
- 60000,
- );
- const want = [
- "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
- "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
- "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
- "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
- "55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc49ca9cccf179b645991664b39d77ef317c71b845b1e30bd509112041d3a19783",
- ];
- want.forEach((hash, i) => {
- if (out[i] !== hash) t.fail(`vector ${i + 1} gave ${out[i]}`);
- });
- },
- },
- {
- id: "hopper",
- name: "hopper.lua",
- url: "https://github.com/umnikos/hopper.lua",
- category: "library",
- section: "Peripheral management",
- ...storageRoom(
- chest(0, {
- 1: { name: "minecraft:cobblestone", count: 64 },
- 2: { name: "minecraft:cobblestone", count: 10 },
- 3: { name: "minecraft:iron_ingot", count: 32 },
- 5: { name: "minecraft:diamond", count: 3 },
- }),
- chest(1),
- chest(2),
- ),
- async run(t) {
- await shellInstall(t, `wget ${RAW}/umnikos/hopper.lua/main/hopper.lua`);
- t.hash("hopper.lua");
- // everything but the diamonds from chest 0 to chest 1, once
- await t.shell("hopper -once *chest_0 *chest_1 -not *:diamond");
- await t.waitForPrompt(30000);
- await t.shot("moved");
- t.noCrash();
- const count = `
- local function count(name)
- local total = {}
- for _, item in pairs(peripheral.call(name, "list")) do total[item.name] = (total[item.name] or 0) + item.count end
- local keys = {} for k in pairs(total) do keys[#keys + 1] = k end table.sort(keys)
- for i, k in ipairs(keys) do keys[i] = k:gsub("minecraft:", "") .. "=" .. total[k] end
- return table.concat(keys, " ")
- end`;
- let out = await t.lua(
- `${count}\nresult(count("minecraft:chest_0")) result(count("minecraft:chest_1"))`,
- );
- if (out[0] !== "diamond=3")
- t.fail(`chest 0 should keep only its diamonds, it holds: ${out[0]}`);
- if (out[1] !== "cobblestone=74 iron_ingot=32")
- t.fail(`chest 1 holds: ${out[1]}`);
- // as a library: require it and move a limited amount
- out = await t.lua(
- `${count}
- local hopper = require("hopper")
- hopper("*chest_1 *chest_2 *:iron_ingot -transfer-limit 20 -once")
- result(count("minecraft:chest_1")) result(count("minecraft:chest_2"))`,
- );
- if (out[1] !== "iron_ingot=20")
- t.fail(
- `a 20 item limit moved: ${out[1]} (chest 1 left with ${out[0]})`,
- );
- if (out[0] !== "cobblestone=74 iron_ingot=12")
- t.fail(`chest 1 holds: ${out[0]}`);
- },
- },
- {
- id: "oil",
- name: "Open Inventory Library",
- url: "https://github.com/afonya2/CC-OpenInvLib",
- category: "library",
- section: "Peripheral management",
- ...storageRoom(
- chest(0, {
- 1: { name: "minecraft:cobblestone", count: 64 },
- 2: { name: "minecraft:oak_log", count: 16 },
- }),
- chest(1),
- chest(2),
- ),
- async run(t) {
- await shellInstall(
- t,
- `wget ${RAW}/afonya2/CC-OpenInvLib/refs/heads/main/openinvlib.lua oil.lua`,
- );
- t.hash("oil.lua");
- const out = await t.lua(
- `
- shell.run("oil.lua")
- local oil = openInvLib
- result(type(oil))
- oil.scanPeripherals()
- local id = assert(oil.createStorage("main", { "minecraft:chest_0", "minecraft:chest_1" }))
- local storage = oil.getStorage(id)
- result(storage.getName(), storage.getSize())
- local part = storage.getPartition(assert(storage.createPartition("all", 1, storage.getSize())))
- oil.scanStorages()
- result(part.getItemCount("minecraft:cobblestone"), part.getItemCount("minecraft:oak_log"))
- `,
- 60000,
- );
- await t.shot("oil");
- if (out[0] !== "table") t.fail("oil.lua left no openInvLib global");
- if (out[1] !== "main\t54")
- t.fail(`the storage of two chests is ${out[1]}`);
- if (out[2] !== "64\t16") t.fail(`the partition counts ${out[2]}`);
- },
- },
- {
- id: "desyncc",
- name: "DesynCC",
- url: "https://github.com/afonya2/DesynCC",
- category: "library",
- section: "Other libraries",
- async run(t) {
- await t.boot();
- await t.shell(
- `wget run ${RAW}/afonya2/DesynCC/refs/heads/main/installer.lua test`,
- );
- await t.waitFor("[y/n]", 30000);
- await t.shell("y");
- await t.waitForPrompt(60000);
- t.noCrash();
- await t.shot("installed");
- const out = await t.lua(`
- local desyncc = require("desyncc.main")
- local sys = desyncc:new()
- local order = {}
- local function main()
- local slow = sys:async(function() sleep(0.3) return "slow" end)
- local fast = sys:async(function() sleep(0.1) return "fast" end)
- local a, b = slow(), fast()
- order[#order + 1] = b.status()
- order[#order + 1] = b.await()
- order[#order + 1] = a.await()
- end
- -- start() ends by raising "Main task died" once main returns: that is how the library stops
- local ok, err = pcall(function() sys:start(main) end)
- assert(not ok and tostring(err):find("Main task died"), err)
- result(table.concat(order, ","))
- `);
- if (!out[0].endsWith("suspended,fast,slow"))
- t.fail(`async/await gave ${out[0]}`);
- // one of its own tests, which says what it should print: nil, "Before the function is awaited", suspended,
- // then five seconds later "Hello, world!", "a b", "After the function is awaited" and "a b" again
- await t.shell("clear");
- const started = Date.now();
- await t.shell("desyncc/test/asyncAwait.lua");
- await t.waitFor("Main task died", 15000);
- const waited = Date.now() - started;
- await t.waitForPrompt(10000);
- await t.shot("test");
- t.expect(
- /nil\s+Before the function is awaited\s+suspended\s+Hello,\s+world!\s+a\s+b\s+After the function is awaited\s+(resolved\s+)?a\s+b/,
- );
- if (waited < 4000 || waited > 8000)
- t.fail(`the awaited sleep(5) took ${waited} ms`);
- },
- },
- {
- id: "telem",
- name: "Telem",
- url: "https://github.com/cyberbit/telem",
- category: "library",
- section: "Other libraries",
- // its installer fetches the compressed modules as text and writes them with a text handle, which only keeps
- // bytes as they are from CC:Tweaked 1.109 on
- minCC: "1.109.0",
- ...storageRoom(
- chest(0, {
- 1: { name: "minecraft:cobblestone", count: 64 },
- 2: { name: "minecraft:cobblestone", count: 36 },
- 3: { name: "minecraft:iron_ingot", count: 32 },
- }),
- ),
- async run(t) {
- await t.boot();
- await t.shell("wget run https://pinestore.cc/d/14");
- // the installer is a mouse-driven wizard: pick the compact release, then Finish
- await t.waitFor("Telem Installer", 30000);
- await t.shot("installer");
- await t.waitFor("Release (compact)", 30000);
- await t.key("enter");
- await t.waitFor("Press Enter", 30000);
- await t.key("enter");
- await t.waitFor("Complete", 90000);
- await t.shot("installed");
- await t.key("enter");
- await t.waitForPrompt(30000);
- t.noCrash();
- if (!t.exists("telem.lua"))
- t.fail(`the installer left no telem.lua: ${t.list()}`);
- t.hash("telem.lua");
- const out = await t.lua(`
- local telem = require("telem")
- local seen = {}
- local backplane = telem.backplane()
- :addInput("hello", telem.input.helloWorld(123))
- :addInput("chest", telem.input.itemStorage("minecraft:chest_0"))
- :addInput("mine", telem.input.custom(function() return { answer = 42 } end))
- :addOutput("collect", telem.output.custom(function(collection)
- for _, metric in ipairs(collection.metrics) do seen[metric.name] = metric.value end
- end))
- backplane:cycle()
- local names = {} for k, v in pairs(seen) do names[#names + 1] = k .. "=" .. v end table.sort(names)
- result(table.concat(names, " "))
- `);
- await t.shot("metrics");
- for (const want of [
- "hello_world=123",
- "answer=42",
- "storage:minecraft:cobblestone=100",
- "storage:minecraft:iron_ingot=32",
- ])
- if (!out[0].includes(want))
- t.fail(`the backplane collected "${out[0]}", without ${want}`);
- },
- },
- ];
scripts/compat/projects/libraries-ui.mjs · Bundled script · 499 lines · 2 findings marked
- // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
- import { shellInstall, watchAnimation } from "../helpers.mjs";
- const RAW = "https://raw.githubusercontent.com";
- /** A Lua line that writes `value` to `file`, for demos that report what happened. */
- const NOTE = `local function note(file, value) local h = fs.open(file, "w") h.write(tostring(value)) h.close() end`;
- export default [
- {
- id: "basalt",
- name: "Basalt",
- url: "https://github.com/Pyroxenium/Basalt",
- category: "library",
- section: "UI frameworks",
- monitors: [{ name: "top", blocksWide: 3, blocksHigh: 2 }],
- async run(t) {
- await shellInstall(
- t,
- `wget run ${RAW}/Pyroxenium/Basalt/master/docs/install.lua release latest.lua`,
- );
- if (!t.exists("basalt.lua")) t.fail("the installer left no basalt.lua");
- t.hash("basalt.lua");
- t.put(
- "demo.lua",
- `${NOTE}
- local basalt = require("basalt")
- local main = basalt.createFrame()
- local label = main:addLabel():setText("Hello Basalt"):setPosition(2, 2)
- local button = main:addButton():setText("Press"):setPosition(2, 4):setSize(12, 3)
- button:onClick(function() label:setText("Clicked!") note("clicked.txt", "yes") end)
- local input = main:addInput():setPosition(2, 8):setSize(20, 1)
- input:onChange(function(self) note("typed.txt", self:getValue()) end)
- local list = main:addList():setPosition(26, 2):setSize(14, 6)
- for i = 1, 10 do list:addItem("Item " .. i) end
- list:onChange(function(self) note("picked.txt", self:getItem(self:getItemIndex()).text) end)
- local mon = basalt.addMonitor():setMonitor("top")
- mon:addButton():setText("Touch"):setPosition(2, 2):setSize(10, 3):onClick(function(self)
- self:setText("Touched") note("touched.txt", "yes")
- end)
- basalt.autoUpdate()
- `,
- );
- await t.shell("demo");
- await t.waitFor("Hello Basalt");
- await t.waitFor("Touch", 5000, "top");
- await t.shot("start");
- await t.click(5, 5);
- await t.waitFor("Clicked!");
- await t.click(4, 8);
- await t.type("hello");
- await t.waitFor("hello");
- await t.click(28, 4);
- await t.touch("top", 4, 3);
- await t.waitFor("Touched", 5000, "top");
- await t.shot("used");
- t.noCrash();
- if (t.read("typed.txt") !== "hello")
- t.fail(`the input holds "${t.read("typed.txt")}", not hello`);
- if (t.read("picked.txt") !== "Item 3")
- t.fail(`the list picked "${t.read("picked.txt")}", not Item 3`);
- },
- },
- {
- id: "basalt2",
- name: "Basalt 2",
- url: "https://github.com/Pyroxenium/Basalt2",
- category: "library",
- section: "UI frameworks",
- async run(t) {
- await shellInstall(
- t,
- `wget run ${RAW}/Pyroxenium/Basalt2/main/install.lua -f`,
- );
- if (!t.exists("basalt.lua")) t.fail("the installer left no basalt.lua");
- t.hash("basalt.lua");
- t.put(
- "demo.lua",
- `${NOTE}
- local basalt = require("basalt")
- local main = basalt.getMainFrame()
- local label = main:addLabel({ x = 2, y = 2, text = "Hello Basalt2" })
- main:addButton({ x = 2, y = 4, width = 12, height = 3, text = "Press" }):onClick(function()
- label:setText("Clicked!") note("clicked.txt", "yes")
- end)
- local input = main:addInput({ x = 2, y = 8, width = 20 })
- input:onChange("text", function(self, value) note("typed.txt", value) end)
- basalt.run()
- `,
- );
- await t.shell("demo");
- await t.waitFor("Hello Basalt2");
- await t.shot("start");
- await t.click(5, 5);
- await t.waitFor("Clicked!");
- await t.click(4, 8);
- await t.type("hello");
- await t.waitFor("hello");
- await t.shot("used");
- t.noCrash();
- if (t.read("typed.txt") !== "hello")
- t.fail(`the input holds "${t.read("typed.txt")}", not hello`);
- // its own examples
- await t.terminate();
- await t.shell("clear");
- for (const example of ["graphs", "TabControl"]) {
- await t.shell(
- `wget ${RAW}/Pyroxenium/Basalt2/main/examples/${example}.lua ${example}.lua`,
- 1500,
- );
- await t.waitForPrompt();
- await t.shell(example);
- await t.settle(700, 8000);
- await t.shot(example);
- t.noCrash();
- if (t.variety() < 4) t.fail(`${example} drew next to nothing`);
- await t.click(10, 2);
- await t.click(20, 8);
- t.noCrash();
- await t.terminate();
- await t.shell("clear");
- }
- },
- },
- {
- id: "pixelui",
- name: "PixelUI",
- url: "https://github.com/Shlomo1412/PixelUI",
- category: "library",
- section: "UI frameworks",
- // written with goto, which CC:Tweaked has from 1.109 (Lua 5.2)
- minCC: "1.109.0",
- async run(t) {
- await shellInstall(t, `wget ${RAW}/Shlomo1412/PixelUI/main/pixelui.lua`);
- await shellInstall(t, `wget ${RAW}/Shlomo1412/PixelUI/main/demo.lua`);
- t.hash("pixelui.lua");
- await t.shell("demo");
- await t.settle(700, 10000);
- await t.shot("demo");
- t.noCrash();
- if (t.variety() < 6) t.fail("the demo drew next to nothing");
- const before = t.frameHash();
- await t.click(10, 5);
- await t.click(25, 8);
- await t.key("tab");
- await t.type("abc");
- await t.settle(400, 3000);
- await t.shot("used");
- t.noCrash();
- if (t.frameHash() === before)
- t.fail("clicking and typing changed nothing on screen");
- },
- },
- {
- id: "primeui",
- name: "PrimeUI",
- url: "https://github.com/MCJack123/PrimeUI",
- category: "library",
- section: "UI frameworks",
- async run(t) {
- const repo = t.clone("https://github.com/MCJack123/PrimeUI");
- t.install(repo, "primeui");
- await t.boot();
- await t.shell("cd primeui");
- await t.shell("test");
- // its test program walks through every component, one page at a time
- await t.waitFor("Sample Text");
- await t.waitFor("Next");
- await t.shot("scrollbox");
- await t.scroll(10, 10, 1);
- await t.key("enter");
- await t.waitFor("Item 1");
- await t.shot("checkboxes");
- await t.key("space");
- await t.key("down");
- await t.key("space");
- await t.key("enter");
- await t.settle(500, 5000);
- await t.shot("page3");
- t.noCrash();
- for (let page = 0; page < 8 && !/> ?$/.test(t.text().trimEnd()); page++) {
- await t.type("x");
- await t.key("enter");
- await t.settle(500, 4000);
- t.noCrash();
- }
- await t.shot("end");
- },
- },
- {
- id: "tamperer",
- name: "Tamperer 2.0",
- url: "https://github.com/Fatboychummy-CC/Tamperer",
- category: "library",
- section: "UI frameworks",
- async run(t) {
- await t.boot();
- await t.shell(
- `wget run ${RAW}/Fatboychummy-CC/Tamperer/refs/heads/better/installer.lua lib no_ccryptolib`,
- );
- await t.waitFor("(y/n)", 30000);
- await t.shell("y");
- await t.waitFor("What version", 30000);
- await t.shell("no_ccryptolib");
- await t.waitForPrompt(60000);
- t.noCrash();
- await t.shot("installed");
- if (!t.exists("lib/tamperer.lua") && !t.exists("lib/tamperer/init.lua"))
- t.fail(`the installer left no tamperer in lib: ${t.list("lib")}`);
- await t.shell("clear");
- t.put(
- "demo.lua",
- `${NOTE}
- package.path = package.path .. ";lib/?.lua;lib/?/init.lua"
- local tamperer = require("tamperer")
- local menu = tamperer.new({ title = "Main Menu", description = "A menu of ours" })
- menu:add_number("volume", "Volume", "Volume of the music", 50, 0, 100)
- menu:add_boolean("fullscreen", "Fullscreen", "Enable fullscreen mode", false)
- menu:set_on_change(function(m, selection)
- note("changed.txt", selection.i_label .. "=" .. tostring(selection.value))
- end)
- menu:run()
- `,
- );
- await t.shell("demo");
- await t.waitFor("Main Menu");
- await t.waitFor("Fullscreen");
- await t.shot("menu");
- await t.key("down");
- await t.key("enter");
- await t.settle(400, 3000);
- await t.shot("toggled");
- t.noCrash();
- if (!t.exists("changed.txt"))
- t.fail("toggling Fullscreen never reached the change callback");
- if (t.read("changed.txt") !== "fullscreen=true")
- t.fail(`the callback saw ${t.read("changed.txt")}`);
- },
- },
- {
- id: "obsi2",
- name: "Obsi 2",
- url: "https://github.com/simadude/obsi2",
- category: "library",
- section: "2D game development",
- async run(t) {
- const repo = t.clone("https://github.com/simadude/obsi2");
- t.install(repo, "obsi2");
- t.put(
- "main.lua",
- `local obsi = require("obsi2")
- local x, frames = 1, 0
- function obsi.update(dt)
- if obsi.keyboard.isDown("right") then x = x + 40 * dt end
- frames = frames + 1
- if frames % 5 == 0 then
- local h = fs.open("state.txt", "w") h.write(math.floor(x) .. " " .. frames) h.close()
- end
- end
- function obsi.draw()
- obsi.graphics.setBackgroundColor(colors.blue)
- obsi.graphics.setForegroundColor(colors.yellow)
- obsi.graphics.rectangle("fill", math.floor(x), 5, 6, 4)
- obsi.graphics.write("obsi " .. frames, 2, 1)
- end
- obsi.init()
- `,
- );
- await t.boot();
- await t.shell("main");
- await t.waitFor(/obsi \d+/);
- await watchAnimation(t, 1500, 5);
- await t.shot("start");
- const before = Number(t.read("state.txt").split(" ")[0]);
- await t.hold("right", 1000);
- await t.sleep(300);
- await t.shot("moved");
- const after = Number(t.read("state.txt").split(" ")[0]);
- if (!(after > before + 10))
- t.fail(`holding right moved the box from ${before} to ${after}`);
- t.noCrash();
- },
- },
- {
- id: "pine3d",
- name: "Pine3D",
- url: "https://github.com/Xella37/Pine3D",
- category: "library",
- section: "3D renderers",
- async run(t) {
- const repo = t.clone("https://github.com/Xella37/Pine3D");
- t.install(repo, ".");
- await t.boot();
- await t.shell("Mountains");
- await t.sleep(2500);
- t.noCrash();
- await t.shot("mountains");
- if (t.variety() < 10) t.fail("the mountains scene drew next to nothing");
- const before = t.frameHash();
- await t.hold("w", 800);
- await t.hold("left", 600);
- await t.shot("flown");
- t.noCrash();
- if (t.frameHash() === before)
- t.fail("flying with W and the arrow keys did not change the view");
- },
- },
- {
- id: "c3d",
- name: "C3D",
- url: "https://github.com/9551-Dev/libC3D-dev",
- category: "library",
- section: "3D renderers",
- async run(t) {
- await shellInstall(
- t,
- `wget run ${RAW}/9551-Dev/C3D/master/installer.lua`,
- 180000,
- );
- if (!t.exists("c3d.lua")) t.fail("the installer left no c3d.lua");
- // the spinning cube of its documentation (c3d.madefor.cc, "texturing"), without the texture
- t.put(
- "cube/main.lua",
- `local cube = c3d.geometry.cube_simple()
- local frames = 0
- function c3d.load()
- cube = cube:push():reposition(0, 0, 1)
- end
- function c3d.update()
- frames = frames + 1
- cube:set_rotation(0, 1, 0, os.epoch("utc") / 10)
- if frames % 5 == 0 then
- local h = fs.open("frames.txt", "w") h.write(tostring(frames)) h.close()
- end
- end
- `,
- );
- await t.shell("c3d cube");
- await t.sleep(2000);
- t.noCrash();
- await watchAnimation(t, 2000, 4);
- await t.shot("cube");
- if (!(Number(t.read("frames.txt")) > 10))
- t.fail("the update callback barely ran");
- },
- },
- {
- id: "pixelbox",
- name: "Pixelbox Lite",
- url: "https://github.com/9551-Dev/pixelbox_lite",
- category: "library",
- section: "Teletext renderers",
- async run(t) {
- await shellInstall(
- t,
- `wget ${RAW}/9551-Dev/pixelbox_lite/master/pixelbox_lite.lua`,
- );
- t.hash("pixelbox_lite.lua");
- // the two programs in its examples folder
- for (const example of ["first", "chladni"]) {
- await shellInstall(
- t,
- `wget ${RAW}/9551-Dev/pixelbox_lite/master/examples/${example}.lua`,
- );
- }
- await t.shell("clear");
- await t.shell("first");
- await t.sleep(500);
- await t.shot("first");
- t.noCrash();
- // first.lua: a blue column at pixel x 5 and a yellow one at 7, rows 5 to 7, joined by one blue pixel. Pixels are
- // 2x3 to a cell, so that is cells (3,2) to (4,3), drawn with teletext characters in those two colours. The
- // render leaves the cursor on the last line, so the shell's next prompt scrolls it all up a line.
- const drawn = [t.cell(3, 1), t.cell(4, 1), t.cell(3, 2), t.cell(4, 2)];
- const colours = new Set(drawn.flatMap((c) => [c.fg, c.bg]));
- if (!drawn.every((c) => c.code >= 128 && c.code < 160))
- t.fail(`expected teletext characters, got ${JSON.stringify(drawn)}`);
- if (!colours.has(11) || !colours.has(4))
- t.fail(`expected blue and yellow, got ${JSON.stringify(drawn)}`);
- await t.shell("clear");
- await t.shell("chladni");
- await t.sleep(1500);
- await t.shot("chladni");
- t.noCrash();
- if (t.variety() < 8) t.fail("the Chladni figure drew next to nothing");
- },
- },
- {
- id: "shrekbox",
- name: "Shrekbox",
- url: "https://codeberg.org/ShreksHellraiser/shrekbox",
- category: "library",
- section: "Teletext renderers",
- async run(t) {
- const repo = t.clone("https://codeberg.org/ShreksHellraiser/shrekbox");
- // the demos folder reaches the two libraries through symbolic links, which a computer has none of: a player
- // puts the libraries and a demo side by side
- for (const file of ["shrekbox.lua", "shrekdraw.lua"])
- t.install(`${repo}/${file}`, file);
- for (const demo of ["snow", "lines", "pipes"])
- t.install(`${repo}/demos/${demo}.lua`, `${demo}.lua`);
- await t.boot();
- for (const demo of ["snow", "pipes"]) {
- await t.shell(demo);
- await t.sleep(1200);
- t.noCrash();
- const frames = await watchAnimation(t, 1500, 3);
- t.note(`${demo}: ${frames} frames in 1.5 s`);
- await t.shot(demo);
- await t.terminate();
- await t.shell("clear");
- }
- // lines.lua is a drawing program: drag the mouse and the three layers each get a line
- await t.shell("lines");
- await t.waitFor("Draw!");
- const empty = t.variety();
- await t.drag(5, 3, 40, 14);
- await t.shot("lines");
- t.noCrash();
- if (t.variety() <= empty + 2)
- t.fail("dragging the mouse across the screen drew no line");
- },
- },
- {
- id: "morefonts",
- name: "More Fonts",
- url: "https://github.com/MichielP1807/more-fonts",
- category: "library",
- section: "Fonts",
- async run(t) {
- await t.boot();
- await t.shell(
- `wget run ${RAW}/MichielP1807/more-fonts/main/installer.lua`,
- );
- await t.waitFor("Finished installation!", 60000);
- await t.shot("installer");
- await t.key("enter");
- await t.waitForPrompt();
- if (!t.exists("morefonts.lua"))
- t.fail("the installer left no morefonts.lua");
- t.hash("morefonts.lua");
- await t.shell("fontbrowser");
- // on its first run it downloads every font and sleeps a second (which drops keys); it draws nothing until the
- // first event after that, so the download list stays up until a key is pressed
- await t.waitFor("Downloading", 30000);
- await t.settle(2500, 120000);
- await t.key("left");
- await t.waitFor(/^(?![\s\S]*Downloading)/, 20000);
- await t.shot("browser");
- t.noCrash();
- const first = t.frameHash();
- await t.key("right");
- await t.settle(600, 8000);
- await t.shot("next-font");
- t.noCrash();
- if (t.frameHash() === first)
- t.fail("the right arrow did not show another font");
- if (t.variety() < 6) t.fail("the font browser drew next to nothing");
- },
- },
- {
- id: "bigfont",
- name: "Bigfont",
- url: "https://pastebin.com/3LfWxRWh",
- Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
- Warning: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 464 on GitHub
- category: "library",
- section: "Fonts",
- monitors: [{ name: "top", blocksWide: 4, blocksHigh: 2, textScale: 0.5 }],
- async run(t) {
- await shellInstall(t, "pastebin get 3LfWxRWh bigfont");
- t.hash("bigfont");
- t.put(
- "demo.lua",
- `local bigfont = require("bigfont")
- term.clear() term.setCursorPos(1, 1)
- bigfont.bigPrint("Big")
- bigfont.hugePrint("Huge")
- local mon = peripheral.wrap("top")
- mon.clear()
- bigfont.writeOn(mon, 1, "MONITOR", 2, 2)
- print("done")
- `,
- );
- await t.shell("demo");
- await t.waitFor("done");
- await t.shot("fonts");
- t.noCrash();
- // big text is drawn with the teletext characters 128 to 159, three rows a line
- const teletext = (monitor) =>
- t
- .lines(monitor)
- .join("")
- .split("")
- .filter((c) => c.charCodeAt(0) >= 128 && c.charCodeAt(0) < 160)
- .length;
- if (teletext() < 20) t.fail("the terminal shows no big letters");
- if (teletext("top") < 10) t.fail("the monitor shows no big letters");
- },
- },
- ];
scripts/compat/projects/programs.mjs · Bundled script · 461 lines · 2 findings marked
- // See ../projects.mjs. Each entry: { id, name, url, category, section, run(t) } with the driver from ../lib.mjs.
- import { shellInstall } from "../helpers.mjs";
- const RAW = "https://raw.githubusercontent.com";
- /** A short DFPWM clip that is public on GitHub (the Jane demo's soundtrack), for the players that take a URL. */
- const DFPWM_URL = `${RAW}/piguman3/PineJam2026Demo/main/janecut.dfpwm`;
- const chest = (n, items = {}) => ({
- name: `minecraft:chest_${n}`,
- type: "minecraft:chest",
- size: 27,
- items,
- });
- /** Wait until a speaker has been given audio, and say how much. */
- async function expectAudio(t, speaker, timeoutMs = 30000) {
- const end = Date.now() + timeoutMs;
- for (;;) {
- const played = t
- .speaker(speaker)
- .sounds.filter((s) => s.kind === "audio" && s.accepted !== false);
- if (played.length >= 3) return played;
- if (Date.now() > end)
- t.fail(
- `speaker ${speaker} got ${played.length} audio buffers in ${timeoutMs} ms: ${JSON.stringify(t.speaker(speaker).raw).slice(0, 300)}`,
- );
- await t.sleep(250);
- }
- }
- export default [
- {
- id: "cc-misc",
- name: "MISC (Modular Item Storage and Crafting)",
- url: "https://github.com/Storehaus/CC-MISC",
- category: "program",
- section: "Storage, turtles and peripherals",
- world: {
- peripherals: [
- { name: "back", type: "modem", kind: "wired", network: "storage" },
- ],
- },
- wired: [
- {
- id: "storage",
- peripherals: [
- chest(0, {
- 1: { name: "minecraft:cobblestone", count: 64 },
- 2: { name: "minecraft:cobblestone", count: 36 },
- 3: { name: "minecraft:iron_ingot", count: 32 },
- }),
- chest(1, { 5: { name: "minecraft:oak_log", count: 16 } }),
- chest(2),
- chest(3),
- ],
- },
- ],
- async run(t) {
- await t.boot();
- await t.shell(`wget run ${RAW}/Storehaus/CC-MISC/master/installer.lua`);
- await t.waitFor("MISC INSTALLER", 30000);
- await t.shot("installer");
- // server, then the base install (storage and its modules)
- await t.type("s");
- await t.waitFor("Base");
- await t.shot("server-options");
- await t.type("b");
- await t.waitForPrompt(120000);
- t.noCrash();
- await t.shot("installed");
- if (!t.exists("startup.lua") || !t.exists("modules"))
- t.fail(`the installer left no startup.lua and modules: ${t.list()}`);
- // it runs from startup.lua: restart the computer, as the installer says
- await t.shell("reboot");
- await t.rebooted();
- // first start: it asks for what its config lacks, the modem the chests are behind
- await t.waitFor("Please input a string:", 20000);
- await t.shot("config");
- await t.shell("back");
- await t.sleep(6000);
- await t.shot("running");
- t.noCrash();
- },
- },
- {
- id: "github-downloader",
- name: "Github Downloader",
- url: "https://pinestore.cc/projects/157/github-downloader-on-cc",
- category: "program",
- section: "Utility",
- async run(t) {
- await shellInstall(t, "pastebin get jP9CNvYS githubdw");
- t.hash("githubdw");
- await t.shell("githubdw");
- await t.waitFor("Paste repository URL");
- await t.shot("start");
- // the address is pasted, as the screen asks
- t.event("paste", "https://github.com/9551-Dev/pixelbox_lite");
- await t.waitFor("pixelbox_lite");
- await t.key("enter");
- await t.waitFor(/files downloaded/, 120000);
- await t.shot("done");
- t.expect("All files downloaded successfully!");
- t.noCrash();
- if (t.size("pixelbox_lite.lua") < 1000)
- t.fail(`pixelbox_lite.lua was not downloaded: ${t.list()}`);
- if (!t.exists("examples/first.lua"))
- t.fail("the examples folder was not downloaded");
- await t.clickText("Continue");
- await t.waitFor("Paste repository URL");
- },
- },
- {
- id: "consult",
- name: "CONSULT",
- url: "https://github.com/SammyForReal/CONSULT",
- category: "program",
- section: "Code editors",
- async run(t) {
- await shellInstall(
- t,
- "wget https://github.com/1Turtle/consult/releases/latest/download/cosu.lua",
- );
- t.hash("cosu.lua");
- await t.shell("cosu hello.lua");
- await t.waitFor("hello.lua");
- await t.waitFor("Ln 1, Col 1");
- await t.shot("empty");
- await t.type('print("hello from consult")');
- await t.key("enter");
- await t.type("local x = 1 + 2");
- await t.waitFor("Ln 2, Col 16");
- await t.shot("typed");
- await t.combo("leftCtrl", "s");
- await t.sleep(800);
- await t.shot("saved");
- t.noCrash();
- if (!t.exists("hello.lua")) t.fail("Ctrl+S did not write hello.lua");
- const saved = t.read("hello.lua").replace(/\r/g, "").trimEnd();
- if (saved !== 'print("hello from consult")\nlocal x = 1 + 2')
- t.fail(`hello.lua holds:\n${saved}`);
- // F5 runs the file
- await t.key("f5");
- await t.waitFor("hello from consult", 10000);
- await t.shot("ran");
- },
- },
- {
- id: "quark",
- name: "Quark",
- url: "https://github.com/aTimmYm/Quark",
- category: "program",
- section: "Code editors",
- minCC: "1.109.0", // goto
- async run(t) {
- await t.boot();
- await t.shell(
- `wget run "${RAW}/aTimmYm/Quark/refs/heads/main/installer_updater/installer.lua"`,
- );
- await t.waitFor("Enter the path", 30000);
- await t.shell("/");
- await t.waitForPrompt(180000);
- t.noCrash();
- await t.shot("installed");
- if (!t.exists("Quark/main.lua"))
- t.fail(`the installer left no Quark/main.lua: ${t.list()}`);
- t.put("notes.lua", 'print("one")\n');
- await t.shell("clear");
- await t.shell("Quark/main.lua");
- await t.waitFor("New File", 20000);
- await t.shot("welcome");
- t.noCrash();
- t.expect("Open Project");
- await t.clickText("New File");
- await t.settle(600, 8000);
- await t.shot("new-file");
- await t.type('print("typed in quark")');
- await t.settle(500, 5000);
- await t.shot("typed");
- t.noCrash();
- t.expect('print("typed in quark")');
- },
- },
- {
- id: "shrekword",
- name: "ShrekWord",
- url: "https://github.com/ShrekshelleraiserCC/shrekword",
- category: "program",
- section: "Code editors",
- async run(t) {
- await shellInstall(
- t,
- "wget https://github.com/ShrekshelleraiserCC/shrekword/releases/latest/download/sword.lua",
- );
- t.hash("sword.lua");
- await t.shell("sword");
- await t.waitFor("Check for updates on startup?");
- await t.shell("n");
- await t.waitFor("File");
- await t.waitFor(/Page 1\/1/);
- await t.shot("empty");
- await t.type("Dear reader, this was typed in ShrekWord.");
- await t.waitFor("ShrekWord.");
- await t.shot("typed");
- t.noCrash();
- // File > Save As
- await t.clickText("File");
- await t.waitFor("Save As");
- await t.shot("file-menu");
- await t.clickText("Save As");
- await t.settle(400, 3000);
- await t.shot("save-as");
- await t.type("letter.sdoc");
- await t.key("enter");
- await t.settle(400, 3000);
- await t.shot("saved");
- t.noCrash();
- if (!t.exists("letter.sdoc"))
- t.fail(`Save As wrote no letter.sdoc: ${t.list()}`);
- if (!t.read("letter.sdoc").includes("this was typed in ShrekWord"))
- t.fail("the saved document does not hold the text");
- // Ctrl+Q quits
- await t.combo("leftCtrl", "q");
- await t.waitForPrompt(10000);
- },
- },
- {
- id: "spritemog",
- name: "SpriteMog 1.2",
- url: "https://pastebin.com/iHpQhwvy",
- Note: Quoted as data in code: Links to a paste site (pastebin.com), a common place to stage installer commands or send stolen data
- Warning: Talks to a raw IP address or throwaway host, where malware is often staged
- Line 230 on GitHub
- category: "program",
- section: "Code editors",
- async run(t) {
- await shellInstall(t, "pastebin get iHpQhwvy spritemog");
- t.hash("spritemog");
- await t.shell("spritemog");
- await t.waitFor("-SELECT PALETTE-");
- await t.shot("palettes");
- await t.clickText("default");
- await t.waitFor("-SELECT SPRITE-");
- await t.clickText("newSprite");
- await t.settle(600, 8000);
- await t.shot("editor");
- t.noCrash();
- const before = t.frameHash();
- await t.drag(20, 8, 30, 12);
- await t.settle(400, 4000);
- await t.shot("drawn");
- t.noCrash();
- if (t.frameHash() === before)
- t.fail("drawing with the mouse changed nothing");
- },
- },
- {
- id: "pixelcode",
- name: "PixelCode",
- url: "https://github.com/Shlomo1412/PixelUI/blob/main/code_editor_app.lua",
- category: "program",
- section: "Code editors",
- minCC: "1.109.0",
- async run(t) {
- await shellInstall(t, `wget ${RAW}/Shlomo1412/PixelUI/main/pixelui.lua`);
- await shellInstall(
- t,
- `wget ${RAW}/Shlomo1412/PixelUI/main/code_editor_app.lua`,
- );
- await t.shell("code_editor_app");
- await t.waitFor("Press Alt to open toolbar");
- await t.shot("start");
- await t.click(20, 4);
- await t.type("local answer = 42");
- await t.settle(400, 3000);
- await t.shot("typed");
- t.noCrash();
- t.expect("local answer = 42");
- // F1 is its help; Alt opens the toolbar
- await t.key("leftAlt");
- await t.settle(400, 3000);
- await t.shot("toolbar");
- t.noCrash();
- },
- },
- {
- id: "craft-web",
- name: "Craft-Web",
- url: "https://github.com/Elemnto56/Craft-Web",
- category: "program",
- section: "Web, internet and communication",
- minCC: "1.109.0",
- async run(t) {
- await shellInstall(
- t,
- `wget ${RAW}/Elemnto56/Craft-Web/refs/heads/main/craft-installer.lua`,
- );
- await t.shell("craft-installer");
- await t.waitFor("(y/n)", 30000);
- await t.shell("y");
- await t.waitFor("Done! Goodbye.", 30000);
- await t.waitForPrompt();
- await t.shell("clear");
- await t.shell("craft-web");
- await t.waitFor("Welcome to Craft-Web!", 15000);
- await t.shot("home");
- t.noCrash();
- t.expect("Address Bar");
- await t.clickText("Exit");
- await t.waitForPrompt(10000);
- },
- },
- {
- id: "musicify",
- name: "Musicify",
- url: "https://github.com/knijn/musicify",
- category: "program",
- section: "Audio and video players",
- world: { peripherals: [{ name: "right", type: "speaker" }] },
- async run(t) {
- await t.boot();
- await t.shell(`wget run ${RAW}/knijn/musicify/main/install.lua`);
- await t.waitFor("anything else to continue", 30000);
- await t.shell("y");
- await t.waitForPrompt(60000);
- t.noCrash();
- await t.shot("installed");
- await t.shell("clear");
- await t.shell("musicify list");
- await t.waitFor(/1 \| /, 30000);
- await t.shot("list");
- // S and W scroll the list, Q leaves it (by raising "Closed list")
- const first = t.text();
- await t.hold("s", 400);
- if (t.text() === first) t.fail("S did not scroll the song list");
- await t.key("q");
- await t.waitFor("Closed list", 10000);
- // the q of that key press lands on the shell's line, as it does at a real keyboard
- await t.key("backspace");
- await t.shell("clear");
- await t.shell("musicify play 1");
- const played = await expectAudio(t, "right", 60000);
- await t.shot("playing");
- t.noCrash();
- t.note(
- `speaker got ${played.length} buffers, ${played[0].samples} samples each`,
- );
- },
- },
- {
- id: "quartz",
- name: "Quartz Audio Player",
- url: "https://github.com/Ale32bit/Quartz",
- category: "program",
- section: "Audio and video players",
- // "insert a disk containing a .dfpwm": two speakers for its stereo, and a drive with a floppy in it
- world: {
- peripherals: [
- { name: "left", type: "speaker" },
- { name: "right", type: "speaker" },
- { name: "top", type: "drive", disk: 0 },
- ],
- },
- async run(t) {
- await shellInstall(
- t,
- "wget run https://raw.github.com/Ale32bit/Quartz/main/download.lua",
- 60000,
- );
- // record a song onto the floppy: the first 100 kB of a clip, since a floppy holds 125 kB
- const recorded = await t.lua(`
- local h = assert(http.get(${JSON.stringify(DFPWM_URL)}, nil, true))
- local data = h.read(100000)
- h.close()
- local f = fs.open("disk/song.dfpwm", "wb")
- f.write(data)
- f.close()
- result(#data, fs.getSize("disk/song.dfpwm"))`);
- if (recorded[0] !== "100000\t100000")
- t.fail(`the song on the disk is ${recorded[0]} bytes`);
- await t.shell("clear");
- await t.shell("player");
- await t.waitFor("Ready", 15000);
- await t.shot("log");
- t.noCrash();
- t.expect(/Speaker configuration:\s+stereo/);
- // F1 leaves the log for the player; space plays
- await t.key("f1");
- await t.settle(500, 5000);
- await t.shot("player");
- await t.key("space");
- await t.sleep(4000);
- await t.shot("playing");
- t.noCrash();
- const left = t.speaker("left").raw?.audio?.pushed ?? 0;
- const right = t.speaker("right").raw?.audio?.pushed ?? 0;
- if (left < 1 || right < 1)
- t.fail(`the speakers got ${left} and ${right} audio buffers`);
- t.note(`left ${left}, right ${right} audio buffers in 4 s`);
- },
- },
- {
- id: "pocketbox",
- name: "Pocketbox",
- url: "https://github.com/windclan/pocketbox",
- category: "program",
- section: "Audio and video players",
- world: { peripherals: [{ name: "right", type: "speaker" }] },
- async run(t) {
- await shellInstall(
- t,
- `wget ${RAW}/windclan/pocketbox/main/pocketboxv4.lua pocketbox.lua`,
- );
- t.hash("pocketbox.lua");
- t.put(
- "autoplay.pb",
- `[url]\npath:${DFPWM_URL}\ntitle:Jane\nartist:piguman3\n`,
- );
- await t.shell("clear");
- await t.shell("pocketbox");
- const played = await expectAudio(t, "right", 60000);
- await t.shot("playing");
- t.noCrash();
- t.note(`speaker got ${played.length} buffers`);
- t.expect(/Jane/);
- },
- },
- {
- id: "ccmaps",
- name: "CCMaps",
- url: "https://pinestore.cc/projects/66/ccmaps",
- category: "program",
- section: "Demoscene and proof of concept",
- async run(t) {
- await shellInstall(
- t,
- "wget run https://gist.githubusercontent.com/cyberbit/993372d662918aeb4973701ac7122987/raw/ccmaps_install.lua",
- 60000,
- );
- await t.shell("ccmaps");
- // it fetches its map data, then draws coastlines with teletext characters: wait for those
- const drawn = () =>
- t
- .lines()
- .join("")
- .split("")
- .filter((c) => c.charCodeAt(0) > 128 && c.charCodeAt(0) < 160).length;
- for (let i = 0; i < 180 && drawn() < 20; i++) await t.sleep(500);
- await t.settle(1500, 30000);
- await t.shot("map");
- t.noCrash();
- if (drawn() < 20) t.fail("no map was drawn");
- const before = t.frameHash();
- // drag the map, then zoom
- await t.drag(30, 10, 15, 6);
- await t.scroll(25, 9, -1);
- await t.settle(1500, 30000);
- await t.shot("moved");
- t.noCrash();
- if (t.frameHash() === before)
- t.fail("dragging and zooming left the map as it was");
- },
- },
- ];
tools/turtledata/extract.py · Bundled script · 847 lines · 1 finding marked
- """Pull the block and item data a turtle needs out of the real game jars.
- Reads the Minecraft client jar, Forge, and every mod jar in the pack, and writes compact Lua tables, one file per
- namespace plus the combined _recipes.lua, _cooking.lua and _tag_members.lua, to rom-overlay/rom/ccsim/turtle/data/
- (1.18.2) or rom-overlay/rom/ccsim/turtle/data/<mc>/ (any other Minecraft version), or --out:
- names.lua id -> English display name (assets/<ns>/lang/en_us.json)
- blocks.lua every block id, with its state properties and their values (assets/<ns>/blockstates)
- items.lua every item id (item models, lang keys, loot table outputs, recipe outputs)
- loot.lua block loot tables (data/<ns>/loot_tables/blocks), kept as JSON-shaped Lua tables
- block_tags.lua block id -> its tags, fully resolved (nested #tags and "replace" honoured)
- item_tags.lua item id -> its tags
- recipes.lua crafting_shaped / crafting_shapeless recipes, for turtle.craft
- The pack's CraftTweaker and KubeJS scripts change some recipes at runtime; those changes are not in the jars
- (docs/conformance/emulator-vs-real-deviations.md).
- Two data sets:
- pack (default) vanilla + Forge + every jar in <instance>/mods. Mod data is All Rights Reserved: private repo only.
- --vanilla vanilla + Forge + the CC:Tweaked jar only, safe to publish. Use with --out so it does not
- overwrite the pack set.
- Minecraft versions (--mc, the MC table below):
- 1.18.2 (default) Forge 40.2.21 and CC:Tweaked 1.101.3, from the launcher's libraries and the pack instance. The block
- report comes from the client jar run on the launcher's libraries.
- 1.20.1 Forge 47.4.28 and CC:Tweaked 1.121.0 (forge). Vanilla only (there is no 1.20.1 pack instance), so
- --vanilla is implied unless --instance is given. The jars are read from --jars; --download fetches
- them there first: the client and server jars from Mojang's version manifest (sha1 checked), Forge's
- universal jar from its maven and CC:Tweaked from Modrinth (both hash checked). The block report
- comes from the server jar's bundler, so no launcher libraries are needed.
- Usage:
- python -I tools/turtledata/extract.py # pack set into rom-overlay/rom/ccsim/turtle/data
- python -I tools/turtledata/extract.py --vanilla --out .public-data/turtle-data
- python -I tools/turtledata/extract.py --mc 1.20.1 --jars <scratch dir> --download
- python -I tools/turtledata/extract.py --mc 1.20.1 --jars <scratch dir> --out .public-data/turtle-data/1.20.1
- Options (each also has an environment variable; the flag wins):
- --mc VERSION Minecraft version, 1.18.2 or 1.20.1 (TURTLEDATA_MC; default 1.18.2)
- --jars DIR a folder holding the version's jars under their own names (TURTLEDATA_JARS; looked in before
- --libraries and the instance); --download fills it
- --download fetch the jars --jars lacks (1.20.1 only)
- --out DIR output directory; every *.lua in it is deleted first (default rom-overlay/rom/ccsim/turtle/data,
- or its <mc>/ folder)
- --instance DIR the instance's minecraft dir, holding mods/ (TURTLEDATA_INSTANCE)
- --libraries DIR launcher libraries dir (TURTLEDATA_LIBRARIES; default %APPDATA%\\PrismLauncher\\libraries)
- --client-jar JAR minecraft-<mc>-client.jar (TURTLEDATA_CLIENT_JAR; default in --jars, then under --libraries)
- --server-jar JAR minecraft-<mc>-server.jar, 1.20.1 only (TURTLEDATA_SERVER_JAR; default in --jars)
- --forge-jar JAR forge-<mc>-<forge>-universal.jar, or the -client jar (TURTLEDATA_FORGE_JAR; default in --jars,
- then under --libraries, universal first)
- --cc-jar JAR the version's CC:Tweaked jar, --vanilla only (TURTLEDATA_CC_JAR; default in --jars, then
- <instance>/mods/)
- Java on PATH is needed for the vanilla block report (blocks.json). On 1.18.2 it runs on the client jar plus every jar
- under --libraries except Forge, LWJGL and the launcher's own; on 1.20.1 on the server jar alone.
- Data formats: 1.20.1 keeps 1.18.2's folders (loot_tables, recipes, tags/blocks, tags/items) and JSON shapes; its
- recipes add "category" and "show_notification", which are ignored, and its smithing recipes (smithing_transform,
- smithing_trim) are not crafting recipes, so they are skipped like 1.18.2's smithing. 1.21 renames the folders to the
- singular and gives recipe results components: the MC table's "folders" is where that goes.
- """
- import argparse
- import hashlib
- import json
- import os
- import re
- import sys
- import zipfile
- from collections import defaultdict
- HERE = os.path.dirname(os.path.abspath(__file__))
- REPO = os.path.dirname(os.path.dirname(HERE))
- DEFAULT_OUT = os.path.join(REPO, "rom-overlay", "rom", "ccsim", "turtle", "data")
- PRISM = os.path.join(os.environ.get("APPDATA", ""), "PrismLauncher")
- DEFAULT_LIBS = os.path.join(PRISM, "libraries")
- DEFAULT_INSTANCE = "" # no default: pass --instance (or --cc-jar with --vanilla)
- # Data folder names under data/<ns>/: 1.18.2 to 1.20.6 (1.21 makes them singular)
- PLURAL = {"loot": "loot_tables", "recipes": "recipes", "block_tags": "blocks", "item_tags": "items"}
- # Per Minecraft version: Forge, the CC:Tweaked jar (packages/runner/src/versions.ts has the same pins), the data
- # folder layout, how the block report is made, where the set goes, and whether the owner has a pack for it.
- MC = {
- "1.18.2": {
- "forge": "1.18.2-40.2.21",
- "cc_jar": "cc-tweaked-1.18.2-1.101.3.jar",
- "folders": PLURAL,
- "reports": "classpath",
- "out": DEFAULT_OUT,
- "pack": True,
- },
- "1.20.1": {
- "forge": "1.20.1-47.4.28",
- "cc_jar": "cc-tweaked-1.20.1-forge-1.121.0.jar",
- "folders": PLURAL,
- "reports": "server",
- "out": os.path.join(DEFAULT_OUT, "1.20.1"),
- "pack": False,
- # CC:Tweaked's own blocks are not in the vanilla server the map colours are read from: ModRegistry.Blocks
- # (MapColor.STONE 0x707070, GOLD 0xFAEE4D, WOOD 0x8F7748; the command computer and the cable's item have
- # none of their own: NONE, and Block.byItem(wired_modem) is the cable)
- "map_colours": {
- "computercraft:computer_normal": 0x707070, "computercraft:computer_advanced": 0xFAEE4D,
- "computercraft:computer_command": 0,
- "computercraft:turtle_normal": 0x707070, "computercraft:turtle_advanced": 0xFAEE4D,
- "computercraft:speaker": 0x707070, "computercraft:disk_drive": 0x707070, "computercraft:printer": 0x707070,
- "computercraft:monitor_normal": 0x707070, "computercraft:monitor_advanced": 0xFAEE4D,
- "computercraft:wireless_modem_normal": 0x707070, "computercraft:wireless_modem_advanced": 0xFAEE4D,
- "computercraft:wired_modem_full": 0x707070, "computercraft:cable": 0x707070,
- "computercraft:lectern": 0x8F7748, "computercraft:redstone_relay": 0x707070,
- },
- "downloads": {
- "forge": ("https://maven.minecraftforge.net/net/minecraftforge/forge/1.20.1-47.4.28/"
- "forge-1.20.1-47.4.28-universal.jar", "sha1", "1c2208dc1db2a61ddb6d5dcbe8eae4fd44629e9d"),
- "cc": ("https://cdn.modrinth.com/data/gu7yAYhd/versions/Qm9iIIEY/cc-tweaked-1.20.1-forge-1.121.0.jar",
- Warning: Links to a Windows program from code, which is how droppers fetch their payload
- Line 117 on GitHub
- "sha512", "6ebe4c1e8e6165cb97f071a5a54acd942c234ae62d36330369fdae4bf720a93e99b84e833385f0f103e8fb"
- "03425ed20c9f9122411f0008e8ac9efa24b719522d"),
- },
- },
- }
- MANIFEST = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"
- FORGE_VERSION = MC["1.18.2"]["forge"]
- CC_JAR = MC["1.18.2"]["cc_jar"]
- ID = re.compile(r"^[a-z0-9_.-]+:[a-z0-9_./-]+$")
- def fail(message):
- sys.exit("extract.py: " + message)
- def parse_args(argv):
- p = argparse.ArgumentParser(description="Regenerate the turtle block/item/tag/recipe/loot data from the game jars.")
- p.add_argument("--mc", default=os.environ.get("TURTLEDATA_MC") or "1.18.2", choices=sorted(MC),
- help="Minecraft version (env TURTLEDATA_MC; default 1.18.2)")
- p.add_argument("--vanilla", action="store_true",
- help="only vanilla, Forge and CC:Tweaked (the publishable set); no other mod jars")
- p.add_argument("--out", default=None, help="output directory (default rom-overlay/rom/ccsim/turtle/data[/<mc>])")
- p.add_argument("--jars", default=os.environ.get("TURTLEDATA_JARS"),
- help="folder holding the version's jars under their own names (env TURTLEDATA_JARS)")
- p.add_argument("--download", action="store_true", help="fetch the jars --jars lacks (1.20.1 only)")
- p.add_argument("--instance", default=os.environ.get("TURTLEDATA_INSTANCE"),
- help="instance minecraft dir holding mods/ (env TURTLEDATA_INSTANCE)")
- p.add_argument("--libraries", default=os.environ.get("TURTLEDATA_LIBRARIES") or DEFAULT_LIBS,
- help="launcher libraries dir (env TURTLEDATA_LIBRARIES)")
- p.add_argument("--client-jar", default=os.environ.get("TURTLEDATA_CLIENT_JAR"),
- help="minecraft client jar (env TURTLEDATA_CLIENT_JAR)")
- p.add_argument("--server-jar", default=os.environ.get("TURTLEDATA_SERVER_JAR"),
- help="minecraft server jar, 1.20.1 only (env TURTLEDATA_SERVER_JAR)")
- p.add_argument("--forge-jar", default=os.environ.get("TURTLEDATA_FORGE_JAR"),
- help="Forge universal or client jar (env TURTLEDATA_FORGE_JAR)")
- p.add_argument("--cc-jar", default=os.environ.get("TURTLEDATA_CC_JAR"),
- help="CC:Tweaked jar for --vanilla (env TURTLEDATA_CC_JAR)")
- args = p.parse_args(argv)
- info = MC[args.mc]
- args.info = info
- forge_version, cc_name = info["forge"], info["cc_jar"]
- if args.out is None:
- args.out = info["out"]
- if not info["pack"] and not args.instance and not args.vanilla:
- print("no " + args.mc + " pack instance: making the vanilla set (--vanilla)")
- args.vanilla = True
- if not args.instance:
- args.instance = DEFAULT_INSTANCE
- if args.download:
- if not args.jars:
- fail("--download needs --jars (the folder to download into)")
- download(args.mc, args.jars)
- def in_jars(name):
- path = os.path.join(args.jars, name) if args.jars else None
- return path if path and os.path.isfile(path) else None
- client_name = "minecraft-" + args.mc + "-client.jar"
- if not args.client_jar:
- args.client_jar = in_jars(client_name)
- if info["reports"] == "classpath" or not args.client_jar:
- if not os.path.isdir(args.libraries):
- fail("libraries dir not found: " + args.libraries + " (pass --libraries or set TURTLEDATA_LIBRARIES)")
- if not args.client_jar:
- args.client_jar = os.path.join(args.libraries, "com", "mojang", "minecraft", args.mc, client_name)
- if not os.path.isfile(args.client_jar):
- fail("Minecraft client jar not found: " + args.client_jar + " (pass --client-jar or set TURTLEDATA_CLIENT_JAR"
- + (", or --jars with --download)" if info.get("downloads") else ")"))
- if info["reports"] == "server":
- args.server_jar = args.server_jar or in_jars("minecraft-" + args.mc + "-server.jar")
- if not args.server_jar or not os.path.isfile(args.server_jar):
- fail("Minecraft " + args.mc + " server jar not found (pass --server-jar, or --jars with --download)")
- name = "minecraft-" + args.mc + "-server-mappings.txt"
- args.mappings = in_jars(name) or os.path.join(os.path.dirname(os.path.abspath(args.server_jar)), name)
- if not args.forge_jar:
- for name in ("forge-" + forge_version + "-universal.jar", "forge-" + forge_version + "-client.jar"):
- if in_jars(name):
- args.forge_jar = in_jars(name)
- break
- if not args.forge_jar:
- forge_dir = os.path.join(args.libraries, "net", "minecraftforge", "forge", forge_version)
- for name in ("forge-" + forge_version + "-universal.jar", "forge-" + forge_version + "-client.jar"):
- if os.path.isfile(os.path.join(forge_dir, name)):
- args.forge_jar = os.path.join(forge_dir, name)
- break
- else:
- fail("Forge " + forge_version + " universal/client jar not found in " + forge_dir +
- " (pass --forge-jar or set TURTLEDATA_FORGE_JAR)")
- elif not os.path.isfile(args.forge_jar):
- fail("Forge jar not found: " + args.forge_jar + " (pass --forge-jar or set TURTLEDATA_FORGE_JAR)")
- mods = os.path.join(args.instance, "mods")
- if args.vanilla:
- if not args.cc_jar:
- args.cc_jar = in_jars(cc_name)
- if not args.cc_jar:
- if not os.path.isdir(mods):
- fail("no mods dir at " + mods + " to find " + cc_name +
- " in (pass --cc-jar / TURTLEDATA_CC_JAR, or --instance / TURTLEDATA_INSTANCE)")
- args.cc_jar = os.path.join(mods, cc_name)
- if not os.path.isfile(args.cc_jar):
- fail("CC:Tweaked jar not found: " + args.cc_jar + " (pass --cc-jar or set TURTLEDATA_CC_JAR)")
- elif not os.path.isdir(mods):
- fail("no mods dir at " + mods + " (pass --instance or set TURTLEDATA_INSTANCE to the instance's minecraft dir)")
- return args
- def jars(args):
- found = [args.client_jar, args.forge_jar]
- if args.vanilla:
- found.append(args.cc_jar)
- return found
- mods = os.path.join(args.instance, "mods")
- for name in sorted(os.listdir(mods)):
- if name.endswith(".jar"):
- found.append(os.path.join(mods, name))
- return found
- def fetch(url):
- import urllib.request
- req = urllib.request.Request(url, headers={"User-Agent": "turtledata-extract"})
- with urllib.request.urlopen(req, timeout=300) as r:
- return r.read()
- def download(mc, folder):
- """Fetch the client and server jars (Mojang's version manifest, sha1 checked), Forge and CC:Tweaked (pinned
- hashes) into folder, skipping the ones already there with the right hash. The jars are only read as data."""
- info = MC[mc]
- if not info.get("downloads"):
- fail("--download is not set up for " + mc + ": pass the jars")
- os.makedirs(folder, exist_ok=True)
- def get(name, url, algo, digest):
- path = os.path.join(folder, name)
- if os.path.isfile(path):
- with open(path, "rb") as f:
- if hashlib.new(algo, f.read()).hexdigest() == digest:
- return
- print("downloading " + url)
- body = fetch(url)
- if hashlib.new(algo, body).hexdigest() != digest:
- fail(name + ": " + algo + " mismatch from " + url)
- with open(path, "wb") as f:
- f.write(body)
- manifest = json.loads(fetch(MANIFEST))
- entry = next((v for v in manifest.get("versions", []) if v.get("id") == mc), None)
- if not entry:
- fail("Minecraft " + mc + " is not in Mojang's version manifest")
- version = json.loads(fetch(entry["url"]))
- for side in ("client", "server"):
- d = version["downloads"][side]
- get("minecraft-" + mc + "-" + side + ".jar", d["url"], "sha1", d["sha1"])
- # Mojang's own name mappings, only to find the game's map colours and compostables by name (server_extras)
- d = version["downloads"]["server_mappings"]
- get("minecraft-" + mc + "-server-mappings.txt", d["url"], "sha1", d["sha1"])
- url, algo, digest = info["downloads"]["forge"]
- get("forge-" + info["forge"] + "-universal.jar", url, algo, digest)
- url, algo, digest = info["downloads"]["cc"]
- get(info["cc_jar"], url, algo, digest)
- def server_reports(server_jar, mappings=None):
- """The block report from the server jar's bundler (1.18 and later ship the data generator there with its
- libraries): java -DbundlerMainClass=net.minecraft.data.Main -jar server.jar --reports. With Mojang's mappings, also
- what only the game's code knows (server_extras): (blocks, registries, extras)."""
- import shutil
- import subprocess
- import tempfile
- java = shutil.which("java")
- if not java:
- print("java not found: block properties come from blockstate files only")
- return None, None, None
- out = tempfile.mkdtemp(prefix="mcreports-")
- try:
- subprocess.run([java, "-DbundlerMainClass=net.minecraft.data.Main", "-jar", os.path.abspath(server_jar),
- "--reports", "--output", os.path.join(out, "generated")],
- cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
- with open(os.path.join(out, "generated", "reports", "blocks.json"), encoding="utf-8") as f:
- blocks = json.load(f)
- with open(os.path.join(out, "generated", "reports", "registries.json"), encoding="utf-8") as f:
- registries = json.load(f)
- extras = None
- if mappings and os.path.isfile(mappings):
- try:
- extras = server_extras(java, out, mappings)
- except Exception as e:
- print("map colours and compostables not read (" + str(e) + ")")
- elif mappings is not None:
- print("no server mappings (" + str(mappings) + "): no map colours or compostables; --download fetches them")
- return blocks, registries, extras
- except Exception as e:
- print("data generator failed (" + str(e) + "): block properties come from blockstate files only")
- return None, None, None
- finally:
- shutil.rmtree(out, ignore_errors=True)
- # Read by server_extras through reflection: every block state's map colour (BlockStateBase.getMapColor on an empty
- # level at 0,0,0, as CC:Tweaked 1.121.0's DetailHelpers.fillMapColour asks for an item's block) and ComposterBlock's
- # COMPOSTABLES. The @names@ are filled from Mojang's mappings, since the jar's own names are obfuscated.
- EXTRAS_JAVA = r"""
- import java.lang.reflect.*;
- import java.util.*;
- import java.io.*;
- public class TurtleDataExtras {
- static Method m(Class<?> c, String name, Class<?>... p) throws Exception {
- for (Class<?> k = c; k != null; k = k.getSuperclass()) {
- try { Method x = k.getDeclaredMethod(name, p); x.setAccessible(true); return x; } catch (NoSuchMethodException e) {}
- }
- throw new NoSuchMethodException(c + "." + name);
- }
- static Object f(Class<?> c, String name, Object o) throws Exception {
- Field x = c.getDeclaredField(name); x.setAccessible(true); return x.get(o);
- }
- static String q(String s) { return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""; }
- public static void main(String[] a) throws Exception {
- m(Class.forName("@SC@"), "@SC_detect@").invoke(null);
- m(Class.forName("@BS@"), "@BS_boot@").invoke(null);
- Class<?> bir = Class.forName("@BIR@");
- Object blocks = f(bir, "@BIR_BLOCK@", null), items = f(bir, "@BIR_ITEM@", null);
- Method getKey = m(Class.forName("@REG@"), "@REG_getKey@", Object.class);
- Class<?> bp = Class.forName("@BP@"), mc = Class.forName("@MC@");
- Method stateDef = m(Class.forName("@BLK@"), "@BLK_states@");
- Method possible = m(Class.forName("@SD@"), "@SD_states@");
- Method mapColor = m(Class.forName("@BSB@"), "@BSB_map@", Class.forName("@BG@"), bp);
- Object level = f(Class.forName("@EBG@"), "@EBG_I@", null), zero = f(bp, "@BP_ZERO@", null);
- StringBuilder out = new StringBuilder("{\"mapColours\":{");
- String sep = "";
- for (Object block : (Iterable<?>) blocks) {
- out.append(sep).append(q(getKey.invoke(blocks, block).toString())).append(":{");
- sep = ",";
- String sep2 = "";
- for (Object st : (List<?>) possible.invoke(stateDef.invoke(block))) {
- int col = (int) f(mc, "@MC_col@", mapColor.invoke(st, level, zero));
- String s = st.toString();
- int i = s.indexOf('[');
- out.append(sep2).append(q(i < 0 ? "" : s.substring(i + 1, s.length() - 1))).append(':').append(col);
- sep2 = ",";
- }
- out.append('}');
- }
- out.append("},\"compostables\":{");
- Method asItem = m(Class.forName("@IL@"), "@IL_as@");
- sep = "";
- for (Map.Entry<?, ?> e : ((Map<?, ?>) f(Class.forName("@CB@"), "@CB_C@", null)).entrySet()) {
- out.append(sep).append(q(getKey.invoke(items, asItem.invoke(e.getKey())).toString())).append(':')
- .append(Float.floatToIntBits(((Number) e.getValue()).floatValue()));
- sep = ",";
- }
- out.append("}}");
- try (Writer w = new OutputStreamWriter(new FileOutputStream(a[0]), "UTF-8")) { w.write(out.toString()); }
- }
- }
- """
- def obf_names(mappings):
- """The obfuscated names EXTRAS_JAVA needs, from Mojang's ProGuard-format mappings."""
- classes, members, cur = {}, {}, None
- with open(mappings, encoding="utf-8") as f:
- for line in f:
- line = line.rstrip("\n")
- if not line or line.startswith("#"):
- continue
- if not line.startswith(" "):
- m = re.match(r"(\S+) -> (\S+):", line)
- cur = m.group(1)
- classes[cur], members[cur] = m.group(2), []
- else:
- members[cur].append(line.strip())
- def method(c, name, params=""):
- for line in members[c]:
- m = re.match(r"(?:\d+:\d+:)?\S+ (\S+)\(([^)]*)\)(?::\d+:\d+)? -> (\S+)", line)
- if m and m.group(1) == name and m.group(2) == params:
- return m.group(3)
- raise KeyError(c + "." + name)
- def field(c, name):
- for line in members[c]:
- m = re.match(r"\S+ (\S+) -> (\S+)$", line)
- if m and m.group(1) == name:
- return m.group(2)
- raise KeyError(c + "." + name)
- p = "net.minecraft."
- reg, blk, sd = p + "core.registries.BuiltInRegistries", p + "world.level.block.Block", \
- p + "world.level.block.state.StateDefinition"
- bsb = p + "world.level.block.state.BlockBehaviour$BlockStateBase"
- return {
- "SC": classes[p + "SharedConstants"], "SC_detect": method(p + "SharedConstants", "tryDetectVersion"),
- "BS": classes[p + "server.Bootstrap"], "BS_boot": method(p + "server.Bootstrap", "bootStrap"),
- "BIR": classes[reg], "BIR_BLOCK": field(reg, "BLOCK"), "BIR_ITEM": field(reg, "ITEM"),
- "REG": classes[p + "core.Registry"], "REG_getKey": method(p + "core.Registry", "getKey", "java.lang.Object"),
- "BLK": classes[blk], "BLK_states": method(blk, "getStateDefinition"),
- "SD": classes[sd], "SD_states": method(sd, "getPossibleStates"),
- "BSB": classes[bsb],
- "BSB_map": method(bsb, "getMapColor", "net.minecraft.world.level.BlockGetter,net.minecraft.core.BlockPos"),
- "BG": classes[p + "world.level.BlockGetter"],
- "BP": classes[p + "core.BlockPos"], "BP_ZERO": field(p + "core.BlockPos", "ZERO"),
- "MC": classes[p + "world.level.material.MapColor"], "MC_col": field(p + "world.level.material.MapColor", "col"),
- "EBG": classes[p + "world.level.EmptyBlockGetter"], "EBG_I": field(p + "world.level.EmptyBlockGetter", "INSTANCE"),
- "CB": classes[p + "world.level.block.ComposterBlock"],
- "CB_C": field(p + "world.level.block.ComposterBlock", "COMPOSTABLES"),
- "IL": classes[p + "world.level.ItemLike"], "IL_as": method(p + "world.level.ItemLike", "asItem"),
- }
- def server_extras(java, run_dir, mappings):
- """Run EXTRAS_JAVA on the server the bundler unpacked into run_dir: {"mapColours": {id: {stateKey: rgb}},
- "compostables": {id: chance}}. The chance is the game's float, kept exact."""
- import struct
- import subprocess
- src = EXTRAS_JAVA
- names = obf_names(mappings)
- for key in sorted(names, key=len, reverse=True):
- src = src.replace("@" + key + "@", names[key])
- java_file = os.path.join(run_dir, "TurtleDataExtras.java")
- with open(java_file, "w", encoding="utf-8") as f:
- f.write(src)
- cp = []
- for root, _, files in os.walk(os.path.join(run_dir, "versions")):
- cp += [os.path.join(root, f) for f in files if f.endswith(".jar")]
- for root, _, files in os.walk(os.path.join(run_dir, "libraries")):
- cp += [os.path.join(root, f) for f in sorted(files) if f.endswith(".jar")]
- result = os.path.join(run_dir, "extras.json")
- subprocess.run([java, "-cp", os.pathsep.join(cp), java_file, result], cwd=run_dir, check=True,
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
- with open(result, encoding="utf-8") as f:
- extras = json.load(f)
- extras["compostables"] = {k: struct.unpack(">f", struct.pack(">i", v))[0]
- for k, v in extras["compostables"].items()}
- return extras
- def map_colour_entry(states):
- """One block's map colours, compact: the colour when every state shares it, else {by, default, values} where
- `by` are the fewest state properties that decide it and values maps their values ("x" or "head,true") to it."""
- colours = set(states.values())
- if len(colours) == 1:
- return colours.pop()
- parsed = []
- for key, col in states.items():
- props = dict(pair.split("=", 1) for pair in key.split(",")) if key else {}
- parsed.append((props, col))
- names = sorted(parsed[0][0])
- from itertools import combinations
- for size in range(1, len(names) + 1):
- for by in combinations(names, size):
- values, ok = {}, True
- for props, col in parsed:
- k = ",".join(props[n] for n in by)
- if values.setdefault(k, col) != col:
- ok = False
- break
- if ok:
- default = max(colours, key=lambda c: sum(1 for _, x in parsed if x == c))
- return {"by": list(by), "default": default,
- "values": {k: v for k, v in sorted(values.items()) if v != default}}
- return None
- def vanilla_reports(client_jar, libs):
- """Run Minecraft's own data generator (net.minecraft.data.Main --reports) from the client jar: blocks.json has every
- vanilla block's real properties and default state, registries.json every item. None when Java is missing."""
- import shutil
- import subprocess
- import tempfile
- java = shutil.which("java")
- if not java:
- print("java not found: block properties come from blockstate files only")
- return None, None
- skip = re.compile(r"forge|minecraftforge|[\\/]com[\\/]mojang[\\/]minecraft[\\/]|lwjgl|fmlloader|cpw|modlauncher|natives")
- cp = [client_jar]
- for root, _, files in os.walk(libs):
- for f in files:
- path = os.path.join(root, f)
- if f.endswith(".jar") and not skip.search(path):
- cp.append(path)
- out = tempfile.mkdtemp(prefix="mcreports-")
- try:
- subprocess.run([java, "-cp", os.pathsep.join(cp), "net.minecraft.data.Main", "--reports", "--output", out],
- cwd=out, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=600)
- with open(os.path.join(out, "reports", "blocks.json"), encoding="utf-8") as f:
- blocks = json.load(f)
- with open(os.path.join(out, "reports", "registries.json"), encoding="utf-8") as f:
- registries = json.load(f)
- return blocks, registries
- except Exception as e:
- print("data generator failed (" + str(e) + "): block properties come from blockstate files only")
- return None, None
- finally:
- shutil.rmtree(out, ignore_errors=True)
- def load_json(data):
- try:
- text = data.decode("utf-8-sig")
- # some mods ship JSON with comments or trailing commas
- text = re.sub(r"^\s*//.*$", "", text, flags=re.M)
- text = re.sub(r",(\s*[}\]])", r"\1", text)
- return json.loads(text)
- except Exception:
- return None
- def main():
- args = parse_args(sys.argv[1:])
- out_dir = os.path.abspath(args.out)
- names = {}
- blocks = {} # id -> {prop: [values]}
- items = set()
- loot = {}
- tag_files = {"blocks": defaultdict(list), "items": defaultdict(list)} # tag -> [json, ...] in load order
- recipes = {}
- cooking = {}
- folders = args.info["folders"]
- tag_groups = {folders["block_tags"]: "blocks", folders["item_tags"]: "items"}
- for jar in jars(args):
- try:
- z = zipfile.ZipFile(jar)
- except Exception:
- continue
- for entry in z.namelist():
- if not entry.endswith(".json"):
- continue
- parts = entry.split("/")
- if len(parts) < 4:
- continue
- root, ns, kind = parts[0], parts[1], parts[2]
- rest = "/".join(parts[3:])[:-5]
- if root == "assets" and kind == "lang" and rest == "en_us":
- data = load_json(z.read(entry))
- if isinstance(data, dict):
- for key, value in data.items():
- m = re.match(r"^(block|item)\.([a-z0-9_.-]+)\.([a-z0-9_./-]+)$", key)
- if m and isinstance(value, str):
- ident = m.group(2) + ":" + m.group(3)
- # an item name wins over the block name only when there is no block name
- if m.group(1) == "block" or ident not in names:
- names[ident] = value
- if m.group(1) == "item":
- items.add(ident)
- elif root == "assets" and kind == "blockstates" and "/" not in rest:
- data = load_json(z.read(entry))
- ident = ns + ":" + rest
- props = defaultdict(set)
- if isinstance(data, dict):
- keys = []
- if isinstance(data.get("variants"), dict):
- keys = list(data["variants"].keys())
- for key in keys:
- for pair in key.split(","):
- if "=" in pair:
- k, v = pair.split("=", 1)
- props[k].add(v)
- for part in data.get("multipart", []) or []:
- when = part.get("when") if isinstance(part, dict) else None
- conds = []
- if isinstance(when, dict):
- if "OR" in when and isinstance(when["OR"], list):
- conds = [c for c in when["OR"] if isinstance(c, dict)]
- else:
- conds = [when]
- for c in conds:
- for k, v in c.items():
- for one in str(v).split("|"):
- props[k].add(one)
- blocks[ident] = {k: sorted(v) for k, v in props.items()}
- elif root == "assets" and kind == "models" and rest.startswith("item/") and "/" not in rest[5:]:
- items.add(ns + ":" + rest[5:])
- elif root == "data" and kind == folders["loot"] and rest.startswith("blocks/"):
- data = load_json(z.read(entry))
- if isinstance(data, dict):
- loot[ns + ":" + rest[7:]] = data
- elif root == "data" and kind == "tags" and rest.split("/", 1)[0] in tag_groups and "/" in rest:
- group, path = rest.split("/", 1)
- data = load_json(z.read(entry))
- if isinstance(data, dict):
- tag_files[tag_groups[group]][ns + ":" + path].append(data)
- elif root == "data" and kind == folders["recipes"]:
- data = load_json(z.read(entry))
- if isinstance(data, dict):
- recipe = crafting_recipe(data)
- if recipe:
- recipes[ns + ":" + rest] = recipe
- cook = cooking_recipe(data)
- if cook:
- cooking[ns + ":" + rest] = cook
- # Vanilla: the real properties and default states, and the real item registry, over the model-file guesses
- defaults = {}
- extras = None
- if args.info["reports"] == "server":
- report, registries, extras = server_reports(args.server_jar, args.mappings)
- else:
- report, registries = vanilla_reports(args.client_jar, args.libraries)
- if report:
- for ident, info in report.items():
- blocks[ident] = {k: list(v) for k, v in (info.get("properties") or {}).items()}
- for st in info.get("states", []):
- if st.get("default"):
- defaults[ident] = st.get("properties") or {}
- if registries:
- vanilla_items = set((registries.get("minecraft:item") or {}).get("entries", {}).keys())
- items = {i for i in items if not i.startswith("minecraft:")} | vanilla_items
- for data in loot.values():
- for out in loot_outputs(data):
- if not out.startswith("minecraft:") or not registries:
- items.add(out)
- for recipe in recipes.values():
- items.add(recipe["result"]["item"])
- # a block with an item model is also an item; a block alone (fire, water) is not
- items = {i for i in items if ID.match(i)}
- block_tags = resolve_tags(tag_files["blocks"])
- item_tags = resolve_tags(tag_files["items"])
- # One file per namespace, so a turtle that only meets vanilla blocks loads only minecraft.lua
- sections = {
- "names": names,
- "blocks": blocks,
- "defaults": defaults,
- "items": {i: True for i in items},
- "loot": loot,
- "blockTags": invert(block_tags),
- "itemTags": invert(item_tags),
- }
- # Map colours (CC:Tweaked 1.121.0's item and block details have them): only from the server's code, so only
- # where server_extras ran; a set without them keeps exactly the sections it always had
- if extras:
- colours = {ident: map_colour_entry(states) for ident, states in extras["mapColours"].items()}
- colours.update(args.info.get("map_colours", {}))
- sections["mapColours"] = {k: v for k, v in colours.items() if v is not None}
- by_ns = defaultdict(lambda: {k: {} for k in sections})
- for section, table in sections.items():
- for ident, value in table.items():
- by_ns[ident.split(":", 1)[0]][section][ident] = value
- if os.path.isdir(out_dir):
- for old in os.listdir(out_dir):
- if old.endswith(".lua"):
- os.remove(os.path.join(out_dir, old))
- os.makedirs(out_dir, exist_ok=True)
- for ns, data in by_ns.items():
- write_sections(os.path.join(out_dir, ns + ".lua"), data)
- write_sections(os.path.join(out_dir, "_recipes.lua"), {"recipes": recipes})
- write_sections(os.path.join(out_dir, "_cooking.lua"), {"cooking": cooking})
- # Tag members, for recipe ingredients given as a tag
- write_sections(os.path.join(out_dir, "_tag_members.lua"), {"items": {t: sorted(m) for t, m in item_tags.items()}})
- if extras:
- # ComposterBlock.COMPOSTABLES: item id -> the chance one item raises the level
- write_sections(os.path.join(out_dir, "_compostables.lua"), {"compostables": extras["compostables"]})
- print("Minecraft " + args.mc + " " + ("vanilla" if args.vanilla else "pack") + " set -> " + out_dir)
- print(f"{len(blocks)} blocks, {len(items)} items, {len(names)} names, {len(loot)} loot tables, "
- f"{len(block_tags)} block tags, {len(item_tags)} item tags, {len(recipes)} crafting recipes")
- def crafting_recipe(data):
- """A shaped or shapeless crafting recipe, unwrapped from forge:conditional; None for anything else."""
- if data.get("type") == "forge:conditional" and isinstance(data.get("recipes"), list) and data["recipes"]:
- first = data["recipes"][0]
- data = first.get("recipe") if isinstance(first, dict) else None
- if not isinstance(data, dict):
- return None
- kind = data.get("type")
- result = data.get("result")
- if isinstance(result, str):
- result = {"item": result}
- if not isinstance(result, dict) or not isinstance(result.get("item"), str):
- return None
- out = {"item": result["item"], "count": int(result.get("count", 1))}
- if isinstance(result.get("nbt"), (dict, str)):
- out["nbt"] = result["nbt"] if isinstance(result["nbt"], str) else json.dumps(result["nbt"])
- if kind == "minecraft:crafting_shaped":
- pattern = data.get("pattern")
- key = data.get("key")
- if not isinstance(pattern, list) or not isinstance(key, dict):
- return None
- return {"type": "shaped", "pattern": pattern, "key": {k: ingredient(v) for k, v in key.items()}, "result": out}
- if kind == "minecraft:crafting_shapeless":
- ings = data.get("ingredients")
- if not isinstance(ings, list):
- return None
- return {"type": "shapeless", "ingredients": [ingredient(v) for v in ings], "result": out}
- return None
- def cooking_recipe(data):
- """A smelting, blasting, smoking or campfire cooking recipe: {type, ingredient, result, time}; None for anything else."""
- kind = data.get("type")
- short = {"minecraft:smelting": "smelting", "minecraft:blasting": "blasting", "minecraft:smoking": "smoking",
- "minecraft:campfire_cooking": "campfire_cooking"}.get(kind)
- result = data.get("result")
- if isinstance(result, dict):
- result = result.get("item")
- if not short or not isinstance(result, str) or "ingredient" not in data:
- return None
- default = {"smelting": 200, "blasting": 100, "smoking": 100, "campfire_cooking": 600}[short]
- return {"type": short, "ingredient": ingredient(data["ingredient"]), "result": result,
- "time": int(data.get("cookingtime", default))}
- def ingredient(value):
- """An ingredient as a list of alternatives, each {"item": id} or {"tag": id}."""
- alts = value if isinstance(value, list) else [value]
- out = []
- for alt in alts:
- if isinstance(alt, dict):
- if isinstance(alt.get("item"), str):
- out.append({"item": alt["item"]})
- elif isinstance(alt.get("tag"), str):
- out.append({"tag": alt["tag"]})
- return out
- def loot_outputs(node):
- if isinstance(node, dict):
- if node.get("type") == "minecraft:item" and isinstance(node.get("name"), str):
- yield node["name"]
- for v in node.values():
- yield from loot_outputs(v)
- elif isinstance(node, list):
- for v in node:
- yield from loot_outputs(v)
- def resolve_tags(files):
- raw = {}
- for tag, datas in files.items():
- values = []
- for data in datas:
- if data.get("replace") is True:
- values = []
- for v in data.get("values", []) or []:
- if isinstance(v, dict):
- v = v.get("id")
- if isinstance(v, str):
- values.append(v)
- raw[tag] = values
- resolved = {}
- def members(tag, seen):
- if tag in resolved:
- return resolved[tag]
- if tag in seen:
- return set()
- seen.add(tag)
- out = set()
- for v in raw.get(tag, []):
- if v.startswith("#"):
- out |= members(v[1:], seen)
- elif ID.match(v):
- out.add(v)
- resolved[tag] = out
- return out
- for tag in raw:
- members(tag, set())
- return resolved
- def invert(tags):
- by_id = defaultdict(list)
- for tag, ids in tags.items():
- for ident in ids:
- by_id[ident].append(tag)
- return {k: sorted(v) for k, v in sorted(by_id.items())}
- def lua(value, out):
- if value is None:
- out.append("nil")
- elif value is True:
- out.append("true")
- elif value is False:
- out.append("false")
- elif isinstance(value, (int, float)):
- out.append(repr(value) if isinstance(value, float) else str(value))
- elif isinstance(value, str):
- out.append(json.dumps(value, ensure_ascii=False))
- elif isinstance(value, list):
- out.append("{")
- for v in value:
- lua(v, out)
- out.append(",")
- out.append("}")
- elif isinstance(value, dict):
- out.append("{")
- for k, v in value.items():
- if isinstance(k, str) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", k) and k not in LUA_KEYWORDS:
- out.append(k + "=")
- else:
- out.append("[" + json.dumps(str(k), ensure_ascii=False) + "]=")
- lua(v, out)
- out.append(",")
- out.append("}")
- else:
- out.append(json.dumps(str(value)))
- LUA_KEYWORDS = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in",
- "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while"}
- def write_sections(path, sections):
- # one entry per line, so a diff of a regenerated file stays readable
- lines = ["-- generated by tools/turtledata/extract.py from the game jars; do not edit", "return {"]
- for section in sorted(sections):
- lines.append(section + "={")
- value = sections[section]
- for k in sorted(value):
- out = []
- lua(value[k], out)
- lines.append("[" + json.dumps(k, ensure_ascii=False) + "]=" + "".join(out) + ",")
- lines.append("},")
- lines.append("}")
- with open(path, "w", encoding="utf-8", newline="\n") as f:
- f.write("\n".join(lines) + "\n")
- if __name__ == "__main__":
- main()
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.