diff --git a/src/Bitmap.h b/src/Bitmap.h index 876139fe5..43c654f05 100644 --- a/src/Bitmap.h +++ b/src/Bitmap.h @@ -80,7 +80,7 @@ CC_API void Bitmap_Scale(struct Bitmap* dst, struct Bitmap* src, int srcX, int srcY, int srcWidth, int srcHeight); #define PNG_SIG_SIZE 8 -#if defined CC_BUILD_PSP || defined CC_BUILD_3DS +#if defined CC_BUILD_LOWMEM /* No point supporting > 1K x 1K bitmaps when system has less than 64 MB of RAM anyways */ #define PNG_MAX_DIMS 1024 #else diff --git a/src/Core.h b/src/Core.h index f9b2eb22e..13c08b0a9 100644 --- a/src/Core.h +++ b/src/Core.h @@ -117,9 +117,6 @@ typedef cc_uint8 cc_bool; #endif #endif -#define EXTENDED_BLOCKS -#define EXTENDED_TEXTURES - #define CC_BUILD_FREETYPE /*#define CC_BUILD_GL11*/ @@ -244,18 +241,29 @@ typedef cc_uint8 cc_bool; #define CC_BUILD_HTTPCLIENT #define CC_BUILD_OPENAL #define CC_BUILD_PSP +#define CC_BUILD_LOWMEM #undef CC_BUILD_FREETYPE -#undef EXTENDED_BLOCKS #elif defined __3DS__ #define CC_BUILD_HTTPCLIENT #define CC_BUILD_OPENAL #define CC_BUILD_3DS +#define CC_BUILD_LOWMEM +#undef CC_BUILD_FREETYPE +#elif defined GEKKO +#define CC_BUILD_HTTPCLIENT +#define CC_BUILD_OPENAL +#define CC_BUILD_GCWII +#define CC_BUILD_LOWMEM #undef CC_BUILD_FREETYPE -#undef EXTENDED_BLOCKS #endif #endif +#ifndef CC_BUILD_LOWMEM +#define EXTENDED_BLOCKS +#endif +#define EXTENDED_TEXTURES + #ifdef EXTENDED_BLOCKS typedef cc_uint16 BlockID; #else diff --git a/src/Graphics_GCWii.c b/src/Graphics_GCWii.c new file mode 100644 index 000000000..65249e382 --- /dev/null +++ b/src/Graphics_GCWii.c @@ -0,0 +1,719 @@ +#include "Core.h" + +#if defined CC_BUILD_GCWII + +#include "_GraphicsBase.h" + +#include "Errors.h" + +#include "Logger.h" + +#include "Window.h" + +#include +#include + +#include + + + +static void* fifo_buffer; + +#define FIFO_SIZE (256 * 1024) + +extern void* Window_XFB; + +static void* xfbs[2]; + +static int curFB; + + + + + +/*########################################################################################################################* + +*---------------------------------------------------------General---------------------------------------------------------* + +*#########################################################################################################################*/ + +static void InitGX(void) { + + GXRModeObj* mode = VIDEO_GetPreferredMode(NULL); + + fifo_buffer = MEM_K0_TO_K1(memalign(32, FIFO_SIZE)); + + memset(fifo_buffer, 0, FIFO_SIZE); + + + + GX_Init(fifo_buffer, FIFO_SIZE); + + GX_SetViewport(0, 0, mode->fbWidth, mode->efbHeight, 0, 1); + + GX_SetDispCopyYScale((f32)mode->xfbHeight / (f32)mode->efbHeight); + + GX_SetScissor(0, 0, mode->fbWidth, mode->efbHeight); + + GX_SetDispCopySrc(0, 0, mode->fbWidth, mode->efbHeight); + + GX_SetDispCopyDst(mode->fbWidth, mode->xfbHeight); + + GX_SetCopyFilter(mode->aa, mode->sample_pattern, + + GX_TRUE, mode->vfilter); + + GX_SetFieldMode(mode->field_rendering, + + ((mode->viHeight==2*mode->xfbHeight)?GX_ENABLE:GX_DISABLE)); + + + + GX_SetCullMode(GX_CULL_NONE); + + GX_SetDispCopyGamma(GX_GM_1_0); + GX_InvVtxCache(); + + + + xfbs[0] = Window_XFB; + + xfbs[1] = MEM_K0_TO_K1(SYS_AllocateFramebuffer(mode)); + +} + + + +static GfxResourceID white_square; + +void Gfx_Create(void) { + + Gfx.MaxTexWidth = 512; + + Gfx.MaxTexHeight = 512; + + Gfx.Created = true; + + + + InitGX(); + + InitDefaultResources(); + + // INITDFAULTRESOURCES causes stack overflow due to gfx_indices + + //Thread_Sleep(20 * 1000); + +} + + + +void Gfx_Free(void) { + + FreeDefaultResources(); + +} + + + +cc_bool Gfx_TryRestoreContext(void) { return true; } + +void Gfx_RestoreState(void) { } + +void Gfx_FreeState(void) { } + + + +/*########################################################################################################################* + +*---------------------------------------------------------Textures--------------------------------------------------------* + +*#########################################################################################################################*/ + +GfxResourceID Gfx_CreateTexture(struct Bitmap* bmp, cc_uint8 flags, cc_bool mipmaps) { + + return 0; + +} + + + +void Gfx_UpdateTexture(GfxResourceID texId, int x, int y, struct Bitmap* part, int rowWidth, cc_bool mipmaps) { + +} + + + +void Gfx_UpdateTexturePart(GfxResourceID texId, int x, int y, struct Bitmap* part, cc_bool mipmaps) { + +} + + + +void Gfx_DeleteTexture(GfxResourceID* texId) { + +} + + + +void Gfx_EnableMipmaps(void) { } + +void Gfx_DisableMipmaps(void) { } + + + +void Gfx_BindTexture(GfxResourceID texId) { + +} + + + + + +/*########################################################################################################################* + +*-----------------------------------------------------State management----------------------------------------------------* + +*#########################################################################################################################*/ + +static GXColor gfx_clearColor = { 0, 0, 0, 255 }; + +void Gfx_SetFaceCulling(cc_bool enabled) { } + +void Gfx_SetAlphaBlending(cc_bool enabled) { } + +void Gfx_SetAlphaArgBlend(cc_bool enabled) { } + + + +void Gfx_ClearCol(PackedCol color) { + + gfx_clearColor.r = PackedCol_R(color); + + gfx_clearColor.g = PackedCol_G(color); + + gfx_clearColor.b = PackedCol_B(color); + + + + GX_SetCopyClear(gfx_clearColor, 0x00ffffff); // TODO: use GX_MAX_Z24 + +} + + + +void Gfx_SetColWriteMask(cc_bool r, cc_bool g, cc_bool b, cc_bool a) { + +} + +static cc_bool depth_write = true, depth_test = true; +static void UpdateDepthState(void) { + // match Desktop behaviour, where disabling depth testing also disables depth writing + // TODO do we actually need to & here? + GX_SetZMode(depth_test, GX_LEQUAL, depth_write & depth_test); +} + + +void Gfx_SetDepthWrite(cc_bool enabled) { + depth_write = enabled; + UpdateDepthState(); + +} + + +void Gfx_SetDepthTest(cc_bool enabled) { + depth_test = enabled; + UpdateDepthState(); + +} + + + +/*########################################################################################################################* + +*---------------------------------------------------------Matrices--------------------------------------------------------* + +*#########################################################################################################################*/ + +void Gfx_CalcOrthoMatrix(struct Matrix* matrix, float width, float height, float zNear, float zFar) { + + // Transposed, source https://learn.microsoft.com/en-us/windows/win32/opengl/glortho + + // The simplified calculation below uses: L = 0, R = width, T = 0, B = height + + // NOTE: Shared with OpenGL. might be wrong to do that though? + + *matrix = Matrix_Identity; + + + + matrix->row1.X = 2.0f / width; + + matrix->row2.Y = -2.0f / height; + + matrix->row3.Z = -2.0f / (zFar - zNear); + + + + matrix->row4.X = -1.0f; + + matrix->row4.Y = 1.0f; + + matrix->row4.Z = -(zFar + zNear) / (zFar - zNear); + +} + + + +static double Cotangent(double x) { return Math_Cos(x) / Math_Sin(x); } + +void Gfx_CalcPerspectiveMatrix(struct Matrix* matrix, float fov, float aspect, float zFar) { + + float zNear = 0.1f; + + float c = (float)Cotangent(0.5f * fov); + + + + // Transposed, source https://learn.microsoft.com/en-us/windows/win32/opengl/glfrustum + + // For a FOV based perspective matrix, left/right/top/bottom are calculated as: + + // left = -c * aspect, right = c * aspect, bottom = -c, top = c + + // Calculations are simplified because of left/right and top/bottom symmetry + + *matrix = Matrix_Identity; + + + + matrix->row1.X = c / aspect; + + matrix->row2.Y = c; + + matrix->row3.Z = -(zFar + zNear) / (zFar - zNear); + + matrix->row3.W = -1.0f; + + matrix->row4.Z = -(2.0f * zFar * zNear) / (zFar - zNear); + + matrix->row4.W = 0.0f; + +} + + + + + +/*########################################################################################################################* + +*-----------------------------------------------------------Misc----------------------------------------------------------* + +*#########################################################################################################################*/ + +cc_result Gfx_TakeScreenshot(struct Stream* output) { + + return ERR_NOT_SUPPORTED; + +} + + + +void Gfx_GetApiInfo(cc_string* info) { + + int pointerSize = sizeof(void*) * 8; + + + + String_Format1(info, "-- Using GC/WII (%i bit) --\n", &pointerSize); + + String_Format2(info, "Max texture size: (%i, %i)\n", &Gfx.MaxTexWidth, &Gfx.MaxTexHeight); + +} + + + +void Gfx_SetFpsLimit(cc_bool vsync, float minFrameMs) { + + gfx_minFrameMs = minFrameMs; + + gfx_vsync = vsync; + +} + + + +void Gfx_BeginFrame(void) { + +} + + + +void Gfx_Clear(void) { + +} + + + +void Gfx_EndFrame(void) { + + curFB ^= 1; + + GX_CopyDisp(xfbs[curFB], GX_TRUE); + + GX_DrawDone(); + + + + VIDEO_SetNextFramebuffer(xfbs[curFB]); + + VIDEO_Flush(); + + VIDEO_WaitVSync(); + + if (gfx_minFrameMs) LimitFPS(); + +} + + + +void Gfx_OnWindowResize(void) { } + + + + + +static cc_uint8* gfx_vertices; + +/* Current format and size of vertices */ + +static int gfx_stride, gfx_format = -1, gfx_fields; + + + + + +/*########################################################################################################################* + +*----------------------------------------------------------Buffers--------------------------------------------------------* + +*#########################################################################################################################*/ + +GfxResourceID Gfx_CreateIb(void* indices, int indicesCount) { return 0; } + +void Gfx_BindIb(GfxResourceID ib) { } + +void Gfx_DeleteIb(GfxResourceID* ib) { } + +static int vb_size; + + + + + +GfxResourceID Gfx_CreateVb(VertexFormat fmt, int count) { + + void* data = memalign(16, count * strideSizes[fmt]); + + if (!data) Logger_Abort("Failed to allocate memory for GFX VB"); + + return data; + +} + + + +void Gfx_BindVb(GfxResourceID vb) { gfx_vertices = vb; } + + + +void Gfx_DeleteVb(GfxResourceID* vb) { + + GfxResourceID data = *vb; + + if (data) Mem_Free(data); + + *vb = 0; + +} + + + +void* Gfx_LockVb(GfxResourceID vb, VertexFormat fmt, int count) { + + vb_size = count * strideSizes[fmt]; + + return vb; + +} + + + +void Gfx_UnlockVb(GfxResourceID vb) { + + gfx_vertices = vb; + + //sceKernelDcacheWritebackInvalidateRange(vb, vb_size); + +} + + + + + +GfxResourceID Gfx_CreateDynamicVb(VertexFormat fmt, int maxVertices) { + + void* data = memalign(16, maxVertices * strideSizes[fmt]); + + if (!data) Logger_Abort("Failed to allocate memory for GFX VB"); + + return data; + +} + + + +void* Gfx_LockDynamicVb(GfxResourceID vb, VertexFormat fmt, int count) { + + vb_size = count * strideSizes[fmt]; + + return vb; + +} + + + +void Gfx_UnlockDynamicVb(GfxResourceID vb) { + + gfx_vertices = vb; + + //sceKernelDcacheWritebackInvalidateRange(vb, vb_size); + +} + + + +void Gfx_SetDynamicVbData(GfxResourceID vb, void* vertices, int vCount) { + + Mem_Copy(vb, vertices, vCount * gfx_stride); + + //sceKernelDcacheWritebackInvalidateRange(vertices, vCount * gfx_stride); + +} + + + + + +/*########################################################################################################################* + +*-----------------------------------------------------State management----------------------------------------------------* + +*#########################################################################################################################*/ + +static PackedCol gfx_fogColor; + +static float gfx_fogEnd = -1.0f, gfx_fogDensity = -1.0f; + +static int gfx_fogMode = -1; + + + +void Gfx_SetFog(cc_bool enabled) { + + gfx_fogEnabled = enabled; + +} + + + +void Gfx_SetFogCol(PackedCol color) { + + if (color == gfx_fogColor) return; + + gfx_fogColor = color; + +} + + + +void Gfx_SetFogDensity(float value) { + +} + + + +void Gfx_SetFogEnd(float value) { + + if (value == gfx_fogEnd) return; + + gfx_fogEnd = value; + +} + + + +void Gfx_SetFogMode(FogFunc func) { + +} + + + +void Gfx_SetAlphaTest(cc_bool enabled) { + +} + + + +void Gfx_DepthOnlyRendering(cc_bool depthOnly) { + //GX_SetColorUpdate(!depthOnly); + +} + + + + + +/*########################################################################################################################* + +*---------------------------------------------------------Matrices--------------------------------------------------------* + +*#########################################################################################################################*/ + +void Gfx_LoadMatrix(MatrixType type, const struct Matrix* matrix) { + if (type == MATRIX_PROJECTION) { + GX_LoadProjectionMtx(matrix, GX_PERSPECTIVE); + } else { + GX_LoadPosMtxImm(matrix, GX_PNMTX0); + } + +} + + + +void Gfx_LoadIdentityMatrix(MatrixType type) { + Gfx_LoadMatrix(type, &Matrix_Identity); + +} + + + +void Gfx_EnableTextureOffset(float x, float y) { + +} + + + +void Gfx_DisableTextureOffset(void) { + +} + + + + + + + +/*########################################################################################################################* + +*---------------------------------------------------------Drawing---------------------------------------------------------* + +*#########################################################################################################################*/ + +cc_bool Gfx_WarnIfNecessary(void) { return false; } + + + +void Gfx_SetVertexFormat(VertexFormat fmt) { + if (fmt == gfx_format) return; + gfx_format = fmt; + gfx_stride = strideSizes[fmt]; + + GX_ClearVtxDesc(); + if (fmt == VERTEX_FORMAT_TEXTURED) { + GX_SetVtxDesc(GX_VA_POS, GX_DIRECT); + GX_SetVtxDesc(GX_VA_CLR0, GX_DIRECT); + GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT); + + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0); + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0); + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0); + } else { + GX_SetVtxDesc(GX_VA_POS, GX_DIRECT); + GX_SetVtxDesc(GX_VA_CLR0, GX_DIRECT); + + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0); + GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_CLR0, GX_CLR_RGBA, GX_RGBA8, 0); + } + + + GX_SetNumChans(1); + GX_SetNumTexGens(0); + GX_SetTevOrder(GX_TEVSTAGE0, GX_TEXCOORDNULL, GX_TEXMAP_NULL, GX_COLOR0A0); + GX_SetTevOp(GX_TEVSTAGE0, GX_PASSCLR); + +} + + + +void Gfx_DrawVb_Lines(int verticesCount) { + +} + + +// TODO totally wrong, since should be using indexed drawing... +static void Draw_ColouredTriangles(int verticesCount, int startVertex) { + GX_Begin(GX_TRIANGLES, GX_VTXFMT0, verticesCount); + for (int i = startVertex; i < startVertex + verticesCount; i++) + { + struct VertexColoured* v = (struct VertexColoured*)gfx_vertices + i; + + GX_Position3f32(v->X, v->Y, v->Z); + GX_Color4u8(PackedCol_R(v->Col), PackedCol_G(v->Col), PackedCol_B(v->Col), PackedCol_A(v->Col)); + } + GX_End(); +} + +static void Draw_TexturedTriangles(int verticesCount, int startVertex) { + GX_Begin(GX_TRIANGLES, GX_VTXFMT0, verticesCount); + for (int i = startVertex; i < startVertex + verticesCount; i++) + { + struct VertexTextured* v = (struct VertexTextured*)gfx_vertices + i; + + GX_Position3f32(v->X, v->Y, v->Z); + GX_Color4u8(PackedCol_R(v->Col), PackedCol_G(v->Col), PackedCol_B(v->Col), PackedCol_A(v->Col)); + GX_TexCoord2f32(v->U, v->V); + } + GX_End(); +} + + + +void Gfx_DrawVb_IndexedTris_Range(int verticesCount, int startVertex) { + if (gfx_format == VERTEX_FORMAT_TEXTURED) { + Draw_TexturedTriangles(verticesCount, startVertex); + } else { + Draw_ColouredTriangles(verticesCount, startVertex); + } + +} + + + +void Gfx_DrawVb_IndexedTris(int verticesCount) { + if (gfx_format == VERTEX_FORMAT_TEXTURED) { + Draw_TexturedTriangles(verticesCount, 0); + } else { + Draw_ColouredTriangles(verticesCount, 0); + } + +} + + + +void Gfx_DrawIndexedTris_T2fC4b(int verticesCount, int startVertex) { + Draw_TexturedTriangles(verticesCount, startVertex); + +} + +#endif \ No newline at end of file diff --git a/src/Platform_GCWii.c b/src/Platform_GCWii.c new file mode 100644 index 000000000..e82002c5d --- /dev/null +++ b/src/Platform_GCWii.c @@ -0,0 +1,633 @@ +#include "Core.h" +#if defined CC_BUILD_GCWII +#include "_PlatformBase.h" +#include "Stream.h" +#include "ExtMath.h" +#include "Funcs.h" +#include "Window.h" +#include "Utils.h" +#include "Errors.h" +#include "PackedCol.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const cc_result ReturnCode_FileShareViolation = 1000000000; /* TODO: not used apparently */ +const cc_result ReturnCode_FileNotFound = ENOENT; +const cc_result ReturnCode_SocketInProgess = EINPROGRESS; +const cc_result ReturnCode_SocketWouldBlock = EWOULDBLOCK; +const cc_result ReturnCode_DirectoryExists = EEXIST; + + +/*########################################################################################################################* +*---------------------------------------------------------Memory----------------------------------------------------------* +*#########################################################################################################################*/ +void Mem_Set(void* dst, cc_uint8 value, cc_uint32 numBytes) { memset(dst, value, numBytes); } +void Mem_Copy(void* dst, const void* src, cc_uint32 numBytes) { memcpy(dst, src, numBytes); } + +void* Mem_TryAlloc(cc_uint32 numElems, cc_uint32 elemsSize) { + cc_uint32 size = CalcMemSize(numElems, elemsSize); + return size ? malloc(size) : NULL; +} + +void* Mem_TryAllocCleared(cc_uint32 numElems, cc_uint32 elemsSize) { + return calloc(numElems, elemsSize); +} + +void* Mem_TryRealloc(void* mem, cc_uint32 numElems, cc_uint32 elemsSize) { + cc_uint32 size = CalcMemSize(numElems, elemsSize); + return size ? realloc(mem, size) : NULL; +} + +void Mem_Free(void* mem) { + if (mem) free(mem); +} + + +/*########################################################################################################################* +*------------------------------------------------------Logging/Time-------------------------------------------------------* +*#########################################################################################################################*/ +void Platform_Log(const char* msg, int len) { + write(STDOUT_FILENO, msg, len); + write(STDOUT_FILENO, "\n", 1); +} + +#define UnixTime_TotalMS(time) ((cc_uint64)time.tv_sec * 1000 + UNIX_EPOCH + (time.tv_usec / 1000)) +TimeMS DateTime_CurrentUTC_MS(void) { + struct timeval cur; + gettimeofday(&cur, NULL); + return UnixTime_TotalMS(cur); +} + +void DateTime_CurrentLocal(struct DateTime* t) { + struct timeval cur; + struct tm loc_time; + gettimeofday(&cur, NULL); + localtime_r(&cur.tv_sec, &loc_time); + + t->year = loc_time.tm_year + 1900; + t->month = loc_time.tm_mon + 1; + t->day = loc_time.tm_mday; + t->hour = loc_time.tm_hour; + t->minute = loc_time.tm_min; + t->second = loc_time.tm_sec; +} + +cc_uint64 Stopwatch_Measure(void) { + return gettime(); +} + +cc_uint64 Stopwatch_ElapsedMicroseconds(cc_uint64 beg, cc_uint64 end) { + if (end < beg) return 0; + return ticks_to_microsecs(end - beg); +} + + +/*########################################################################################################################* +*-----------------------------------------------------Directory/File------------------------------------------------------* +*#########################################################################################################################*/ +void Directory_GetCachePath(cc_string* path) { } + +static void GetNativePath(char* str, const cc_string* path) { + static const char root_path[16] = "sd:/ClassiCube/"; + Mem_Copy(str, root_path, sizeof(root_path)); + str += sizeof(root_path); + String_EncodeUtf8(str, path); +} + +cc_result Directory_Create(const cc_string* path) { + return 1; +} +int File_Exists(const cc_string* path) { + return 0; +} + +cc_result Directory_Enum(const cc_string* dirPath, void* obj, Directory_EnumCallback callback) { + return 1; +} + +cc_result File_Open(cc_file* file, const cc_string* path) { + return 1; +} +cc_result File_Create(cc_file* file, const cc_string* path) { + return 1; +} +cc_result File_OpenOrCreate(cc_file* file, const cc_string* path) { + return 1; +} + +cc_result File_Read(cc_file file, void* data, cc_uint32 count, cc_uint32* bytesRead) { + *bytesRead = read(file, data, count); + return 1; +} + +cc_result File_Write(cc_file file, const void* data, cc_uint32 count, cc_uint32* bytesWrote) { + return 1; +} + +cc_result File_Close(cc_file file) { + return 1; +} + +cc_result File_Seek(cc_file file, int offset, int seekType) { + return 1; +} + +cc_result File_Position(cc_file file, cc_uint32* pos) { + return 1; +} + +cc_result File_Length(cc_file file, cc_uint32* len) { + return 1; +} + +/* +cc_result Directory_Create(const cc_string* path) { + char str[NATIVE_STR_LEN]; + String_EncodeUtf8(str, path); + // read/write/search permissions for owner and group, and with read/search permissions for others. + // TODO: Is the default mode in all cases + + return mkdir(str, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1 ? errno : 0; +} + +int File_Exists(const cc_string* path) { + char str[NATIVE_STR_LEN]; + struct stat sb; + String_EncodeUtf8(str, path); + return stat(str, &sb) == 0 && S_ISREG(sb.st_mode); +} + +cc_result Directory_Enum(const cc_string* dirPath, void* obj, Directory_EnumCallback callback) { + cc_string path; char pathBuffer[FILENAME_SIZE]; + char str[NATIVE_STR_LEN]; + DIR* dirPtr; + struct dirent* entry; + char* src; + int len, res, is_dir; + + String_EncodeUtf8(str, dirPath); + dirPtr = opendir(str); + if (!dirPtr) return errno; + + // POSIX docs: "When the end of the directory is encountered, a null pointer is returned and errno is not changed." + // errno is sometimes leftover from previous calls, so always reset it before readdir gets called + errno = 0; + String_InitArray(path, pathBuffer); + + while ((entry = readdir(dirPtr))) { + path.length = 0; + String_Format1(&path, "%s/", dirPath); + + // ignore . and .. entry + src = entry->d_name; + if (src[0] == '.' && src[1] == '\0') continue; + if (src[0] == '.' && src[1] == '.' && src[2] == '\0') continue; + + len = String_Length(src); + String_AppendUtf8(&path, src, len); + +#if defined CC_BUILD_HAIKU || defined CC_BUILD_SOLARIS || defined CC_BUILD_IRIX + { + char full_path[NATIVE_STR_LEN]; + struct stat sb; + String_EncodeUtf8(full_path, &path); + is_dir = stat(full_path, &sb) == 0 && S_ISDIR(sb.st_mode); + } +#else + is_dir = entry->d_type == DT_DIR; + // TODO: fallback to stat when this fails +#endif + + if (is_dir) { + res = Directory_Enum(&path, obj, callback); + if (res) { closedir(dirPtr); return res; } + } else { + callback(&path, obj); + } + errno = 0; + } + + res = errno; // return code from readdir + closedir(dirPtr); + return res; +} + +static cc_result File_Do(cc_file* file, const cc_string* path, int mode) { + char str[NATIVE_STR_LEN]; + String_EncodeUtf8(str, path); + *file = open(str, mode, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + return *file == -1 ? errno : 0; +} + +cc_result File_Open(cc_file* file, const cc_string* path) { + return File_Do(file, path, O_RDONLY); +} +cc_result File_Create(cc_file* file, const cc_string* path) { + return File_Do(file, path, O_RDWR | O_CREAT | O_TRUNC); +} +cc_result File_OpenOrCreate(cc_file* file, const cc_string* path) { + return File_Do(file, path, O_RDWR | O_CREAT); +} + +cc_result File_Read(cc_file file, void* data, cc_uint32 count, cc_uint32* bytesRead) { + *bytesRead = read(file, data, count); + return *bytesRead == -1 ? errno : 0; +} + +cc_result File_Write(cc_file file, const void* data, cc_uint32 count, cc_uint32* bytesWrote) { + *bytesWrote = write(file, data, count); + return *bytesWrote == -1 ? errno : 0; +} + +cc_result File_Close(cc_file file) { + return close(file) == -1 ? errno : 0; +} + +cc_result File_Seek(cc_file file, int offset, int seekType) { + static cc_uint8 modes[3] = { SEEK_SET, SEEK_CUR, SEEK_END }; + return lseek(file, offset, modes[seekType]) == -1 ? errno : 0; +} + +cc_result File_Position(cc_file file, cc_uint32* pos) { + *pos = lseek(file, 0, SEEK_CUR); + return *pos == -1 ? errno : 0; +} + +cc_result File_Length(cc_file file, cc_uint32* len) { + struct stat st; + if (fstat(file, &st) == -1) { *len = -1; return errno; } + *len = st.st_size; return 0; +}*/ + + +/*########################################################################################################################* +*--------------------------------------------------------Threading--------------------------------------------------------* +*#########################################################################################################################*/ +void Thread_Sleep(cc_uint32 milliseconds) { usleep(milliseconds * 1000); } + +static void* ExecThread(void* param) { + ((Thread_StartFunc)param)(); + return NULL; +} + +void* Thread_Create(Thread_StartFunc func) { + return Mem_Alloc(1, sizeof(lwp_t), "thread"); +} + +void Thread_Start2(void* handle, Thread_StartFunc func) { + lwp_t* ptr = (lwp_t*)handle; + int res = LWP_CreateThread(ptr, ExecThread, (void*)func, NULL, 256 * 1024, 80); + if (res) Logger_Abort2(res, "Creating thread"); +} + +void Thread_Detach(void* handle) { + // TODO: Leaks return value of thread ??? + lwp_t* ptr = (lwp_t*)handle;; + Mem_Free(ptr); +} + +void Thread_Join(void* handle) { + lwp_t* ptr = (lwp_t*)handle; + int res = LWP_JoinThread(*ptr, NULL); + if (res) Logger_Abort2(res, "Joining thread"); + Mem_Free(ptr); +} + +void* Mutex_Create(void) { + mutex_t* ptr = (mutex_t*)Mem_Alloc(1, sizeof(mutex_t), "mutex"); + int res = LWP_MutexInit(ptr, false); + if (res) Logger_Abort2(res, "Creating mutex"); + return ptr; +} + +void Mutex_Free(void* handle) { + mutex_t* mutex = (mutex_t*)handle; + int res = LWP_MutexDestroy(*mutex); + if (res) Logger_Abort2(res, "Destroying mutex"); + Mem_Free(handle); +} + +void Mutex_Lock(void* handle) { + mutex_t* mutex = (mutex_t*)handle; + int res = LWP_MutexLock(*mutex); + if (res) Logger_Abort2(res, "Locking mutex"); +} + +void Mutex_Unlock(void* handle) { + mutex_t* mutex = (mutex_t*)handle; + int res = LWP_MutexUnlock(*mutex); + if (res) Logger_Abort2(res, "Unlocking mutex"); +} + +// should really use a semaphore with max 1.. too bad no 'TimedWait' though +struct WaitData { + cond_t cond; + mutex_t mutex; + int signalled; // For when Waitable_Signal is called before Waitable_Wait +}; + +void* Waitable_Create(void) { + struct WaitData* ptr = (struct WaitData*)Mem_Alloc(1, sizeof(struct WaitData), "waitable"); + int res; + + res = LWP_CondInit(&ptr->cond); + if (res) Logger_Abort2(res, "Creating waitable"); + res = LWP_MutexInit(&ptr->mutex, false); + if (res) Logger_Abort2(res, "Creating waitable mutex"); + + ptr->signalled = false; + return ptr; +} + +void Waitable_Free(void* handle) { + struct WaitData* ptr = (struct WaitData*)handle; + int res; + + res = LWP_CondDestroy(ptr->cond); + if (res) Logger_Abort2(res, "Destroying waitable"); + res = LWP_MutexDestroy(ptr->mutex); + if (res) Logger_Abort2(res, "Destroying waitable mutex"); + Mem_Free(handle); +} + +void Waitable_Signal(void* handle) { + struct WaitData* ptr = (struct WaitData*)handle; + int res; + + Mutex_Lock(&ptr->mutex); + ptr->signalled = true; + Mutex_Unlock(&ptr->mutex); + + res = LWP_CondSignal(ptr->cond); + if (res) Logger_Abort2(res, "Signalling event"); +} + +void Waitable_Wait(void* handle) { + struct WaitData* ptr = (struct WaitData*)handle; + int res; + + Mutex_Lock(&ptr->mutex); + if (!ptr->signalled) { + res = LWP_CondWait(ptr->cond, ptr->mutex); + if (res) Logger_Abort2(res, "Waitable wait"); + } + ptr->signalled = false; + Mutex_Unlock(&ptr->mutex); +} + +void Waitable_WaitFor(void* handle, cc_uint32 milliseconds) { + struct WaitData* ptr = (struct WaitData*)handle; + struct timespec ts; + int res; + + ts.tv_sec = milliseconds / 1000; + ts.tv_nsec = milliseconds % 1000; + + Mutex_Lock(&ptr->mutex); + if (!ptr->signalled) { + res = LWP_CondTimedWait(ptr->cond, ptr->mutex, &ts); + if (res && res != ETIMEDOUT) Logger_Abort2(res, "Waitable wait for"); + } + ptr->signalled = false; + Mutex_Unlock(&ptr->mutex); +} + + +/*########################################################################################################################* +*--------------------------------------------------------Font/Text--------------------------------------------------------* +*#########################################################################################################################*/ +void Platform_LoadSysFonts(void) { } + + +/*########################################################################################################################* +*---------------------------------------------------------Socket----------------------------------------------------------* +*#########################################################################################################################*/ +union SocketAddress { + struct sockaddr raw; + struct sockaddr_in v4; +}; + +static int ParseHost(union SocketAddress* addr, const char* host) { + struct hostent* res = net_gethostbyname(host); + + if (!res || res->h_addrtype != AF_INET) return false; + // Must have at least one IPv4 address + if (!res->h_addr_list[0]) return false; + + addr->v4.sin_addr = *(struct in_addr*)res->h_addr_list[0]; + return true; +} + +static int ParseAddress(union SocketAddress* addr, const cc_string* address) { + char str[NATIVE_STR_LEN]; + String_EncodeUtf8(str, address); + + if (inet_aton(str, &addr->v4.sin_addr) > 0) return true; + return ParseHost(addr, str); +} + +int Socket_ValidAddress(const cc_string* address) { + union SocketAddress addr; + return ParseAddress(&addr, address); +} + +cc_result Socket_Connect(cc_socket* s, const cc_string* address, int port, cc_bool nonblocking) { + union SocketAddress addr; + cc_result res; + + *s = -1; + if (!ParseAddress(&addr, address)) return ERR_INVALID_ARGUMENT; + + *s = net_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (*s == -1) return errno; + + if (nonblocking) { + int blocking_raw = -1; /* non-blocking mode */ + net_ioctl(*s, FIONBIO, &blocking_raw); + } + + addr.v4.sin_family = AF_INET; + addr.v4.sin_port = htons(port); + + res = net_connect(*s, &addr.raw, sizeof(addr.v4)); + return res == -1 ? errno : 0; +} + +cc_result Socket_Read(cc_socket s, cc_uint8* data, cc_uint32 count, cc_uint32* modified) { + int recvCount = net_recv(s, data, count, 0); + if (recvCount != -1) { *modified = recvCount; return 0; } + *modified = 0; return errno; +} + +cc_result Socket_Write(cc_socket s, const cc_uint8* data, cc_uint32 count, cc_uint32* modified) { + int sentCount = net_send(s, data, count, 0); + if (sentCount != -1) { *modified = sentCount; return 0; } + *modified = 0; return errno; +} + +void Socket_Close(cc_socket s) { + net_shutdown(s, 2); // SHUT_RDWR = 2 + net_close(s); +} + +static cc_result Socket_Poll(cc_socket s, int mode, cc_bool* success) { + struct pollsd pfd; + int flags; + + pfd.socket = s; + pfd.events = mode == SOCKET_POLL_READ ? POLLIN : POLLOUT; + if (net_poll(&pfd, 1, 0) == -1) { *success = false; return errno; } + + /* to match select, closed socket still counts as readable */ + flags = mode == SOCKET_POLL_READ ? (POLLIN | POLLHUP) : POLLOUT; + *success = (pfd.revents & flags) != 0; + return 0; +} + +cc_result Socket_CheckReadable(cc_socket s, cc_bool* readable) { + return Socket_Poll(s, SOCKET_POLL_READ, readable); +} + +cc_result Socket_CheckWritable(cc_socket s, cc_bool* writable) { + u32 resultSize = sizeof(u32); + cc_result res = Socket_Poll(s, SOCKET_POLL_WRITE, writable); + if (res || *writable) return res; + + return 0; + // TODO FIX with updated devkitpro ??? + + /* https://stackoverflow.com/questions/29479953/so-error-value-after-successful-socket-operation */ + net_getsockopt(s, SOL_SOCKET, SO_ERROR, &res, resultSize); + return res; +} + + +/*########################################################################################################################* +*-----------------------------------------------------Process/Module------------------------------------------------------* +*#########################################################################################################################*/ +cc_result Process_StartGame2(const cc_string* args, int numArgs) { + return ERR_NOT_SUPPORTED; +} + +void Process_Exit(cc_result code) { exit(code); } + +cc_result Process_StartOpen(const cc_string* args) { + // TODO launch browser + return ERR_NOT_SUPPORTED; +} + + +/*########################################################################################################################* +*--------------------------------------------------------Updater----------------------------------------------------------* +*#########################################################################################################################*/ +const char* const Updater_D3D9 = NULL; +cc_bool Updater_Clean(void) { return true; } + +const struct UpdaterInfo Updater_Info = { "&eCompile latest source code to update", 0 }; + +cc_result Updater_Start(const char** action) { + *action = "Starting game"; + return ERR_NOT_SUPPORTED; +} + +cc_result Updater_GetBuildTime(cc_uint64* timestamp) { + return ERR_NOT_SUPPORTED; +} + +cc_result Updater_MarkExecutable(void) { + return ERR_NOT_SUPPORTED; +} + +cc_result Updater_SetNewBuildTime(cc_uint64 timestamp) { + return ERR_NOT_SUPPORTED; +} + + +/*########################################################################################################################* +*-------------------------------------------------------Dynamic lib-------------------------------------------------------* +*#########################################################################################################################*/ +/* TODO can this actually be supported somehow */ +const cc_string DynamicLib_Ext = String_FromConst(".so"); + +void* DynamicLib_Load2(const cc_string* path) { return NULL; } +void* DynamicLib_Get2(void* lib, const char* name) { return NULL; } + +cc_bool DynamicLib_DescribeError(cc_string* dst) { + String_AppendConst(dst, "Dynamic linking unsupported"); + return true; +} + + +/*########################################################################################################################* +*--------------------------------------------------------Platform---------------------------------------------------------* +*#########################################################################################################################*/ +void Platform_Init(void) { + //fatInitDefault(); + net_init(); +} +void Platform_Free(void) { } + +cc_bool Platform_DescribeError(cc_result res, cc_string* dst) { + char chars[NATIVE_STR_LEN]; + int len; + + /* For unrecognised error codes, strerror_r might return messages */ + /* such as 'No error information', which is not very useful */ + /* (could check errno here but quicker just to skip entirely) */ + if (res >= 1000) return false; + + len = strerror_r(res, chars, NATIVE_STR_LEN); + if (len == -1) return false; + + len = String_CalcLen(chars, NATIVE_STR_LEN); + String_AppendUtf8(dst, chars, len); + return true; +} + + +/*########################################################################################################################* +*-------------------------------------------------------Encryption--------------------------------------------------------* +*#########################################################################################################################*/ +cc_result Platform_Encrypt(const void* data, int len, cc_string* dst) { + return ERR_NOT_SUPPORTED; +} +cc_result Platform_Decrypt(const void* data, int len, cc_string* dst) { + return ERR_NOT_SUPPORTED; +} + + +/*########################################################################################################################* +*-----------------------------------------------------Configuration-------------------------------------------------------* +*#########################################################################################################################*/ +int Platform_GetCommandLineArgs(int argc, STRING_REF char** argv, cc_string* args) { + int i, count; + argc--; argv++; /* skip executable path argument */ + + count = min(argc, GAME_MAX_CMDARGS); + for (i = 0; i < count; i++) { + args[i] = String_FromReadonly(argv[i]); + } + + count = 0; + return count; +} + +cc_result Platform_SetDefaultCurrentDirectory(int argc, char **argv) { + return 0; +} +#endif \ No newline at end of file diff --git a/src/Window_GCWii.c b/src/Window_GCWii.c new file mode 100644 index 000000000..37a535b81 --- /dev/null +++ b/src/Window_GCWii.c @@ -0,0 +1,142 @@ +#include "Core.h" +#if defined CC_BUILD_GCWII +#include "_WindowBase.h" +#include "Graphics.h" +#include "String.h" +#include "Funcs.h" +#include "Bitmap.h" +#include "Errors.h" +#include + +static void* xfb; +static GXRModeObj* rmode; + +void* Window_XFB; + +void Window_Init(void) { + // Initialise the video system + VIDEO_Init(); + + // Obtain the preferred video mode from the system + // This will correspond to the settings in the Wii menu + rmode = VIDEO_GetPreferredMode(NULL); + // Allocate memory for the display in the uncached region + xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode)); + + Window_XFB = xfb; + + //console_init(xfb,20,20,rmode->fbWidth,rmode->xfbHeight,rmode->fbWidth*VI_DISPLAY_PIX_SZ); + + // Set up the video registers with the chosen mode + VIDEO_Configure(rmode); + // Tell the video hardware where our display memory is + VIDEO_SetNextFramebuffer(xfb); + + // Make the display visible + VIDEO_SetBlack(FALSE); + // Flush the video register changes to the hardware + VIDEO_Flush(); + // Wait for Video setup to complete + VIDEO_WaitVSync(); + + DisplayInfo.Width = rmode->fbWidth; + DisplayInfo.Height = rmode->xfbHeight; + DisplayInfo.ScaleX = 1; + DisplayInfo.ScaleY = 1; + + WindowInfo.Width = rmode->fbWidth; + WindowInfo.Height = rmode->xfbHeight; + //WindowInfo.Focused = true; +} + +static void DoCreateWindow(int _3d) { + WindowInfo.Exists = true; +} +void Window_Create2D(int width, int height) { DoCreateWindow(0); } +void Window_Create3D(int width, int height) { DoCreateWindow(1); } + +void Window_SetTitle(const cc_string* title) { } +void Clipboard_GetText(cc_string* value) { } +void Clipboard_SetText(const cc_string* value) { } + +int Window_GetWindowState(void) { return WINDOW_STATE_FULLSCREEN; } +cc_result Window_EnterFullscreen(void) { return 0; } +cc_result Window_ExitFullscreen(void) { return 0; } +int Window_IsObscured(void) { return 0; } + +void Window_Show(void) { } +void Window_SetSize(int width, int height) { } + +void Window_Close(void) { + /* TODO implement */ +} + +void Window_ProcessEvents(void) { + /* TODO implement */ +} + +static void Cursor_GetRawPos(int* x, int* y) { + /* TODO implement */ + *x = 0; *y = 0; +} +void Cursor_SetPosition(int x, int y) { + /* TODO implement */ +} + +static void Cursor_DoSetVisible(cc_bool visible) { + /* TODO implement */ +} + +static void ShowDialogCore(const char* title, const char* msg) { + /* TODO implement */ +} + +cc_result Window_OpenFileDialog(const struct OpenFileDialogArgs* args) { + return ERR_NOT_SUPPORTED; +} + +cc_result Window_SaveFileDialog(const struct SaveFileDialogArgs* args) { + return ERR_NOT_SUPPORTED; +} + +static struct Bitmap fb_bmp; +void Window_AllocFramebuffer(struct Bitmap* bmp) { + bmp->scan0 = (BitmapCol*)Mem_Alloc(bmp->width * bmp->height, 4, "window pixels"); + fb_bmp = *bmp; +} + + + +void Window_DrawFramebuffer(Rect2D r) { + VIDEO_WaitVSync(); + + // TODO XFB is raw yuv, but is absolutely a pain to work with.. + for (int y = r.Y; y < r.Y + r.Height; y++) + { + cc_uint32* src = fb_bmp.scan0 + y * fb_bmp.width + r.X; + u16* dst = (u16*)xfb + y * rmode->fbWidth + r.X; + + for (int x = 0; x < r.Width; x++) + dst[x] = src[x]; + } +} + +void Window_FreeFramebuffer(struct Bitmap* bmp) { + Mem_Free(bmp->scan0); +} + +void Window_OpenKeyboard(struct OpenKeyboardArgs* args) { /* TODO implement */ } +void Window_SetKeyboardText(const cc_string* text) { } +void Window_CloseKeyboard(void) { /* TODO implement */ } + +void Window_EnableRawMouse(void) { + RegrabMouse(); + Input_RawMode = true; +} +void Window_UpdateRawMouse(void) { CentreMousePosition(); } + +void Window_DisableRawMouse(void) { + RegrabMouse(); + Input_RawMode = false; +} +#endif \ No newline at end of file