From f791a1d3d5d00b96222bdf87c3c1a80059691cf9 Mon Sep 17 00:00:00 2001 From: a dinosaur Date: Sun, 1 Jun 2025 11:36:15 +1000 Subject: [PATCH] c: Shared random implementation --- src/c/lesson9.c | 24 ++++++------------------ src/c/nehe.c | 14 ++++++++++++++ src/c/nehe.h | 3 +++ 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/src/c/lesson9.c b/src/c/lesson9.c index 0426ce0..082a488 100644 --- a/src/c/lesson9.c +++ b/src/c/lesson9.c @@ -55,18 +55,6 @@ static float zoom = -15.0f; static float tilt = 90.0f; static float spin = 0.0f; -static uint32_t rngState = 1; -static inline int RngNext(void) -{ - //TODO: check which one of these matches win32 -#if 0 - rngState = rngState * 1103515245 + 12345; -#else - rngState = rngState * 214013 + 2531011; -#endif - return (int)((rngState >> 16) & 0x7FFF); // (s / 65536) % 32768 -} - static bool Lesson9_Init(NeHeContext* ctx) { @@ -192,9 +180,9 @@ static bool Lesson9_Init(NeHeContext* ctx) { .angle = 0.0f, .distance = 5.0f * ((float)i / (float)numStars), - .r = (uint8_t)(RngNext() % 256), - .g = (uint8_t)(RngNext() % 256), - .b = (uint8_t)(RngNext() % 256) + .r = (uint8_t)(NeHe_Random() % 256), + .g = (uint8_t)(NeHe_Random() % 256), + .b = (uint8_t)(NeHe_Random() % 256) }; } @@ -270,9 +258,9 @@ static void Lesson9_Draw(NeHeContext* restrict ctx, SDL_GPUCommandBuffer* restri if (star->distance < 0.0f) { star->distance += 5.0f; - star->r = (uint8_t)(RngNext() % 256); - star->g = (uint8_t)(RngNext() % 256); - star->b = (uint8_t)(RngNext() % 256); + star->r = (uint8_t)(NeHe_Random() % 256); + star->g = (uint8_t)(NeHe_Random() % 256); + star->b = (uint8_t)(NeHe_Random() % 256); } } SDL_UnmapGPUTransferBuffer(ctx->device, instanceXferBuffer); diff --git a/src/c/nehe.c b/src/c/nehe.c index 620860f..142eb52 100644 --- a/src/c/nehe.c +++ b/src/c/nehe.c @@ -6,6 +6,20 @@ #include "nehe.h" +static uint32_t rngState = 1; + +int NeHe_Random(void) +{ + rngState = rngState * 214013 + 2531011; + return (int)((rngState >> 16) & 0x7FFF); // (s / 65536) % 32768 +} + +void NeHe_RandomSeed(uint32_t seed) +{ + rngState = seed; +} + + bool NeHe_InitGPU(NeHeContext* ctx, const char* title, int width, int height) { // Create window diff --git a/src/c/nehe.h b/src/c/nehe.h index 2f72ef1..80b8072 100644 --- a/src/c/nehe.h +++ b/src/c/nehe.h @@ -26,6 +26,9 @@ typedef struct unsigned fragmentSamplers; } NeHeShaderProgramCreateInfo; +int NeHe_Random(void); +void NeHe_RandomSeed(uint32_t seed); + bool NeHe_InitGPU(NeHeContext* ctx, const char* title, int width, int height); bool NeHe_SetupDepthTexture(NeHeContext* ctx, uint32_t width, uint32_t height, SDL_GPUTextureFormat format, float clearDepth);