+static int colour_set_id = 0;
+static int world_theme_id = 0;
+static int enable_bloom = 1;
+static int enable_vignette = 1;
+static float music_volume = 1.0f;
+
+static void music_volume_update(void)
+{
+ sfx_vol_fset( &audio_volume_music, music_volume );
+}
+
+static v3f colour_sets[][4] =
+{
+ { { 1.0f, 0.9f, 0.3f },
+ { 0.4f, 0.8f, 1.00f },
+ { 0.2f, 0.9f, 0.14f },
+ { 0.882f, 0.204f, 0.922f }
+ },
+ { { 1.0f, 0.9f, 0.3f },
+ { 0.4f, 0.8f, 1.00f },
+ { 0.85f, 0.85f, 0.85f },
+ { 0.2f, 0.2f, 0.2f }
+ },
+ { { 1.0f, 0.9f, 0.3f },
+ { 0.827f, 0.373f, 0.718f },
+ { 0.0f, 0.353f, 0.71f },
+ { 0.863f, 0.196f, 0.125f }
+ },
+};
+
+static struct world_theme
+{
+ const char *name;
+ v3f col_shadow;
+
+ vg_tex2d *tex_tiles;
+}
+world_themes[] =
+{
+ {
+ "Minimal",
+ { 0.6f, 0.6f, 0.6f },
+ &tex_tiles_min
+ },
+ {
+ "Wood",
+ { 0.89f, 0.8f, 0.7f },
+ &tex_tiles_wood
+ },
+ {
+ "Lab",
+ { 0.7f, 0.7f, 0.7f },
+ &tex_tiles_lab
+ }
+};
+
+static void colour_code_v3( i8 cc, v3f target )
+{
+ if( (cc >= 0) && (cc < vg_list_size( colour_sets[0] )) )
+ {
+ v3_copy( colour_sets[colour_set_id][ cc ], target );
+ return;
+ }
+
+ vg_error( "Invalid colour code used '%d'\n", (int)cc );
+ v3_copy( (v3f){0.0f,0.0f,0.0f}, target );
+}
+
+static int hash21i( v2i p, u32 umod )
+{
+static const int random_noise[] = {
+0x46,0xD5,0xB8,0xD3,0xF2,0xE5,0xCC,0x07,0xD0,0xB3,0x7A,0xA2,0xC3,0xDA,0xDC,0x7F,
+0xE0,0xB7,0x42,0xA0,0xBF,0x41,0x92,0x32,0x6F,0x0D,0x45,0xC7,0x54,0xDB,0x30,0xC2,
+0xD5,0xDA,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x81,0xA3,0x53,0x99,0x4B,0x3C,0x93,0x3B,0xFE,0x55,0xFF,
+0x25,0x9F,0xCC,0x07,0xC5,0x2C,0x14,0xA7,0xA4,0x1E,0x6C,0xB6,0x91,0x2A,0xE0,0x3E,
+0x7F,0x39,0x0A,0xD9,0x24,0x3C,0x01,0xA0,0x30,0x99,0x8E,0xB8,0x1D,0xF9,0xA7,0x78,
+0x86,0x95,0x35,0x0E,0x21,0xDA,0x7A,0x7B,0xAD,0x9F,0x4E,0xF6,0x63,0x5B,0x96,0xBB,
+0x87,0x36,0x3F,0xA7,0x1A,0x66,0x91,0xCD,0xB0,0x3B,0xC0,0x4F,0x54,0xD2,0x5F,0xBB,
+0x38,0x89,0x1C,0x79,0x7E,0xA2,0x02,0xE4,0x80,0x84,0x1E,0x33,0xAB,0x74,0xFA,0xBE,
+0x31,0x46,0x2E,0xC5,0x15,0xB9,0x12,0xE9,0xD3,0x73,0x43,0xEA,0x74,0x11,0xA7,0xC0,
+0xD5,0xD8,0x39,0x08,0x9F,0x4F,0xC7,0x71,0x25,0x09,0x51,0x65,0xD6,0xA8,0x02,0x1F
+};
+
+ return random_noise[ (random_noise[p[1] & 1023] + p[0]) & 1023 ] & umod;
+}
+
+static void init_mesh( struct mesh *m, float const *tris, u32 length )
+{
+ m->elements = length/3;
+ glGenVertexArrays( 1, &m->vao );
+ glGenBuffers( 1, &m->vbo );
+
+ glBindVertexArray( m->vao );
+ glBindBuffer( GL_ARRAY_BUFFER, m->vbo );
+ glBufferData( GL_ARRAY_BUFFER, length*sizeof(float), tris, GL_STATIC_DRAW );
+
+ glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0 );
+ glEnableVertexAttribArray( 0 );
+
+ VG_CHECK_GL();
+}
+
+static void free_mesh( struct mesh *m )
+{
+ glDeleteVertexArrays( 1, &m->vao );
+ glDeleteBuffers( 1, &m->vbo );
+}
+
+static void draw_mesh( int const start, int const count )
+{
+ glDrawArrays( GL_TRIANGLES, start*3, count*3 );
+}
+
+static void use_mesh( struct mesh *m )
+{
+ glBindVertexArray( m->vao );
+}
+
+void leaderboard_set_score( struct cmp_level *cmp_level, u32 score );
+
+static void map_free(void)
+{
+ arrfree( world.data );
+ arrfree( world.io );
+
+ free( world.cmd_buf_tiles );
+ world.cmd_buf_tiles = NULL;
+
+ world.w = 0;
+ world.h = 0;
+ world.data = NULL;
+ world.io = NULL;
+ world.score = 0;
+ world.time = 0;
+ world.completed = 0;
+ world.max_runs = 0;
+ world.initialzed = 0;
+}
+
+static void io_reset(void)
+{
+ for( int i = 0; i < arrlen( world.io ); i ++ )
+ {
+ struct cell_terminal *term = &world.io[i];
+
+ for( int j = 0; j < term->run_count; j ++ )
+ term->runs[j].recv_count = 0;
+ }
+}
+
+static struct cell *pcell( v2i pos )
+{
+ return &world.data[ pos[1]*world.w + pos[0] ];
+}
+
+static void lcell( int id, v2i pos )
+{
+ pos[0] = id % world.w;
+ pos[1] = (id - pos[0]) / world.w;
+}
+
+static void map_reclassify( v2i start, v2i end, int update_texbuffer )
+{
+ v2i full_start = { 1,1 };
+ v2i full_end = { world.w-1, world.h-1 };
+
+ if( !start || !end )
+ {
+ start = full_start;
+ end = full_end;
+ }
+
+ /* Texture data */
+ u8 info_buffer[64*64*4];
+ u32 pixel_id = 0;
+
+ int px0 = vg_max( start[0], full_start[0] ),
+ px1 = vg_min( end[0], full_end[0] ),
+ py0 = vg_max( start[1], full_start[1] ),
+ py1 = vg_min( end[1], full_end[1] );
+
+ for( int y = py0; y < py1; y ++ )
+ {
+ for( int x = px0; x < px1; x ++ )
+ {
+ struct cell *cell = pcell((v2i){x,y});
+
+ v2i dirs[] = {{1,0},{0,1},{-1,0},{0,-1}};
+
+ u8 height = 0;
+ u8 config = 0x00;
+
+ if( cell->state & (FLAG_CANAL|FLAG_INPUT|FLAG_OUTPUT|FLAG_EMITTER) )
+ {
+ for( int i = 0; i < vg_list_size( dirs ); i ++ )
+ {
+ struct cell *neighbour =
+ pcell((v2i){ x+dirs[i][0], y+dirs[i][1] });
+
+ if( neighbour->state &
+ (FLAG_CANAL|FLAG_INPUT|FLAG_OUTPUT|FLAG_EMITTER) )
+ {
+ config |= 0x1 << i;
+ }
+ }
+
+ height = 128;
+ }
+ else
+ {
+ if( cell->state & FLAG_WALL )
+ height = 0xFF; /*-0x3F + hash21i( (v2i){x,y}, 0x3F );*/
+
+ config = cell->state & FLAG_INPUT_NICE? 0xB: 0xF;
+ }
+
+ pcell((v2i){x,y})->config = config;
+
+ u8 *info_px = &info_buffer[ (pixel_id ++)*4 ];
+ info_px[0] = height;
+ info_px[1] = cell->state & FLAG_WALL? 0: 255;
+ info_px[2] = 0;
+ info_px[3] = 0;
+
+ /*
+ * Detecting hanging links that should be removed
+ */
+ int is_trigger = cell->state & FLAG_IS_TRIGGER;
+ int trigger_invalid = cell->config == 0xF ||
+ cell->config == k_cell_type_split;
+ int is_targeted = cell->state & FLAG_TARGETED;
+ int target_invalid = (cell->config != k_cell_type_split) &&
+ !(cell->state & FLAG_EMITTER);
+
+ if((
+ (is_trigger && trigger_invalid) ||
+ (is_targeted && target_invalid)
+ ) && update_texbuffer)
+ {
+ cell->state &= ~(FLAG_TARGETED|FLAG_IS_TRIGGER);
+ for( u32 i = 0; i < 2; i ++ )
+ {
+ if( cell->links[i] )
+ {
+ struct cell *other_ptr = &world.data[ cell->links[i] ];
+ other_ptr->links[ i ] = 0;
+ other_ptr->state &= ~FLAG_IS_TRIGGER;
+
+ if( other_ptr->links[ i ^ 0x1 ] == 0 )
+ other_ptr->state &= ~FLAG_TARGETED;
+ }
+ }
+
+ cell->links[0] = 0;
+ cell->links[1] = 0;
+ }
+ }
+ }
+
+ if( update_texbuffer )
+ {
+ glBindTexture( GL_TEXTURE_2D, world.background_data );
+ glTexSubImage2D( GL_TEXTURE_2D, 0,
+ px0 + 16, py0 + 16,
+ px1-px0, py1-py0, GL_RGBA, GL_UNSIGNED_BYTE, info_buffer );
+ }
+}
+
+static void gen_level_text(void)
+{
+ ui_px const unit_scale_px = 4*UI_GLYPH_SPACING_X;
+ ui_begin( &world.st.world_text, world.w*unit_scale_px,
+ world.h*unit_scale_px );
+
+ if( world.pCmpLevel )
+ {
+ for( int i = 0; i < vg_list_size( world.pCmpLevel->strings ); i ++ )
+ {
+ struct world_string *wstr = &world.pCmpLevel->strings[i];
+
+ if( wstr->str )
+ {
+ ui_px pos[2];
+
+ pos[0] = -UI_GLYPH_SPACING_X/2;
+
+ if( wstr->placement == k_placement_bottom )
+ pos[1] = 2*-unit_scale_px;
+ else
+ pos[1] = (world.h-1)*-unit_scale_px -6;
+
+ ui_text( &world.st.world_text, pos, wstr->str,
+ 1, k_text_align_left );
+ }
+ }
+ }
+
+ // re-create level scores
+ for( int i = 0; i < vg_list_size( career_packs ); i ++ )
+ {
+ struct career_level_pack *set = &career_packs[i];
+
+ /*
+ ui_text( &world.st.world_text,
+ (ui_px [2]){
+ set->origin[0]*unit_scale_px,
+ -(set->origin[1]+set->dims[1]+1)*unit_scale_px + 18
+ },
+ set->title, 1, k_text_align_left );
+ */
+
+ for( int j = 0; j < set->count; j ++ )
+ {
+ struct cmp_level *lvl = &set->pack[j];
+
+ if( lvl->completed_score && !lvl->is_tutorial )
+ {
+ char num[10];
+ snprintf( num, 9, "%d", lvl->completed_score );
+
+ ui_text( &world.st.world_text,
+ (ui_px [2]){
+ lvl->btn.position[0]*unit_scale_px + unit_scale_px/2,
+ -lvl->btn.position[1]*unit_scale_px - unit_scale_px/2
+ },
+ num, 1, k_text_align_center );
+ }
+ }
+ }
+
+ ui_resolve( &world.st.world_text );
+}
+
+/* Usually for ignoring windows crap */
+static int map_load_char_ignore( char c )
+{
+ if( c == '\r' ) return 1;
+ return 0;
+}
+
+static int map_load_sequence_char( struct terminal_run *run, char c )
+{
+ if( (c >= 'a' && c <= 'z') || c == ' ' )
+ {
+ i8 code = -1;
+ if( c != ' ' )
+ code = c - 'a';
+
+ run->steps[ run->step_count ++ ] = code;
+
+ return 1;
+ }
+
+ return 0;
+}
+
+static int map_load_is_digit( char c )
+{
+ if( (((u32)c >= (u32)'0') && ((u32)c <= (u32)'9')) || c == '-' )
+ {
+ return 1;
+ }
+
+ return 0;
+}
+
+static int map_load_is_terminal( char c )
+{
+ if( c == '+' || c == '-' || c == '*' )
+ return 1;
+ return 0;
+}
+
+static int map_load_apply_emitter_codes( struct cell_terminal *term )
+{
+ struct cell *cell = pcell( term->pos );
+
+ if( cell->state & FLAG_EMITTER )
+ {
+ if( (term->run_count > 0) && (term->runs[0].step_count >= 2) )
+ {
+ cell->emit[0] = term->runs[0].steps[0];
+ cell->emit[1] = term->runs[0].steps[1];
+ }
+ else
+ {
+ vg_error( "Emitter was not assigned emit values\n" );
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+static void map_load_cell( struct cell *cell, char c, int cx )
+{
+ cell->config = 0xF;
+
+ cell->links[0] = 0;
+ cell->links[1] = 0;
+
+ v3_zero( cell->glow[0] );
+ v3_zero( cell->glow[1] );
+
+ /* Input, output, emitter */
+ if( map_load_is_terminal(c) )
+ {
+ struct cell_terminal *term = arraddnptr( world.io, 1 );
+ term->pos[0] = cx;
+ term->pos[1] = world.h;
+
+ term->run_count = 1;
+ term->runs[0].step_count = 0;
+
+ switch( c )
+ {
+ case '+': cell->state = FLAG_INPUT; break;
+ case '-': cell->state = FLAG_OUTPUT; break;
+ case '*': cell->state = FLAG_EMITTER; break;
+ }
+ }
+ else if( c == '.' ) cell->state = FLAG_INPUT_NICE;
+ else if( c == '#' ) cell->state = FLAG_WALL;
+ else if( ((u32)c >= (u32)'A') && ((u32)c <= (u32)'A'+0xf) )
+ {
+ /*
+ * Canal flag bits (4bit/16 value):
+ * 0: Canal present
+ * 1: Is trigger
+ * 2: Reserved
+ * 3: Reserved
+ */
+ cell->state = ((u32)c - (u32)'A') & (FLAG_CANAL|FLAG_IS_TRIGGER);
+ world.score ++;
+ }
+ else cell->state = 0x00;
+}
+
+static void map_load_draw_background(void)
+{
+ u8 info_buffer[64*64*4];
+
+ for( int x = 0; x < 64; x ++ )
+ {
+ for( int y = 0; y < 64; y ++ )
+ {
+ u8 *px = &info_buffer[((x*64)+y)*4];
+
+#if 0
+ /* Fade out edges of world so that there isnt an obvious line */
+ int dx = 16 - VG_MIN( VG_MIN( x, 16 ), 16-VG_MAX( x-16-world.w, 0 ) ),
+ dy = 16 - VG_MIN( VG_MIN( y, 16 ), 16-VG_MAX( y-16-world.h, 0 ) ),
+
+ dist = VG_MAX( dx, dy ) * 16,
+ value = VG_MAX( 0, 0xFF-0x3F + hash21i( (v2i){x,y}, 0x3F ) - dist);
+#endif
+
+ px[0] = 0xFF;
+ px[1] = 0;
+ px[2] = 0;
+ px[3] = 0;
+ }
+ }
+
+ /*
+ * Level selection indentation, to make it look like the buttons are in a
+ * recessed area of the map.
+ */
+ for( int i = 0; i < vg_list_size( career_packs ); i ++ )
+ {
+ struct career_level_pack *grid = &career_packs[ i ];
+
+ int j = 0;
+
+ for( int y = 0; y < grid->dims[1]; y ++ )
+ {
+ for( int x = 0; x < grid->dims[0]; x ++ )
+ {
+ int cy = y+16+grid->origin[1],
+ cx = 16+x+grid->origin[0];
+
+ u8 *px = &info_buffer[(cy*64+cx)*4];
+ px[0] = 0x10;
+
+ if( j < grid->count )
+ {
+ struct cmp_level *lvl = &grid->pack[ j ++ ];
+ v2i_add( grid->origin, (v2i){x,y}, lvl->btn.position );
+ }
+ }
+ }
+ }
+
+ /*
+ * Recess the UI buttons, this adds a little bit of a (subtle) outline
+ * to them when the background shader is run
+ */
+ for( int i=0; i<4; i++ )
+ info_buffer[(((16+world.h-(i+2))*64)+world.w+16-1)*4] = 0x30;
+
+ /*
+ * Digging 'wires' from the output/input terminals, to make it look like
+ * there is something connecting our world.
+ */
+ for( int i = 0; i < arrlen(world.io); i ++ )
+ {
+ struct cell_terminal *term = &world.io[ i ];
+
+ v2i turtle;
+ v2i turtle_dir;
+ int original_y;
+
+ /*
+ * Only make breakouts for terminals on the edge,
+ * starting them from every position leads to some weird overlapping
+ * and confusing lines.
+ * */
+ if( !(term->pos[1] == 1 || term->pos[1] == world.h-2) )
+ continue;
+
+ turtle[0] = 16+term->pos[0];
+ turtle[1] = 16+term->pos[1];
+
+ turtle_dir[0] = 0;
+ turtle_dir[1] =
+ pcell(term->pos)->state & (FLAG_INPUT|FLAG_EMITTER)? 1: -1;
+ original_y = turtle_dir[1];
+
+ info_buffer[((turtle[1]*64)+turtle[0])*4] = 0;
+ v2i_add( turtle_dir, turtle, turtle );
+
+ for( int i = 0; i < 100; i ++ )
+ {
+ info_buffer[((turtle[1]*64)+turtle[0])*4] = 0;
+
+ v2i_add( turtle_dir, turtle, turtle );
+
+ if( turtle[0] == 0 ) break;
+ if( turtle[0] == 63 ) break;
+ if( turtle[1] == 0 ) break;
+ if( turtle[1] == 63 ) break;
+
+ int random_value = hash21i( turtle, 0xFF );
+ if( random_value > 255-40 && !turtle_dir[0] )
+ {
+ turtle_dir[0] = -1;
+ turtle_dir[1] = 0;
+ }
+ else if( random_value > 255-80 && !turtle_dir[0] )
+ {
+ turtle_dir[0] = 1;
+ turtle_dir[1] = 0;
+ }
+ else if( random_value > 255-100 )
+ {
+ turtle_dir[0] = 0;
+ turtle_dir[1] = original_y;
+ }
+ }
+ }
+
+ glBindTexture( GL_TEXTURE_2D, world.background_data );
+ glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 64, 64,
+ GL_RGBA, GL_UNSIGNED_BYTE, info_buffer );
+}
+
+static int map_load_validate(void)
+{
+ for( int i = 0; i < world.h*world.w; i ++ )
+ {
+ struct cell *src = &world.data[i];
+
+ if( src->state & FLAG_IS_TRIGGER )
+ {
+ int link_id = src->links[0]?0:1;
+ if( src->links[link_id] <= world.h*world.w )
+ {
+ struct cell *target = &world.data[ src->links[link_id] ];
+
+ int is_canal = target->state & FLAG_CANAL,
+ is_splitter = target->config == k_cell_type_split,
+ is_emitter = target->state & FLAG_EMITTER;
+
+ if((is_canal && is_splitter) || is_emitter)
+ {
+ if( target->links[ link_id ] )
+ {
+ vg_error( "Link target was already targeted\n" );
+ return 0;
+ }
+ else
+ {
+ /*
+ * Valid link, apply reverse mapping to other cell so it
+ * knows who is linking to it
+ */
+ target->links[ link_id ] = i;
+ target->state |= FLAG_TARGETED;
+ }
+ }
+ else
+ {
+ vg_error( "Link target was invalid\n" );
+ return 0;
+ }
+ }
+ else
+ {
+ vg_error( "Link target out of bounds\n" );
+ return 0;
+ }
+ }
+ }
+
+ return 1;
+}
+
+static int map_load( const char *str, const char *name )
+{
+ map_free();
+
+ char const *c = str;
+
+ /* Predetermine width */
+ for(;; world.w ++)
+ {
+ if( c[world.w] == ';' )
+ break;
+ else if( !c[world.w] )
+ {
+ vg_error( "Unexpected EOF when parsing level\n" );
+ return 0;
+ }
+ }
+
+ struct cell *row = arraddnptr( world.data, world.w );
+ int cx = 0;
+ int reg_start = 0, reg_end = 0;
+
+ u32 *links_to_make = NULL;
+ int links_satisfied = 0;
+
+ char link_id_buffer[32];
+ int link_id_n = 0;
+
+ for(;;)
+ {
+ if( !*c )
+ break;
+
+ if( map_load_char_ignore( *c ) ) { c++; continue; }
+
+ if( *c == ';' )
+ {
+ c ++;
+
+ if( *c == '\r' ) c ++;
+
+ /* Parse attribs */
+ if( *c != '\n' )
+ {
+ while( *c )
+ {
+ if( map_load_char_ignore( *c ) ) { c++; continue; }
+
+ if( reg_start < reg_end )
+ {
+ struct cell_terminal *terminal = &world.io[ reg_start ];
+ struct terminal_run *run =
+ &terminal->runs[ terminal->run_count-1 ];
+
+ if( !map_load_sequence_char( run, *c ) )
+ {
+ /* Control characters */
+ if( *c == ',' || *c == '\n' ) /* Next terminal */
+ {
+ reg_start ++;
+
+ if( *c == '\n' )
+ break;
+ }
+ else if( *c == ':' ) /* New run starting */
+ {
+ terminal->runs[ terminal->run_count ].step_count = 0;
+ terminal->run_count ++;
+ world.max_runs =
+ vg_max( world.max_runs, terminal->run_count );
+ }
+ else
+ {
+ vg_error( "Unkown attribute '%c' (row: %u)\n",
+ *c, world.h );
+ goto IL_REG_ERROR;
+ }
+ }
+ }
+ else
+ {
+ if( links_satisfied < arrlen( links_to_make ) )
+ {
+ struct cell *target =
+ &world.data[ links_to_make[ links_satisfied ] ];
+
+ if( map_load_is_digit( *c ) )
+ {
+ if( link_id_n >= vg_list_size( link_id_buffer )-1 )
+ {
+ vg_error( "Number was way too long to be parsed"
+ " (row: %u)\n", world.h );
+ goto IL_REG_ERROR;
+ }
+
+ link_id_buffer[ link_id_n ++ ] = *c;
+ }
+ else if( *c == ',' || *c == '\n' )
+ {
+ link_id_buffer[ link_id_n ] = 0x00;
+ int value = atoi( link_id_buffer );
+
+ target->links[value >= 0? 1:0] = abs(value);
+ links_satisfied ++;
+ link_id_n = 0;
+
+ if( *c == '\n' )
+ break;
+ }
+ else
+ {
+ vg_error( "Invalid character '%c'"
+ " (row: %u)\n", *c, world.h );
+ goto IL_REG_ERROR;
+ }
+ }
+ else
+ {
+ vg_error( "Too many values to assign"
+ " (row: %u)\n", world.h );
+ goto IL_REG_ERROR;
+ }
+ }
+
+ c ++;
+ }
+ }
+
+ /* Registry length-error checks */
+ if( reg_start != reg_end )
+ {
+ vg_error( "Not enough spawn values assigned (row: %u, %u of %u)\n",
+ world.h, reg_start, reg_end );
+ goto IL_REG_ERROR;
+ }
+
+ if( links_satisfied != arrlen( links_to_make ) )
+ {
+ vg_error( "Not enough link values assigned (row: %u, %u of %u)\n",
+ world.h, links_satisfied, arrlen( links_to_make ) );
+ goto IL_REG_ERROR;
+ }
+
+ if( cx != world.w )
+ {
+ vg_error( "Not enough cells to match previous row definition"
+ " (row: %u, %u<%u)\n", world.h, cx, world.w );
+ goto IL_REG_ERROR;
+ }
+
+ row = arraddnptr( world.data, world.w );
+ cx = 0;
+ world.h ++;
+ reg_end = reg_start = arrlen( world.io );
+
+ arrsetlen( links_to_make, 0 );
+ links_satisfied = 0;
+ }
+ else
+ {
+ if( cx == world.w )
+ {
+ vg_error( "Too many cells to match previous row definition"
+ " (row: %u, %u>%u)\n", world.h, cx, world.w );
+ goto IL_REG_ERROR;
+ }
+
+ struct cell *cell = &row[ cx ];
+ map_load_cell( cell, *c, cx );
+
+ if( map_load_is_terminal(*c) )
+ reg_end ++;
+
+ if( cell->state & FLAG_IS_TRIGGER )
+ arrpush( links_to_make, cx + world.h*world.w );
+
+ cx ++;
+ }
+
+ c ++;
+ }
+
+ for( int i = 0; i < arrlen( world.io ); i ++ )
+ {
+ if( !map_load_apply_emitter_codes( &world.io[i] ) )
+ goto IL_REG_ERROR;
+ }
+
+ map_load_draw_background();
+ map_reclassify( NULL, NULL, 1 );
+
+ if( !map_load_validate() )
+ goto IL_REG_ERROR;
+
+ /*
+ * At this point the world is in a fully loaded and complete state
+ */
+
+ arrfree( links_to_make );
+
+ vg_success( "Map '%s' loaded! (%u:%u)\n", name, world.w, world.h );
+
+ io_reset();
+
+ strncpy( world.map_name, name, vg_list_size( world.map_name )-1 );
+ world.initialzed = 1;
+
+ /* Setup world button locations */
+ for( int i = 0; i < vg_list_size( world.st.buttons ); i ++ )
+ {
+ struct world_button *btn = &world.st.buttons[i];
+ btn->position[0] = world.w -1;
+ btn->position[1] = world.h -i -2;
+ }
+
+ /* Allocate buffers for render commands */
+ world.cmd_buf_tiles = malloc( world.w*world.h* sizeof( struct render_cmd ) );
+ world.max_commands = world.w*world.h;
+ return 1;
+
+IL_REG_ERROR:
+ arrfree( links_to_make );
+ map_free();
+ return 0;
+}
+
+static void map_serialize( FILE *stream )
+{
+ for( int y = 0; y < world.h; y ++ )
+ {
+ for( int x = 0; x < world.w; x ++ )
+ {
+ struct cell *cell = pcell( (v2i){ x, y } );
+
+ if( cell->state & FLAG_WALL ) fputc( '#', stream );
+ else if( cell->state & FLAG_INPUT_NICE ) fputc( '.', stream );
+ else if( cell->state & FLAG_INPUT ) fputc( '+', stream );
+ else if( cell->state & FLAG_OUTPUT ) fputc( '-', stream );
+ else if( cell->state & FLAG_EMITTER ) fputc( '*', stream );
+ else if( cell->state & FLAG_4B_GROUP )
+ {
+ /*
+ * Serialize the '4 bit group' into ABCD...
+ */
+ fputc( (cell->state & FLAG_4B_GROUP) + (u32)'A', stream );
+ }
+ else fputc( ' ', stream );
+ }
+
+ fputc( ';', stream );
+ int terminal_write_count = 0;
+
+ for( int x = 0; x < world.w; x ++ )
+ {
+ for( int i = 0; i < arrlen( world.io ); i ++ )
+ {
+ struct cell_terminal *term = &world.io[i];
+ if( v2i_eq( term->pos, (v2i){x,y} ) )
+ {
+ if( terminal_write_count )
+ fputc( ',', stream );
+ terminal_write_count ++;
+
+ for( int j = 0; j < term->run_count; j ++ )
+ {
+ struct terminal_run *run = &term->runs[j];
+
+ for( int k = 0; k < run->step_count; k ++ )
+ {
+ i8 step = run->steps[k];
+ fputc( step == -1? ' ': ('a' + run->steps[k]), stream );
+ }
+
+ if( j < term->run_count-1 )
+ fputc( ':', stream );
+ }
+ }
+ }
+ }
+
+ for( int x = 0; x < world.w; x ++ )
+ {
+ struct cell *cell = pcell( (v2i){ x,y } );
+ if( cell->state & FLAG_IS_TRIGGER )
+ {
+ if( terminal_write_count )
+ fputc( ',', stream );
+ terminal_write_count ++;
+
+ fprintf( stream, "%d",
+ cell->links[0]? -cell->links[0]: cell->links[1] );
+ }
+ }
+
+ fputc( '\n', stream );
+ }
+}
+
+/*
+ * Career state
+ */
+#pragma pack(push,1)
+struct dcareer_state
+{
+ u32 version;
+ i32 in_map;
+
+ u32 reserved[14];
+
+ struct dlevel_state
+ {
+ i32 score;
+
+ i32 unlocked;
+ i32 reserved[2];
+ }
+ levels[ NUM_CAMPAIGN_LEVELS ];
+};
+#pragma pack(pop)
+
+static int career_load_success = 0;
+
+static void career_serialize(void)
+{
+ if( !career_load_success )
+ return;
+
+ struct dcareer_state encoded;
+ encoded.version = MARBLE_COMP_VERSION;
+ encoded.in_map = world.pCmpLevel? world.pCmpLevel->serial_id: -1;
+
+ memset( encoded.reserved, 0, sizeof( encoded.reserved ) );
+
+ for( int i = 0; i < vg_list_size( career_packs ); i ++ )
+ {
+ struct career_level_pack *set = &career_packs[i];
+
+ for( int j = 0; j < set->count; j ++ )
+ {
+ struct cmp_level *lvl = &set->pack[j];
+ struct dlevel_state *dest = &encoded.levels[lvl->serial_id];
+
+ dest->score = lvl->completed_score;
+ dest->unlocked = lvl->unlocked;
+ dest->reserved[0] = 0;
+ dest->reserved[1] = 0;
+ }
+ }
+
+ vg_asset_write( "sav/game.sv2", &encoded, sizeof( struct dcareer_state ) );
+}
+
+static void career_unlock_level( struct cmp_level *lvl );
+static void career_unlock_level( struct cmp_level *lvl )
+{
+ lvl->unlocked = 1;
+
+ if( lvl->linked )
+ career_unlock_level( lvl->linked );
+}
+
+static void career_pass_level( struct cmp_level *lvl, int score, int upload )
+{
+ if( score > 0 )
+ {
+ lvl->completed_score = score;
+ gen_level_text();
+
+ if( lvl->unlock )
+ career_unlock_level( lvl->unlock );
+
+ #ifdef VG_STEAM
+ if( lvl->achievement )
+ sw_set_achievement( lvl->achievement );
+
+ /* Check ALL maps to trigger master engineer */
+ for( int i = 0; i < vg_list_size( career_packs ); i ++ )
+ {
+ struct career_level_pack *set = &career_packs[i];
+
+ for( int j = 0; j < set->count; j ++ )
+ {
+ if( set->pack[j].completed_score == 0 )
+ return;
+ }
+ }
+
+ sw_set_achievement( "MASTER_ENGINEER" );
+ #endif
+ }
+}
+
+static void career_reset_level( struct cmp_level *lvl )
+{
+ lvl->unlocked = 0;
+ lvl->completed_score = 0;
+}
+
+static void career_load(void)
+{
+ i64 sz;
+ struct dcareer_state encoded;
+
+ /* Blank save state */
+ memset( (void*)&encoded, 0, sizeof( struct dcareer_state ) );
+ encoded.in_map = 0;
+ encoded.levels[0].unlocked = 1;
+
+ /*
+ * Load and copy, this step is just to ensure old/newer saves can be loaded
+ * without crashing. Old saves will load fine, too new saves will lose data,
+ * such a situation should rarely (never) happen with the steam version.
+ */
+ void *cr = vg_asset_read_s( "sav/game.sv2", &sz );
+
+ if( cr )
+ {
+ if( sz > sizeof( struct dcareer_state ) )
+ vg_warn( "This save file is too big! Some levels will be lost\n" );
+
+ if( sz <= offsetof( struct dcareer_state, levels ) )
+ {
+ vg_warn( "This save file is too small to have a header. "
+ "Creating a blank one\n" );
+ free( cr );
+ }
+
+ memcpy( (void*)&encoded, cr, VG_MIN( sizeof( struct dcareer_state ), sz));
+ free( cr );
+ }
+ else
+ vg_info( "No save file... Using blank one\n" );
+
+ /* Reset memory */
+ for( int i = 0; i < vg_list_size( career_packs ); i ++ )
+ {
+ struct career_level_pack *set = &career_packs[i];
+
+ for( int j = 0; j < set->count; j ++ )
+ career_reset_level( &set->pack[j] );
+ }
+
+ /* Header information */
+
+ struct cmp_level *lvl_to_load = &career_packs[0].pack[0];
+
+ /* Decode everything from dstate */
+ for( int i = 0; i < vg_list_size( career_packs ); i ++ )
+ {
+ struct career_level_pack *set = &career_packs[i];
+
+ for( int j = 0; j < set->count; j ++ )
+ {
+ struct cmp_level *lvl = &set->pack[j];
+ struct dlevel_state *src = &encoded.levels[lvl->serial_id];
+
+ if( src->unlocked ) career_unlock_level( lvl );
+ if( src->score )
+ {
+ lvl->completed_score = src->score;
+
+ /*
+ * Apply unlocking trigger to next levels,
+ * in case the level graph was updated in the future
+ */
+ if( lvl->unlock )
+ career_unlock_level( lvl->unlock );
+ }
+
+ if( lvl->serial_id == encoded.in_map )
+ lvl_to_load = lvl;
+ }
+ }
+
+ if( console_changelevel( 1, &lvl_to_load->map_name ) )
+ {
+ world.pCmpLevel = lvl_to_load;
+ gen_level_text();
+ }
+
+ career_load_success = 1;
+
+#if 0
+ if( encoded.version < MARBLE_COMP_VERSION )
+ world.st.state = k_game_state_update;
+#endif
+}
+
+/*
+ * Main gameplay
+ */
+static int is_simulation_running(void)
+{
+ return world.st.buttons[ k_world_button_sim ].state;
+}
+
+static void clear_animation_flags(void)
+{
+ for( int i = 0; i < world.w*world.h; i ++ )
+ world.data[ i ].state &= ~(FLAG_FLIP_FLOP|FLAG_FLIP_ROTATING);
+}
+
+static void simulation_stop(void)