summaryrefslogtreecommitdiff
path: root/src/platform_sdl.c
blob: 22168e6084b0b8dfe2904ffe17d7e89204d5e1a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#include "platform_sdl.h"

#ifdef __linux__
#include "util_linux.h"
#elif __WIN32
#endif

#include <stdbool.h>
#include <stdio.h>
#include <time.h>

#ifndef MAP_ANONYMOUS
#define MAP_ANONYMOUS MAP_ANON
#endif

extern bool PAUSED;

static struct SDLOffscreenBuffer global_back_buffer = {0};
static struct SDLInputRecord input_record = {0};
static bool TRACE = false;


struct SDLWindowDimension sdl_get_window_dimension(SDL_Window *window)
{
    struct SDLWindowDimension result = {0};
    SDL_GetWindowSize(window, &result.width, &result.height);
    return(result);
}


void sdl_resize_texture(struct SDLOffscreenBuffer *buffer, SDL_Renderer *renderer, int width, int height)
{
    if (buffer->memory)
    {
        free(buffer->memory);
    }

    if (buffer->texture)
    {
        SDL_DestroyTexture(buffer->texture);
    }

    buffer->texture = SDL_CreateTexture(
            renderer,
            SDL_PIXELFORMAT_ARGB8888,
            SDL_TEXTUREACCESS_STREAMING,
            width, height);

    buffer->width = width;
    buffer->height = height;
    buffer->pitch = width * BYTES_PER_PIXEL;

    buffer->memory = malloc(width * height * BYTES_PER_PIXEL);
}


void sdl_update_window(SDL_Renderer *renderer, struct SDLOffscreenBuffer *buffer)
{
    if (SDL_UpdateTexture(buffer->texture, 0, buffer->memory, buffer->pitch))
    {
        // TODO(amin): Handle this error
    }

    SDL_RenderCopy(renderer, buffer->texture, 0, 0);
    SDL_RenderPresent(renderer);
}


void clear_screen(struct SDLOffscreenBuffer *buffer, uint32_t pixel_value)
{
    // NOTE(amin): Memset is faster than nested for loops, but can only set
    // pixels to single byte values
    memset(buffer->memory, pixel_value, buffer->height * buffer->width * BYTES_PER_PIXEL);
}


// TODO: make the deadzone circular
float sdl_process_controller_axis_value(int16_t value, int16_t deadzone_threshold)
{
    float result = 0.0;
    if (value < -deadzone_threshold)
    {
        result = (float)(value + deadzone_threshold) / (32768.0f - deadzone_threshold);
    }
    else if (value > deadzone_threshold)
    {
        result = (float)(value - deadzone_threshold) / (32767.0f - deadzone_threshold);
    }
    return result;
}


bool sdl_handle_event(SDL_Event *event, struct GameControllerInput *controller_input)
{
    if (!event || !controller_input)
    {
        return true;
    }

    bool should_quit = false;

    switch(event->type)
    {
        case SDL_QUIT:
        {
            printf("SDL_QUIT\n");
            should_quit = true;
        } break;

        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
            SDL_Keycode key_code = event->key.keysym.sym;
            bool is_down = (event->key.state == SDL_PRESSED);
            if (is_down)
            {
                if (key_code == SDLK_p)
                {
                    PAUSED = !PAUSED;
                }
                else if (key_code == SDLK_t)
                {
                    TRACE = !TRACE;
                }
                else if (key_code == SDLK_r)
                {
                    if (input_record.state == INACTIVE)
                    {
                        printf("input_record: RECORDING\n");
                        input_record.initial_state_recorded = false;
                        input_record.record_head = 0;
                        input_record.state = RECORDING;
                    }
                    else if (input_record.state == RECORDING)
                    {
                        printf("input_record: INACTIVE\n");
                        input_record.state = INACTIVE;
                    }
                    else if (input_record.state == PLAYING_BACK)
                    {
                        printf("Can't record while playing back\n");
                    }
                    else
                    {
                        printf("ERROR: input_record invalid state\n");
                    }
                }
                else if (key_code == SDLK_l)
                {
                    if (input_record.state == INACTIVE)
                    {
                        printf("input_record: PLAYING_BACK\n");
                        input_record.playback_head = 0;
                        input_record.state = PLAYING_BACK;
                    }
                    else if (input_record.state == PLAYING_BACK)
                    {
                        printf("input_record: INACTIVE\n");
                        input_record.state = INACTIVE;
                    }
                    else if (input_record.state == RECORDING)
                    {
                        printf("Can't play back while recording\n");
                    }
                    else
                    {
                        printf("ERROR: input_record invalid state\n");
                    }
                }
            }
        } break;

        case SDL_CONTROLLERAXISMOTION:
        {
            // down and right are positive
            float normalized_axis_value = sdl_process_controller_axis_value(event->caxis.value, DEADZONE_THRESHOLD);

            //printf("SDL_CONTROLLERAXISMOTION (%d, %s, %d, %f)\n",
            //        event->caxis.which,
            //        SDL_GameControllerGetStringForAxis(event->caxis.axis),
            //        event->caxis.value,
            //        normalized_axis_value);

            switch(event->caxis.axis)
            {
                case SDL_CONTROLLER_AXIS_LEFTX:
                {
                    controller_input->left_stick_x = normalized_axis_value;
                } break;
                case SDL_CONTROLLER_AXIS_LEFTY:
                {
                    controller_input->left_stick_y = normalized_axis_value;
                } break;
                case SDL_CONTROLLER_AXIS_RIGHTX:
                {
                    controller_input->right_stick_x = normalized_axis_value;
                } break;
                case SDL_CONTROLLER_AXIS_RIGHTY:
                {
                    controller_input->right_stick_y = normalized_axis_value;
                } break;
                default:
                {
                    printf("Unhandled axis input\n");
                }
            }
        } break;

        case SDL_WINDOWEVENT:
        {
            switch(event->window.event)
            {
                case SDL_WINDOWEVENT_SIZE_CHANGED:
                {
                    SDL_Window *window = SDL_GetWindowFromID(event->window.windowID);
                    SDL_Renderer *renderer = SDL_GetRenderer(window);
                    printf("SDL_WINDOWEVENT_SIZE_CHANGED (%d, %d)\n", event->window.data1, event->window.data2);
                    sdl_resize_texture(&global_back_buffer, renderer, event->window.data1, event->window.data2);
                } break;

                case SDL_WINDOWEVENT_FOCUS_GAINED:
                {
                    printf("SDL_WINDOWEVENT_FOCUS_GAINED\n");
                } break;

                case SDL_WINDOWEVENT_EXPOSED:
                {
                    SDL_Window *window = SDL_GetWindowFromID(event->window.windowID);
                    SDL_Renderer *renderer = SDL_GetRenderer(window);
                    sdl_update_window(renderer, &global_back_buffer);
                } break;
            }
        } break;
    }
    return(should_quit);
}


int main(int argc, char *argv[])
{
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER))
    {
        // TODO(amin): log SDL_Init error
    }

    SDL_Window *window = SDL_CreateWindow(
            TITLE,
            SDL_WINDOWPOS_UNDEFINED,
            SDL_WINDOWPOS_UNDEFINED,
            SCREEN_WIDTH,
            SCREEN_HEIGHT,
            SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);

#ifdef FULLSCREEN
    SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP);
#endif

    if (window)
    {
        SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);

        if (renderer)
        {
            struct SDLWindowDimension dimension = sdl_get_window_dimension(window);
            sdl_resize_texture(&global_back_buffer, renderer, dimension.width, dimension.height);

            bool running = true;

#ifdef USE_TEST_SEED
            srand((uint32_t)0);
#else
            srand((uint32_t)time(NULL));
#endif

            int num_joysticks = SDL_NumJoysticks();
            SDL_GameController *controller_handles[MAX_CONTROLLERS];
            for (int controller_index = 0; controller_index < num_joysticks; ++controller_index)
            {
                if (!SDL_IsGameController(controller_index))
                {
                    continue;
                }

                if (controller_index >= MAX_CONTROLLERS)
                {
                    break;
                }

                controller_handles[controller_index] = SDL_GameControllerOpen(controller_index);
            }

            uint64_t lag = 0;
            uint64_t previous_ms = (SDL_GetPerformanceCounter() * SECOND) / SDL_GetPerformanceFrequency();

            struct GameState game_state = {0};
            game_init(&game_state, dimension.width, dimension.height);

            struct GameControllerInput controller_input = {0};

            struct SDLGameCode game_code = load_game_code(GAME_LIB_PATH);

            while (running)
            {
                uint64_t current_ms = (SDL_GetPerformanceCounter() * SECOND) / SDL_GetPerformanceFrequency();
                uint64_t elapsed_ms = current_ms - previous_ms;
                previous_ms = current_ms;
                lag += elapsed_ms;
                //printf("%" PRIu64 ", %" PRIu64 ", %f\n", elapsed_ms, lag, MS_PER_UPDATE);

                time_t last_write_time = file_get_modified_time(GAME_LIB_PATH);
                bool game_code_has_changed = last_write_time && (last_write_time != game_code.last_write_time);
                if (game_code_has_changed)
                {
                    unload_game_code(&game_code);
                    game_code = load_game_code(GAME_LIB_PATH);
                    if (!game_code.is_valid)
                    {
                        // TODO: fall back to backup?
                    }
                }

                SDL_Event event;
                while (SDL_PollEvent(&event))
                {
                    running = !sdl_handle_event(&event, &controller_input);
                }
                SDL_PumpEvents();

                switch (input_record.state)
                {
                    case INACTIVE: {} break;

                    case RECORDING:
                    {
                        // TODO: sdl_input_record(&controller_input);
                        if (input_record.record_head < INPUT_RECORD_SIZE)
                        {
                            if (input_record.record_head == 0)
                            {
                                input_record.initial_state = game_state;
                                input_record.initial_state_recorded = true;
                            }
                            input_record.input_buffer[input_record.record_head] = controller_input;
                            ++input_record.record_head;
                        }
                        else
                        {
                            printf("Input record buffer full\n");
                            input_record.state = INACTIVE;
                        }
                    } break;

                    case PLAYING_BACK:
                    {
                        if (input_record.playback_head < input_record.record_head)
                        {
                            if (input_record.playback_head == 0 && input_record.initial_state_recorded)
                            {
                                game_state = input_record.initial_state;
                            }

                            // TODO: sdl_input_playback(&controller_input);
                            controller_input = input_record.input_buffer[input_record.playback_head];
                            ++input_record.playback_head;
                        }
                        else
                        {
                            printf("Playback restarting\n");
                            input_record.playback_head = 0;
                        }
                    } break;

                    default:
                    {
                        printf("Unhandled SDLInputRecordState\n");
                    } break;
                }

                dimension = sdl_get_window_dimension(window);

                struct OffscreenBuffer buffer =
                {
                    // WARNING: these pointers are aliased until the end of the
                    // loop
                    .memory = global_back_buffer.memory,
                    .width = global_back_buffer.width,
                    .height = global_back_buffer.height,
                    .pitch = global_back_buffer.pitch,
                };

                if (PAUSED)
                {
                    lag = 0;
                }
                else if (input_record.state == RECORDING || input_record.state == PLAYING_BACK)
                {
                    // TODO: Make up your mind about what kind of time step and game loop this game needs.

                    // When recording or playing back, we do exactly one update
                    // per frame. This is so that recorded input played back
                    // over the initial state always results in the same
                    // sequence of states.
                    game_code.game_update(&game_state, controller_input, buffer.width, buffer.height);
                    lag -= MS_PER_UPDATE;
                }
                else
                {
                    while (lag >= MS_PER_UPDATE)
                    {
                        game_code.game_update(&game_state, controller_input, buffer.width, buffer.height);
                        //printf("\t%" PRIu64 ", %f\n", lag, MS_PER_UPDATE);
                        lag -= MS_PER_UPDATE;
                    }
                }

                if (!TRACE)
                {
                    clear_screen(&global_back_buffer, COLOR_BACKGROUND);
                }
                game_code.game_render(&buffer, lag/SECOND, &game_state);
                sdl_update_window(renderer, &global_back_buffer);
                if (elapsed_ms <= MS_PER_FRAME)
                {
                    SDL_Delay(MS_PER_FRAME - elapsed_ms);
                }
            }

            game_cleanup(&game_state);

            for (int controller_index = 0; controller_index < num_joysticks; ++controller_index)
            {
                if (!SDL_IsGameController(controller_index))
                {
                    continue;
                }

                if (controller_index >= MAX_CONTROLLERS)
                {
                    break;
                }

                SDL_GameControllerClose(controller_handles[controller_index]);
            }
        }
        else
        {
            // TODO(amin): log SDL_Renderer error
        }
    }
    else
    {
        // TODO(amin): log SDL_Window error
    }

    SDL_Quit();
    return(0);
}