Full Code of nickmqb/fpga_craft for AI

main d77083d57713 cached
4 files
24.5 KB
6.0k tokens
1 requests
Download .txt
Repository: nickmqb/fpga_craft
Branch: main
Commit: d77083d57713
Files: 4
Total size: 24.5 KB

Directory structure:
gitextract_xyzmpzx_/

├── .gitattributes
├── .gitignore
├── LICENSE
└── README.md

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitattributes
================================================
* -text


================================================
FILE: .gitignore
================================================
*
!*/
!.gitignore
!.gitattributes
!*.v
!*.w
!*.pcf
!*.ka
!*.mu
!*.args
!*.h
!*.glsl
!*.sh
!*.md
!LICENSE
!screenshot.png
!data_gen/*.png
!hw/build/unused.txt
!textures/custom_*.png
data_gen/generated_block_info.mu
hw/core.v
hw/core_*.v
hw/src/data_sim.w
hw/src/firmware.w
hw/src/static_data.w


================================================
FILE: LICENSE
================================================
Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# FPGA craft

A voxel game/Minecraft clone for the iCE40 UP5K FPGA (for the iCEBreaker board).

## Disclaimer

Use this project at your own risk. This project has had no real testing, and unlike typical software, it may have bugs that damage your hardware (board, N64 controller, etc.). Only use it if you're familiar with FPGA/HW dev and you understand the risks.

## Screenshot

Note: this repo *does not* contain any assets/textures, you need to provide these yourself (more details below). 

![image](screenshot.png "Screenshot, made using the 'Unity' texture pack (see below)")

## Features

* 3D voxel rendering on tiny FPGA!
* 256x192 resolution (256x128 3D area), 30 fps, 12 bit color
* Input via N64 controller
* Real-time terrain streaming from flash memory
* Placing and mining blocks
* Terrain changes by player are saved back to flash
* Max overworld size: 512x512x32 blocks (wraps at edges)
* Offline terrain generator (run on PC, then upload terrain to flash) with multiple biomes/features (grass, forest, desert, snow, caves)
* Low memory usage (15kb BRAM, 128kb SPRAM, 16MB flash)
* Custom ray tracing GPU that handles ~1 million rays/second
* Custom 16-bit CPU with its own instruction set, running at 32.625Mhz
* Compiled firmware is ~5kb, written in custom Forth like assembly langage, compiled using custom assembler ("kasm")
* Hardware design written in [Wyre, a custom hardware design language](https://github.com/nickmqb/wyre)
* Fully dynamic hardware based lighting system
* Day/night cycle (each full day is ~18 minutes)
* Up to 128 textures (using palette based texture compression to save memory)
* Dithering to emulate higher color bit depth
* Animated textures (lava, portals)
* Portals and multiple dimensions (though terrain gen for these is not implemented in this version, see note below)
* Transparent water rendering (slightly hacky)
* Underwater rendering & swim physics
* Fly around using rockets (item)
* Falling sand/gravel physics
* Water/lava physics (limited to modified terrain chunks)
* Noclip mode & debug info overlay (including player XYZ coords)
* Inventory system

Note: you may have seen (videos of) this project [on my twitter](https://twitter.com/nickmqb). This open source repo is a "light version" of the project, without the Minecraft specific terrain gen/biomes/structures.

## Requirements

* iCEBreaker board
* VGA PMOD
* VGA display
* N64 controller (You don't need an original "vintage" controller. For example, I'm just using a cheap third party replica.)
* Bring your own textures (see [Setting up textures](#setting-up-textures) below).

It should be possible to port the project to other boards/FPGAs, displays (e.g. using HDMI PMOD) and input devices (e.g. PS2 mouse/keyboard or GameCube controller). If you do, let me know and I'd be happy to add a link to your project.

## Build steps

### Preparation

1. Disconnect any currently connected peripherals from board.
1. Ensure yosys, nextpnr and icestorm are installed ([e.g. from here](https://github.com/esden/summon-fpga-tools)) and are available on your path.

### Getting the code

1. `git clone https://github.com/nickmqb/fpga_craft` (this repo) 
1. `git clone https://github.com/nickmqb/muon` and [follow the installation instructions](https://github.com/nickmqb/muon/blob/master/docs/getting_started.md).
1. If not already done, move the Muon compiler binary `mu` to the `muon` directory (i.e. file path of the binary, including filename should be: `muon/mu`).
1. `git clone https://github.com/nickmqb/wyre` and [follow the installation instructions](https://github.com/nickmqb/wyre/blob/master/docs/getting_started.md).
1. If not already done, move the Wyre compiler binary `wyre` to the `wyre/compiler` directory (i.e. file path of the binary, including filename should be: `wyre/compiler/wyre`).

### Setting up textures

As mentioned above, this repo does not include any textures (except for a few custom textures specifically made for this project). You need to provide your own. You have several options:

* If you own Minecraft, find your Minecraft .jar file (e.g. `.minecraft/versions/{latest_version}/{version.jar}`). From the .jar file, extract all .png files from `assets/minecraft/textures/block` and copy them to `fpga_craft/textures`.
* Download a Minecraft texture pack (e.g. [from here](https://www.curseforge.com/minecraft/texture-packs/sixteen-x?filter-game-version=&filter-sort=5)). This will be a .zip file with the same directory structure as the Minecraft .jar file. See the previous bullet point for which files to copy. Note: not all texture packs contain all required textures, so you may need to combine multiple packs. (Based on some quick experimentation, the ["Unity" pack](https://www.curseforge.com/minecraft/texture-packs/unity) works. The screenshot near the top of this doc was made with this pack.)
* Create your own textures or use a different source (e.g. a [Minetest texture pack](https://content.minetest.net/packages/?type=txp&page=1&tag=16px)). Because the naming scheme of the texture filenames will likely be different, you will need to manually tweak `fpga_craft/block_info_gen/block_info_generator.mu` (namespace `Ids`) and provide the right filenames.

### Building tools

1. `cd fpga_craft`
1. `cd bram_swap && ./build.sh && cd ..`
1. `cd kasm && ./build.sh && cd ..`

### Data gen

1. `cd block_info_gen && ./run.sh && cd ..`
1. `cd data_gen && ./run.sh && cd ..` (generates `fpga_craft/ram_a.bin` and `fpga_craft/textures.bin`)
1. `iceprog -o 2048k ram_a.bin`
1. `iceprog -o 2112k textures.bin`

### Terrain gen

1. Go to dir `fpga_craft/terrain_gen`
1. `./build.sh`
1. `./terrain_gen --dimension 1 --output overworld.bin` (Note: alternatively, you can use the OpenGL terrain_viewer for a preview of the generated terrain, see section below: [OpenGL terrain viewer: generating terrain](#opengl-terrain-viewer-generating-terrain))
1. `./terrain_gen --dimension 2 --output dim2.bin` ("Stub" generator, also see [Multiple dimensions](#multiple-dimensions))
1. `./terrain_gen --dimension 3 --output dim3.bin` ("Stub" generator)
1. `iceprog -o 8192k overworld.bin` (file is 8MB, so this will take several minutes)
1. `iceprog -o 4096k dim2.bin` (file is 0.5MB)
1. `iceprog -o 6144k dim3.bin` (file is 2MB)

### Building the hardware design

1. Go to dir `fpga_craft/hw`
1. By default, the code to save terrain changes to flash is commented out. You can choose to enable it.
	* To enable saving, overwrite `src/firmware.ka` with `src/firmware_save.ka`, i.e.: `cp src/firmware_save.ka src/firmware.ka`. Terrain changes are buffered in memory. The game automatically saves changes to flash, as needed, to keep the buffer from getting too full. Before quitting, you must manually save any remaining changes (see gameplay tips below). When the game is saving, a progress bar (consisting out of floppy disk icons) is shown in the top right. Saving is done when all floppy disks have vanished.
	* Keep an eye out for rapid flash usage bugs (though I didn't encounter any bugs like that so far). If the progress bar gets stuck and doesn't update at all for a long time (e.g. >10 seconds), the game may be stuck in a "save loop", you should disconnect power if that happens. Additionally: there are hardware counters that track the number of flash sector erase and page program operations, if you enable 'DEBUG INFO' in the game menu, these are shown on the 3rd line from the top (first 2 numbers). If these counters start going crazy, or if the game freezes, you should also disconnect power.	
	* If you don't enable saving, the game buffers up to 32 changed terrain chunks (2x2) in memory. After that, subsequent placed blocks/changes will disappear as you move through the terrain. Note: if the game freezes, it's still a good idea to disconnect power; flash bugs are less likely if you don't enable saving but are still possible.
1. `./build.sh` (builds FPGA bitstream; pay close attention to the result, may fail timing; if that happens, just re-run the command until you get a result that meets timing; may need to run a few times).
1. When the design meets timing: `./prog.sh` (upload bitstream to FPGA)

### Final steps

1. Disconnect board from power
1. Connect VGA and N64 controller according to pinout spec in `fpga_craft/hw/icebreaker_spi.pcf`
1. Reconnect power
1. Ready to play! (See below for controls and some useful gameplay tips)

## Controls

* Look around: stick
* Move/strafe: C buttons
* Jump: R
* Place block: Z
* Mine block: B (hold)
* Select hotbar slot: DPAD left/right
* Open door: A
* Move down (noclip mode): A
* Open/close inventory: L
* Inventory, move cursor: C buttons
* Inventory, select: A (or R)
* Open/close game menu: Start
* Game menu, move cursor: DPAD up/down
* Game menu, select: A
* Flying/boost: select rockets in hotbar, then: Z
* When flying: brake: B

## Gameplay tips

* There is a day/night cycle. If it gets dark and you want to skip the night, hit Start, then select 'TIME' and hit A a bunch of times (TIME 0x10-0x80 = day, TIME 0x90-0x00 = night).
* If you enabled saving (see instructions above), before quitting, hit Start on the controller, then select 'SAVE XY CHUNKS' to save remaining changes to flash. A progress bar (consisting out of floppy disk icons) is shown in the top right; saving is done when all floppy disks have vanished.

## Optional steps

### Changing the firmware

1. Go to dir `fpga_craft/hw`
1. Modify `src/firmware.ka`, e.g. to change controls or game logic.
1. `./bfw.sh` (compiles the firmware to `src/firmware.w`, then modifies the bitstream directly; this avoids synthesis & routing stages to allow quick iteration on the firmware)
1. `./prog.sh` to upload bitstream to FPGA.

### Changing the hardware design (.w)

The HW design is written in [Wyre](https://github.com/nickmqb/wyre).

*Important*: to avoid errors, set your tab size to 4 when editing .w files. (Wyre uses significant whitespace, but the feature still needs more work; this is the easiest workaround for now.)

### Changing other tools (.mu)

The other tools in this repo are written in [Muon](https://github.com/nickmqb/muon). 

*Important*: to avoid errors, set your tab size to 4 when editing .mu files. (Muon uses significant whitespace, but the feature still needs more work; this is the easiest workaround for now.)

### OpenGL terrain viewer: set up

1. Go back to base directory (i.e. directory with `fpga_craft`, `muon`, etc.) 
1. `git clone https://github.com/nickmqb/muon_gfx` and [follow the setup instructions for sdl_bindings](https://github.com/nickmqb/muon_gfx/tree/master/sdl_bindings). Note: the `SDL2` directory should be a subdirectory of the `sdl_bindings` directory.
1. `cd fpga_craft/terrain_viewer`
1. `./build.sh`

### OpenGL terrain viewer: generating terrain

1. Ensure previous section is done.
1. `./terrain_viewer --dimension 1 --output overworld.bin`
1. Fly around with WASD/space/C. Look around with arrow keys. Move slowly by holding shift.
1. To generate a new random world, press F3.
1. To save the world to the output path, press F12 (you must do this before exiting, otherwise output file will not be written).
1. The tool never frees memory, and will crash if you generate a lot of random worlds -- just restart in that case ("good enough, ship it!" ;)).

### OpenGL terrain viewer: viewing terrain

1. After playing, download modified world from flash. E.g.: `iceprog -o 8192k -R 8192k overworld_device.bin`
1. `./terrain_viewer --input overworld_device.bin`
1. Fly around with WASD/space/C. Look around with arrow keys. Move slowly by holding shift.

### Adding new blocks/textures

There currently is room for ~75 additional textures. To add new blocks/textures:

1. Modify `block_info_gen/block_info_generator.mu`. Add the textures under `Ids`, then add the block definitions in function `BlockInfoGenerator.generate`.
1. Run block_info_gen.
1. Add the new blocks to the inventory in `data_gen/data_generator.mu` (function `buildInventory`).
1. Run data_gen, reupload ram_a.bin and textures.bin, and rebuild and reupload the firmware.

### Multiple dimensions

The game supports multiple dimensions, though terrain gen is only implemented for the overworld.

* Dimension 1: 512x512x32 (overworld)
* Dimension 2: 128x128x32 (access by building an obsidian portal (like Nether portal in Minecraft))
* Dimension 3: 256x256x32 (access only through portal_3 block; can be enabled by adding the block to the inventory in `data_gen/data_generator.mu` (function `buildInventory`), or modifying terrain gen).

### Map file format

Each map consists of a series of 128 byte chunks. There is no header.

A chunk consists of 128 blocks. It has a base of 2x2 blocks (x, z) and a height of 32 blocks (y). 1 block = 1 byte. After running the block_info_generator, `block_info_generator/block_info.txt` contains the mapping from byte value to block type.

The offset (in bytes) of a block within a chunk has the bit pattern: `yyyyyzx` (rightmost bit is LSB, e.g. x=0, z=1, y=2 -> offset=10)

The offset (in whole chunks) of a chunk within a map file has the bit pattern: `zxzx xxxz zzzz zxxx` (rightmost bit is LSB, this pattern is used to ensure good data locality).

## License & acknowledgements

See [LICENSE](LICENSE).

stb_image.h: [https://github.com/nothings/stb](https://github.com/nothings/stb)

textures/custom_cracked.png: from ["Pixel pack" texture pack for Minetest by isaiah658](https://content.minetest.net/packages/isaiah658/the_pixel_pack/) (modified)
Download .txt
gitextract_xyzmpzx_/

├── .gitattributes
├── .gitignore
├── LICENSE
└── README.md
Condensed preview — 4 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (26K chars).
[
  {
    "path": ".gitattributes",
    "chars": 8,
    "preview": "* -text\n"
  },
  {
    "path": ".gitignore",
    "chars": 293,
    "preview": "*\n!*/\n!.gitignore\n!.gitattributes\n!*.v\n!*.w\n!*.pcf\n!*.ka\n!*.mu\n!*.args\n!*.h\n!*.glsl\n!*.sh\n!*.md\n!LICENSE\n!screenshot.png"
  },
  {
    "path": "LICENSE",
    "chars": 11324,
    "preview": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licens"
  },
  {
    "path": "README.md",
    "chars": 13507,
    "preview": "# FPGA craft\n\nA voxel game/Minecraft clone for the iCE40 UP5K FPGA (for the iCEBreaker board).\n\n## Disclaimer\n\nUse this "
  }
]

About this extraction

This page contains the full source code of the nickmqb/fpga_craft GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 4 files (24.5 KB), approximately 6.0k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!