Skip to content

Commit

Permalink
Buffer: Add support for loading spritesheet directly.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gadgetoid committed Jul 28, 2022
1 parent 994165f commit 78d971e
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions micropython/modules/picosystem/buffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ extern "C" {
#include "picosystem.h"
#include "math.h"
#include "cstring"
#include "py/stream.h"
#include "py/reader.h"
#include "extmod/vfs.h"

typedef struct _PicosystemBuffer_obj_t {
mp_obj_base_t base;
Expand Down Expand Up @@ -43,10 +46,11 @@ mp_obj_t PicosystemBuffer___del__(mp_obj_t self_in) {
mp_obj_t PicosystemBuffer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
_PicosystemBuffer_obj_t *self = nullptr;

enum { ARG_w, ARG_h };
enum { ARG_w, ARG_h, ARG_file };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_w, MP_ARG_INT | MP_ARG_REQUIRED, {.u_int = 0} },
{ MP_QSTR_h, MP_ARG_INT | MP_ARG_REQUIRED, {.u_int = 0} },
{ MP_QSTR_file, MP_ARG_OBJ, {.u_obj = nullptr} },
};

mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
Expand All @@ -65,8 +69,32 @@ mp_obj_t PicosystemBuffer_make_new(const mp_obj_type_t *type, size_t n_args, siz
self->buffer = m_new(buffer_t, 1);
self->buffer->w = w;
self->buffer->h = h;
uint32_t size = w * h;
self->buffer->data = m_new(color_t, size);
uint32_t buffer_size = w * h;
self->buffer->data = m_new(color_t, buffer_size);

mp_obj_t filename = args[ARG_file].u_obj;

if(filename) {
mp_obj_t stat = mp_vfs_stat(filename);
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR2(stat, mp_obj_tuple_t);
uint32_t file_size = mp_obj_get_int(tuple->items[6]);

if(file_size > buffer_size * sizeof(color_t)) {
mp_raise_ValueError("Buffer(): file too large!");
}

mp_obj_t args[2] = {
filename,
MP_OBJ_NEW_QSTR(MP_QSTR_r),
};

mp_obj_t file = mp_vfs_open(MP_ARRAY_SIZE(args), &args[0], (mp_map_t *)&mp_const_empty_map);
int errcode;
uint32_t read_len = mp_stream_rw(file, self->buffer->data, file_size, &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE);
if (errcode != 0) {
mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("Buffer(): error reading file!"));
}
}

return MP_OBJ_FROM_PTR(self);
}
Expand Down

0 comments on commit 78d971e

Please sign in to comment.