Format to LLVL

This commit is contained in:
tobid7vx
2022-11-12 23:19:41 +01:00
parent 36e5676d9f
commit 8b70d0e9b7
44 changed files with 4869 additions and 4889 deletions

View File

@ -6,459 +6,460 @@
extern bool shouldbe_disabled;
extern std::string csvpc;
RenderD7::BitmapPrinter::BitmapPrinter(int w, int h)
{
BMP newmap(w, h, true);
bitmap = newmap;
//renderframe.LoadPFromBuffer(BitmapConverter::ConvertData(bitmap.DATA()));
blank = newmap;
RenderD7::BitmapPrinter::BitmapPrinter(int w, int h) {
BMP newmap(w, h, true);
bitmap = newmap;
// renderframe.LoadPFromBuffer(BitmapConverter::ConvertData(bitmap.DATA()));
blank = newmap;
}
RenderD7::BitmapPrinter::~BitmapPrinter()
{
if(this->renderframe.loadet) this->renderframe.Unload();
RenderD7::BitmapPrinter::~BitmapPrinter() {
if (this->renderframe.loadet)
this->renderframe.Unload();
}
bool RenderD7::BitmapPrinter::DecodeFile(std::string file)
{
unsigned error = bitmap.read(file.c_str());
if (error)
{
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("BitmapPrinter", "Error Code: " + std::to_string(error)));
return false;
}
bool RenderD7::BitmapPrinter::DecodeFile(std::string file) {
unsigned error = bitmap.read(file.c_str());
return true;
if (error) {
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"BitmapPrinter", "Error Code: " + std::to_string(error)));
return false;
}
return true;
}
void RenderD7::BitmapPrinter::DrawPixel(int x, int y, u8 b, u8 g, u8 r, u8 a)
{
unsigned error = bitmap.set_pixel(x, bitmap.bmp_info_header.height - y, b, g, r, a);
if (error)
{
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("BitmapPrinter->Pixel", "Error Code: " + std::to_string(error)));
}
void RenderD7::BitmapPrinter::DrawPixel(int x, int y, u8 b, u8 g, u8 r, u8 a) {
unsigned error =
bitmap.set_pixel(x, bitmap.bmp_info_header.height - y, b, g, r, a);
if (error) {
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"BitmapPrinter->Pixel", "Error Code: " + std::to_string(error)));
}
}
void RenderD7::BitmapPrinter::DrawRect(int x, int y, int w, int h, u8 line_w, u8 b, u8 g, u8 r, u8 a)
{
unsigned error = bitmap.draw_rectangle(x, bitmap.bmp_info_header.height - y - h, w, h, b, g, r, a, line_w);
if (error)
{
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("BitmapPrinter->Rect", "Error Code: " + std::to_string(error)));
}
void RenderD7::BitmapPrinter::DrawRect(int x, int y, int w, int h, u8 line_w,
u8 b, u8 g, u8 r, u8 a) {
unsigned error = bitmap.draw_rectangle(
x, bitmap.bmp_info_header.height - y - h, w, h, b, g, r, a, line_w);
if (error) {
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"BitmapPrinter->Rect", "Error Code: " + std::to_string(error)));
}
}
void RenderD7::BitmapPrinter::DrawRectFilled(int x, int y, int w, int h, u8 b, u8 g, u8 r, u8 a)
{
unsigned error = bitmap.fill_region(x, bitmap.bmp_info_header.height - h - y, w, h, b, g, r, a);
if (error)
{
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("BitmapPrinter->RectF", "Error Code: " + std::to_string(error)));
}
void RenderD7::BitmapPrinter::DrawRectFilled(int x, int y, int w, int h, u8 b,
u8 g, u8 r, u8 a) {
unsigned error = bitmap.fill_region(x, bitmap.bmp_info_header.height - h - y,
w, h, b, g, r, a);
if (error) {
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"BitmapPrinter->RectF", "Error Code: " + std::to_string(error)));
}
}
void RenderD7::BitmapPrinter::SaveBmp(std::string name)
{
if(!RenderD7::NameIsEndingWith(name, {"bmp"}))
{
name += ".bmp";
void RenderD7::BitmapPrinter::SaveBmp(std::string name) {
if (!RenderD7::NameIsEndingWith(name, {"bmp"})) {
name += ".bmp";
}
bitmap.write(name.c_str());
}
void RenderD7::BitmapPrinter::SavePng(std::string name) {
if (!RenderD7::NameIsEndingWith(name, {"png"})) {
name += ".png";
}
std::vector<unsigned char> ImageBuffer;
ImageBuffer = BitmapConverter::ConvertData(bitmap.DATA());
lodepng::save_file(ImageBuffer, name);
}
void RenderD7::BitmapPrinter::CreateScreen(C3D_RenderTarget *target) {
isscreen = true;
targetr = target;
if (target == Top) {
bitmap = BMP(400, 240, true);
blank = BMP(400, 240, true);
}
if (target == TopRight) {
bitmap = BMP(400, 240, true);
blank = BMP(400, 240, true);
}
if (target == Bottom) {
bitmap = BMP(320, 240, true);
blank = BMP(320, 240, true);
}
renderframe.LoadPFromBuffer(BitmapConverter::ConvertData(bitmap.DATA()));
}
bool RenderD7::BitmapPrinter::DrawScreenDirectF(int framerate) {
bool updtt = false;
if (isscreen) {
if (frame == (60 / framerate)) {
RenderD7::OnScreen(targetr);
if (renderframe.loadet)
renderframe.Unload();
this->Decode(decc);
frame = 0;
updtt = true;
}
bitmap.write(name.c_str());
if (renderframe.loadet)
renderframe.Draw(0, 0);
frame++;
}
return updtt;
}
void RenderD7::BitmapPrinter::SavePng(std::string name)
{
if(!RenderD7::NameIsEndingWith(name, {"png"}))
{
name += ".png";
bool RenderD7::BitmapPrinter::DrawScreenDirect() {
bool updtt = false;
if (isscreen) {
RenderD7::OnScreen(targetr);
if (renderframe.loadet)
renderframe.Unload();
this->Decode(decc);
updtt = true;
if (renderframe.loadet)
renderframe.Draw(0, 0);
}
return updtt;
}
RenderD7::Image RenderD7::BitmapPrinter::GetImage() {
RenderD7::Image img;
img.LoadFromBitmap(bitmap);
return img;
}
void RenderD7::BitmapPrinter::UsePreMap(BMP map) { bitmap = map; }
void RenderD7::BitmapPrinter::UsePrePrintMap(BitmapPrinter printmap) {
bitmap = printmap.GetBitmap();
}
void RenderD7::BitmapPrinter::Clear(u8 b, u8 g, u8 r, u8 a) {
bitmap.fill_region(0, 0, bitmap.bmp_info_header.width,
bitmap.bmp_info_header.height, b, g, r, a);
}
void RenderD7::BitmapPrinter::ClearBlank() { bitmap = blank; }
void RenderD7::BitmapPrinter::DrawScreenF(int framerate) {
if (isscreen) {
if (frame == (60 / framerate)) {
RenderD7::OnScreen(targetr);
frame = 0;
}
std::vector<unsigned char> ImageBuffer;
ImageBuffer = BitmapConverter::ConvertData(bitmap.DATA());
lodepng::save_file(ImageBuffer, name);
}
void RenderD7::BitmapPrinter::CreateScreen(C3D_RenderTarget *target)
{
isscreen = true;
targetr = target;
if (target == Top)
{
bitmap = BMP(400, 240, true);
blank = BMP(400, 240, true);
}
if (target == TopRight)
{
bitmap = BMP(400, 240, true);
blank = BMP(400, 240, true);
}
if (target == Bottom)
{
bitmap = BMP(320, 240, true);
blank = BMP(320, 240, true);
}
renderframe.LoadPFromBuffer(BitmapConverter::ConvertData(bitmap.DATA()));
if (renderframe.loadet)
renderframe.Draw(0, 0);
frame++;
}
}
bool RenderD7::BitmapPrinter::DrawScreenDirectF(int framerate)
{
bool updtt = false;
if (isscreen)
{
if(frame == (60/framerate)){
RenderD7::OnScreen(targetr);
if(renderframe.loadet) renderframe.Unload();
this->Decode(decc);
frame = 0;
updtt = true;
}
if(renderframe.loadet) renderframe.Draw(0, 0);
frame++;
}
return updtt;
void RenderD7::BitmapPrinter::DrawScreen() {
if (isscreen) {
RenderD7::OnScreen(targetr);
if (renderframe.loadet)
renderframe.Draw(0, 0);
}
}
bool RenderD7::BitmapPrinter::DrawScreenDirect()
{
bool updtt = false;
if (isscreen)
{
RenderD7::OnScreen(targetr);
if(renderframe.loadet) renderframe.Unload();
this->Decode(decc);
updtt = true;
if(renderframe.loadet) renderframe.Draw(0, 0);
}
return updtt;
bool RenderD7::BitmapPrinter::UpdateScreenF(int framerate) {
bool updtt = false;
if (isscreen) {
if (frame == (60 / framerate)) {
if (renderframe.loadet)
renderframe.Unload();
// renderframe.LoadFromBitmap(bitmap);
this->Decode(decc);
frame = 0;
updtt = true;
}
frame++;
}
return updtt;
}
RenderD7::Image RenderD7::BitmapPrinter::GetImage()
{
RenderD7::Image img;
img.LoadFromBitmap(bitmap);
return img;
}
void RenderD7::BitmapPrinter::UsePreMap(BMP map)
{
bitmap = map;
}
void RenderD7::BitmapPrinter::UsePrePrintMap(BitmapPrinter printmap)
{
bitmap = printmap.GetBitmap();
}
void RenderD7::BitmapPrinter::Clear(u8 b, u8 g, u8 r, u8 a)
{
bitmap.fill_region(0, 0, bitmap.bmp_info_header.width, bitmap.bmp_info_header.height, b, g, r, a);
}
void RenderD7::BitmapPrinter::ClearBlank()
{
bitmap = blank;
}
void RenderD7::BitmapPrinter::DrawScreenF(int framerate)
{
if (isscreen)
{
if(frame == (60/framerate)){
RenderD7::OnScreen(targetr);
frame = 0;
}
if(renderframe.loadet) renderframe.Draw(0, 0);
frame++;
}
}
void RenderD7::BitmapPrinter::DrawScreen()
{
if (isscreen)
{
RenderD7::OnScreen(targetr);
if(renderframe.loadet) renderframe.Draw(0, 0);
}
}
bool RenderD7::BitmapPrinter::UpdateScreenF(int framerate)
{
bool updtt = false;
if (isscreen)
{
if(frame == (60/framerate)){
if(renderframe.loadet) renderframe.Unload();
//renderframe.LoadFromBitmap(bitmap);
this->Decode(decc);
frame = 0;
updtt = true;
}
frame++;
}
return updtt;
}
bool RenderD7::BitmapPrinter::UpdateScreen()
{
bool updtt = false;
if (isscreen)
{
if(renderframe.loadet) renderframe.Unload();
this->Decode(decc);
updtt = true;
}
return updtt;
bool RenderD7::BitmapPrinter::UpdateScreen() {
bool updtt = false;
if (isscreen) {
if (renderframe.loadet)
renderframe.Unload();
this->Decode(decc);
updtt = true;
}
return updtt;
}
#define TICKS_PER_MSEC 268111.856
void RenderD7::BitmapPrinter::Benchmark()
{
if(setupbenchmark)
{
frametime = 0;
renderedframes = 0;
timer = 0;
setupbenchmark = false;
lastTime = svcGetSystemTick();
}
if(benchmark)
{
if(timer >= 60)
{
std::string renderedf = std::to_string(renderedframes);
std::string avgdtt = std::to_string(mhdtt);
float alldtt = 0;
for (size_t i = 1; i < hdttt.size(); i++)
{
alldtt += hdttt[i];
}
float alldtt2 = 0;
for (size_t i = 0; i < hdttt2.size(); i++)
{
alldtt2 += hdttt2[i];
}
float alldtt3 = 0;
for (size_t i = 0; i < hdttt3.size(); i++)
{
alldtt3 += hdttt3[i];
}
int allfps = 0;
for (size_t f = 1; f < fpscountc.size(); f++)
{
allfps += fpscountc[f];
}
std::string avgcpu = std::to_string((alldtt/(float)hdttt.size()-1));
std::string avgcpu2 = std::to_string(((alldtt2/(float)hdttt2.size())*1000));
std::string avgcpu3 = std::to_string(((alldtt3/(float)hdttt3.size())*1000));
std::string avgfps = std::to_string((allfps/(int)fpscountc.size()-1));
void RenderD7::BitmapPrinter::Benchmark() {
if (setupbenchmark) {
frametime = 0;
renderedframes = 0;
timer = 0;
setupbenchmark = false;
lastTime = svcGetSystemTick();
}
if (benchmark) {
if (timer >= 60) {
std::string renderedf = std::to_string(renderedframes);
std::string avgdtt = std::to_string(mhdtt);
float alldtt = 0;
for (size_t i = 1; i < hdttt.size(); i++) {
alldtt += hdttt[i];
}
float alldtt2 = 0;
for (size_t i = 0; i < hdttt2.size(); i++) {
alldtt2 += hdttt2[i];
}
float alldtt3 = 0;
for (size_t i = 0; i < hdttt3.size(); i++) {
alldtt3 += hdttt3[i];
}
int allfps = 0;
for (size_t f = 1; f < fpscountc.size(); f++) {
allfps += fpscountc[f];
}
std::string resultt = "TestMode: " + std::to_string(testfpsd) + "fps" + "\nRendered Frames: " + renderedf + "\nMax Cpu Time: " + avgdtt + "\nAvg Cpu Time: " + avgcpu + "\nAvg Fps: " + avgfps + "\nAvg EncodeTime: " + avgcpu2 + "ms/f\nAvg DecodeTime: " + avgcpu3 + "ms\n";
this->ClearBlank();
this->DrawRectFilled(0, 0, this->bitmap.bmp_info_header.width, this->bitmap.bmp_info_header.height, 0, 0, 0, 255);
this->DrawDebugText(0, 0, 0, RenderD7::Color::Hex("#ffffff"), resultt);
std::string outname = csvpc + "/benchmark_" + RenderD7::GetTimeStr() + ".png";
this->SavePng(outname);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("Benchmark", "Saved to: \n" + outname));
benchmark = false;
}
uint64_t currentTime = svcGetSystemTick();
dtt = ((float)(currentTime / (float)TICKS_PER_MSEC) - (float)(lastTime / (float)TICKS_PER_MSEC)) / 1000.f;
lastTime = currentTime;
lastTime = currentTime;
frameCounter++;
fpsClock += dtt;
if (fpsClock >= 1.f) {
fps = frameCounter;
frameCounter = 0;
fpsClock = 0.f;
}
uint64_t lastTime2 = svcGetSystemTick();
this->ClearBlank();
this->DrawRectFilled(0, 0, this->bitmap.bmp_info_header.width, this->bitmap.bmp_info_header.width, 255, 255, 255, 255);
this->DrawRect(5, 5, this->bitmap.bmp_info_header.width - 10, this->bitmap.bmp_info_header.height - 10, 5, 0, 0, 0, 0);
//this->DrawDebugText(20, 20, 0, RenderD7::Color::Hex("#ffffff"), "Fps: " + std::to_string(fps));
this->DrawDebugText(0, 0, 0.5f, RenderD7::Color::Hex("#ff0000"), "Time: " + std::to_string(timer));
this->DrawDebugText(0, 10, 0.5f, RenderD7::Color::Hex("#ff0000"), "Fps: " + std::to_string(fps));
this->DrawDebugText(0, 20, 0.5f, RenderD7::Color::Hex("#ff0000"), "dt: " + std::to_string(dtt));
this->DrawDebugText(0, 30, 0.5f, RenderD7::Color::Hex("#ff0000"), "MaxEncodeTime: " + std::to_string(mdtt2*1000) + "ms/f");
this->DrawDebugText(0, 40, 0.5f, RenderD7::Color::Hex("#ff0000"), "MaxDecodeTime: " + std::to_string(mdtt3*1000) + "ms");
uint64_t currentTime2 = svcGetSystemTick();
dtt2 = ((float)(currentTime2 / (float)TICKS_PER_MSEC) - (float)(lastTime2 / (float)TICKS_PER_MSEC)) / 1000.f;
hdttt2.push_back(dtt2);
lastTime2 = svcGetSystemTick();
bool updgg = this->UpdateScreenF(testfps);
currentTime2 = svcGetSystemTick();
dtt3 = ((float)(currentTime2 / (float)TICKS_PER_MSEC) - (float)(lastTime2 / (float)TICKS_PER_MSEC)) / 1000.f;
if(updgg) hdttt3.push_back(dtt3);
if (!shouldbe_disabled) this->DrawScreen();
renderedframes++;
if(mdtt2 < dtt2)
{
mdtt2 = dtt2;
}
if(mdtt3 < dtt3 && updgg)
{
mdtt3 = dtt3;
}
timer+= 1*dtt;
float hdtt = C3D_GetProcessingTime();
hdttt.push_back(hdtt);
fpscountc.push_back(fps);
if(mhdtt < hdtt)
{
mhdtt = C3D_GetProcessingTime();
}
/*if (!shouldbe_disabled)
{
RenderD7::OnScreen(Bottom);
RenderD7::DrawText(0, 0, 0.5f, RenderD7::Color::Hex("#ff0000"), "Time: " + std::to_string(timer));
RenderD7::DrawText(0, 20, 0.5f, RenderD7::Color::Hex("#ff0000"), "Fps: " + std::to_string(fps));
RenderD7::DrawText(0, 40, 0.5f, RenderD7::Color::Hex("#ff0000"), "dt: " + std::to_string(dtt));
RenderD7::DrawText(0, 60, 0.5f, RenderD7::Color::Hex("#ff0000"), "MaxRenderTime: " + std::to_string(mdtt2*1000) + "ms/f");
RenderD7::DrawText(0, 80, 0.5f, RenderD7::Color::Hex("#ff0000"), "MaxConvertTime: " + std::to_string(mdtt3*1000) + "ms");
std::string avgcpu = std::to_string((alldtt / (float)hdttt.size() - 1));
std::string avgcpu2 =
std::to_string(((alldtt2 / (float)hdttt2.size()) * 1000));
std::string avgcpu3 =
std::to_string(((alldtt3 / (float)hdttt3.size()) * 1000));
std::string avgfps = std::to_string((allfps / (int)fpscountc.size() - 1));
}*/
}
std::string resultt =
"TestMode: " + std::to_string(testfpsd) + "fps" +
"\nRendered Frames: " + renderedf + "\nMax Cpu Time: " + avgdtt +
"\nAvg Cpu Time: " + avgcpu + "\nAvg Fps: " + avgfps +
"\nAvg EncodeTime: " + avgcpu2 + "ms/f\nAvg DecodeTime: " + avgcpu3 +
"ms\n";
this->ClearBlank();
this->DrawRectFilled(0, 0, this->bitmap.bmp_info_header.width,
this->bitmap.bmp_info_header.height, 0, 0, 0, 255);
this->DrawDebugText(0, 0, 0, RenderD7::Color::Hex("#ffffff"), resultt);
std::string outname =
csvpc + "/benchmark_" + RenderD7::GetTimeStr() + ".png";
this->SavePng(outname);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"Benchmark", "Saved to: \n" + outname));
benchmark = false;
}
uint64_t currentTime = svcGetSystemTick();
dtt = ((float)(currentTime / (float)TICKS_PER_MSEC) -
(float)(lastTime / (float)TICKS_PER_MSEC)) /
1000.f;
lastTime = currentTime;
lastTime = currentTime;
frameCounter++;
fpsClock += dtt;
if (fpsClock >= 1.f) {
fps = frameCounter;
frameCounter = 0;
fpsClock = 0.f;
}
uint64_t lastTime2 = svcGetSystemTick();
this->ClearBlank();
this->DrawRectFilled(0, 0, this->bitmap.bmp_info_header.width,
this->bitmap.bmp_info_header.width, 255, 255, 255,
255);
this->DrawRect(5, 5, this->bitmap.bmp_info_header.width - 10,
this->bitmap.bmp_info_header.height - 10, 5, 0, 0, 0, 0);
// this->DrawDebugText(20, 20, 0, RenderD7::Color::Hex("#ffffff"), "Fps: " +
// std::to_string(fps));
this->DrawDebugText(0, 0, 0.5f, RenderD7::Color::Hex("#ff0000"),
"Time: " + std::to_string(timer));
this->DrawDebugText(0, 10, 0.5f, RenderD7::Color::Hex("#ff0000"),
"Fps: " + std::to_string(fps));
this->DrawDebugText(0, 20, 0.5f, RenderD7::Color::Hex("#ff0000"),
"dt: " + std::to_string(dtt));
this->DrawDebugText(0, 30, 0.5f, RenderD7::Color::Hex("#ff0000"),
"MaxEncodeTime: " + std::to_string(mdtt2 * 1000) +
"ms/f");
this->DrawDebugText(0, 40, 0.5f, RenderD7::Color::Hex("#ff0000"),
"MaxDecodeTime: " + std::to_string(mdtt3 * 1000) +
"ms");
uint64_t currentTime2 = svcGetSystemTick();
dtt2 = ((float)(currentTime2 / (float)TICKS_PER_MSEC) -
(float)(lastTime2 / (float)TICKS_PER_MSEC)) /
1000.f;
hdttt2.push_back(dtt2);
lastTime2 = svcGetSystemTick();
bool updgg = this->UpdateScreenF(testfps);
currentTime2 = svcGetSystemTick();
dtt3 = ((float)(currentTime2 / (float)TICKS_PER_MSEC) -
(float)(lastTime2 / (float)TICKS_PER_MSEC)) /
1000.f;
if (updgg)
hdttt3.push_back(dtt3);
if (!shouldbe_disabled)
this->DrawScreen();
renderedframes++;
if (mdtt2 < dtt2) {
mdtt2 = dtt2;
}
if (mdtt3 < dtt3 && updgg) {
mdtt3 = dtt3;
}
timer += 1 * dtt;
float hdtt = C3D_GetProcessingTime();
hdttt.push_back(hdtt);
fpscountc.push_back(fps);
if (mhdtt < hdtt) {
mhdtt = C3D_GetProcessingTime();
}
/*if (!shouldbe_disabled)
{
RenderD7::OnScreen(Bottom);
RenderD7::DrawText(0, 0, 0.5f, RenderD7::Color::Hex("#ff0000"),
"Time: " + std::to_string(timer)); RenderD7::DrawText(0, 20, 0.5f,
RenderD7::Color::Hex("#ff0000"), "Fps: " + std::to_string(fps));
RenderD7::DrawText(0, 40, 0.5f, RenderD7::Color::Hex("#ff0000"),
"dt: " + std::to_string(dtt)); RenderD7::DrawText(0, 60, 0.5f,
RenderD7::Color::Hex("#ff0000"), "MaxRenderTime: " +
std::to_string(mdtt2*1000) + "ms/f"); RenderD7::DrawText(0, 80, 0.5f,
RenderD7::Color::Hex("#ff0000"), "MaxConvertTime: " +
std::to_string(mdtt3*1000) + "ms");
}*/
}
}
void RenderD7::BitmapPrinter::SetupBenchmark(int framerate)
{
benchmark = true;
setupbenchmark = true;
this->testfps = framerate;
this->testfpsd = framerate;
void RenderD7::BitmapPrinter::SetupBenchmark(int framerate) {
benchmark = true;
setupbenchmark = true;
this->testfps = framerate;
this->testfpsd = framerate;
}
#include <renderd7/debugfont.h>
void RenderD7::BitmapPrinter::DrawDebugChar(u32 posX, u32 posY, int t_size, u32 color, char character)
{
bool isscale = (t_size > 1) ? true : false;
for(u32 y = 0; y < 8; y++)
{
char charPos = debugfont[character * 8 + y];
void RenderD7::BitmapPrinter::DrawDebugChar(u32 posX, u32 posY, int t_size,
u32 color, char character) {
bool isscale = (t_size > 1) ? true : false;
for (u32 y = 0; y < 8; y++) {
char charPos = debugfont[character * 8 + y];
for(u32 x = 0; x < 8; x++)
if(((charPos >> (7 - x)) & 1) == 1)
{
if (!isscale) DrawPixel((int)posX + x + 1, (int)posY + y + 1, UNPACK_BGRA(color));
if (isscale) DrawRectFilled(((int)posX) + (x*t_size) + 1, ((int)posY) + (y*t_size) + 1, t_size, t_size, UNPACK_BGRA(color));
}
}
for (u32 x = 0; x < 8; x++)
if (((charPos >> (7 - x)) & 1) == 1) {
if (!isscale)
DrawPixel((int)posX + x + 1, (int)posY + y + 1, UNPACK_BGRA(color));
if (isscale)
DrawRectFilled(((int)posX) + (x * t_size) + 1,
((int)posY) + (y * t_size) + 1, t_size, t_size,
UNPACK_BGRA(color));
}
}
}
void RenderD7::BitmapPrinter::DrawChar(int posX, int posY, float t_size, u32 color, char character, RenderD7::NFontApi font)
{
for(int y = 0; y < font.GetGlyphHeight(character); y++)
{
for(int x = 0; x < font.GetGlyphWidth(character); x++)
{
DrawPixel(posX + x + 1, posY + y + 1, 255, 255, 255, font.GetGlyphBitmap(character)[((y * font.GetGlyphWidth(character) + x) * 1)]);
if(((font.GetGlyphBitmap(character)[font.GetGlyphHeight(character) + y] >> (font.GetGlyphWidth(character - 1) - x)) & 1) == 1)
{
}
}
void RenderD7::BitmapPrinter::DrawChar(int posX, int posY, float t_size,
u32 color, char character,
RenderD7::NFontApi font) {
for (int y = 0; y < font.GetGlyphHeight(character); y++) {
for (int x = 0; x < font.GetGlyphWidth(character); x++) {
DrawPixel(posX + x + 1, posY + y + 1, 255, 255, 255,
font.GetGlyphBitmap(
character)[((y * font.GetGlyphWidth(character) + x) * 1)]);
if (((font.GetGlyphBitmap(
character)[font.GetGlyphHeight(character) + y] >>
(font.GetGlyphWidth(character - 1) - x)) &
1) == 1) {
}
}
//for(int y = 0; y < font.GetGlyphHeight(character) * font.GetGlyphWidth(character); y++)
//{
// DrawPixel(posX + x + 1, posY + y + 1, UNPACK_BGRA(color));
//}
}
// for(int y = 0; y < font.GetGlyphHeight(character) *
// font.GetGlyphWidth(character); y++)
//{
// DrawPixel(posX + x + 1, posY + y + 1, UNPACK_BGRA(color));
//}
}
#define SPACING_Y 10
#define SPACING_X 8
void RenderD7::BitmapPrinter::DrawDebugText(int x, int y, int t_size, u32 color, std::string text)
{
if (t_size < 1)
{
t_size = 1;
}
for(u32 i = 0, line_i = 0; i < strlen(text.c_str()); i++)
switch(text[i])
{
case '\n':
y += (SPACING_Y*t_size);
line_i = 0;
break;
void RenderD7::BitmapPrinter::DrawDebugText(int x, int y, int t_size, u32 color,
std::string text) {
if (t_size < 1) {
t_size = 1;
}
case '\t':
line_i += 2;
break;
for (u32 i = 0, line_i = 0; i < strlen(text.c_str()); i++)
switch (text[i]) {
case '\n':
y += (SPACING_Y * t_size);
line_i = 0;
break;
default:
//Make sure we never get out of the screen
if(line_i >= (((u32)this->bitmap.bmp_info_header.width) - (u32)x) / (SPACING_X*t_size))
{
y += (SPACING_Y*t_size);
line_i = 1; //Little offset so we know the same text continues
if(text[i] == ' ') break; //Spaces at the start look weird
}
case '\t':
line_i += 2;
break;
this->DrawDebugChar((u32)x + line_i * (SPACING_X*t_size), (u32)y, t_size, color, text[i]);
default:
// Make sure we never get out of the screen
if (line_i >= (((u32)this->bitmap.bmp_info_header.width) - (u32)x) /
(SPACING_X * t_size)) {
y += (SPACING_Y * t_size);
line_i = 1; // Little offset so we know the same text continues
if (text[i] == ' ')
break; // Spaces at the start look weird
}
line_i++;
break;
}
this->DrawDebugChar((u32)x + line_i * (SPACING_X * t_size), (u32)y,
t_size, color, text[i]);
line_i++;
break;
}
}
void RenderD7::BitmapPrinter::DrawText(int x, int y, float t_size, u32 color, std::string text, RenderD7::NFontApi font)
{
if (t_size < 1)
{
t_size = 1;
}
for(u32 i = 0, line_i = 0; i < strlen(text.c_str()); i++)
switch(text[i])
{
case '\n':
y += (font.GetLineHeight());
line_i = 0;
break;
void RenderD7::BitmapPrinter::DrawText(int x, int y, float t_size, u32 color,
std::string text,
RenderD7::NFontApi font) {
if (t_size < 1) {
t_size = 1;
}
case '\t':
line_i += 2;
break;
for (u32 i = 0, line_i = 0; i < strlen(text.c_str()); i++)
switch (text[i]) {
case '\n':
y += (font.GetLineHeight());
line_i = 0;
break;
default:
//Make sure we never get out of the screen
if(line_i >= (((u32)this->bitmap.bmp_info_header.width) - (u32)x) / (u32)(font.GetGlyphWidth(text[i])))
{
y += (SPACING_Y*t_size);
line_i = 1; //Little offset so we know the same text continues
if(text[i] == ' ') break; //Spaces at the start look weird
}
case '\t':
line_i += 2;
break;
this->DrawChar(x + line_i * (font.GetGlyphWidth(text[i])), y, t_size, color, text[i], font);
default:
// Make sure we never get out of the screen
if (line_i >= (((u32)this->bitmap.bmp_info_header.width) - (u32)x) /
(u32)(font.GetGlyphWidth(text[i]))) {
y += (SPACING_Y * t_size);
line_i = 1; // Little offset so we know the same text continues
if (text[i] == ' ')
break; // Spaces at the start look weird
}
line_i++;
break;
}
this->DrawChar(x + line_i * (font.GetGlyphWidth(text[i])), y, t_size,
color, text[i], font);
line_i++;
break;
}
}
bool RenderD7::BitmapPrinter::Decode(Decoder deccc)
{
bool res = false;
bool RenderD7::BitmapPrinter::Decode(Decoder deccc) {
bool res = false;
switch (deccc)
{
case Decoder::BITMAP2PNG2C3D:
renderframe.LoadPFromBuffer(BitmapConverter::ConvertData(this->bitmap.DATA()));
res = true;
break;
case Decoder::BITMAP2C3D:
renderframe.LoadFromBitmap(this->bitmap);
res = true;
break;
default:
res = false;
break;
}
return res;
switch (deccc) {
case Decoder::BITMAP2PNG2C3D:
renderframe.LoadPFromBuffer(
BitmapConverter::ConvertData(this->bitmap.DATA()));
res = true;
break;
case Decoder::BITMAP2C3D:
renderframe.LoadFromBitmap(this->bitmap);
res = true;
break;
default:
res = false;
break;
}
return res;
}

View File

@ -1,22 +1,24 @@
#include <renderd7/Color.hpp>
#define RGBA8(r, g, b, a) ((((r) & 0xFF) << 0) | (((g) & 0xFF) << 8) | (((b) & 0xFF) << 16) | (((a) & 0xFF) << 24))
#define RGBA8(r, g, b, a) \
((((r)&0xFF) << 0) | (((g)&0xFF) << 8) | (((b)&0xFF) << 16) | \
(((a)&0xFF) << 24))
uint32_t RenderD7::Color::Hex(const std::string color, uint8_t a)
{
if (color.length() < 7 || std::regex_search(color.substr(1), std::regex("[^0-9A-Fa-f]"))) { // invalid color.
return RenderD7::Color::Hex("#000000", 0);
}
int r = std::stoi(color.substr(1, 2), nullptr, 16);
int g = std::stoi(color.substr(3, 2), nullptr, 16);
int b = std::stoi(color.substr(5, 2), nullptr, 16);
return RGBA8(r, g, b, a);
uint32_t RenderD7::Color::Hex(const std::string color, uint8_t a) {
if (color.length() < 7 ||
std::regex_search(color.substr(1),
std::regex("[^0-9A-Fa-f]"))) { // invalid color.
return RenderD7::Color::Hex("#000000", 0);
}
int r = std::stoi(color.substr(1, 2), nullptr, 16);
int g = std::stoi(color.substr(3, 2), nullptr, 16);
int b = std::stoi(color.substr(5, 2), nullptr, 16);
return RGBA8(r, g, b, a);
}
std::string RenderD7::Color::RGB2Hex(int r, int g, int b)
{
std::stringstream ss;
ss << "#";
ss << std::hex << (r << 16 | g << 8 | b );
return ss.str();
std::string RenderD7::Color::RGB2Hex(int r, int g, int b) {
std::stringstream ss;
ss << "#";
ss << std::hex << (r << 16 | g << 8 | b);
return ss.str();
}

View File

@ -4,174 +4,213 @@ extern C2D_TextBuf TextBuf;
extern C2D_Font Font;
extern bool currentScreen;
bool RenderD7::Draw::Rect(float x, float y, float w, float h, u32 color)
{
return C2D_DrawRectSolid(x, y, 0.5f, w, h, color);
bool RenderD7::Draw::Rect(float x, float y, float w, float h, u32 color) {
return C2D_DrawRectSolid(x, y, 0.5f, w, h, color);
}
bool RenderD7::Draw::Px(float x, float y, u32 color)
{
return C2D_DrawRectSolid(x, y, 0.5f, 1, 1, color);
bool RenderD7::Draw::Px(float x, float y, u32 color) {
return C2D_DrawRectSolid(x, y, 0.5f, 1, 1, color);
}
void RenderD7::Draw::TextCentered(float x, float y, float size, u32 color, std::string Text, int maxWidth, int maxHeight, C2D_Font fnt) {
float lineHeight, widthScale;
void RenderD7::Draw::TextCentered(float x, float y, float size, u32 color,
std::string Text, int maxWidth, int maxHeight,
C2D_Font fnt) {
float lineHeight, widthScale;
// Check for the lineHeight.
if (fnt != nullptr) {
lineHeight = RenderD7::Draw::GetTextHeight(size, " ", fnt);
} else {
lineHeight = RenderD7::Draw::GetTextHeight(size, " ");
}
// Check for the lineHeight.
if (fnt != nullptr) {
lineHeight = RenderD7::Draw::GetTextHeight(size, " ", fnt);
} else {
lineHeight = RenderD7::Draw::GetTextHeight(size, " ");
}
int line = 0;
while(Text.find('\n') != Text.npos) {
if (maxWidth == 0) {
// Do the widthScale.
if (fnt != nullptr) {
widthScale = RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')), fnt);
} else {
widthScale = RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')));
}
} else {
// Do the widthScale 2.
if (fnt != nullptr) {
widthScale = std::min((float)maxWidth, RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')), fnt));
} else {
widthScale = std::min((float)maxWidth, RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n'))));
}
}
if (fnt != nullptr) {
RenderD7::Draw::Text((currentScreen ? 200 : 160)+x-(widthScale/2), y+(lineHeight*line), size, color, Text.substr(0, Text.find('\n')), maxWidth, maxHeight, fnt);
} else {
RenderD7::Draw::Text((currentScreen ? 200 : 160)+x-(widthScale/2), y+(lineHeight*line), size, color, Text.substr(0, Text.find('\n')), maxWidth, maxHeight);
}
int line = 0;
while (Text.find('\n') != Text.npos) {
if (maxWidth == 0) {
// Do the widthScale.
if (fnt != nullptr) {
widthScale = RenderD7::Draw::GetTextWidth(
size, Text.substr(0, Text.find('\n')), fnt);
} else {
widthScale =
RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')));
}
} else {
// Do the widthScale 2.
if (fnt != nullptr) {
widthScale = std::min((float)maxWidth,
RenderD7::Draw::GetTextWidth(
size, Text.substr(0, Text.find('\n')), fnt));
} else {
widthScale = std::min((float)maxWidth,
RenderD7::Draw::GetTextWidth(
size, Text.substr(0, Text.find('\n'))));
}
}
if (fnt != nullptr) {
RenderD7::Draw::Text((currentScreen ? 200 : 160) + x - (widthScale / 2),
y + (lineHeight * line), size, color,
Text.substr(0, Text.find('\n')), maxWidth, maxHeight,
fnt);
} else {
RenderD7::Draw::Text((currentScreen ? 200 : 160) + x - (widthScale / 2),
y + (lineHeight * line), size, color,
Text.substr(0, Text.find('\n')), maxWidth,
maxHeight);
}
Text = Text.substr(Text.find('\n')+1);
line++;
}
Text = Text.substr(Text.find('\n') + 1);
line++;
}
if (maxWidth == 0) {
// Do the next WidthScale.
if (fnt != nullptr) {
widthScale = RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')), fnt);
} else {
widthScale = RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')));
}
} else {
// And again.
if (fnt != nullptr) {
widthScale = std::min((float)maxWidth, RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')), fnt));
} else {
widthScale = std::min((float)maxWidth, RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n'))));
}
}
if (fnt != nullptr) {
RenderD7::Draw::Text((currentScreen ? 200 : 160)+x-(widthScale/2), y+(lineHeight*line), size, color, Text.substr(0, Text.find('\n')), maxWidth, maxHeight, fnt);
} else {
RenderD7::Draw::Text((currentScreen ? 200 : 160)+x-(widthScale/2), y+(lineHeight*line), size, color, Text.substr(0, Text.find('\n')), maxWidth, maxHeight);
}
if (maxWidth == 0) {
// Do the next WidthScale.
if (fnt != nullptr) {
widthScale = RenderD7::Draw::GetTextWidth(
size, Text.substr(0, Text.find('\n')), fnt);
} else {
widthScale =
RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n')));
}
} else {
// And again.
if (fnt != nullptr) {
widthScale = std::min((float)maxWidth,
RenderD7::Draw::GetTextWidth(
size, Text.substr(0, Text.find('\n')), fnt));
} else {
widthScale = std::min(
(float)maxWidth,
RenderD7::Draw::GetTextWidth(size, Text.substr(0, Text.find('\n'))));
}
}
if (fnt != nullptr) {
RenderD7::Draw::Text((currentScreen ? 200 : 160) + x - (widthScale / 2),
y + (lineHeight * line), size, color,
Text.substr(0, Text.find('\n')), maxWidth, maxHeight,
fnt);
} else {
RenderD7::Draw::Text((currentScreen ? 200 : 160) + x - (widthScale / 2),
y + (lineHeight * line), size, color,
Text.substr(0, Text.find('\n')), maxWidth, maxHeight);
}
}
// Draw String or Text.
void RenderD7::Draw::Text(float x, float y, float size, u32 color, std::string Text, int maxWidth, int maxHeight, C2D_Font fnt) {
C2D_Text c2d_text;
void RenderD7::Draw::Text(float x, float y, float size, u32 color,
std::string Text, int maxWidth, int maxHeight,
C2D_Font fnt) {
C2D_Text c2d_text;
if (fnt != nullptr) {
C2D_TextFontParse(&c2d_text, fnt, TextBuf, Text.c_str());
} else {
C2D_TextFontParse(&c2d_text, Font, TextBuf, Text.c_str());
}
if (fnt != nullptr) {
C2D_TextFontParse(&c2d_text, fnt, TextBuf, Text.c_str());
} else {
C2D_TextFontParse(&c2d_text, Font, TextBuf, Text.c_str());
}
C2D_TextOptimize(&c2d_text);
C2D_TextOptimize(&c2d_text);
float heightScale;
if (maxHeight == 0) {
heightScale = size;
} else {
if (fnt != nullptr) {
heightScale = std::min(size, size*(maxHeight/RenderD7::Draw::GetTextHeight(size, Text, fnt)));
} else {
heightScale = std::min(size, size*(maxHeight/RenderD7::Draw::GetTextHeight(size, Text)));
}
}
float heightScale;
if (maxHeight == 0) {
heightScale = size;
} else {
if (fnt != nullptr) {
heightScale = std::min(
size,
size * (maxHeight / RenderD7::Draw::GetTextHeight(size, Text, fnt)));
} else {
heightScale = std::min(
size, size * (maxHeight / RenderD7::Draw::GetTextHeight(size, Text)));
}
}
if (maxWidth == 0) {
C2D_DrawText(&c2d_text, C2D_WithColor, x, y, 0.5f, size, heightScale, color);
} else {
if (fnt != nullptr) {
C2D_DrawText(&c2d_text, C2D_WithColor, x, y, 0.5f, std::min(size, size*(maxWidth/RenderD7::Draw::GetTextWidth(size, Text, fnt))), heightScale, color);
} else {
C2D_DrawText(&c2d_text, C2D_WithColor, x, y, 0.5f, std::min(size, size*(maxWidth/RenderD7::Draw::GetTextWidth(size, Text))), heightScale, color);
}
}
if (maxWidth == 0) {
C2D_DrawText(&c2d_text, C2D_WithColor, x, y, 0.5f, size, heightScale,
color);
} else {
if (fnt != nullptr) {
C2D_DrawText(
&c2d_text, C2D_WithColor, x, y, 0.5f,
std::min(size, size * (maxWidth / RenderD7::Draw::GetTextWidth(
size, Text, fnt))),
heightScale, color);
} else {
C2D_DrawText(
&c2d_text, C2D_WithColor, x, y, 0.5f,
std::min(size, size * (maxWidth /
RenderD7::Draw::GetTextWidth(size, Text))),
heightScale, color);
}
}
}
void RenderD7::Draw::TextRight(float x, float y, float size, u32 color, std::string Text, int maxWidth, int maxHeight, C2D_Font fnt)
{
RenderD7::Draw::Text(x - RenderD7::Draw::GetTextWidth(size, Text, fnt), y, size, color, Text, maxWidth, maxHeight, fnt);
void RenderD7::Draw::TextRight(float x, float y, float size, u32 color,
std::string Text, int maxWidth, int maxHeight,
C2D_Font fnt) {
RenderD7::Draw::Text(x - RenderD7::Draw::GetTextWidth(size, Text, fnt), y,
size, color, Text, maxWidth, maxHeight, fnt);
}
// Get String or Text Width.
float RenderD7::Draw::GetTextWidth(float size, std::string Text, C2D_Font fnt) {
float width = 0;
if (fnt != nullptr) {
GetTextSize(size, &width, NULL, Text, fnt);
} else {
GetTextSize(size, &width, NULL, Text);
}
return width;
float width = 0;
if (fnt != nullptr) {
GetTextSize(size, &width, NULL, Text, fnt);
} else {
GetTextSize(size, &width, NULL, Text);
}
return width;
}
// Get String or Text Size.
void RenderD7::Draw::GetTextSize(float size, float *width, float *height, std::string Text, C2D_Font fnt) {
C2D_Text c2d_text;
if (fnt != nullptr) {
C2D_TextFontParse(&c2d_text, fnt, TextBuf, Text.c_str());
} else {
C2D_TextFontParse(&c2d_text, Font, TextBuf, Text.c_str());
}
C2D_TextGetDimensions(&c2d_text, size, size, width, height);
void RenderD7::Draw::GetTextSize(float size, float *width, float *height,
std::string Text, C2D_Font fnt) {
C2D_Text c2d_text;
if (fnt != nullptr) {
C2D_TextFontParse(&c2d_text, fnt, TextBuf, Text.c_str());
} else {
C2D_TextFontParse(&c2d_text, Font, TextBuf, Text.c_str());
}
C2D_TextGetDimensions(&c2d_text, size, size, width, height);
}
// Get String or Text Height.
float RenderD7::Draw::GetTextHeight(float size, std::string Text, C2D_Font fnt) {
float height = 0;
if (fnt != nullptr) {
GetTextSize(size, NULL, &height, Text.c_str(), fnt);
} else {
GetTextSize(size, NULL, &height, Text.c_str());
}
return height;
float RenderD7::Draw::GetTextHeight(float size, std::string Text,
C2D_Font fnt) {
float height = 0;
if (fnt != nullptr) {
GetTextSize(size, NULL, &height, Text.c_str(), fnt);
} else {
GetTextSize(size, NULL, &height, Text.c_str());
}
return height;
}
Result RenderD7::Draw::LoadFont(C2D_Font &fnt, const char* Path) {
fnt = C2D_FontLoad(Path); // Only load if found.
return 0;
Result RenderD7::Draw::LoadFont(C2D_Font &fnt, const char *Path) {
fnt = C2D_FontLoad(Path); // Only load if found.
return 0;
}
// Unload a Font.
Result RenderD7::Draw::UnloadFont(C2D_Font &fnt) {
if (fnt != nullptr) {
C2D_FontFree(fnt); // Make sure to only unload if not nullptr.
}
return 0;
if (fnt != nullptr) {
C2D_FontFree(fnt); // Make sure to only unload if not nullptr.
}
return 0;
}
bool RenderD7::Draw::Circle(float x, float y, float radius, u32 color)
{
return C2D_DrawCircleSolid(x, y, 0.5f, radius, color);
bool RenderD7::Draw::Circle(float x, float y, float radius, u32 color) {
return C2D_DrawCircleSolid(x, y, 0.5f, radius, color);
}
bool RenderD7::Draw::Image(C2D_Image img, float x, float y, float scaleX, float scaleY)
{
return C2D_DrawImageAt(img, x, y, 0.5f, nullptr, scaleX, scaleY);
bool RenderD7::Draw::Image(C2D_Image img, float x, float y, float scaleX,
float scaleY) {
return C2D_DrawImageAt(img, x, y, 0.5f, nullptr, scaleX, scaleY);
}
bool RenderD7::Draw::NFRect(float p1x, float p1y, float w, float h, u32 color, float scale)
{
C2D_DrawLine(p1x, p1y, color,w, p1y, color, scale, 1);
C2D_DrawLine(w, p1y, color,w, h, color, scale, 1);
C2D_DrawLine(w, h, color,p1x, h, color, scale, 1);
C2D_DrawLine(p1x, h, color,p1x, p1y, color, scale, 1);
return true;
bool RenderD7::Draw::NFRect(float p1x, float p1y, float w, float h, u32 color,
float scale) {
C2D_DrawLine(p1x, p1y, color, w, p1y, color, scale, 1);
C2D_DrawLine(w, p1y, color, w, h, color, scale, 1);
C2D_DrawLine(w, h, color, p1x, h, color, scale, 1);
C2D_DrawLine(p1x, h, color, p1x, p1y, color, scale, 1);
return true;
}

View File

@ -1,324 +1,344 @@
#include <renderd7/FileSystem.hpp>
#include <3ds.h>
#include <cstring>
//Debugging
#include <renderd7/FileSystem.hpp>
// Debugging
#include <memory>
#include <renderd7/Ovl.hpp>
#include <renderd7/Toast.hpp>
const char* RenderD7::FileSystem::GetPhysfsError()
{
return PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
const char *RenderD7::FileSystem::GetPhysfsError() {
return PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
}
std::string RenderD7::FileSystem::Normalize(const std::string& input)
{
std::string out;
bool seenSep = false, isSep = false;
std::string RenderD7::FileSystem::Normalize(const std::string &input) {
std::string out;
bool seenSep = false, isSep = false;
for (size_t i = 0; i < input.size(); ++i)
{
isSep = (input[i] == '/');
for (size_t i = 0; i < input.size(); ++i) {
isSep = (input[i] == '/');
if (!isSep || !seenSep)
out += input[i];
if (!isSep || !seenSep)
out += input[i];
seenSep = isSep;
}
seenSep = isSep;
}
return out;
return out;
}
void RenderD7::FileSystem::Initialize()
{
RenderD7::FileSystem::savePath = "";
void RenderD7::FileSystem::Initialize() { RenderD7::FileSystem::savePath = ""; }
int RenderD7::FileSystem::Init(const char *argv) {
int res = PHYSFS_init(argv);
if (res != 1) {
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
}
return res;
}
int RenderD7::FileSystem::Init(const char* argv)
{
int res = PHYSFS_init(argv);
if (res != 1)
{
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
}
return res;
bool RenderD7::FileSystem::SetSource(const char *source) {
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
std::string searchPath = source;
if (!PHYSFS_mount(searchPath.c_str(), NULL, 1))
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
return true;
}
bool RenderD7::FileSystem::SetSource(const char* source)
{
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
bool RenderD7::FileSystem::SetIdentity(const char *name, bool append) {
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
std::string searchPath = source;
if (!PHYSFS_mount(searchPath.c_str(), NULL, 1))
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
std::string old = RenderD7::FileSystem::savePath;
return true;
RenderD7::FileSystem::savePath = RenderD7::FileSystem::Normalize(
RenderD7::FileSystem::GetUserDirectory() + "/save/" + name);
printf("Save Path set to %s\n", savePath.c_str());
if (!old.empty())
PHYSFS_unmount(old.c_str());
int success = PHYSFS_mount(savePath.c_str(), NULL, append);
printf("Save Path mounted %d\n", success);
PHYSFS_setWriteDir(nullptr);
return true;
}
bool RenderD7::FileSystem::SetIdentity(const char* name, bool append)
{
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
std::string RenderD7::FileSystem::GetSaveDirectory() {
return RenderD7::FileSystem::Normalize(
RenderD7::FileSystem::GetUserDirectory() + "/save");
}
std::string old = RenderD7::FileSystem::savePath;
bool RenderD7::FileSystem::SetupWriteDirectory() {
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
RenderD7::FileSystem::savePath = RenderD7::FileSystem::Normalize(RenderD7::FileSystem::GetUserDirectory() + "/save/" + name);
printf("Save Path set to %s\n", savePath.c_str());
if (RenderD7::FileSystem::savePath.empty())
RenderD7::AddOvl(
std::make_unique<RenderD7::Toast>("PHYSFS-Error", "Path is Empty"));
return false;
if (!old.empty())
PHYSFS_unmount(old.c_str());
std::string tmpWritePath = RenderD7::FileSystem::savePath;
std::string tmpDirectoryPath = RenderD7::FileSystem::savePath;
int success = PHYSFS_mount(savePath.c_str(), NULL, append);
printf("Save Path mounted %d\n", success);
if (RenderD7::FileSystem::savePath.find(
RenderD7::FileSystem::GetUserDirectory()) == 0) {
tmpWritePath = RenderD7::FileSystem::GetUserDirectory();
tmpDirectoryPath =
savePath.substr(RenderD7::FileSystem::GetUserDirectory().length());
/* strip leading '/' characters from the path we want to create */
size_t startPosition = tmpDirectoryPath.find_first_not_of('/');
if (startPosition != std::string::npos)
tmpDirectoryPath = tmpDirectoryPath.substr(startPosition);
}
if (!PHYSFS_setWriteDir(tmpWritePath.c_str())) {
printf("Failed to set write dir to %s\n", tmpWritePath.c_str());
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Failed to set write dir to %s\n",
tmpWritePath.c_str())));
return false;
}
if (!RenderD7::FileSystem::CreateDirectory(tmpDirectoryPath.c_str())) {
printf("Failed to create dir %s\n", tmpDirectoryPath.c_str());
/* clear the write directory in case of error */
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FormatString("Failed to create dir %s\n",
tmpDirectoryPath.c_str())));
PHYSFS_setWriteDir(nullptr);
return false;
}
return true;
if (!PHYSFS_setWriteDir(savePath.c_str())) {
printf("Failed to set write dir to %s\n", savePath.c_str());
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Failed to set write dir to %s\n",
savePath.c_str())));
return false;
}
if (!PHYSFS_mount(savePath.c_str(), nullptr, 0)) {
printf("Failed to mount write dir (%s)\n",
RenderD7::FileSystem::GetPhysfsError());
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Failed to mount write dir (%s)\n",
RenderD7::FileSystem::GetPhysfsError())));
/* clear the write directory in case of error */
PHYSFS_setWriteDir(nullptr);
return false;
}
return true;
}
std::string RenderD7::FileSystem::GetSaveDirectory()
{
return RenderD7::FileSystem::Normalize(RenderD7::FileSystem::GetUserDirectory() + "/save");
std::string RenderD7::FileSystem::GetUserDirectory() {
return RenderD7::FileSystem::Normalize(
PHYSFS_getPrefDir("npi-d7", "renderd7"));
}
bool RenderD7::FileSystem::SetupWriteDirectory()
{
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
bool RenderD7::FileSystem::GetInfo(const char *filename,
RenderD7::FileSystem::Info &info) {
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (RenderD7::FileSystem::savePath.empty())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", "Path is Empty"));
return false;
PHYSFS_Stat stat = {};
std::string tmpWritePath = RenderD7::FileSystem::savePath;
std::string tmpDirectoryPath = RenderD7::FileSystem::savePath;
if (!PHYSFS_stat(filename, &stat))
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (RenderD7::FileSystem::savePath.find(RenderD7::FileSystem::GetUserDirectory()) == 0)
{
tmpWritePath = RenderD7::FileSystem::GetUserDirectory();
tmpDirectoryPath = savePath.substr(RenderD7::FileSystem::GetUserDirectory().length());
info.mod_time =
std::min<int64_t>(stat.modtime, RenderD7::FileSystem::MAX_STAMP);
info.size = std::min<int64_t>(stat.filesize, RenderD7::FileSystem::MAX_STAMP);
/* strip leading '/' characters from the path we want to create */
size_t startPosition = tmpDirectoryPath.find_first_not_of('/');
if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
info.type = RenderD7::FileSystem::FileType_File;
else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
info.type = RenderD7::FileSystem::FileType_Directory;
else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
info.type = RenderD7::FileSystem::FileType_SymLink;
else
info.type = RenderD7::FileSystem::FileType_Other;
if (startPosition != std::string::npos)
tmpDirectoryPath = tmpDirectoryPath.substr(startPosition);
}
if (!PHYSFS_setWriteDir(tmpWritePath.c_str()))
{
printf("Failed to set write dir to %s\n", tmpWritePath.c_str());
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Failed to set write dir to %s\n", tmpWritePath.c_str())));
return false;
}
if (!RenderD7::FileSystem::CreateDirectory(tmpDirectoryPath.c_str()))
{
printf("Failed to create dir %s\n", tmpDirectoryPath.c_str());
/* clear the write directory in case of error */
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Failed to create dir %s\n", tmpDirectoryPath.c_str())));
PHYSFS_setWriteDir(nullptr);
return false;
}
if (!PHYSFS_setWriteDir(savePath.c_str()))
{
printf("Failed to set write dir to %s\n", savePath.c_str());
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Failed to set write dir to %s\n", savePath.c_str())));
return false;
}
if (!PHYSFS_mount(savePath.c_str(), nullptr, 0))
{
printf("Failed to mount write dir (%s)\n", RenderD7::FileSystem::GetPhysfsError());
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Failed to mount write dir (%s)\n", RenderD7::FileSystem::GetPhysfsError())));
/* clear the write directory in case of error */
PHYSFS_setWriteDir(nullptr);
return false;
}
return true;
return true;
}
std::string RenderD7::FileSystem::GetUserDirectory()
{
return RenderD7::FileSystem::Normalize(PHYSFS_getPrefDir("npi-d7", "renderd7"));
void RenderD7::FileSystem::GetDirectoryItems(const char *path,
std::vector<std::string> &items) {
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return;
char **results = PHYSFS_enumerateFiles(path);
if (results == nullptr)
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return;
for (char **item = results; *item != 0; item++)
items.push_back(*item);
PHYSFS_freeList(results);
}
bool RenderD7::FileSystem::GetInfo(const char* filename, RenderD7::FileSystem::Info& info)
{
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
bool RenderD7::FileSystem::OpenFile(File &file, const char *name,
FileMode mode) {
if (mode == FileMode_Closed)
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
PHYSFS_Stat stat = {};
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (!PHYSFS_stat(filename, &stat))
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (file.handle)
RenderD7::FileSystem::CloseFile(file);
info.mod_time = std::min<int64_t>(stat.modtime, RenderD7::FileSystem::MAX_STAMP);
info.size = std::min<int64_t>(stat.filesize, RenderD7::FileSystem::MAX_STAMP);
if (mode == FileMode_Read && !PHYSFS_exists(name)) {
printf("Could not open file %s, does not exist.\n", name);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Could not open file %s, does not exist.\n",
name)));
return false;
}
if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
info.type = RenderD7::FileSystem::FileType_File;
else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
info.type = RenderD7::FileSystem::FileType_Directory;
else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
info.type = RenderD7::FileSystem::FileType_SymLink;
else
info.type = RenderD7::FileSystem::FileType_Other;
if ((mode == FileMode_Write) &&
(PHYSFS_getWriteDir() == nullptr &&
RenderD7::FileSystem::SetupWriteDirectory())) {
printf("Could not set write directory.\n");
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Could not set write directory.\n")));
return false;
}
return true;
PHYSFS_getLastErrorCode();
switch (mode) {
case FileMode_Read:
file.handle = PHYSFS_openRead(name);
break;
case FileMode_Write:
file.handle = PHYSFS_openWrite(name);
break;
default:
break;
}
if (!file.handle) {
const char *error = RenderD7::FileSystem::GetPhysfsError();
if (error == nullptr)
error = "unknown error";
printf("Could not open file %s (%s)\n", name, error);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Could not open file %s (%s)\n", name, error)));
return false;
}
file.mode = mode;
return true;
}
void RenderD7::FileSystem::GetDirectoryItems(const char* path, std::vector<std::string>& items)
{
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return;
bool RenderD7::FileSystem::CloseFile(File &file) {
if (file.handle == nullptr || !PHYSFS_close(file.handle))
return false;
char** results = PHYSFS_enumerateFiles(path);
file.handle = nullptr;
if (results == nullptr)
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return;
for (char** item = results; *item != 0; item++)
items.push_back(*item);
PHYSFS_freeList(results);
return true;
}
bool RenderD7::FileSystem::OpenFile(File& file, const char* name, FileMode mode)
{
if (mode == FileMode_Closed)
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
bool RenderD7::FileSystem::CreateDirectory(const char *name) {
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (PHYSFS_getWriteDir() == nullptr &&
!RenderD7::FileSystem::SetupWriteDirectory())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (file.handle)
RenderD7::FileSystem::CloseFile(file);
if (!PHYSFS_mkdir(name))
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (mode == FileMode_Read && !PHYSFS_exists(name))
{
printf("Could not open file %s, does not exist.\n", name);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Could not open file %s, does not exist.\n", name)));
return false;
}
if ((mode == FileMode_Write) &&
(PHYSFS_getWriteDir() == nullptr && RenderD7::FileSystem::SetupWriteDirectory()))
{
printf("Could not set write directory.\n");
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Could not set write directory.\n")));
return false;
}
PHYSFS_getLastErrorCode();
switch (mode)
{
case FileMode_Read:
file.handle = PHYSFS_openRead(name);
break;
case FileMode_Write:
file.handle = PHYSFS_openWrite(name);
break;
default:
break;
}
if (!file.handle)
{
const char* error = RenderD7::FileSystem::GetPhysfsError();
if (error == nullptr)
error = "unknown error";
printf("Could not open file %s (%s)\n", name, error);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Could not open file %s (%s)\n", name, error)));
return false;
}
file.mode = mode;
return true;
return true;
}
bool RenderD7::FileSystem::CloseFile(File& file)
{
if (file.handle == nullptr || !PHYSFS_close(file.handle))
return false;
int64_t RenderD7::FileSystem::ReadFile(File &file, void *destination,
int64_t size) {
if (!file.handle || file.mode != FileMode_Read) {
printf("File is not opened for reading.\n");
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", "File is not opened for reading.\n"));
return 0;
}
file.handle = nullptr;
if (size > file.GetSize())
size = file.GetSize();
else if (size < 0) {
printf("Invalid read size %lld\n", size);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error",
RenderD7::FormatString("Invalid read size %lld\n", size)));
return 0;
}
return true;
return PHYSFS_readBytes(file.handle, destination, (PHYSFS_uint64)size);
}
bool RenderD7::FileSystem::CreateDirectory(const char* name)
{
if (!PHYSFS_isInit())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
bool RenderD7::FileSystem::WriteFile(File &file, const void *data,
int64_t size) {
if (!file.handle || file.mode != FileMode_Write) {
printf("File is not opened for writing.\n");
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", "File is not opened for writing.\n"));
return false;
}
if (PHYSFS_getWriteDir() == nullptr && !RenderD7::FileSystem::SetupWriteDirectory())
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
int64_t written = PHYSFS_writeBytes(file.handle, data, (PHYSFS_uint64)size);
if (!PHYSFS_mkdir(name))
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
if (written != size) {
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
}
return true;
}
int64_t RenderD7::FileSystem::ReadFile(File& file, void* destination, int64_t size)
{
if (!file.handle || file.mode != FileMode_Read)
{
printf("File is not opened for reading.\n");
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", "File is not opened for reading.\n"));
return 0;
}
if (size > file.GetSize())
size = file.GetSize();
else if (size < 0)
{
printf("Invalid read size %lld\n", size);
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FormatString("Invalid read size %lld\n", size)));
return 0;
}
return PHYSFS_readBytes(file.handle, destination, (PHYSFS_uint64)size);
}
bool RenderD7::FileSystem::WriteFile(File& file, const void* data, int64_t size)
{
if (!file.handle || file.mode != FileMode_Write)
{
printf("File is not opened for writing.\n");
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", "File is not opened for writing.\n"));
return false;
}
int64_t written = PHYSFS_writeBytes(file.handle, data, (PHYSFS_uint64)size);
if (written != size){
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("PHYSFS-Error", RenderD7::FileSystem::GetPhysfsError()));
return false;
}
return true;
return true;
}

View File

@ -4,252 +4,257 @@
extern bool usedbgmsg;
static u32 GetNextPowerOf2(u32 v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return (v >= 64 ? v : 64);
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return (v >= 64 ? v : 64);
}
static bool C3DTexToC2DImage(C2D_Image *texture, u32 width, u32 height, u8 *buf) {
if (width >= 1024 || height >= 1024)
return false;
C3D_Tex *tex = new C3D_Tex[sizeof(C3D_Tex)];
Tex3DS_SubTexture *subtex = new Tex3DS_SubTexture[sizeof(Tex3DS_SubTexture)];
subtex->width = static_cast<u16>(width);
subtex->height = static_cast<u16>(height);
// RGBA -> ABGR
for (u32 row = 0; row < subtex->width; row++) {
for (u32 col = 0; col < subtex->height; col++) {
u32 z = (row + col * subtex->width) * 4;
u8 r = *(u8 *)(buf + z);
u8 g = *(u8 *)(buf + z + 1);
u8 b = *(u8 *)(buf + z + 2);
u8 a = *(u8 *)(buf + z + 3);
*(buf + z) = a;
*(buf + z + 1) = b;
*(buf + z + 2) = g;
*(buf + z + 3) = r;
}
}
u32 w_pow2 = GetNextPowerOf2(subtex->width);
u32 h_pow2 = GetNextPowerOf2(subtex->height);
subtex->left = 0.f;
subtex->top = 1.f;
subtex->right = (subtex->width /static_cast<float>(w_pow2));
subtex->bottom = (1.0 - (subtex->height / static_cast<float>(h_pow2)));
C3D_TexInit(tex, static_cast<u16>(w_pow2), static_cast<u16>(h_pow2), GPU_RGBA8);
C3D_TexSetFilter(tex, GPU_NEAREST, GPU_NEAREST);
std::memset(tex->data, 0, tex->size);
for (u32 x = 0; x < subtex->width; x++) {
for (u32 y = 0; y < subtex->height; y++) {
u32 dst_pos = ((((y >> 3) * (w_pow2 >> 3) + (x >> 3)) << 6) + ((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) | ((y & 2) << 2) | ((x & 4) << 2) | ((y & 4) << 3))) * 4;
u32 src_pos = (y * subtex->width + x) * 4;
std::memcpy(&(static_cast<u8 *>(tex->data))[dst_pos], &(static_cast<u8 *>(buf))[src_pos], 4);
}
}
C3D_TexFlush(tex);
tex->border = RenderD7::Color::Hex("#000000", 0);
C3D_TexSetWrap(tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER);
if (tex && subtex) {
texture->tex = tex;
texture->subtex = subtex;
return true;
}
static bool C3DTexToC2DImage(C2D_Image *texture, u32 width, u32 height,
u8 *buf) {
if (width >= 1024 || height >= 1024)
return false;
C3D_Tex *tex = new C3D_Tex[sizeof(C3D_Tex)];
Tex3DS_SubTexture *subtex = new Tex3DS_SubTexture[sizeof(Tex3DS_SubTexture)];
subtex->width = static_cast<u16>(width);
subtex->height = static_cast<u16>(height);
// RGBA -> ABGR
for (u32 row = 0; row < subtex->width; row++) {
for (u32 col = 0; col < subtex->height; col++) {
u32 z = (row + col * subtex->width) * 4;
u8 r = *(u8 *)(buf + z);
u8 g = *(u8 *)(buf + z + 1);
u8 b = *(u8 *)(buf + z + 2);
u8 a = *(u8 *)(buf + z + 3);
*(buf + z) = a;
*(buf + z + 1) = b;
*(buf + z + 2) = g;
*(buf + z + 3) = r;
}
}
u32 w_pow2 = GetNextPowerOf2(subtex->width);
u32 h_pow2 = GetNextPowerOf2(subtex->height);
subtex->left = 0.f;
subtex->top = 1.f;
subtex->right = (subtex->width / static_cast<float>(w_pow2));
subtex->bottom = (1.0 - (subtex->height / static_cast<float>(h_pow2)));
C3D_TexInit(tex, static_cast<u16>(w_pow2), static_cast<u16>(h_pow2),
GPU_RGBA8);
C3D_TexSetFilter(tex, GPU_NEAREST, GPU_NEAREST);
std::memset(tex->data, 0, tex->size);
for (u32 x = 0; x < subtex->width; x++) {
for (u32 y = 0; y < subtex->height; y++) {
u32 dst_pos = ((((y >> 3) * (w_pow2 >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) |
((y & 2) << 2) | ((x & 4) << 2) | ((y & 4) << 3))) *
4;
u32 src_pos = (y * subtex->width + x) * 4;
std::memcpy(&(static_cast<u8 *>(tex->data))[dst_pos],
&(static_cast<u8 *>(buf))[src_pos], 4);
}
}
C3D_TexFlush(tex);
tex->border = RenderD7::Color::Hex("#000000", 0);
C3D_TexSetWrap(tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER);
if (tex && subtex) {
texture->tex = tex;
texture->subtex = subtex;
return true;
}
return false;
}
extern "C"
{
#include <renderd7/external/libnsbmp/libnsbmp.h>
extern "C" {
#include <renderd7/external/libnsbmp/libnsbmp.h>
}
static const u32 BYTES_PER_PIXEL = 4;
#define MAX_IMAGE_BYTES (48 * 1024 * 1024)
namespace LIBBMP {
static void *bitmap_create(int width, int height, [[maybe_unused]] unsigned int state) {
/* ensure a stupidly large (>50Megs or so) bitmap is not created */
if ((static_cast<long long>(width) * static_cast<long long>(height)) > (MAX_IMAGE_BYTES/BYTES_PER_PIXEL))
return nullptr;
return std::calloc(width * height, BYTES_PER_PIXEL);
static void *bitmap_create(int width, int height,
[[maybe_unused]] unsigned int state) {
/* ensure a stupidly large (>50Megs or so) bitmap is not created */
if ((static_cast<long long>(width) * static_cast<long long>(height)) >
(MAX_IMAGE_BYTES / BYTES_PER_PIXEL))
return nullptr;
return std::calloc(width * height, BYTES_PER_PIXEL);
}
static unsigned char *bitmap_get_buffer(void *bitmap) {
assert(bitmap);
return static_cast<unsigned char *>(bitmap);
}
static size_t bitmap_get_bpp([[maybe_unused]] void *bitmap) {
return BYTES_PER_PIXEL;
}
static void bitmap_destroy(void *bitmap) {
assert(bitmap);
std::free(bitmap);
}
} // namespace LIBBMP
unsigned Image_to_C3D(C2D_Image img, const std::vector<unsigned char> &bmpc) {
bmp_bitmap_callback_vt bitmap_callbacks = {
LIBBMP::bitmap_create, LIBBMP::bitmap_destroy, LIBBMP::bitmap_get_buffer,
LIBBMP::bitmap_get_bpp};
bmp_result code = BMP_OK;
bmp_image bmp;
bmp_create(&bmp, &bitmap_callbacks);
code = bmp_analyse(&bmp, bmpc.size(), (u8 *)bmpc.data());
if (code != BMP_OK) {
bmp_finalise(&bmp);
return 1;
}
code = bmp_decode(&bmp);
if (code != BMP_OK) {
if ((code != BMP_INSUFFICIENT_DATA) && (code != BMP_DATA_ERROR)) {
bmp_finalise(&bmp);
return 2;
}
static unsigned char *bitmap_get_buffer(void *bitmap) {
assert(bitmap);
return static_cast<unsigned char *>(bitmap);
/* skip if the decoded image would be ridiculously large */
if ((bmp.width * bmp.height) > 200000) {
bmp_finalise(&bmp);
return 3;
}
static size_t bitmap_get_bpp([[maybe_unused]] void *bitmap) {
return BYTES_PER_PIXEL;
}
C2D_Image *texture = new C2D_Image();
bool ret = C3DTexToC2DImage(texture, static_cast<u32>(bmp.width),
static_cast<u32>(bmp.height),
static_cast<u8 *>(bmp.bitmap));
bmp_finalise(&bmp);
delete texture;
if (!ret) {
return 4;
}
return 0;
}
void RenderD7::Image::LoadPng(const std::string path) {
if (usedbgmsg) {
// RenderD7::Msg::Display("RenderD7", "Loading Png:" + path, Top);
}
std::vector<u8> ImageBuffer;
unsigned width, height;
if (loadet) {
C3D_TexDelete(this->img.tex);
loadet = false;
}
lodepng::decode(ImageBuffer, width, height, path);
this->img.tex = new C3D_Tex;
this->img.subtex =
new Tex3DS_SubTexture({(u16)width, (u16)height, 0.0f, 1.0f,
width / 1024.0f, 1.0f - (height / 1024.0f)});
C3D_TexInit(this->img.tex, 1024, 1024, GPU_RGBA8);
C3D_TexSetFilter(this->img.tex, GPU_LINEAR, GPU_LINEAR);
this->img.tex->border = 0xFFFFFFFF;
C3D_TexSetWrap(this->img.tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER);
for (u32 x = 0; x < width && x < 1024; x++) {
for (u32 y = 0; y < height && y < 1024; y++) {
const u32 dstPos = ((((y >> 3) * (1024 >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) |
((y & 2) << 2) | ((x & 4) << 2) | ((y & 4) << 3))) *
4;
const u32 srcPos = (y * width + x) * 4;
((uint8_t *)this->img.tex->data)[dstPos + 0] =
ImageBuffer.data()[srcPos + 3];
((uint8_t *)this->img.tex->data)[dstPos + 1] =
ImageBuffer.data()[srcPos + 2];
((uint8_t *)this->img.tex->data)[dstPos + 2] =
ImageBuffer.data()[srcPos + 1];
((uint8_t *)this->img.tex->data)[dstPos + 3] =
ImageBuffer.data()[srcPos + 0];
}
static void bitmap_destroy(void *bitmap) {
assert(bitmap);
std::free(bitmap);
}
loadet = true;
}
RenderD7::Image::~Image() {
if (loadet)
C3D_TexDelete(img.tex);
loadet = false;
}
void RenderD7::Image::Unload() {
if (loadet)
C3D_TexDelete(img.tex);
loadet = false;
}
void RenderD7::Image::LoadPFromBuffer(const std::vector<u8> &buffer) {
std::vector<u8> ImageBuffer;
if (loadet) {
C3D_TexDelete(this->img.tex);
loadet = false;
}
unsigned width, height;
lodepng::decode(ImageBuffer, width, height, buffer);
img.tex = new C3D_Tex;
img.subtex =
new Tex3DS_SubTexture({(u16)width, (u16)height, 0.0f, 1.0f,
width / 512.0f, 1.0f - (height / 512.0f)});
C3D_TexInit(img.tex, 512, 512, GPU_RGBA8);
C3D_TexSetFilter(img.tex, GPU_LINEAR, GPU_LINEAR);
img.tex->border = 0xFFFFFFFF;
C3D_TexSetWrap(img.tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER);
for (u32 x = 0; x < width && x < 512; x++) {
for (u32 y = 0; y < height && y < 512; y++) {
const u32 dstPos = ((((y >> 3) * (512 >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) |
((y & 2) << 2) | ((x & 4) << 2) | ((y & 4) << 3))) *
4;
const u32 srcPos = (y * width + x) * 4;
((uint8_t *)img.tex->data)[dstPos + 0] = ImageBuffer.data()[srcPos + 3];
((uint8_t *)img.tex->data)[dstPos + 1] = ImageBuffer.data()[srcPos + 2];
((uint8_t *)img.tex->data)[dstPos + 2] = ImageBuffer.data()[srcPos + 1];
((uint8_t *)img.tex->data)[dstPos + 3] = ImageBuffer.data()[srcPos + 0];
}
}
}
void RenderD7::Image::FromSheet(RenderD7::Sheet sheet, size_t index) {}
unsigned Image_to_C3D(C2D_Image img, const std::vector<unsigned char>& bmpc) {
bmp_bitmap_callback_vt bitmap_callbacks = {
LIBBMP::bitmap_create,
LIBBMP::bitmap_destroy,
LIBBMP::bitmap_get_buffer,
LIBBMP::bitmap_get_bpp
};
bmp_result code = BMP_OK;
bmp_image bmp;
bmp_create(&bmp, &bitmap_callbacks);
code = bmp_analyse(&bmp, bmpc.size(), (u8*)bmpc.data());
if (code != BMP_OK) {
bmp_finalise(&bmp);
return 1;
}
code = bmp_decode(&bmp);
if (code != BMP_OK) {
if ((code != BMP_INSUFFICIENT_DATA) && (code != BMP_DATA_ERROR)) {
bmp_finalise(&bmp);
return 2;
}
/* skip if the decoded image would be ridiculously large */
if ((bmp.width * bmp.height) > 200000) {
bmp_finalise(&bmp);
return 3;
}
}
C2D_Image* texture = new C2D_Image();
bool ret = C3DTexToC2DImage(texture, static_cast<u32>(bmp.width), static_cast<u32>(bmp.height), static_cast<u8 *>(bmp.bitmap));
bmp_finalise(&bmp);
delete texture;
if (!ret)
{
return 4;
}
return 0;
bool RenderD7::Image::Draw(float x, float y, float scaleX, float scaleY) {
if (loadet)
return C2D_DrawImageAt(this->img, x, y, 0.5f, nullptr, scaleX, scaleY);
return false;
}
void RenderD7::Image::LoadPng(const std::string path)
{
if (usedbgmsg)
{
//RenderD7::Msg::Display("RenderD7", "Loading Png:" + path, Top);
}
std::vector<u8> ImageBuffer;
unsigned width, height;
if (loadet)
{
C3D_TexDelete(this->img.tex);
loadet = false;
}
lodepng::decode(ImageBuffer, width, height, path);
void RenderD7::Image::LoadFromBitmap(BMP bitmap) {
loadet = false;
unsigned error = Image_to_C3D(this->img, bitmap.DATA());
if (error == 0) {
this->loadet = true;
}
this->img.tex = new C3D_Tex;
this->img.subtex = new Tex3DS_SubTexture({(u16)width, (u16)height, 0.0f, 1.0f, width / 1024.0f, 1.0f - (height / 1024.0f)});
C3D_TexInit(this->img.tex, 1024, 1024, GPU_RGBA8);
C3D_TexSetFilter(this->img.tex, GPU_LINEAR, GPU_LINEAR);
this->img.tex->border = 0xFFFFFFFF;
C3D_TexSetWrap(this->img.tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER);
for (u32 x = 0; x < width && x < 1024; x++) {
for (u32 y = 0; y < height && y < 1024; y++) {
const u32 dstPos = ((((y >> 3) * (1024 >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) | ((y & 2) << 2) |
((x & 4) << 2) | ((y & 4) << 3))) * 4;
const u32 srcPos = (y * width + x) * 4;
((uint8_t *)this->img.tex->data)[dstPos + 0] = ImageBuffer.data()[srcPos + 3];
((uint8_t *)this->img.tex->data)[dstPos + 1] = ImageBuffer.data()[srcPos + 2];
((uint8_t *)this->img.tex->data)[dstPos + 2] = ImageBuffer.data()[srcPos + 1];
((uint8_t *)this->img.tex->data)[dstPos + 3] = ImageBuffer.data()[srcPos + 0];
}
}
loadet = true;
}
RenderD7::Image::~Image()
{
if(loadet) C3D_TexDelete(img.tex);
loadet = false;
}
void RenderD7::Image::Unload()
{
if(loadet) C3D_TexDelete(img.tex);
loadet = false;
}
void RenderD7::Image::LoadPFromBuffer(const std::vector<u8> &buffer)
{
std::vector<u8> ImageBuffer;
if (loadet)
{
C3D_TexDelete(this->img.tex);
loadet = false;
}
unsigned width, height;
lodepng::decode(ImageBuffer, width, height, buffer);
img.tex = new C3D_Tex;
img.subtex = new Tex3DS_SubTexture({(u16)width, (u16)height, 0.0f, 1.0f, width / 512.0f, 1.0f - (height / 512.0f)});
C3D_TexInit(img.tex, 512, 512, GPU_RGBA8);
C3D_TexSetFilter(img.tex, GPU_LINEAR, GPU_LINEAR);
img.tex->border = 0xFFFFFFFF;
C3D_TexSetWrap(img.tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER);
for (u32 x = 0; x < width && x < 512; x++) {
for (u32 y = 0; y < height && y < 512; y++) {
const u32 dstPos = ((((y >> 3) * (512 >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) | ((y & 2) << 2) |
((x & 4) << 2) | ((y & 4) << 3))) * 4;
const u32 srcPos = (y * width + x) * 4;
((uint8_t *)img.tex->data)[dstPos + 0] = ImageBuffer.data()[srcPos + 3];
((uint8_t *)img.tex->data)[dstPos + 1] = ImageBuffer.data()[srcPos + 2];
((uint8_t *)img.tex->data)[dstPos + 2] = ImageBuffer.data()[srcPos + 1];
((uint8_t *)img.tex->data)[dstPos + 3] = ImageBuffer.data()[srcPos + 0];
}
}
}
void RenderD7::Image::FromSheet(RenderD7::Sheet sheet, size_t index)
{
}
bool RenderD7::Image::Draw(float x, float y, float scaleX, float scaleY)
{
if(loadet) return C2D_DrawImageAt(this->img, x, y, 0.5f, nullptr, scaleX, scaleY);
return false;
}
void RenderD7::Image::LoadFromBitmap(BMP bitmap)
{
loadet = false;
unsigned error = Image_to_C3D(this->img, bitmap.DATA());
if (error == 0)
{
this->loadet = true;
}
if(error) {
if (error) {
std::cout << "BMP decoding error " << error << std::endl;
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>("Bmp - Error", "Code: " + std::to_string(error)));
RenderD7::AddOvl(std::make_unique<RenderD7::Toast>(
"Bmp - Error", "Code: " + std::to_string(error)));
}
}

View File

@ -1,76 +1,66 @@
#include <renderd7/Fonts/NFontApi.hpp>
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate
// implementation
#include <renderd7/external/stb_truetype.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <renderd7/external/stb_image_write.h>
RenderD7::NFontApi::NFontApi()
{
RenderD7::NFontApi::NFontApi() {}
RenderD7::NFontApi::~NFontApi() {}
void RenderD7::NFontApi::LoadTTF(std::string path) {
/////READ FILE
unsigned char *buffer;
long size = 0;
FILE *ttf__ = fopen(path.c_str(), "rb");
fseek(ttf__, 0, SEEK_END);
size = ftell(ttf__);
fseek(ttf__, 0, SEEK_SET);
buffer = (unsigned char *)malloc(size);
fread(buffer, size, 1, ttf__);
fclose(ttf__);
/////Setup Font
if (!stbtt_InitFont(&font, buffer, 0)) {
printf("failed\n");
status += "failed\n";
return;
}
status += "success!\n";
b_h = 128;
b_w = 512;
l_h = 24; /* line height */
scale = stbtt_ScaleForPixelHeight(&font, l_h);
stbtt_GetFontVMetrics(&font, &ascent, &decent, &linegap);
linespace = scale * (ascent - decent + linegap);
baseline = (int)(ascent * scale);
height = (int)((ascent - decent) * scale);
}
RenderD7::NFontApi::~NFontApi()
{
unsigned char *RenderD7::NFontApi::GetGlyphBitmap(char glyph) {
// stbtt_GetGlyphBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
stbtt_GetCodepointBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
w = x1 - x0;
h = y1 - y0;
unsigned char *bitmap;
bitmap = stbtt_GetCodepointBitmap(&font, scale, scale, glyph, &w, &h, 0, 0);
return bitmap;
}
void RenderD7::NFontApi::LoadTTF(std::string path)
{
/////READ FILE
unsigned char* buffer;
long size = 0;
FILE *ttf__ = fopen(path.c_str(), "rb");
fseek(ttf__, 0, SEEK_END);
size = ftell(ttf__);
fseek(ttf__, 0, SEEK_SET);
buffer = (unsigned char*)malloc(size);
fread(buffer, size, 1, ttf__);
fclose(ttf__);
/////Setup Font
if (!stbtt_InitFont(&font, buffer, 0))
{
printf("failed\n");
status+="failed\n";
return;
}
status+="success!\n";
b_h = 128;
b_w = 512;
l_h = 24; /* line height */
scale = stbtt_ScaleForPixelHeight(&font, l_h);
stbtt_GetFontVMetrics(&font, &ascent,&decent,&linegap);
linespace = scale * (ascent - decent + linegap);
baseline = (int) (ascent*scale);
height = (int) ((ascent - decent)*scale);
int RenderD7::NFontApi::GetGlyphHeight(char glyph) {
stbtt_GetCodepointBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
w = x1 - x0;
h = y1 - y0;
return h;
}
unsigned char* RenderD7::NFontApi::GetGlyphBitmap(char glyph)
{
//stbtt_GetGlyphBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
stbtt_GetCodepointBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
w = x1-x0;
h = y1-y0;
unsigned char* bitmap;
bitmap = stbtt_GetCodepointBitmap(&font, scale, scale, glyph, &w, &h, 0, 0);
return bitmap;
}
int RenderD7::NFontApi::GetGlyphHeight(char glyph)
{
stbtt_GetCodepointBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
w = x1-x0;
h = y1-y0;
return h;
}
int RenderD7::NFontApi::GetGlyphWidth(char glyph)
{
stbtt_GetCodepointBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
w = x1-x0;
h = y1-y0;
return w;
int RenderD7::NFontApi::GetGlyphWidth(char glyph) {
stbtt_GetCodepointBitmapBox(&font, glyph, scale, scale, &x0, &y0, &x1, &y1);
w = x1 - x0;
h = y1 - y0;
return w;
}

View File

@ -2,8 +2,7 @@
extern bool currentScreen;
void RenderD7::OnScreen(C3D_RenderTarget *target)
{
C2D_SceneBegin(target);
currentScreen = (target == Top || target == TopRight) ? 1 : 0;
void RenderD7::OnScreen(C3D_RenderTarget *target) {
C2D_SceneBegin(target);
currentScreen = (target == Top || target == TopRight) ? 1 : 0;
}

View File

@ -1,21 +1,15 @@
#include <renderd7/Sheet.hpp>
RenderD7::Sheet::Sheet()
{
//
RenderD7::Sheet::Sheet() {
//
}
RenderD7::Sheet::~Sheet()
{
//
RenderD7::Sheet::~Sheet() {
//
}
Result RenderD7::Sheet::Load(const char *path)
{
this->spritesheet = C2D_SpriteSheetLoad(path);
return 0;
Result RenderD7::Sheet::Load(const char *path) {
this->spritesheet = C2D_SpriteSheetLoad(path);
return 0;
}
void RenderD7::Sheet::Free()
{
C2D_SpriteSheetFree(this->spritesheet);
}
void RenderD7::Sheet::Free() { C2D_SpriteSheetFree(this->spritesheet); }

View File

@ -1,60 +1,36 @@
#include <renderd7/Sprite.hpp>
RenderD7::Sprite::Sprite()
{
//
RenderD7::Sprite::Sprite() {
//
}
RenderD7::Sprite::~Sprite()
{
//
RenderD7::Sprite::~Sprite() {
//
}
void RenderD7::Sprite::FromSheet(RenderD7::Sheet *sheet, size_t index)
{
C2D_SpriteFromSheet(&this->sprite, sheet->spritesheet, index);
void RenderD7::Sprite::FromSheet(RenderD7::Sheet *sheet, size_t index) {
C2D_SpriteFromSheet(&this->sprite, sheet->spritesheet, index);
}
bool RenderD7::Sprite::Draw()
{
return C2D_DrawSprite(&this->sprite);
bool RenderD7::Sprite::Draw() { return C2D_DrawSprite(&this->sprite); }
void RenderD7::Sprite::SetCenter(float x, float y) {
C2D_SpriteSetCenter(&this->sprite, x, y);
}
void RenderD7::Sprite::SetCenter(float x, float y)
{
C2D_SpriteSetCenter(&this->sprite, x, y);
void RenderD7::Sprite::SetPos(float x, float y) {
C2D_SpriteSetPos(&this->sprite, x, y);
}
void RenderD7::Sprite::SetPos(float x, float y)
{
C2D_SpriteSetPos(&this->sprite, x, y);
void RenderD7::Sprite::SetRotation(float rotation) {
C2D_SpriteSetRotation(&this->sprite, rotation);
}
void RenderD7::Sprite::SetRotation(float rotation)
{
C2D_SpriteSetRotation(&this->sprite, rotation);
void RenderD7::Sprite::Rotate(float speed) {
C2D_SpriteRotateDegrees(&this->sprite, speed);
}
void RenderD7::Sprite::Rotate(float speed)
{
C2D_SpriteRotateDegrees(&this->sprite, speed);
}
float RenderD7::Sprite::getHeigh()
{
return this->sprite.params.pos.h;
}
float RenderD7::Sprite::getWidth()
{
return this->sprite.params.pos.w;
}
float RenderD7::Sprite::getPosX()
{
return this->sprite.params.pos.x;
}
float RenderD7::Sprite::getPosY()
{
return this->sprite.params.pos.y;
float RenderD7::Sprite::getHeigh() { return this->sprite.params.pos.h; }
float RenderD7::Sprite::getWidth() { return this->sprite.params.pos.w; }
float RenderD7::Sprite::getPosX() { return this->sprite.params.pos.x; }
float RenderD7::Sprite::getPosY() { return this->sprite.params.pos.y; }
void RenderD7::Sprite::FromImage(RenderD7::Image *img) {
C2D_SpriteFromImage(&this->sprite, img->img);
}
void RenderD7::Sprite::FromImage(RenderD7::Image *img)
{
C2D_SpriteFromImage(&this->sprite, img->img);
}
void RenderD7::Sprite::SetScale(float x, float y)
{
C2D_SpriteScale(&this->sprite, x, y);
void RenderD7::Sprite::SetScale(float x, float y) {
C2D_SpriteScale(&this->sprite, x, y);
}

View File

@ -3,39 +3,36 @@
extern Log renderd7log;
RenderD7::SpriteSheetAnimation::SpriteSheetAnimation()
{
renderd7log.Write("SpriteSheetAnimation createt!");
RenderD7::SpriteSheetAnimation::SpriteSheetAnimation() {
renderd7log.Write("SpriteSheetAnimation createt!");
}
RenderD7::SpriteSheetAnimation::~SpriteSheetAnimation()
{
//
RenderD7::SpriteSheetAnimation::~SpriteSheetAnimation() {
//
}
void RenderD7::SpriteSheetAnimation::Setup(RenderD7::Sheet *sheet, size_t imagecount, size_t startimage, float frame_begin, float frame_finish)
{
D_totaltime = frame_begin;
renderd7log.Write("frame_begin success");
this->images = imagecount;
renderd7log.Write("imagecount success");
this->sheet = sheet;
renderd7log.Write("sheet success");
this->time = frame_finish;
renderd7log.Write("frame_finish success");
RenderD7::SpriteSheetAnimation::FromSheet(this->sheet, startimage);
void RenderD7::SpriteSheetAnimation::Setup(RenderD7::Sheet *sheet,
size_t imagecount, size_t startimage,
float frame_begin,
float frame_finish) {
D_totaltime = frame_begin;
renderd7log.Write("frame_begin success");
this->images = imagecount;
renderd7log.Write("imagecount success");
this->sheet = sheet;
renderd7log.Write("sheet success");
this->time = frame_finish;
renderd7log.Write("frame_finish success");
RenderD7::SpriteSheetAnimation::FromSheet(this->sheet, startimage);
}
void RenderD7::SpriteSheetAnimation::Play(float timespeed)
{
D_totaltime += timespeed;
if (D_totaltime >= time)
{
D_totaltime -= time;
imgs++;
if (imgs == images)
{
imgs = 0;
}
void RenderD7::SpriteSheetAnimation::Play(float timespeed) {
D_totaltime += timespeed;
if (D_totaltime >= time) {
D_totaltime -= time;
imgs++;
if (imgs == images) {
imgs = 0;
}
RenderD7::SpriteSheetAnimation::FromSheet(sheet, imgs);
//RenderD7::SpriteSheetAnimation::Draw();
}
RenderD7::SpriteSheetAnimation::FromSheet(sheet, imgs);
// RenderD7::SpriteSheetAnimation::Draw();
}

View File

@ -1,31 +1,30 @@
#include <renderd7/Time.hpp>
#include <memory>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <unistd.h>
#include <fstream>
#include <memory>
#include <renderd7/Time.hpp>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <time.h>
#include <unistd.h>
std::string RenderD7::FormatString(std::string fmt_str, ...)
{
va_list ap;
char* fp = NULL;
va_start(ap, fmt_str);
vasprintf(&fp, fmt_str.c_str(), ap);
va_end(ap);
std::unique_ptr<char, decltype(free)*> formatted(fp, free);
return std::string(formatted.get());
std::string RenderD7::FormatString(std::string fmt_str, ...) {
va_list ap;
char *fp = NULL;
va_start(ap, fmt_str);
vasprintf(&fp, fmt_str.c_str(), ap);
va_end(ap);
std::unique_ptr<char, decltype(free) *> formatted(fp, free);
return std::string(formatted.get());
}
std::string RenderD7::GetTimeStr(void)
{
time_t unixTime;
struct tm timeStruct;
time(&unixTime);
localtime_r(&unixTime, &timeStruct);
return FormatString("%04i-%02i-%02i_%02i-%02i-%02i", timeStruct.tm_year + 1900, timeStruct.tm_mon + 1, timeStruct.tm_mday,
timeStruct.tm_hour, timeStruct.tm_min, timeStruct.tm_sec);
std::string RenderD7::GetTimeStr(void) {
time_t unixTime;
struct tm timeStruct;
time(&unixTime);
localtime_r(&unixTime, &timeStruct);
return FormatString("%04i-%02i-%02i_%02i-%02i-%02i",
timeStruct.tm_year + 1900, timeStruct.tm_mon + 1,
timeStruct.tm_mday, timeStruct.tm_hour, timeStruct.tm_min,
timeStruct.tm_sec);
}

View File

@ -1,37 +1,38 @@
#include <renderd7/Toast.hpp>
#include <renderd7/Draw.hpp>
#include <renderd7/Toast.hpp>
RenderD7::Toast::Toast(std::string head, std::string msg)
{
this->head = head;
this->msg = msg;
/*this->toast = RenderD7::BitmapPrinter(400, 70);
this->toast.ClearBlank();
this->toast.DrawRectFilled(0, 0, 400, 70, 40, 40, 40, 255);
this->toast.DrawRectFilled(0, 0, 400, 25, 70, 70, 70, 255);
this->toast.DrawDebugText(4, 5, 0, RenderD7::Color::Hex("#ffffff"), this->head);
this->toast.DrawDebugText(4, 40, 0, RenderD7::Color::Hex("#ffffff"), this->msg);
this->toastrendered->LoadPFromBuffer(BitmapConverter::ConvertData(toast.GetBitmap().DATA()));*/
RenderD7::Toast::Toast(std::string head, std::string msg) {
this->head = head;
this->msg = msg;
/*this->toast = RenderD7::BitmapPrinter(400, 70);
this->toast.ClearBlank();
this->toast.DrawRectFilled(0, 0, 400, 70, 40, 40, 40, 255);
this->toast.DrawRectFilled(0, 0, 400, 25, 70, 70, 70, 255);
this->toast.DrawDebugText(4, 5, 0, RenderD7::Color::Hex("#ffffff"),
this->head); this->toast.DrawDebugText(4, 40, 0,
RenderD7::Color::Hex("#ffffff"), this->msg);
this->toastrendered->LoadPFromBuffer(BitmapConverter::ConvertData(toast.GetBitmap().DATA()));*/
}
void RenderD7::Toast::Draw(void) const
{
RenderD7::OnScreen(Top);
RenderD7::Draw::Rect(0, msgposy, 400, 70, RenderD7::Color::Hex("#111111"));
RenderD7::Draw::Rect(0, msgposy, 400, 25, RenderD7::Color::Hex("#222222"));
RenderD7::Draw::Text(2, msgposy+3, 0.7f, RenderD7::Color::Hex("#ffffff"), head);
RenderD7::Draw::Text(2, msgposy+30, 0.6f, RenderD7::Color::Hex("#ffffff"), msg);
//toastrendered->Draw(0, msgposy);
void RenderD7::Toast::Draw(void) const {
RenderD7::OnScreen(Top);
RenderD7::Draw::Rect(0, msgposy, 400, 70, RenderD7::Color::Hex("#111111"));
RenderD7::Draw::Rect(0, msgposy, 400, 25, RenderD7::Color::Hex("#222222"));
RenderD7::Draw::Text(2, msgposy + 3, 0.7f, RenderD7::Color::Hex("#ffffff"),
head);
RenderD7::Draw::Text(2, msgposy + 30, 0.6f, RenderD7::Color::Hex("#ffffff"),
msg);
// toastrendered->Draw(0, msgposy);
}
void RenderD7::Toast::Logic()
{
this->delay++/*=1*(int)RenderD7::GetDeltaTime()*/;
if (msgposy > 170 && delay < 2*60) msgposy--/*=(int)RenderD7::GetDeltaTime()*/;
if (delay >= 5*60)
{
msgposy++/*=(int)RenderD7::GetDeltaTime*/;
if(msgposy > 400) this->Kill();
}
void RenderD7::Toast::Logic() {
this->delay++ /*=1*(int)RenderD7::GetDeltaTime()*/;
if (msgposy > 170 && delay < 2 * 60)
msgposy-- /*=(int)RenderD7::GetDeltaTime()*/;
if (delay >= 5 * 60) {
msgposy++ /*=(int)RenderD7::GetDeltaTime*/;
if (msgposy > 400)
this->Kill();
}
}

View File

@ -1,29 +1,36 @@
#include <renderd7/bmpconverter.hpp>
namespace BitmapConverter{
namespace BitmapConverter {
//returns 0 if all went ok, non-0 if error
//output image is always given in RGBA (with alpha channel), even if it's a BMP without alpha channel
unsigned decodeBMP(std::vector<unsigned char>& image, unsigned& w, unsigned& h, const std::vector<unsigned char>& bmp) {
static const unsigned MINHEADER = 54; //minimum BMP header size
// returns 0 if all went ok, non-0 if error
// output image is always given in RGBA (with alpha channel), even if it's a BMP
// without alpha channel
unsigned decodeBMP(std::vector<unsigned char> &image, unsigned &w, unsigned &h,
const std::vector<unsigned char> &bmp) {
static const unsigned MINHEADER = 54; // minimum BMP header size
if(bmp.size() < MINHEADER) return -1;
if(bmp[0] != 'B' || bmp[1] != 'M') return 1; //It's not a BMP file if it doesn't start with marker 'BM'
unsigned pixeloffset = bmp[10] + 256 * bmp[11]; //where the pixel data starts
//read width and height from BMP header
if (bmp.size() < MINHEADER)
return -1;
if (bmp[0] != 'B' || bmp[1] != 'M')
return 1; // It's not a BMP file if it doesn't start with marker 'BM'
unsigned pixeloffset = bmp[10] + 256 * bmp[11]; // where the pixel data starts
// read width and height from BMP header
w = bmp[18] + bmp[19] * 256;
h = bmp[22] + bmp[23] * 256;
//read number of channels from BMP header
if(bmp[28] != 24 && bmp[28] != 32) return 2; //only 24-bit and 32-bit BMPs are supported.
// read number of channels from BMP header
if (bmp[28] != 24 && bmp[28] != 32)
return 2; // only 24-bit and 32-bit BMPs are supported.
unsigned numChannels = bmp[28] / 8;
//The amount of scanline bytes is width of image times channels, with extra bytes added if needed
//to make it a multiple of 4 bytes.
// The amount of scanline bytes is width of image times channels, with extra
// bytes added if needed to make it a multiple of 4 bytes.
unsigned scanlineBytes = w * numChannels;
if(scanlineBytes % 4 != 0) scanlineBytes = (scanlineBytes / 4) * 4 + 4;
if (scanlineBytes % 4 != 0)
scanlineBytes = (scanlineBytes / 4) * 4 + 4;
unsigned dataSize = scanlineBytes * h;
if(bmp.size() < dataSize + pixeloffset) return 3; //BMP file too small to contain all pixels
if (bmp.size() < dataSize + pixeloffset)
return 3; // BMP file too small to contain all pixels
image.resize(w * h * 4);
@ -34,24 +41,25 @@ unsigned decodeBMP(std::vector<unsigned char>& image, unsigned& w, unsigned& h,
-each scanline has padding bytes to make it a multiple of 4 if needed
The 2D for loop below does all these 3 conversions at once.
*/
for(unsigned y = 0; y < h; y++)
for(unsigned x = 0; x < w; x++) {
//pixel start byte position in the BMP
unsigned bmpos = pixeloffset + (h - y - 1) * scanlineBytes + numChannels * x;
//pixel start byte position in the new raw image
unsigned newpos = 4 * y * w + 4 * x;
if(numChannels == 3) {
image[newpos + 0] = bmp[bmpos + 2]; //R
image[newpos + 1] = bmp[bmpos + 1]; //G
image[newpos + 2] = bmp[bmpos + 0]; //B
image[newpos + 3] = 255; //A
} else {
image[newpos + 0] = bmp[bmpos + 2]; //R
image[newpos + 1] = bmp[bmpos + 1]; //G
image[newpos + 2] = bmp[bmpos + 0]; //B
image[newpos + 3] = bmp[bmpos + 3]; //A
for (unsigned y = 0; y < h; y++)
for (unsigned x = 0; x < w; x++) {
// pixel start byte position in the BMP
unsigned bmpos =
pixeloffset + (h - y - 1) * scanlineBytes + numChannels * x;
// pixel start byte position in the new raw image
unsigned newpos = 4 * y * w + 4 * x;
if (numChannels == 3) {
image[newpos + 0] = bmp[bmpos + 2]; // R
image[newpos + 1] = bmp[bmpos + 1]; // G
image[newpos + 2] = bmp[bmpos + 0]; // B
image[newpos + 3] = 255; // A
} else {
image[newpos + 0] = bmp[bmpos + 2]; // R
image[newpos + 1] = bmp[bmpos + 1]; // G
image[newpos + 2] = bmp[bmpos + 0]; // B
image[newpos + 3] = bmp[bmpos + 3]; // A
}
}
}
return 0;
}
@ -59,48 +67,44 @@ std::vector<unsigned char> ConvertFile(std::string filename) {
std::vector<unsigned char> bmp;
lodepng::load_file(bmp, filename);
std::vector<unsigned char> image;
unsigned w, h;
unsigned error = BitmapConverter::decodeBMP(image, w, h, bmp);
if(error) {
if (error) {
std::cout << "BMP decoding error " << error << std::endl;
}
std::vector<unsigned char> png;
error = lodepng::encode(png, image, w, h);
if(error) {
std::cout << "PNG encoding error " << error << ": " << lodepng_error_text(error) << std::endl;
if (error) {
std::cout << "PNG encoding error " << error << ": "
<< lodepng_error_text(error) << std::endl;
}
return png;
}
std::vector<unsigned char> ConvertData(std::vector<unsigned char> data) {
std::vector<unsigned char> image;
unsigned w, h;
unsigned error = BitmapConverter::decodeBMP(image, w, h, data);
if(error) {
if (error) {
std::cout << "BMP decoding error " << error << std::endl;
}
std::vector<unsigned char> png;
error = lodepng::encode(png, image, w, h);
if(error) {
std::cout << "PNG encoding error " << error << ": " << lodepng_error_text(error) << std::endl;
if (error) {
std::cout << "PNG encoding error " << error << ": "
<< lodepng_error_text(error) << std::endl;
}
return png;
}
}
} // namespace BitmapConverter

View File

@ -1,98 +1,97 @@
#include <3ds.h>
#include <renderd7/lang.hpp>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <3ds.h>
#include <unistd.h>
static nlohmann::json appJson;
std::string RenderD7::Lang::getSys()
{
u8 language = 1;
CFGU_GetSystemLanguage(&language);
std::string RenderD7::Lang::getSys() {
switch(language) {
case 0:
return "jp"; // Japanese
break;
u8 language = 1;
CFGU_GetSystemLanguage(&language);
case 1:
return "en"; // English
break;
switch (language) {
case 0:
return "jp"; // Japanese
break;
case 2:
return "fr"; // French
break;
case 1:
return "en"; // English
break;
case 3:
return "de"; // German
break;
case 2:
return "fr"; // French
break;
case 4:
return "it"; // Italian
break;
case 3:
return "de"; // German
break;
case 5:
return "es"; // Spanish
break;
case 4:
return "it"; // Italian
break;
case 6:
return "zh-CN"; // Chinese (Simplified)
break;
case 5:
return "es"; // Spanish
break;
// case 7:
// return "ko"; // Korean
// break;
case 6:
return "zh-CN"; // Chinese (Simplified)
break;
// case 8:
// return "nl"; // Dutch
// break;
// case 7:
// return "ko"; // Korean
// break;
case 9:
return "pt"; // Portuguese
break;
// case 8:
// return "nl"; // Dutch
// break;
case 10:
return "ru"; // Russian
break;
case 9:
return "pt"; // Portuguese
break;
case 11:
return "zh-TW"; // Chinese (Traditional)
break;
case 10:
return "ru"; // Russian
break;
default:
return "en"; // Fall back to English if missing
break;
}
case 11:
return "zh-TW"; // Chinese (Traditional)
break;
default:
return "en"; // Fall back to English if missing
break;
}
}
std::string RenderD7::Lang::get(const std::string &key) {
if (!appJson.contains(key)) return key;
if (!appJson.contains(key))
return key;
return appJson.at(key).get_ref<const std::string&>();
return appJson.at(key).get_ref<const std::string &>();
}
void RenderD7::Lang::load(const std::string &lang) {
FILE *values;
FILE *values;
if (access(("romfs:/lang/" + lang + "/app.json").c_str(), F_OK) == 0) {
values = fopen(("romfs:/lang/" + lang + "/app.json").c_str(), "rt");
if (values) {
appJson = nlohmann::json::parse(values, nullptr, false);
fclose(values);
}
if (appJson.is_discarded())
appJson = { };
return;
if (access(("romfs:/lang/" + lang + "/app.json").c_str(), F_OK) == 0) {
values = fopen(("romfs:/lang/" + lang + "/app.json").c_str(), "rt");
if (values) {
appJson = nlohmann::json::parse(values, nullptr, false);
fclose(values);
}
if (appJson.is_discarded())
appJson = {};
return;
} else {
values = fopen("romfs:/lang/en/app.json", "rt");
if (values) {
appJson = nlohmann::json::parse(values, nullptr, false);
fclose(values);
}
if (appJson.is_discarded())
appJson = { };
return;
}
} else {
values = fopen("romfs:/lang/en/app.json", "rt");
if (values) {
appJson = nlohmann::json::parse(values, nullptr, false);
fclose(values);
}
if (appJson.is_discarded())
appJson = {};
return;
}
}

View File

@ -2,62 +2,50 @@
#include <memory>
std::string Log::format(const std::string& fmt_str, ...)
{
va_list ap;
char* fp = NULL;
va_start(ap, fmt_str);
vasprintf(&fp, fmt_str.c_str(), ap);
va_end(ap);
std::unique_ptr<char, decltype(free)*> formatted(fp, free);
return std::string(formatted.get());
std::string Log::format(const std::string &fmt_str, ...) {
va_list ap;
char *fp = NULL;
va_start(ap, fmt_str);
vasprintf(&fp, fmt_str.c_str(), ap);
va_end(ap);
std::unique_ptr<char, decltype(free) *> formatted(fp, free);
return std::string(formatted.get());
}
std::string Log::logDate(void)
{
time_t unixTime;
struct tm timeStruct;
time(&unixTime);
localtime_r(&unixTime, &timeStruct);
return format("%04i-%02i-%02i_%02i-%02i-%02i", timeStruct.tm_year + 1900, timeStruct.tm_mon + 1, timeStruct.tm_mday,
timeStruct.tm_hour, timeStruct.tm_min, timeStruct.tm_sec);
std::string Log::logDate(void) {
time_t unixTime;
struct tm timeStruct;
time(&unixTime);
localtime_r(&unixTime, &timeStruct);
return format("%04i-%02i-%02i_%02i-%02i-%02i", timeStruct.tm_year + 1900,
timeStruct.tm_mon + 1, timeStruct.tm_mday, timeStruct.tm_hour,
timeStruct.tm_min, timeStruct.tm_sec);
}
Log::Log()
{
Log::Log() {}
void Log::Init(const char *filename) {
printf("%s\n", filename);
std::string fn = filename;
std::string name = fn + ".txt";
this->filename = name.c_str();
if ((access(name.c_str(), F_OK) == 0)) {
} else {
FILE *logfile = fopen((name.c_str()), "w");
fclose(logfile);
}
}
void Log::Init(const char *filename)
{
printf("%s\n", filename);
std::string fn = filename;
std::string name = fn + ".txt";
this->filename = name.c_str();
if ((access(name.c_str(), F_OK) == 0))
{
}
else
{
FILE* logfile = fopen((name.c_str()), "w");
fclose(logfile);
}
}
void Log::Write(std::string debug_text)
{
printf("%s\n", debug_text.c_str());
std::ofstream logFile;
logFile.open((this->filename), std::ofstream::app);
std::string writeDebug = "[";
writeDebug += logDate();
writeDebug += "] ";
writeDebug += debug_text.c_str();
logFile << writeDebug << std::endl;
logFile.close();
}
Log::~Log()
{
void Log::Write(std::string debug_text) {
printf("%s\n", debug_text.c_str());
std::ofstream logFile;
logFile.open((this->filename), std::ofstream::app);
std::string writeDebug = "[";
writeDebug += logDate();
writeDebug += "] ";
writeDebug += debug_text.c_str();
logFile << writeDebug << std::endl;
logFile.close();
}
Log::~Log() {}

File diff suppressed because it is too large Load Diff

View File

@ -10,121 +10,125 @@ using std::string;
// Reference: http://yannesposito.com/Scratch/en/blog/2010-10-14-Fun-with-wav/
typedef struct _WavHeader {
char magic[4]; // "RIFF"
u32 totallength; // Total file length, minus 8.
char wavefmt[8]; // Should be "WAVEfmt "
u32 format; // 16 for PCM format
u16 pcm; // 1 for PCM format
u16 channels; // Channels
u32 frequency; // Sampling frequency
u32 bytes_per_second;
u16 bytes_by_capture;
u16 bits_per_sample;
char data[4]; // "data"
u32 bytes_in_data;
char magic[4]; // "RIFF"
u32 totallength; // Total file length, minus 8.
char wavefmt[8]; // Should be "WAVEfmt "
u32 format; // 16 for PCM format
u16 pcm; // 1 for PCM format
u16 channels; // Channels
u32 frequency; // Sampling frequency
u32 bytes_per_second;
u16 bytes_by_capture;
u16 bits_per_sample;
char data[4]; // "data"
u32 bytes_in_data;
} WavHeader;
static_assert(sizeof(WavHeader) == 44, "WavHeader size is not 44 bytes.");
sound::sound(const string& path, int channel, bool toloop) {
if (isndspinit){
ndspSetOutputMode(NDSP_OUTPUT_STEREO);
ndspSetOutputCount(2); // Num of buffers
sound::sound(const string &path, int channel, bool toloop) {
if (isndspinit) {
ndspSetOutputMode(NDSP_OUTPUT_STEREO);
ndspSetOutputCount(2); // Num of buffers
// Reading wav file
FILE* fp = fopen(path.c_str(), "rb");
// Reading wav file
FILE *fp = fopen(path.c_str(), "rb");
if (!fp) {
printf("Could not open the WAV file: %s\n", path.c_str());
return;
}
if (!fp) {
printf("Could not open the WAV file: %s\n", path.c_str());
return;
}
WavHeader wavHeader;
size_t read = fread(&wavHeader, 1, sizeof(wavHeader), fp);
if (read != sizeof(wavHeader)) {
// Short read.
printf("WAV file header is too short: %s\n", path.c_str());
fclose(fp);
return;
}
WavHeader wavHeader;
size_t read = fread(&wavHeader, 1, sizeof(wavHeader), fp);
if (read != sizeof(wavHeader)) {
// Short read.
printf("WAV file header is too short: %s\n", path.c_str());
fclose(fp);
return;
}
// Verify the header.
static const char RIFF_magic[4] = {'R','I','F','F'};
if (memcmp(wavHeader.magic, RIFF_magic, sizeof(wavHeader.magic)) != 0) {
// Incorrect magic number.
printf("Wrong file format.\n");
fclose(fp);
return;
}
// Verify the header.
static const char RIFF_magic[4] = {'R', 'I', 'F', 'F'};
if (memcmp(wavHeader.magic, RIFF_magic, sizeof(wavHeader.magic)) != 0) {
// Incorrect magic number.
printf("Wrong file format.\n");
fclose(fp);
return;
}
if (wavHeader.totallength == 0 ||
(wavHeader.channels != 1 && wavHeader.channels != 2) ||
(wavHeader.bits_per_sample != 8 && wavHeader.bits_per_sample != 16)) {
// Unsupported WAV file.
printf("Corrupted wav file.\n");
fclose(fp);
return;
}
if (wavHeader.totallength == 0 ||
(wavHeader.channels != 1 && wavHeader.channels != 2) ||
(wavHeader.bits_per_sample != 8 && wavHeader.bits_per_sample != 16)) {
// Unsupported WAV file.
printf("Corrupted wav file.\n");
fclose(fp);
return;
}
// Get the file size.
fseek(fp, 0, SEEK_END);
dataSize = ftell(fp) - sizeof(wavHeader);
// Get the file size.
fseek(fp, 0, SEEK_END);
dataSize = ftell(fp) - sizeof(wavHeader);
// Allocating and reading samples
data = static_cast<u8*>(linearAlloc(dataSize));
fseek(fp, 44, SEEK_SET);
fread(data, 1, dataSize, fp);
fclose(fp);
dataSize /= 2; // FIXME: 16-bit or stereo?
// Allocating and reading samples
data = static_cast<u8 *>(linearAlloc(dataSize));
fseek(fp, 44, SEEK_SET);
fread(data, 1, dataSize, fp);
fclose(fp);
dataSize /= 2; // FIXME: 16-bit or stereo?
// Find the right format
u16 ndspFormat;
if (wavHeader.bits_per_sample == 8) {
ndspFormat = (wavHeader.channels == 1) ?
NDSP_FORMAT_MONO_PCM8 :
NDSP_FORMAT_STEREO_PCM8;
} else {
ndspFormat = (wavHeader.channels == 1) ?
NDSP_FORMAT_MONO_PCM16 :
NDSP_FORMAT_STEREO_PCM16;
}
// Find the right format
u16 ndspFormat;
if (wavHeader.bits_per_sample == 8) {
ndspFormat = (wavHeader.channels == 1) ? NDSP_FORMAT_MONO_PCM8
: NDSP_FORMAT_STEREO_PCM8;
} else {
ndspFormat = (wavHeader.channels == 1) ? NDSP_FORMAT_MONO_PCM16
: NDSP_FORMAT_STEREO_PCM16;
}
ndspChnReset(channel);
ndspChnSetInterp(channel, NDSP_INTERP_NONE);
ndspChnSetRate(channel, float(wavHeader.frequency));
ndspChnSetFormat(channel, ndspFormat);
ndspChnReset(channel);
ndspChnSetInterp(channel, NDSP_INTERP_NONE);
ndspChnSetRate(channel, float(wavHeader.frequency));
ndspChnSetFormat(channel, ndspFormat);
// Create and play a wav buffer
memset(&waveBuf, 0, sizeof(waveBuf));
// Create and play a wav buffer
memset(&waveBuf, 0, sizeof(waveBuf));
waveBuf.data_vaddr = reinterpret_cast<u32*>(data);
waveBuf.nsamples = dataSize / (wavHeader.bits_per_sample >> 3);
waveBuf.looping = toloop;
waveBuf.status = NDSP_WBUF_FREE;
chnl = channel;}
waveBuf.data_vaddr = reinterpret_cast<u32 *>(data);
waveBuf.nsamples = dataSize / (wavHeader.bits_per_sample >> 3);
waveBuf.looping = toloop;
waveBuf.status = NDSP_WBUF_FREE;
chnl = channel;
}
}
sound::~sound() {
if (isndspinit){
waveBuf.data_vaddr = 0;
waveBuf.nsamples = 0;
waveBuf.looping = false;
waveBuf.status = 0;
ndspChnWaveBufClear(chnl);
if (isndspinit) {
waveBuf.data_vaddr = 0;
waveBuf.nsamples = 0;
waveBuf.looping = false;
waveBuf.status = 0;
ndspChnWaveBufClear(chnl);
if (data) {
linearFree(data);
}}
if (data) {
linearFree(data);
}
}
}
void sound::play() {
if (isndspinit){
if (!data) return;
DSP_FlushDataCache(data, dataSize);
ndspChnWaveBufAdd(chnl, &waveBuf);}
if (isndspinit) {
if (!data)
return;
DSP_FlushDataCache(data, dataSize);
ndspChnWaveBufAdd(chnl, &waveBuf);
}
}
void sound::stop() {
if (isndspinit){
if (!data) return;
ndspChnWaveBufClear(chnl);}
if (isndspinit) {
if (!data)
return;
ndspChnWaveBufClear(chnl);
}
}

View File

@ -1,81 +1,79 @@
#include <renderd7/thread.hpp>
namespace RenderD7 {
void Threads::Exit()
{
}
Thread::Thread() :
m_started(false),
m_running(false) { /* do nothing */ }
Thread::Thread(std::function<void(RenderD7::Parameter)> t_function, RenderD7::Parameter t_parameter, bool t_autostart, bool t_detached, unsigned long long int t_stackSize) :
m_started(false),
m_running(false) {
initialize(t_function, t_parameter, t_autostart, t_detached, t_stackSize);
}
Thread::~Thread() {
join();
if (m_started) threadFree(m_thread);
}
void Thread::initialize(std::function<void(RenderD7::Parameter)> t_function, RenderD7::Parameter t_parameter, bool t_autostart, bool t_detached, unsigned long long int t_stackSize) {
m_stackSize = t_stackSize;
m_data.m_parameter = t_parameter;
m_data.m_function = t_function;
m_data.m_running = &m_running;
if (t_autostart) {
start(t_detached);
}
}
void Thread::setStackSize(unsigned long long int t_stackSize) {
m_stackSize = t_stackSize;
}
void Thread::start(bool t_detached) {
if (!m_running) {
m_started = true;
m_running = true;
s32 prio;
svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
m_thread = threadCreate(threadFunction, &m_data, m_stackSize, prio + 1, -2, t_detached);
}
}
void Thread::kill() {
threadDetach(m_thread);
m_running = false;
m_started = false;
}
void Thread::join(long long unsigned int t_timeout) {
if (m_running) {
threadJoin(m_thread, t_timeout);
threadFree(m_thread);
m_running = false;
m_started = false;
}
}
bool Thread::isRunning() {
return m_running;
}
void Thread::sleep() {
svcSleepThread(0);
}
void Thread::sleep(int t_milliseconds) {
svcSleepThread(1000000 * t_milliseconds);
}
// private methods
void Thread::threadFunction(void* arg) {
RenderD7::Thread::ThreadData data = *static_cast<RenderD7::Thread::ThreadData*>(arg);
data.m_function(data.m_parameter);
*data.m_running = false;
}
void Threads::Exit() {}
Thread::Thread() : m_started(false), m_running(false) { /* do nothing */
}
Thread::Thread(std::function<void(RenderD7::Parameter)> t_function,
RenderD7::Parameter t_parameter, bool t_autostart,
bool t_detached, unsigned long long int t_stackSize)
: m_started(false), m_running(false) {
initialize(t_function, t_parameter, t_autostart, t_detached, t_stackSize);
}
Thread::~Thread() {
join();
if (m_started)
threadFree(m_thread);
}
void Thread::initialize(std::function<void(RenderD7::Parameter)> t_function,
RenderD7::Parameter t_parameter, bool t_autostart,
bool t_detached, unsigned long long int t_stackSize) {
m_stackSize = t_stackSize;
m_data.m_parameter = t_parameter;
m_data.m_function = t_function;
m_data.m_running = &m_running;
if (t_autostart) {
start(t_detached);
}
}
void Thread::setStackSize(unsigned long long int t_stackSize) {
m_stackSize = t_stackSize;
}
void Thread::start(bool t_detached) {
if (!m_running) {
m_started = true;
m_running = true;
s32 prio;
svcGetThreadPriority(&prio, CUR_THREAD_HANDLE);
m_thread = threadCreate(threadFunction, &m_data, m_stackSize, prio + 1, -2,
t_detached);
}
}
void Thread::kill() {
threadDetach(m_thread);
m_running = false;
m_started = false;
}
void Thread::join(long long unsigned int t_timeout) {
if (m_running) {
threadJoin(m_thread, t_timeout);
threadFree(m_thread);
m_running = false;
m_started = false;
}
}
bool Thread::isRunning() { return m_running; }
void Thread::sleep() { svcSleepThread(0); }
void Thread::sleep(int t_milliseconds) {
svcSleepThread(1000000 * t_milliseconds);
}
// private methods
void Thread::threadFunction(void *arg) {
RenderD7::Thread::ThreadData data =
*static_cast<RenderD7::Thread::ThreadData *>(arg);
data.m_function(data.m_parameter);
*data.m_running = false;
}
} // namespace RenderD7