allow world reloading
[carveJwlIkooP6JGAAIwe30JlM.git] / world_load.c
1 #ifndef WORLD_LOAD_C
2 #define WORLD_LOAD_C
3
4 #include "world_load.h"
5 #include "world_routes.h"
6 #include "world_gate.h"
7 #include "ent_skateshop.h"
8 #include "addon.h"
9 #include "save.h"
10 #include "vg/vg_msg.h"
11 #include "network.h"
12 #include "player_remote.h"
13 #include "vg/vg_loader.h"
14
15 /*
16 * load the .mdl file located in path as a world instance
17 */
18 static void world_instance_load_mdl( u32 instance_id, const char *path ){
19 world_instance *world = &world_static.instances[ instance_id ];
20 world_init_blank( world );
21 world->status = k_world_status_loading;
22
23 vg_info( "Loading instance[%u]: %s\n", instance_id, path );
24
25 void *allocator = NULL;
26 if( instance_id == 0 ) allocator = world_static.heap;
27 else allocator = world_static.instances[instance_id-1].heap;
28
29 u32 heap_availible = vg_linear_remaining( allocator );
30 u32 min_overhead = sizeof(vg_linear_allocator);
31
32 if( heap_availible < (min_overhead+1024) ){
33 vg_fatal_error( "out of memory" );
34 }
35
36 u32 size = heap_availible - min_overhead;
37 void *heap = vg_create_linear_allocator( allocator, size, VG_MEMORY_SYSTEM );
38
39 world->heap = heap;
40 mdl_context *meta = &world->meta;
41
42 mdl_open( meta, path, world->heap );
43 mdl_load_metadata_block( meta, world->heap );
44 mdl_load_animation_block( meta, world->heap );
45 mdl_load_mesh_block( meta, world->heap );
46
47 vg_info( "%u\n", sizeof(ent_cubemap) );
48
49 MDL_LOAD_ARRAY( meta, &world->ent_gate, ent_gate, heap );
50 MDL_LOAD_ARRAY( meta, &world->ent_camera, ent_camera, heap );
51 MDL_LOAD_ARRAY( meta, &world->ent_spawn, ent_spawn, heap );
52 MDL_LOAD_ARRAY( meta, &world->ent_light, ent_light, heap );
53 MDL_LOAD_ARRAY( meta, &world->ent_route_node,ent_route_node, heap );
54 MDL_LOAD_ARRAY( meta, &world->ent_path_index,ent_path_index, heap );
55 MDL_LOAD_ARRAY( meta, &world->ent_checkpoint,ent_checkpoint, heap );
56 MDL_LOAD_ARRAY( meta, &world->ent_route, ent_route, heap );
57 MDL_LOAD_ARRAY( meta, &world->ent_water, ent_water, heap );
58 MDL_LOAD_ARRAY( meta, &world->ent_audio_clip,ent_audio_clip, heap );
59 MDL_LOAD_ARRAY( meta, &world->ent_audio, ent_audio, heap );
60 MDL_LOAD_ARRAY( meta, &world->ent_volume, ent_volume, heap );
61 MDL_LOAD_ARRAY( meta, &world->ent_traffic, ent_traffic, heap );
62 MDL_LOAD_ARRAY( meta, &world->ent_marker, ent_marker, heap );
63 MDL_LOAD_ARRAY( meta, &world->ent_skateshop, ent_skateshop, heap );
64 MDL_LOAD_ARRAY( meta, &world->ent_swspreview,ent_swspreview, heap );
65 MDL_LOAD_ARRAY( meta, &world->ent_ccmd, ent_ccmd, heap );
66 MDL_LOAD_ARRAY( meta, &world->ent_objective, ent_objective, heap );
67 MDL_LOAD_ARRAY( meta, &world->ent_challenge, ent_challenge, heap );
68 MDL_LOAD_ARRAY( meta, &world->ent_relay, ent_relay, heap );
69 MDL_LOAD_ARRAY( meta, &world->ent_cubemap, ent_cubemap, heap );
70 MDL_LOAD_ARRAY( meta, &world->ent_miniworld, ent_miniworld, heap );
71 MDL_LOAD_ARRAY( meta, &world->ent_prop, ent_prop, heap );
72 MDL_LOAD_ARRAY( meta, &world->ent_region, ent_region, heap );
73 MDL_LOAD_ARRAY( meta, &world->ent_glider, ent_glider, heap );
74 MDL_LOAD_ARRAY( meta, &world->ent_npc, ent_npc, heap );
75
76 mdl_array_ptr infos;
77 MDL_LOAD_ARRAY( meta, &infos, ent_worldinfo, vg_mem.scratch );
78
79 world->skybox = k_skybox_default;
80 if( mdl_arrcount(&infos) )
81 {
82 world->info = *((ent_worldinfo *)mdl_arritm(&infos,0));
83
84 if( world->meta.info.version >= 104 )
85 {
86 if( MDL_CONST_PSTREQ( &world->meta, world->info.pstr_skybox,"space"))
87 {
88 world->skybox = k_skybox_space;
89 }
90 }
91 }
92 else
93 {
94 world->info.pstr_author = 0;
95 world->info.pstr_desc = 0;
96 world->info.pstr_name = 0;
97 world->info.timezone = 0.0f;
98 world->info.flags = 0;
99 }
100
101 time_t seconds = time(NULL) % ((u32)vg_maxf(1.0f,k_day_length)*60);
102 world->time = ((f64)(seconds)/(k_day_length*60.0));
103 world->time += (world->info.timezone/24.0);
104
105 /* process resources from pack */
106 u64 t4 = SDL_GetPerformanceCounter();
107 world_gen_load_surfaces( world );
108 u64 t5 = SDL_GetPerformanceCounter();
109 world_gen_routes_ent_init( world );
110 world_gen_entities_init( world );
111 u64 t6 = SDL_GetPerformanceCounter();
112
113 /* main bulk */
114 u64 t0 = SDL_GetPerformanceCounter();
115 world_gen_generate_meshes( world );
116 u64 t1 = SDL_GetPerformanceCounter();
117 world_gen_routes_generate( instance_id );
118 u64 t2 = SDL_GetPerformanceCounter();
119 world_gen_compute_light_indices( world );
120 u64 t3 = SDL_GetPerformanceCounter();
121 mdl_close( meta );
122
123 u64 utime_mesh = t1-t0,
124 utime_route = t2-t1,
125 utime_indices = t3-t2,
126 utime_tex = t5-t4,
127 utime_ent = t6-t5,
128 ufreq = SDL_GetPerformanceFrequency();
129
130 f64 ftime_mesh = ((f64)utime_mesh / (f64)ufreq)*1000.0,
131 ftime_route = ((f64)utime_route / (f64)ufreq)*1000.0,
132 ftime_ind = ((f64)utime_route / (f64)ufreq)*1000.0,
133 ftime_tex = ((f64)utime_tex / (f64)ufreq)*1000.0,
134 ftime_ent = ((f64)utime_ent / (f64)ufreq)*1000.0;
135
136 vg_info( "wtime:mesh %.2fms route %.2fms ind %.2fms tex %.2fms ent %.2fms\n",
137 ftime_mesh, ftime_route, ftime_ind, ftime_tex, ftime_ent );
138
139 /* init player position.
140 * - this is overriden by the save state when(if) it loads */
141 world_default_spawn_pos( world, world->player_co );
142
143 /* allocate leaderboard buffers */
144 u32 bs = mdl_arrcount(&world->ent_route)*sizeof(struct leaderboard_cache);
145 world->leaderboard_cache = vg_linear_alloc( heap, bs );
146
147 for( u32 i=0; i<mdl_arrcount( &world->ent_route ); i ++ )
148 {
149 struct leaderboard_cache *board = &world->leaderboard_cache[i];
150 board->data = vg_linear_alloc( heap, NETWORK_REQUEST_MAX );
151 board->status = k_request_status_client_error;
152 board->cache_time = 0.0;
153 board->data_len = 0;
154 }
155
156 world->routes_ui = vg_linear_alloc( heap,
157 sizeof(struct route_ui)*mdl_arrcount(&world->ent_route) );
158
159 vg_async_call( async_world_postprocess, world, 0 );
160 vg_async_stall();
161 }
162
163 struct world_load_complete_data{
164 savedata_file save;
165 enum world_purpose purpose;
166 };
167
168 static void skaterift_world_load_done( void *payload, u32 size )
169 {
170 struct world_load_complete_data *data = payload;
171 world_instance *world = &world_static.instances[ data->purpose ];
172
173 vg_msg sav;
174 vg_msg_init( &sav, data->save.buf, data->save.len );
175
176 if( data->purpose != k_world_purpose_hub )
177 {
178 vg_msg player_frame = sav;
179 if( vg_msg_seekframe( &player_frame, "player" ) )
180 {
181 vg_msg_getkvvecf( &player_frame, "position", k_vg_msg_v3f,
182 world->player_co, NULL );
183 }
184 }
185
186 world_entity_start( world, &sav );
187 world->status = k_world_status_loaded;
188 world_static.load_state = k_world_loader_none;
189
190 if( world_static.clear_async_op_when_done )
191 {
192 skaterift.op = k_async_op_none;
193 world_static.clear_async_op_when_done = 0;
194 }
195 }
196
197 /*
198 * Does a complete world switch using the remaining free slots
199 */
200 void skaterift_world_load_thread( void *_args )
201 {
202 struct world_load_args args = *((struct world_load_args *)_args);
203
204 addon_reg *reg = args.reg;
205 world_static.instance_addons[ args.purpose ] = reg;
206
207 char uid[ADDON_UID_MAX];
208 addon_alias_uid( &reg->alias, uid );
209 vg_info( "LOAD WORLD %s @%d\n", uid, args.purpose );
210
211 char path_buf[4096];
212 vg_str path;
213 vg_strnull( &path, path_buf, 4096 );
214
215 addon_get_content_folder( reg, &path, 1 );
216
217 vg_str folder = path;
218 if( !vg_strgood( &folder ) ) {
219 vg_error( "Load target too long\n" );
220 return;
221 }
222
223 char worlds[k_world_max-1][4096];
224 u32 i=0;
225
226 vg_dir dir;
227 if( !vg_dir_open(&dir, folder.buffer) ){
228 vg_error( "opendir('%s') failed\n", folder.buffer );
229 return;
230 }
231
232 while( vg_dir_next_entry(&dir) ){
233 if( vg_dir_entry_type(&dir) == k_vg_entry_type_file ){
234 const char *d_name = vg_dir_entry_name(&dir);
235 if( d_name[0] == '.' ) continue;
236
237 vg_str file = folder;
238 vg_strcat( &file, "/" );
239 vg_strcat( &file, d_name );
240 if( !vg_strgood( &file ) ) continue;
241
242 char *ext = vg_strch( &file, '.' );
243 if( !ext ) continue;
244 if( strcmp(ext,".mdl") ) continue;
245
246 if( i == k_world_max-1 ){
247 vg_warn( "There are too many .mdl files in the map folder!(3)\n" );
248 break;
249 }
250
251 strcpy( worlds[i++], file.buffer );
252 }
253 }
254 vg_dir_close(&dir);
255
256 if( i == 0 ){
257 vg_warn( "There are no .mdl files in the map folder.\n" );
258 }
259
260 u32 first_index = 0;
261 for( u32 j=0; j<i; j++ ){
262 vg_str name = { .buffer = worlds[j], .i=strlen(worlds[j]),
263 sizeof(worlds[j]) };
264 char *fname = vg_strch( &name, '/' );
265 if( fname ){
266 if( !strcmp( fname+1, "main.mdl" ) ){
267 first_index = j;
268 }
269 }
270 }
271
272 world_instance_load_mdl( args.purpose, worlds[first_index] );
273
274 vg_async_item *final_call =
275 vg_async_alloc( sizeof(struct world_load_complete_data) );
276
277 struct world_load_complete_data *data = final_call->payload;
278 data->purpose = args.purpose;
279
280 skaterift_world_get_save_path( args.purpose, data->save.path );
281 savedata_file_read( &data->save );
282
283 vg_async_dispatch( final_call, skaterift_world_load_done );
284 vg_async_stall();
285 }
286
287 void skaterift_change_client_world_preupdate(void)
288 {
289 if( world_static.load_state != k_world_loader_preload )
290 return;
291
292 /* holding pattern before we can start loading the new world, since we might
293 * be waiting for audio to stop */
294 for( u32 i=1; i<k_world_max; i++ )
295 {
296 world_instance *inst = &world_static.instances[i];
297
298 if( inst->status == k_world_status_unloading )
299 {
300 if( world_freeable( inst ) )
301 {
302 world_free( inst );
303 }
304 return;
305 }
306 }
307
308 if( vg_loader_availible() )
309 {
310 vg_info( "worlds cleared, begining load\n" );
311 world_static.load_state = k_world_loader_load;
312
313 vg_linear_clear( vg_async.buffer );
314 struct world_load_args *args =
315 vg_linear_alloc( vg_async.buffer, sizeof(struct world_load_args) );
316 args->purpose = k_world_purpose_client;
317 args->reg = world_static.instance_addons[ k_world_purpose_client ];
318
319 /* this is replaces the already correct reg but we have to set it again
320 * TOO BAD */
321
322 /* finally can start the loader */
323 vg_loader_start( skaterift_world_load_thread, args );
324 }
325 }
326
327 /*
328 * places all loaded worlds into unloading state, pass NULL to reload the world
329 */
330 void skaterift_change_world_start( addon_reg *reg )
331 {
332 if( world_static.instance_addons[ k_world_purpose_client ] == reg )
333 {
334 vg_warn( "World is already loaded\n" );
335 return;
336 }
337
338 if( !reg )
339 {
340 if( world_static.instance_addons[ k_world_purpose_client ] )
341 {
342 reg = world_static.instance_addons[ k_world_purpose_client ];
343 world_static.clear_async_op_when_done = 1;
344 }
345 else
346 {
347 vg_warn( "No client world loaded\n" );
348 return;
349 }
350 }
351
352 world_static.load_state = k_world_loader_preload;
353
354 if( world_static.active_instance != 0 )
355 skaterift.op = k_async_op_clientloading;
356
357 char buf[76];
358 addon_alias_uid( &reg->alias, buf );
359 vg_info( "switching to: %s\n", buf );
360 skaterift_autosave(1);
361
362 vg_linear_clear( vg_mem.scratch ); /* ?? */
363 vg_info( "unloading old worlds\n" );
364
365 world_instance *client_world =
366 &world_static.instances[ k_world_purpose_client ];
367
368 if( client_world->status == k_world_status_loaded )
369 {
370 client_world->status = k_world_status_unloading;
371 world_fadeout_audio( client_world );
372 }
373
374 world_static.instance_addons[ k_world_purpose_client ] = reg;
375 network_send_item( k_netmsg_playeritem_world1 );
376 relink_all_remote_player_worlds();
377 world_unlink_nonlocal( &world_static.instances[k_world_purpose_hub] );
378 }
379
380 /* console command for the above function */
381 int skaterift_load_world_command( int argc, const char *argv[] )
382 {
383 if( !vg_loader_availible() )
384 {
385 vg_error( "Loading thread is currently unavailible\n" );
386 return 0;
387 }
388
389 if( argc == 1 )
390 {
391 if( !strcmp( argv[0], "reload" ) )
392 {
393 skaterift_change_world_start( NULL );
394 return 0;
395 }
396
397 addon_alias q;
398 addon_uid_to_alias( argv[0], &q );
399
400 u32 reg_id = addon_match( &q );
401 if( reg_id != 0xffffffff )
402 {
403 addon_reg *reg = get_addon_from_index( k_addon_type_world, reg_id, 0 );
404 skaterift_change_world_start( reg );
405 }
406 else
407 {
408 vg_error( "Addon '%s' is not installed or not found.\n", argv[0] );
409 }
410 }
411 else
412 {
413 vg_info( "worlds availible to load:\n" );
414
415 for( int i=0; i<addon_count(k_addon_type_world,0); i ++ )
416 {
417 addon_reg *w = get_addon_from_index( k_addon_type_world, i, 0);
418
419 char buf[ADDON_UID_MAX];
420 addon_alias_uid( &w->alias, buf );
421
422 if( w->flags & ADDON_REG_HIDDEN )
423 vg_info( " %s [hidden]\n", buf );
424 else
425 vg_info( " %s\n", buf );
426 }
427 }
428
429 return 0;
430 }
431
432 /*
433 * checks:
434 * 1. to see if all audios owned by the world have been stopped
435 * 2. that this is the least significant world
436 */
437 int world_freeable( world_instance *world )
438 {
439 if( world->status != k_world_status_unloading ) return 0;
440 u8 world_id = (world - world_static.instances) + 1;
441
442 for( u32 i=world_id; i<vg_list_size(world_static.instances); i++ ){
443 if( world_static.instances[i].status != k_world_status_unloaded ){
444 return 0;
445 }
446 }
447
448 int freeable = 1;
449 audio_lock();
450 for( u32 i=0; i<AUDIO_CHANNELS; i++ ){
451 audio_channel *ch = &vg_audio.channels[i];
452
453 if( ch->allocated && (ch->world_id == world_id)){
454 if( !audio_channel_finished( ch ) ){
455 freeable = 0;
456 break;
457 }
458 }
459 }
460 audio_unlock();
461 return freeable;
462 }
463
464 /*
465 * Free all resources for world instance
466 */
467 void world_free( world_instance *world )
468 {
469 vg_info( "Free world @%p\n", world );
470
471 /* free meshes */
472 mesh_free( &world->mesh_route_lines );
473 mesh_free( &world->mesh_geo );
474 mesh_free( &world->mesh_no_collide );
475 mesh_free( &world->mesh_water );
476
477 /* glDeleteBuffers silently ignores 0's and names that do not correspond to
478 * existing buffer objects.
479 * */
480 glDeleteBuffers( 1, &world->tbo_light_entities );
481 glDeleteTextures( 1, &world->tex_light_entities );
482 glDeleteTextures( 1, &world->tex_light_cubes );
483
484 /* delete textures and meshes */
485 glDeleteTextures( world->texture_count-1, world->textures+1 );
486
487 u32 world_index = world - world_static.instances;
488 if( world_index ){
489 vg_linear_del( world_static.instances[world_index-1].heap,
490 vg_linear_header(world->heap) );
491 }
492
493 for( u32 i=0; i<mdl_arrcount(&world->ent_cubemap); i++ ){
494 ent_cubemap *cm = mdl_arritm(&world->ent_cubemap,i);
495 glDeleteTextures( 1, &cm->texture_id );
496 glDeleteFramebuffers( 1, &cm->framebuffer_id );
497 glDeleteRenderbuffers( 1, &cm->renderbuffer_id );
498 }
499
500 world->status = k_world_status_unloaded;
501 }
502
503 /*
504 * reset the world structure without deallocating persistent buffers
505 * TODO: Make this a memset(0), and have persistent items live in a static loc
506 */
507 void world_init_blank( world_instance *world )
508 {
509 memset( &world->meta, 0, sizeof(mdl_context) );
510
511 world->textures = NULL;
512 world->texture_count = 0;
513 world->surfaces = NULL;
514 world->surface_count = 0;
515
516 world->geo_bh = NULL;
517 world->entity_bh = NULL;
518 world->entity_list = NULL;
519 world->rendering_gate = NULL;
520
521 world->water.enabled = 0;
522 world->time = 0.0;
523
524 /* default lighting conditions
525 * -------------------------------------------------------------*/
526 struct ub_world_lighting *state = &world->ub_lighting;
527
528 state->g_light_preview = 0;
529 state->g_shadow_samples = 8;
530 state->g_water_fog = 0.04f;
531
532 v4_zero( state->g_water_plane );
533 v4_zero( state->g_depth_bounds );
534
535 state->g_shadow_length = 9.50f;
536 state->g_shadow_spread = 0.65f;
537
538 #if 0
539 /* 2023 style */
540 v3_copy( (v3f){0.37f, 0.54f, 0.97f}, state->g_daysky_colour );
541 v3_copy( (v3f){0.03f, 0.05f, 0.20f}, state->g_nightsky_colour );
542 v3_copy( (v3f){1.00f, 0.32f, 0.01f}, state->g_sunset_colour );
543 v3_copy( (v3f){0.13f, 0.17f, 0.35f}, state->g_ambient_colour );
544 v3_copy( (v3f){0.25f, 0.17f, 0.51f}, state->g_sunset_ambient );
545 v3_copy( (v3f){1.10f, 0.89f, 0.35f}, state->g_sun_colour );
546 #else
547 /* 2024 style */
548 v3_copy( (v3f){0.308f, 0.543f, 0.904f}, state->g_daysky_colour );
549 v3_copy( (v3f){0.030f, 0.050f, 0.200f}, state->g_nightsky_colour );
550 v3_copy( (v3f){1.000f, 0.320f, 0.010f}, state->g_sunset_colour );
551 v3_copy( (v3f){0.130f, 0.170f, 0.350f}, state->g_ambient_colour );
552 v3_copy( (v3f){0.25f, 0.17f, 0.51f}, state->g_sunset_ambient );
553 v3_copy( (v3f){1.000f, 0.809f, 0.318f}, state->g_sun_colour );
554 #endif
555 }
556
557 #endif /* WORLD_LOAD_C */