#Idiomatic way of indexing into comptime array with runtime index

1 messages · Page 1 of 1 (latest)

balmy sedge
#

Hi all,

I am trying to generate a bitmap font in multiple sizes at compile time. In order to do this, I have to bake the size of the bitmap into the type of each size. For example:

const Pixel = struct{r:u8,g:u8,b:u8};
const PRESCALED_WIDTH = 5;
const PRESCALED_HEIGHT = 3;

fn CharBitmap(comptime scale: usize) type {
  return struct {
    pixels: [PRESCALED_WIDTH*scale*PRESCALED_HEIGHT*scale]Pixel
  };
}
fn Font(comptime scale: usize) type {
  return struct {
    chars: [128]CharBitmap(scale), //128 characters in ASCII
  };
}

fn generate_font(comptime scale: usize) Font(scale) {
  //generate fonts at compile time
  ...
}

const possible_fonts = .{
  generate_font(1), generate_font(5), generate_font(8),
};

fn set_up_font(selected_font_index: usize) void {
  //this line is illegal since we are indexing a comptime
  //array with a runtime index.
  const chosen_font = &possible_fonts[selected_font_index];

...
}

In the example above, how would I rewrite this correctly to choose the correct font at runtime, while having the fonts generated at compile time?

I feel interfaces (https://zig.news/kilianvounckx/zig-interfaces-for-the-uninitiated-an-update-4gf1) are involved somehow, but cannot exactly suss out how that would work.

Thanks!

#

Idiomatic way of indexing into comptime array with runtime index

dusk oyster
#

could make a generic runtime font, which acts as a uniform runtime slice version of CharBitmap

#

e.g.

const CharBitmapSlice = struct {
    pixels: []const Pixel,
};
#

then then have an array of CharBitmapSlices