Save/Load file

From dreamcast.wiki
Jump to navigation Jump to search

VMU

The following code will demonstrate how to write a compressed file to the VMU using KallistiOS. It is possible to just write raw data to the VMU, but in order for the file to show up properly in the VMU menu, a VMU package header with a description and icon is specified as well.

The following headers are required for the VMU header and compression.

#include <kos.h>
#include <zlib/zlib.h>


Saving

The save function will write to the first controller's first VMU.

 int DC_SaveToVMU(char *src) {
   char dst[32];
   file_t file;
   int filesize = 0;
   unsigned long zipsize = 0;
   uint8 *data;
   uint8 *zipdata;
   vmu_pkg_t pkg;
   uint8 *pkg_out;
   int pkg_size;
   // Our VMU + full save name
   strcpy(dst, "/vmu/a1/");
   strcat(dst, src);
   // Reads in the file from the CWD
   file = fs_open(src, O_RDONLY);
   filesize = fs_total(file);
   data = (uint8*)malloc(filesize);
   fs_read(file, data, filesize);
   fs_close(file);
   // Allocate some memory for compression
   zipsize = filesize * 2;
   zipdata = (uint8*)malloc(zipsize);
   // The compressed save
   compress(zipdata, &zipsize, data, filesize);
   // Required VMU header
   // You will have to have a VMU icon defined under icon_data
   strcpy(pkg.desc_short, "Wolf4SDL\\DC");
   strcpy(pkg.desc_long, "Game Save");
   strcpy(pkg.app_id, "Wolf4SDL\\DC");
   pkg.icon_cnt = 1;
   pkg.icon_anim_speed = 0;
   memcpy(&pkg.icon_pal[0], icon_data, 32);
   pkg.icon_data = icon_data + 32;
   pkg.eyecatch_type = VMUPKG_EC_NONE;
   pkg.data_len = zipsize;
   pkg.data = zipdata;
   vmu_pkg_build(&pkg, &pkg_out, &pkg_size);
   // Save the newly created VMU save to the VMU
   fs_unlink(dst);
   file = fs_open(dst, O_WRONLY);
   fs_write(file, pkg_out, pkg_size);
   fs_close(file);
   // Free unused memory
   free(pkg_out);
   free(data);
   free(zipdata);
   return 0;
 }

Loading

 int DC_LoadFromVMU(char *dst) {
   char src[32];
   int file;
   int filesize;
   unsigned long unzipsize;
   uint8* data;
   uint8* unzipdata;
   vmu_pkg_t pkg;
   // Our VMU + full save name
   strcpy(src, "/vmu/a1/");
   strcat(src, dst);
   // Remove VMU header
   file = fs_open(src, O_RDONLY);
   if(file == 0) return -1;
   filesize = fs_total(file);
   if(filesize <= 0) return -1;
   data = (uint8*)malloc(filesize);
   fs_read(file, data, filesize);
   vmu_pkg_parse(data, &pkg);
   fs_close(file);
   // Allocate memory for the uncompressed data
   unzipdata = (uint8 *)malloc(65536);
   unzipsize = 65536;
   // Uncompress the data to the CWD
   uncompress(unzipdata, &unzipsize, (uint8 *)pkg.data, pkg.data_len);
   fs_unlink(dst);
   file = fs_open(dst, O_WRONLY);
   fs_write(file, unzipdata, unzipsize);
   fs_close(file);
   // Free unused memory
   free(data);
   free(unzipdata);
   return 0;
 }