[oden][game] Draw the world
This involved basically a giant rewrite of the renderer because I now need to share the vertex buffer across textures and it is *a lot* let me tell you. There's like a vertical seam which I don't understand yet.
This commit is contained in:
parent
22327a71b3
commit
f9648d88cd
7 changed files with 936 additions and 595 deletions
Binary file not shown.
141
game/level.ts
Normal file
141
game/level.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
||||||
|
// NOTE: It's super not clear how much of this should be in rust vs
|
||||||
|
// javascript. Dealing with the level code is really nice in javascript
|
||||||
|
// but there's a bunch of weird stuff that really feels lower level.
|
||||||
|
import { load_texture } from "./assets";
|
||||||
|
import { Texture, print, spr, use_texture } from "./graphics";
|
||||||
|
import { load_string } from "./io";
|
||||||
|
|
||||||
|
// TODO: Use io-ts? YIKES.
|
||||||
|
|
||||||
|
export type Tile = {
|
||||||
|
px: [number, number];
|
||||||
|
src: [number, number];
|
||||||
|
f: number;
|
||||||
|
t: number;
|
||||||
|
a: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TileLayer = {
|
||||||
|
type: "tile";
|
||||||
|
texture: Texture;
|
||||||
|
grid_size: number;
|
||||||
|
offset: [number, number];
|
||||||
|
tiles: Tile[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Layer = TileLayer;
|
||||||
|
|
||||||
|
export type Level = {
|
||||||
|
world_x: number;
|
||||||
|
world_y: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
layers: Layer[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TileSet = { id: number; texture: Texture };
|
||||||
|
|
||||||
|
export type World = { levels: Level[]; tilesets: Map<number, TileSet> };
|
||||||
|
|
||||||
|
async function load_tileset(def: {
|
||||||
|
uid: number;
|
||||||
|
relPath: string;
|
||||||
|
}): Promise<TileSet> {
|
||||||
|
let relPath = def.relPath as string;
|
||||||
|
if (relPath.endsWith(".aseprite")) {
|
||||||
|
// Whoops let's load the export instead?
|
||||||
|
relPath = relPath.substring(0, relPath.length - 8) + "png";
|
||||||
|
}
|
||||||
|
let texture = await load_texture(relPath);
|
||||||
|
|
||||||
|
print("Loaded tileset", def.uid, "from", relPath, "as ID", texture.id());
|
||||||
|
return { id: def.uid, texture };
|
||||||
|
}
|
||||||
|
|
||||||
|
function load_level(
|
||||||
|
tile_sets: Map<number, TileSet>,
|
||||||
|
def: {
|
||||||
|
worldX: number;
|
||||||
|
worldY: number;
|
||||||
|
pxWid: number;
|
||||||
|
pxHei: number;
|
||||||
|
layerInstances: {
|
||||||
|
__gridSize: number;
|
||||||
|
__pxTotalOffsetX: number;
|
||||||
|
__pxTotalOffsetY: number;
|
||||||
|
__tilesetDefUid: number;
|
||||||
|
gridTiles: {
|
||||||
|
px: [number, number];
|
||||||
|
src: [number, number];
|
||||||
|
f: number;
|
||||||
|
t: number;
|
||||||
|
a: number;
|
||||||
|
}[];
|
||||||
|
}[];
|
||||||
|
}
|
||||||
|
): Level {
|
||||||
|
return {
|
||||||
|
world_x: def.worldX,
|
||||||
|
world_y: def.worldY,
|
||||||
|
width: def.pxWid,
|
||||||
|
height: def.pxHei,
|
||||||
|
layers: def.layerInstances.map((li) => {
|
||||||
|
const tileset = tile_sets.get(li.__tilesetDefUid);
|
||||||
|
if (!tileset) {
|
||||||
|
throw new Error("Unable to find texture!!! " + li.__tilesetDefUid);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: "tile",
|
||||||
|
texture: tileset.texture,
|
||||||
|
grid_size: li.__gridSize,
|
||||||
|
offset: [li.__pxTotalOffsetX, li.__pxTotalOffsetY],
|
||||||
|
tiles: li.gridTiles,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function load_world(path: string): Promise<World> {
|
||||||
|
print("Loading map:", path);
|
||||||
|
const blob = await load_string(path);
|
||||||
|
const map = JSON.parse(blob);
|
||||||
|
|
||||||
|
const tilesets = new Map<number, TileSet>();
|
||||||
|
let loaded_tilesets = await Promise.all(
|
||||||
|
map.defs.tilesets
|
||||||
|
.filter((def: any) => def.relPath != null)
|
||||||
|
.map((def: any) => load_tileset(def))
|
||||||
|
);
|
||||||
|
for (const ts of loaded_tilesets) {
|
||||||
|
tilesets.set(ts.id, ts);
|
||||||
|
}
|
||||||
|
|
||||||
|
const levels = map.levels.map((l: any) => load_level(tilesets, l));
|
||||||
|
return { levels, tilesets };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function draw_level(
|
||||||
|
level: Level,
|
||||||
|
offset_x: number = 0,
|
||||||
|
offset_y: number = 0
|
||||||
|
) {
|
||||||
|
for (const layer of level.layers) {
|
||||||
|
use_texture(layer.texture);
|
||||||
|
|
||||||
|
let [ofx, ofy] = layer.offset;
|
||||||
|
ofx += offset_x;
|
||||||
|
ofy += offset_y;
|
||||||
|
for (const tile of layer.tiles) {
|
||||||
|
// TODO: Flip and whatnot.
|
||||||
|
spr(
|
||||||
|
tile.px[0] + ofx,
|
||||||
|
tile.px[1] + ofy,
|
||||||
|
layer.grid_size,
|
||||||
|
layer.grid_size,
|
||||||
|
tile.src[0],
|
||||||
|
tile.src[1]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
26
game/main.ts
26
game/main.ts
|
|
@ -2,8 +2,8 @@ import { cls, print, spr, use_texture, Texture } from "./graphics";
|
||||||
import { load_texture } from "./assets";
|
import { load_texture } from "./assets";
|
||||||
import { since_start } from "./time";
|
import { since_start } from "./time";
|
||||||
import { btn, Button } from "./input";
|
import { btn, Button } from "./input";
|
||||||
// import { load_string } from "./io";
|
|
||||||
import { new_v2, vadd, vmul, vnorm } from "./vector";
|
import { new_v2, vadd, vmul, vnorm } from "./vector";
|
||||||
|
import { load_world, World, Level, draw_level } from "./level";
|
||||||
|
|
||||||
/// TODO: Support reload by saving and restoring state from init/update/restore.
|
/// TODO: Support reload by saving and restoring state from init/update/restore.
|
||||||
|
|
||||||
|
|
@ -11,6 +11,8 @@ import { new_v2, vadd, vmul, vnorm } from "./vector";
|
||||||
let clock = 0;
|
let clock = 0;
|
||||||
|
|
||||||
let bot_sprite: Texture | undefined = undefined;
|
let bot_sprite: Texture | undefined = undefined;
|
||||||
|
let world: World | undefined = undefined;
|
||||||
|
let level: Level | undefined = undefined;
|
||||||
|
|
||||||
// Note zelda overworld is 16x8 screens
|
// Note zelda overworld is 16x8 screens
|
||||||
// zelda screen is 16x11 tiles
|
// zelda screen is 16x11 tiles
|
||||||
|
|
@ -18,13 +20,6 @@ let bot_sprite: Texture | undefined = undefined;
|
||||||
|
|
||||||
let loaded = false;
|
let loaded = false;
|
||||||
|
|
||||||
async function load_map(path: string) {
|
|
||||||
// print("Loading map:", path);
|
|
||||||
// const blob = await load_string(path);
|
|
||||||
// const map = JSON.parse(blob);
|
|
||||||
// print("Loaded map:", map);
|
|
||||||
}
|
|
||||||
|
|
||||||
function load_assets() {
|
function load_assets() {
|
||||||
// Start this load, but then...
|
// Start this load, but then...
|
||||||
let texture_load = load_texture("./bot.png").then((n) => {
|
let texture_load = load_texture("./bot.png").then((n) => {
|
||||||
|
|
@ -32,7 +27,16 @@ function load_assets() {
|
||||||
bot_sprite = n;
|
bot_sprite = n;
|
||||||
});
|
});
|
||||||
|
|
||||||
let map_load = load_map("./overworld.ldtk");
|
let map_load = load_world("./overworld.ldtk").then((w) => {
|
||||||
|
print("World loaded at", since_start());
|
||||||
|
world = w;
|
||||||
|
|
||||||
|
// Assume we start at 0,0
|
||||||
|
level = world.levels.find((l) => l.world_x == 0 && l.world_y == 0);
|
||||||
|
if (!level) {
|
||||||
|
throw new Error("UNABLE TO FIND LEVEL AT 0,0: CANNOT START");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
Promise.all([texture_load, map_load]).then(() => {
|
Promise.all([texture_load, map_load]).then(() => {
|
||||||
loaded = true;
|
loaded = true;
|
||||||
|
|
@ -106,6 +110,10 @@ export function draw() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (level != undefined) {
|
||||||
|
draw_level(level, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
if (bot_sprite != undefined) {
|
if (bot_sprite != undefined) {
|
||||||
// ...it gets resolved here?
|
// ...it gets resolved here?
|
||||||
use_texture(bot_sprite);
|
use_texture(bot_sprite);
|
||||||
|
|
|
||||||
BIN
game/overworld.aseprite
Normal file
BIN
game/overworld.aseprite
Normal file
Binary file not shown.
File diff suppressed because one or more lines are too long
BIN
game/overworld.png
Normal file
BIN
game/overworld.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 543 B |
604
src/lib.rs
604
src/lib.rs
|
|
@ -58,39 +58,30 @@ impl ScreenUniforms {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct State {
|
#[derive(Debug)]
|
||||||
surface: wgpu::Surface,
|
struct VertexBuffer {
|
||||||
device: wgpu::Device,
|
buffer: wgpu::Buffer,
|
||||||
queue: wgpu::Queue,
|
vec: Vec<Vertex>,
|
||||||
config: wgpu::SurfaceConfiguration,
|
|
||||||
size: winit::dpi::PhysicalSize<u32>,
|
|
||||||
window: Window,
|
|
||||||
render_pipeline: wgpu::RenderPipeline,
|
|
||||||
|
|
||||||
vertex_buffer: wgpu::Buffer,
|
|
||||||
max_vertices: usize,
|
max_vertices: usize,
|
||||||
|
|
||||||
sprite_bind_group_layout: wgpu::BindGroupLayout,
|
|
||||||
sprite_textures: HashMap<u32, wgpu::BindGroup>,
|
|
||||||
|
|
||||||
write_textures: HashMap<u32, texture::Texture>,
|
|
||||||
|
|
||||||
screen_uniform: ScreenUniforms,
|
|
||||||
screen_uniform_buffer: wgpu::Buffer,
|
|
||||||
screen_uniform_bind_group: wgpu::BindGroup,
|
|
||||||
|
|
||||||
// Garbage
|
|
||||||
mouse_x: f64,
|
|
||||||
mouse_y: f64,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TUTORIAL FOR BABIES LIKE ME: https://sotrh.github.io/learn-wgpu/beginner/tutorial2-surface/
|
#[derive(Clone, Debug)]
|
||||||
|
struct VertexBufferHandle {
|
||||||
|
index: usize,
|
||||||
|
capacity: usize,
|
||||||
|
}
|
||||||
|
|
||||||
impl State {
|
struct WindowAndDevice {
|
||||||
// Creating some of the wgpu types requires async code
|
pub window: Window,
|
||||||
|
// pub instance: wgpu::Instance,
|
||||||
|
pub surface: wgpu::Surface,
|
||||||
|
pub adapter: wgpu::Adapter,
|
||||||
|
pub device: wgpu::Device,
|
||||||
|
pub queue: wgpu::Queue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowAndDevice {
|
||||||
async fn new(window: Window) -> Self {
|
async fn new(window: Window) -> Self {
|
||||||
let size = window.inner_size();
|
|
||||||
|
|
||||||
// The instance is a handle to our GPU
|
// The instance is a handle to our GPU
|
||||||
// Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
|
// Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
|
||||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||||
|
|
@ -131,7 +122,52 @@ impl State {
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let surface_caps = surface.get_capabilities(&adapter);
|
WindowAndDevice {
|
||||||
|
window,
|
||||||
|
surface,
|
||||||
|
adapter,
|
||||||
|
device,
|
||||||
|
queue,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
surface: wgpu::Surface,
|
||||||
|
device: wgpu::Device,
|
||||||
|
queue: wgpu::Queue,
|
||||||
|
config: wgpu::SurfaceConfiguration,
|
||||||
|
size: winit::dpi::PhysicalSize<u32>,
|
||||||
|
window: Window,
|
||||||
|
render_pipeline: wgpu::RenderPipeline,
|
||||||
|
|
||||||
|
vertex_buffers: Vec<VertexBuffer>,
|
||||||
|
next_free_vertex_buffer: usize,
|
||||||
|
|
||||||
|
sprite_bind_group_layout: wgpu::BindGroupLayout,
|
||||||
|
sprite_textures: HashMap<u32, wgpu::BindGroup>,
|
||||||
|
|
||||||
|
write_textures: HashMap<u32, texture::Texture>,
|
||||||
|
|
||||||
|
screen_uniform: ScreenUniforms,
|
||||||
|
screen_uniform_buffer: wgpu::Buffer,
|
||||||
|
screen_uniform_bind_group: wgpu::BindGroup,
|
||||||
|
|
||||||
|
// Garbage
|
||||||
|
mouse_x: f64,
|
||||||
|
mouse_y: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
// TUTORIAL FOR BABIES LIKE ME: https://sotrh.github.io/learn-wgpu/beginner/tutorial2-surface/
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
// Creating some of the wgpu types requires async code
|
||||||
|
fn new(hardware: WindowAndDevice) -> Self {
|
||||||
|
let size = hardware.window.inner_size();
|
||||||
|
|
||||||
|
let device = hardware.device;
|
||||||
|
|
||||||
|
let surface_caps = hardware.surface.get_capabilities(&hardware.adapter);
|
||||||
|
|
||||||
// Shader code in this tutorial assumes an sRGB surface
|
// Shader code in this tutorial assumes an sRGB surface
|
||||||
// texture. Using a different one will result all the colors coming
|
// texture. Using a different one will result all the colors coming
|
||||||
|
|
@ -152,7 +188,7 @@ impl State {
|
||||||
alpha_mode: surface_caps.alpha_modes[0],
|
alpha_mode: surface_caps.alpha_modes[0],
|
||||||
view_formats: vec![],
|
view_formats: vec![],
|
||||||
};
|
};
|
||||||
surface.configure(&device, &config);
|
hardware.surface.configure(&device, &config);
|
||||||
|
|
||||||
let sprite_bind_group_layout =
|
let sprite_bind_group_layout =
|
||||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
|
@ -260,26 +296,17 @@ impl State {
|
||||||
multiview: None,
|
multiview: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let max_vertices: usize = 4096;
|
|
||||||
let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
|
||||||
label: Some("Vertex Buffer"),
|
|
||||||
size: (max_vertices * std::mem::size_of::<Vertex>())
|
|
||||||
.try_into()
|
|
||||||
.unwrap(),
|
|
||||||
mapped_at_creation: false,
|
|
||||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
|
||||||
});
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
window,
|
window: hardware.window,
|
||||||
surface,
|
surface: hardware.surface,
|
||||||
device,
|
device,
|
||||||
queue,
|
queue: hardware.queue,
|
||||||
config,
|
config,
|
||||||
size,
|
size,
|
||||||
render_pipeline: sprite_pipeline,
|
render_pipeline: sprite_pipeline,
|
||||||
vertex_buffer,
|
vertex_buffers: Vec::new(),
|
||||||
max_vertices,
|
next_free_vertex_buffer: 0,
|
||||||
|
|
||||||
sprite_bind_group_layout,
|
sprite_bind_group_layout,
|
||||||
sprite_textures: HashMap::new(),
|
sprite_textures: HashMap::new(),
|
||||||
write_textures: HashMap::new(),
|
write_textures: HashMap::new(),
|
||||||
|
|
@ -316,42 +343,30 @@ impl State {
|
||||||
|
|
||||||
fn render(&mut self, commands: Vec<GraphicsCommand>) -> Result<(), wgpu::SurfaceError> {
|
fn render(&mut self, commands: Vec<GraphicsCommand>) -> Result<(), wgpu::SurfaceError> {
|
||||||
let _span = span!("context render");
|
let _span = span!("context render");
|
||||||
let output = self.surface.get_current_texture()?;
|
|
||||||
|
|
||||||
// Group the commands into passes.
|
// Reset vertex buffers.
|
||||||
let screen_view = Rc::new(
|
self.next_free_vertex_buffer = 0;
|
||||||
output
|
|
||||||
.texture
|
|
||||||
.create_view(&wgpu::TextureViewDescriptor::default()),
|
|
||||||
);
|
|
||||||
let mut last_view = screen_view.clone();
|
|
||||||
|
|
||||||
struct Pass {
|
let mut builder = FrameBuilder::new(self)?;
|
||||||
color: Option<[f64; 4]>,
|
|
||||||
commands: Vec<GraphicsCommand>,
|
|
||||||
target: Rc<wgpu::TextureView>,
|
|
||||||
}
|
|
||||||
let mut passes = Vec::new();
|
|
||||||
for command in commands {
|
for command in commands {
|
||||||
match command {
|
builder.handle_command(command);
|
||||||
GraphicsCommand::Clear(cc) => passes.push(Pass {
|
}
|
||||||
color: Some(cc.color),
|
FrameBuilder::complete(builder);
|
||||||
commands: Vec::new(),
|
|
||||||
target: last_view.clone(),
|
|
||||||
}),
|
|
||||||
|
|
||||||
GraphicsCommand::CreateTexture(ct) => {
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_texture(&mut self, id: u32, image: image::DynamicImage, label: Option<String>) {
|
||||||
let texture = texture::Texture::from_image(
|
let texture = texture::Texture::from_image(
|
||||||
&self.device,
|
&self.device,
|
||||||
&self.queue,
|
&self.queue,
|
||||||
&ct.image,
|
&image,
|
||||||
match &ct.label {
|
match &label {
|
||||||
Some(l) => Some(&l),
|
Some(l) => Some(&l),
|
||||||
None => None,
|
None => None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let sprite_bind_group =
|
let sprite_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
||||||
layout: &self.sprite_bind_group_layout,
|
layout: &self.sprite_bind_group_layout,
|
||||||
entries: &[
|
entries: &[
|
||||||
wgpu::BindGroupEntry {
|
wgpu::BindGroupEntry {
|
||||||
|
|
@ -363,21 +378,22 @@ impl State {
|
||||||
resource: wgpu::BindingResource::Sampler(&texture.sampler),
|
resource: wgpu::BindingResource::Sampler(&texture.sampler),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
label: match &ct.label {
|
label: match &label {
|
||||||
Some(l) => Some(&l),
|
Some(l) => Some(&l),
|
||||||
None => None,
|
None => None,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
self.sprite_textures.insert(ct.id, sprite_bind_group);
|
self.sprite_textures.insert(id, sprite_bind_group);
|
||||||
}
|
}
|
||||||
|
|
||||||
GraphicsCommand::CreateWritableTexture {
|
fn create_writeable_texture(
|
||||||
id,
|
&mut self,
|
||||||
width,
|
id: u32,
|
||||||
height,
|
width: u32,
|
||||||
label,
|
height: u32,
|
||||||
} => {
|
label: Option<String>,
|
||||||
|
) {
|
||||||
let texture = texture::Texture::new_writable(
|
let texture = texture::Texture::new_writable(
|
||||||
&self.device,
|
&self.device,
|
||||||
width,
|
width,
|
||||||
|
|
@ -387,8 +403,7 @@ impl State {
|
||||||
None => None,
|
None => None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let sprite_bind_group =
|
let sprite_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
||||||
layout: &self.sprite_bind_group_layout,
|
layout: &self.sprite_bind_group_layout,
|
||||||
entries: &[
|
entries: &[
|
||||||
wgpu::BindGroupEntry {
|
wgpu::BindGroupEntry {
|
||||||
|
|
@ -410,80 +425,307 @@ impl State {
|
||||||
self.write_textures.insert(id, texture);
|
self.write_textures.insert(id, texture);
|
||||||
}
|
}
|
||||||
|
|
||||||
GraphicsCommand::WriteToTexture(id) => {
|
fn new_vertex_buffer(&mut self) -> VertexBufferHandle {
|
||||||
let texture = self.write_textures.get(&id).unwrap();
|
if self.next_free_vertex_buffer >= self.vertex_buffers.len() {
|
||||||
last_view = Rc::new(
|
let max_vertices: usize = 4096;
|
||||||
texture
|
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||||
.texture
|
label: Some("Vertex Buffer"),
|
||||||
.create_view(&wgpu::TextureViewDescriptor::default()),
|
size: (max_vertices * std::mem::size_of::<Vertex>())
|
||||||
);
|
.try_into()
|
||||||
let new_pass = match passes.last_mut() {
|
.unwrap(),
|
||||||
Some(pass) => {
|
mapped_at_creation: false,
|
||||||
if pass.commands.is_empty() {
|
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||||
pass.target = last_view.clone();
|
});
|
||||||
false
|
self.vertex_buffers.push(VertexBuffer {
|
||||||
|
buffer,
|
||||||
|
max_vertices,
|
||||||
|
vec: Vec::with_capacity(max_vertices),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = self.next_free_vertex_buffer;
|
||||||
|
self.next_free_vertex_buffer += 1;
|
||||||
|
let vb = &mut self.vertex_buffers[index];
|
||||||
|
vb.vec.clear();
|
||||||
|
VertexBufferHandle {
|
||||||
|
index,
|
||||||
|
capacity: vb.max_vertices,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_vertex_buffer(&self, handle: &VertexBufferHandle) -> &VertexBuffer {
|
||||||
|
&self.vertex_buffers[handle.index]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_vertex_buffer_mut(&mut self, handle: &VertexBufferHandle) -> &mut VertexBuffer {
|
||||||
|
&mut self.vertex_buffers[handle.index]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_vertex_buffers(&mut self) {
|
||||||
|
for i in 0..self.next_free_vertex_buffer {
|
||||||
|
let vb = &self.vertex_buffers[i];
|
||||||
|
self.queue
|
||||||
|
.write_buffer(&vb.buffer, 0, bytemuck::cast_slice(&vb.vec));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct DrawCall {
|
||||||
|
texture_id: Option<u32>,
|
||||||
|
vertex_buffer: VertexBufferHandle,
|
||||||
|
draw_start: u32,
|
||||||
|
draw_end: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DrawCall {
|
||||||
|
pub fn new(vertex_buffer: VertexBufferHandle, draw_start: u32) -> Self {
|
||||||
|
DrawCall {
|
||||||
|
texture_id: None,
|
||||||
|
vertex_buffer,
|
||||||
|
draw_start,
|
||||||
|
draw_end: draw_start,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_at_buffer_tail(&self) -> Self {
|
||||||
|
DrawCall::new(self.vertex_buffer.clone(), self.draw_end)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn switch_textures(&self, id: u32) -> DrawCall {
|
||||||
|
let mut next = self.new_at_buffer_tail();
|
||||||
|
next.texture_id = Some(id);
|
||||||
|
next
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn empty(&self) -> bool {
|
||||||
|
self.draw_start == self.draw_end
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn allocate_capacity(&mut self, capacity: u32) -> Option<VertexBufferHandle> {
|
||||||
|
if self.vertex_buffer.capacity >= (self.draw_end + capacity) as usize {
|
||||||
|
self.draw_end += capacity;
|
||||||
|
Some(self.vertex_buffer.clone())
|
||||||
} else {
|
} else {
|
||||||
true
|
None
|
||||||
}
|
|
||||||
}
|
|
||||||
None => true,
|
|
||||||
};
|
|
||||||
if new_pass {
|
|
||||||
passes.push(Pass {
|
|
||||||
color: None,
|
|
||||||
commands: vec![],
|
|
||||||
target: last_view.clone(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
GraphicsCommand::WriteToScreen => {
|
// pub fn draw<'a>(&'a self, pass: &'a mut wgpu::RenderPass, state: &'a State) {
|
||||||
if !Rc::ptr_eq(&last_view, &screen_view) {
|
// if self.draw_start == self.draw_end {
|
||||||
// If I have a pass already I need a new one.
|
// return;
|
||||||
last_view = screen_view.clone();
|
// }
|
||||||
if !passes.is_empty() {
|
|
||||||
passes.push(Pass {
|
// let texture_id = match self.texture_id {
|
||||||
color: None,
|
// Some(id) => id,
|
||||||
commands: vec![],
|
// None => return,
|
||||||
target: last_view.clone(),
|
// };
|
||||||
})
|
|
||||||
}
|
// let bind_group = state.sprite_textures.get(&texture_id).unwrap();
|
||||||
}
|
// pass.set_bind_group(0, bind_group, &[]);
|
||||||
|
|
||||||
|
// let vb = self.vertex_buffer.borrow();
|
||||||
|
// pass.set_bind_group(1, &state.screen_uniform_bind_group, &[]);
|
||||||
|
// pass.set_vertex_buffer(0, vb.buffer.slice(..));
|
||||||
|
// pass.draw(self.draw_start..self.draw_end, 0..1);
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
|
||||||
GraphicsCommand::EndFrame => (),
|
struct FrameBuilder<'a> {
|
||||||
other => match passes.last_mut() {
|
state: &'a mut State,
|
||||||
Some(pass) => pass.commands.push(other),
|
screen_view: Rc<wgpu::TextureView>,
|
||||||
None => passes.push(Pass {
|
last_view: Rc<wgpu::TextureView>,
|
||||||
color: None,
|
encoder: wgpu::CommandEncoder,
|
||||||
commands: vec![other],
|
output: wgpu::SurfaceTexture,
|
||||||
target: last_view.clone(),
|
|
||||||
}),
|
target: Rc<wgpu::TextureView>,
|
||||||
},
|
color: Option<[f64; 4]>,
|
||||||
}
|
draw_calls: Vec<DrawCall>,
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut vertices = Vec::new();
|
impl<'a> FrameBuilder<'a> {
|
||||||
for pass in passes {
|
fn new(state: &'a mut State) -> Result<Self, wgpu::SurfaceError> {
|
||||||
// TODO: It would be great if we could use multiple passes in a
|
let encoder = state
|
||||||
// single encoder but right now because of the dyanmic
|
|
||||||
// nature of vertices we can't, I think? Because
|
|
||||||
// queue.write_buffer doesn't actually happen until we call
|
|
||||||
// submit...
|
|
||||||
let mut encoder = self
|
|
||||||
.device
|
.device
|
||||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||||
label: Some("Render Encoder"),
|
label: Some("Render Encoder"),
|
||||||
});
|
});
|
||||||
|
|
||||||
{
|
let output = state.surface.get_current_texture()?;
|
||||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
|
||||||
|
let screen_view = Rc::new(
|
||||||
|
output
|
||||||
|
.texture
|
||||||
|
.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||||
|
);
|
||||||
|
let last_view = screen_view.clone();
|
||||||
|
|
||||||
|
Ok(FrameBuilder {
|
||||||
|
state,
|
||||||
|
screen_view,
|
||||||
|
last_view: last_view.clone(),
|
||||||
|
encoder,
|
||||||
|
output,
|
||||||
|
|
||||||
|
target: last_view,
|
||||||
|
color: None,
|
||||||
|
draw_calls: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn complete(builder: FrameBuilder<'a>) {
|
||||||
|
let mut builder = builder;
|
||||||
|
builder.flush();
|
||||||
|
|
||||||
|
// At this point the state needs to copy the vertex buffers we know about.
|
||||||
|
builder.state.copy_vertex_buffers();
|
||||||
|
|
||||||
|
// Submit will accept anything that implements IntoIter
|
||||||
|
builder
|
||||||
|
.state
|
||||||
|
.queue
|
||||||
|
.submit(std::iter::once(builder.encoder.finish()));
|
||||||
|
|
||||||
|
builder.output.present();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_command(&mut self, command: GraphicsCommand) {
|
||||||
|
match command {
|
||||||
|
// ================================================================
|
||||||
|
// Pass commands
|
||||||
|
// ================================================================
|
||||||
|
// NOTE: You would expect a "change target" command to be
|
||||||
|
// followed nearly immediately by a clear command and we
|
||||||
|
// wind up starting an extra pass in that case which sucks.
|
||||||
|
GraphicsCommand::Clear(cc) => self.start_pass(Some(cc.color), self.last_view.clone()),
|
||||||
|
GraphicsCommand::WriteToTexture(id) => {
|
||||||
|
let texture = self.state.write_textures.get(&id).unwrap();
|
||||||
|
self.last_view = Rc::new(
|
||||||
|
texture
|
||||||
|
.texture
|
||||||
|
.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||||
|
);
|
||||||
|
self.start_pass(None, self.last_view.clone());
|
||||||
|
}
|
||||||
|
GraphicsCommand::WriteToScreen => {
|
||||||
|
if !Rc::ptr_eq(&self.last_view, &self.screen_view) {
|
||||||
|
self.last_view = self.screen_view.clone();
|
||||||
|
self.start_pass(None, self.last_view.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
GraphicsCommand::Print(pc) => println!("{}", pc.text),
|
||||||
|
GraphicsCommand::Sprite(sc) => self.push_sprite(sc),
|
||||||
|
GraphicsCommand::UseTexture(id) => self.use_texture(id),
|
||||||
|
GraphicsCommand::EndFrame => self.flush(),
|
||||||
|
|
||||||
|
// ================================================================
|
||||||
|
// Resource commands
|
||||||
|
// ================================================================
|
||||||
|
GraphicsCommand::CreateTexture(ct) => {
|
||||||
|
self.state.create_texture(ct.id, ct.image, ct.label)
|
||||||
|
}
|
||||||
|
GraphicsCommand::CreateWritableTexture {
|
||||||
|
id,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
label,
|
||||||
|
} => self
|
||||||
|
.state
|
||||||
|
.create_writeable_texture(id, width, height, label),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_pass(&mut self, color: Option<[f64; 4]>, target: Rc<wgpu::TextureView>) {
|
||||||
|
self.flush();
|
||||||
|
self.color = color;
|
||||||
|
self.target = target;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn use_texture(&mut self, texture_id: u32) {
|
||||||
|
match self.draw_calls.last_mut() {
|
||||||
|
Some(call) => match call.texture_id {
|
||||||
|
Some(id) => {
|
||||||
|
if id == texture_id {
|
||||||
|
return;
|
||||||
|
} else if call.empty() {
|
||||||
|
call.texture_id = Some(texture_id);
|
||||||
|
} else {
|
||||||
|
let next = call.switch_textures(texture_id);
|
||||||
|
self.draw_calls.push(next);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
call.texture_id = Some(texture_id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
let mut call = DrawCall::new(self.state.new_vertex_buffer(), 0);
|
||||||
|
call.texture_id = Some(texture_id);
|
||||||
|
self.draw_calls.push(call);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_vertex_buffer(&mut self, required_capacity: u32) -> &mut VertexBuffer {
|
||||||
|
match self.draw_calls.last_mut() {
|
||||||
|
Some(call) => match call.allocate_capacity(required_capacity) {
|
||||||
|
Some(vb) => return self.state.get_vertex_buffer_mut(&vb),
|
||||||
|
None => {}
|
||||||
|
},
|
||||||
|
None => {}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut call = DrawCall::new(self.state.new_vertex_buffer(), 0);
|
||||||
|
let vb = call.allocate_capacity(required_capacity).unwrap();
|
||||||
|
self.draw_calls.push(call);
|
||||||
|
self.state.get_vertex_buffer_mut(&vb)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_sprite(&mut self, sc: script::graphics::SpriteCommand) {
|
||||||
|
let vertex_buffer = self.get_vertex_buffer(6);
|
||||||
|
|
||||||
|
vertex_buffer.vec.push(Vertex {
|
||||||
|
position: [sc.x, sc.y, 0.0],
|
||||||
|
tex_coords: [sc.u, sc.v],
|
||||||
|
});
|
||||||
|
vertex_buffer.vec.push(Vertex {
|
||||||
|
position: [sc.x, sc.y + sc.h, 0.0],
|
||||||
|
tex_coords: [sc.u, sc.v + sc.sh],
|
||||||
|
});
|
||||||
|
vertex_buffer.vec.push(Vertex {
|
||||||
|
position: [sc.x + sc.w, sc.y, 0.0],
|
||||||
|
tex_coords: [sc.u + sc.sw, sc.v],
|
||||||
|
});
|
||||||
|
|
||||||
|
vertex_buffer.vec.push(Vertex {
|
||||||
|
position: [sc.x, sc.y + sc.h, 0.0],
|
||||||
|
tex_coords: [sc.u, sc.v + sc.sh],
|
||||||
|
});
|
||||||
|
vertex_buffer.vec.push(Vertex {
|
||||||
|
position: [sc.x + sc.w, sc.y + sc.h, 0.0],
|
||||||
|
tex_coords: [sc.u + sc.sw, sc.v + sc.sh],
|
||||||
|
});
|
||||||
|
vertex_buffer.vec.push(Vertex {
|
||||||
|
position: [sc.x + sc.w, sc.y, 0.0],
|
||||||
|
tex_coords: [sc.u + sc.sw, sc.v],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) {
|
||||||
|
let first_call = match self.draw_calls.last() {
|
||||||
|
Some(call) => call.new_at_buffer_tail(),
|
||||||
|
None => DrawCall::new(self.state.new_vertex_buffer(), 0),
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.draw_calls.len() > 0 {
|
||||||
|
let mut pass = self.encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||||
label: Some("Render Pass"),
|
label: Some("Render Pass"),
|
||||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||||
view: &pass.target,
|
view: &self.target,
|
||||||
resolve_target: None,
|
resolve_target: None,
|
||||||
ops: wgpu::Operations {
|
ops: wgpu::Operations {
|
||||||
load: if let Some([r, g, b, a]) = pass.color {
|
load: if let Some([r, g, b, a]) = self.color {
|
||||||
wgpu::LoadOp::Clear(wgpu::Color {
|
wgpu::LoadOp::Clear(wgpu::Color {
|
||||||
r, //0.1,
|
r, //0.1,
|
||||||
g, //0.2,
|
g, //0.2,
|
||||||
|
|
@ -499,77 +741,32 @@ impl State {
|
||||||
depth_stencil_attachment: None,
|
depth_stencil_attachment: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut texture_id = None;
|
pass.set_pipeline(&self.state.render_pipeline);
|
||||||
vertices.clear();
|
for call in &self.draw_calls {
|
||||||
for command in pass.commands {
|
if call.draw_start == call.draw_end {
|
||||||
match command {
|
continue;
|
||||||
GraphicsCommand::Print(pc) => {
|
|
||||||
println!("{}", pc.text);
|
|
||||||
}
|
|
||||||
GraphicsCommand::Sprite(sc) => {
|
|
||||||
vertices.push(Vertex {
|
|
||||||
position: [sc.x, sc.y, 0.0],
|
|
||||||
tex_coords: [sc.u, sc.v],
|
|
||||||
});
|
|
||||||
vertices.push(Vertex {
|
|
||||||
position: [sc.x, sc.y + sc.h, 0.0],
|
|
||||||
tex_coords: [sc.u, sc.v + sc.sh],
|
|
||||||
});
|
|
||||||
vertices.push(Vertex {
|
|
||||||
position: [sc.x + sc.w, sc.y, 0.0],
|
|
||||||
tex_coords: [sc.u + sc.sw, sc.v],
|
|
||||||
});
|
|
||||||
|
|
||||||
vertices.push(Vertex {
|
|
||||||
position: [sc.x, sc.y + sc.h, 0.0],
|
|
||||||
tex_coords: [sc.u, sc.v + sc.sh],
|
|
||||||
});
|
|
||||||
vertices.push(Vertex {
|
|
||||||
position: [sc.x + sc.w, sc.y + sc.h, 0.0],
|
|
||||||
tex_coords: [sc.u + sc.sw, sc.v + sc.sh],
|
|
||||||
});
|
|
||||||
vertices.push(Vertex {
|
|
||||||
position: [sc.x + sc.w, sc.y, 0.0],
|
|
||||||
tex_coords: [sc.u + sc.sw, sc.v],
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
GraphicsCommand::UseTexture(id) => texture_id = Some(id),
|
let texture_id = match call.texture_id {
|
||||||
|
Some(id) => id,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
GraphicsCommand::CreateTexture(_) => (), // Already handled
|
let bind_group = self.state.sprite_textures.get(&texture_id).unwrap();
|
||||||
GraphicsCommand::CreateWritableTexture { .. } => (), // Already handled
|
pass.set_bind_group(0, bind_group, &[]);
|
||||||
GraphicsCommand::WriteToTexture(_) => (), // Already handled
|
|
||||||
GraphicsCommand::WriteToScreen => (), // Already handled
|
let vb = self.state.get_vertex_buffer(&call.vertex_buffer);
|
||||||
GraphicsCommand::Clear(_) => (), // Already handled
|
pass.set_bind_group(1, &self.state.screen_uniform_bind_group, &[]);
|
||||||
GraphicsCommand::EndFrame => (), // Should never appear
|
pass.set_vertex_buffer(0, vb.buffer.slice(..));
|
||||||
|
pass.draw(call.draw_start..call.draw_end, 0..1);
|
||||||
|
|
||||||
|
// call.draw(&mut pass, &self.state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(id) = texture_id {
|
self.color = None;
|
||||||
assert!(vertices.len() < self.max_vertices); // !
|
self.draw_calls.clear();
|
||||||
self.queue.write_buffer(
|
self.draw_calls.push(first_call);
|
||||||
&self.vertex_buffer,
|
|
||||||
0,
|
|
||||||
bytemuck::cast_slice(&vertices),
|
|
||||||
);
|
|
||||||
render_pass.set_pipeline(&self.render_pipeline);
|
|
||||||
|
|
||||||
let bind_group = self.sprite_textures.get(&id).unwrap();
|
|
||||||
render_pass.set_bind_group(0, bind_group, &[]);
|
|
||||||
|
|
||||||
render_pass.set_bind_group(1, &self.screen_uniform_bind_group, &[]);
|
|
||||||
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
|
||||||
render_pass.draw(0..(vertices.len() as u32), 0..1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Submit will accept anything that implements IntoIter
|
|
||||||
self.queue.submit(std::iter::once(encoder.finish()));
|
|
||||||
}
|
|
||||||
|
|
||||||
output.present();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -670,11 +867,12 @@ pub async fn run() {
|
||||||
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||||
let event_loop_proxy = event_loop.create_proxy();
|
let event_loop_proxy = event_loop.create_proxy();
|
||||||
|
|
||||||
let state = State::new(window).await;
|
let hardware = WindowAndDevice::new(window).await;
|
||||||
let (sender, reciever) = std::sync::mpsc::channel();
|
let (sender, reciever) = std::sync::mpsc::channel();
|
||||||
|
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
set_thread_name!("game thread");
|
set_thread_name!("game thread");
|
||||||
|
let state = State::new(hardware);
|
||||||
main_thread(event_loop_proxy, state, reciever);
|
main_thread(event_loop_proxy, state, reciever);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue