diff --git a/common/port.h b/common/port.h index 9581a61f..89d2d762 100644 --- a/common/port.h +++ b/common/port.h @@ -34,6 +34,9 @@ GNU General Public License for more details. #elif XASH_PS4 #define OS_LIB_EXT "prx" #define OPEN_COMMAND "" +#elif XASH_EMSCRIPTEN + #define OS_LIB_EXT "wasm" + #define OPEN_COMMAND "" #elif XASH_POSIX #define OS_LIB_EXT "so" #define OPEN_COMMAND "xdg-open" diff --git a/engine/client/cl_main.c b/engine/client/cl_main.c index 39e4f9c2..4e65bf5e 100644 --- a/engine/client/cl_main.c +++ b/engine/client/cl_main.c @@ -1773,6 +1773,10 @@ Sends a disconnect message to the server This is also called on Host_Error, so it shouldn't cause any errors ===================== */ +#if XASH_EMSCRIPTEN +static qboolean cl_web_reconnecting; // CL_Reconnect_f: a map change, not a real disconnect +#endif + void CL_Disconnect( void ) { if( cls.state == ca_disconnected ) @@ -1805,6 +1809,12 @@ void CL_Disconnect( void ) cls.signon = 0; cls.net_protocol = PROTO_CURRENT; +#if XASH_EMSCRIPTEN + // SwedenCode: after a real disconnect the page shows its own screen (reconnect / servers) instead of the menu + if( !cl_web_reconnecting && Emscripten_Disconnected( )) + return; +#endif + // back to menu in non-developer mode if( host_developer.value || cls.key_dest == key_menu ) return; @@ -1940,7 +1950,15 @@ static void CL_Reconnect_f( void ) connprotocol_t proto = cls.net_protocol; if( cls.state >= ca_connected ) + { +#if XASH_EMSCRIPTEN + cl_web_reconnecting = true; +#endif CL_Disconnect(); +#if XASH_EMSCRIPTEN + cl_web_reconnecting = false; +#endif + } cls.connect_time = MAX_HEARTBEAT; // fire immediately cls.demonum = cls.movienum = -1; // not in the demo loop now @@ -3641,6 +3659,11 @@ void CL_Escape_f( void ) if( cls.state == ca_cinematic ) SCR_NextMovie(); // jump to next movie +#if XASH_EMSCRIPTEN + // in a game the page may show its own menu over the running game (Module.onGameMenu) + else if( cls.state == ca_active && Emscripten_GameMenu( )) + return; +#endif else UI_SetActiveMenu( true ); } diff --git a/engine/client/console.c b/engine/client/console.c index c7b35c5d..995cf21e 100644 --- a/engine/client/console.c +++ b/engine/client/console.c @@ -2352,7 +2352,7 @@ static void Con_DrawSolidConsole( int lines ) // draw current version memcpy( color, g_color_table[7], sizeof( color )); - Q_snprintf( curbuild, MAX_STRING, XASH_ENGINE_NAME " %i/" XASH_VERSION " (%s-%s build %i)", PROTOCOL_VERSION, Q_buildos(), Q_buildarch(), Q_buildnum( )); + Q_snprintf( curbuild, MAX_STRING, SWC_ENGINE_NAME " (web build %i)", Q_buildnum( )); Con_DrawStringLen( curbuild, &stringLen, &charH ); @@ -2503,7 +2503,7 @@ void Con_DrawVersion( void ) if( cls.key_dest == key_menu ) { Q_snprintf( curbuild, sizeof( curbuild ), - "v%i/" XASH_VERSION " (%s-%s build %i)", PROTOCOL_VERSION, Q_buildos(), Q_buildarch(), Q_buildnum( )); + SWC_ENGINE_NAME " (web build %i)", Q_buildnum( )); } else { @@ -2520,7 +2520,7 @@ void Con_DrawVersion( void ) return; Q_snprintf( curbuild, sizeof( curbuild ), - XASH_ENGINE_NAME " v%i/" XASH_VERSION " (%s-%s build %i)", PROTOCOL_VERSION, Q_buildos(), Q_buildarch(), Q_buildnum( )); + SWC_ENGINE_NAME " (web build %i)", Q_buildnum( )); } int stringLen, charH = 0; diff --git a/engine/client/identification.c b/engine/client/identification.c index dd28842e..277c1b9a 100644 --- a/engine/client/identification.c +++ b/engine/client/identification.c @@ -675,12 +675,34 @@ static void ID_Check( void ) #endif } +#if XASH_EMSCRIPTEN +/* +A web browser exposes no machine data, so every browser would get the same id and the same key: GoldSrc +servers that take the SteamID from the RevEmu2013 ticket would see one player. The page gives each browser +its own random key (Module.playerKey, see platform/emscripten/library_xash.js). The GoldSrc ticket is made +from that key itself, so it is the same ticket the page made before this existed, and players keep their +SteamIDs; Xash3D servers get a per-server hash of it. +*/ +static char id_browser_key[33]; +#endif + void ID_GetMD5ForAddress( char *key, netadr_t adr, size_t size ) { MD5Context_t ctx; byte buf[32], md5[16]; size_t bufsize = 0; +#if XASH_EMSCRIPTEN + if( id_browser_key[0] ) + { + if( NET_NetadrType( &adr ) == NA_LOOPBACK ) + { + Q_strncpy( key, id_browser_key, size ); + return; + } + } +#endif + switch( NET_NetadrType( &adr )) { case NA_IP: @@ -696,6 +718,11 @@ void ID_GetMD5ForAddress( char *key, netadr_t adr, size_t size ) } MD5Init( &ctx ); +#if XASH_EMSCRIPTEN + if( id_browser_key[0] ) + MD5Update( &ctx, (byte *)id_browser_key, 32 ); + else +#endif MD5Update( &ctx, (byte *)&id, sizeof( id )); if( bufsize != 0 ) MD5Update( &ctx, buf, bufsize ); @@ -711,6 +738,12 @@ void ID_Init( void ) Cmd_AddRestrictedCommand( "testcpuinfo", ID_TestCPUInfo_f, "try read cpu serial" ); #endif +#if XASH_EMSCRIPTEN + if( Emscripten_PlayerKey( id_browser_key, sizeof( id_browser_key ))) + return; + id_browser_key[0] = 0; +#endif + #if XASH_ANDROID && !XASH_DEDICATED sscanf( Android_LoadID(), "%016"PRIX64, &id ); if( id ) diff --git a/engine/common/cmd.c b/engine/common/cmd.c index d640a991..e5105a26 100644 --- a/engine/common/cmd.c +++ b/engine/common/cmd.c @@ -940,7 +940,13 @@ static void Cmd_ExecuteStringWithPrivilegeCheck( const char *text, qboolean isPr } else { +#ifdef __EMSCRIPTEN__ + // web build: servers stuff "bind" and the like on join; refusing is right, but the warning only + // cluttered the player's screen, so it goes to the developer console + Con_Reportf( S_WARN "Could not execute privileged command %s\n", cmd->name ); +#else Con_Printf( S_WARN "Could not execute privileged command %s\n", cmd->name ); +#endif } return; } diff --git a/engine/common/com_strings.h b/engine/common/com_strings.h index 74ca70e0..4b5e0c8a 100644 --- a/engine/common/com_strings.h +++ b/engine/common/com_strings.h @@ -75,6 +75,8 @@ GNU General Public License for more details. #define DEFAULT_UPDATE_PAGE "https://github.com/FWGS/xash3d-fwgs/releases/latest" #define XASH_ENGINE_NAME "Xash3D FWGS" +// SwedenCode: the name players see (console, `version`). XASH_ENGINE_NAME stays for paths and protocol strings. +#define SWC_ENGINE_NAME "SwedenCode Engine" #define XASH_DEDICATED_SERVER_NAME "XashDS" #define XASH_VERSION "0.21" // engine current version #define XASH_COMPAT_VERSION "0.99" // version we are based on diff --git a/engine/common/filesystem_engine.c b/engine/common/filesystem_engine.c index f7e9fbfe..51c3e303 100644 --- a/engine/common/filesystem_engine.c +++ b/engine/common/filesystem_engine.c @@ -284,6 +284,12 @@ static qboolean FS_DetermineRootDirectory( char *out, size_t size ) return true; Sys_Error( "couldn't find %s data directory", XASH_ENGINE_NAME ); return false; +#elif XASH_EMSCRIPTEN + // the page puts the game data into the virtual filesystem and changes into that directory before main() + if( getcwd( out, size )) + return true; + Sys_Error( "couldn't determine current directory: %s", strerror( errno )); + return false; #elif ( XASH_SDL >= 2 ) && !XASH_NSWITCH // GetBasePath not impl'd in switch-sdl2 // SDL2 hands the base path over to us, SDL3 keeps ownership and frees it on quit qboolean owned = XASH_SDL == 2; diff --git a/engine/common/host.c b/engine/common/host.c index 8b43cfc2..361607b9 100644 --- a/engine/common/host.c +++ b/engine/common/host.c @@ -119,7 +119,7 @@ static const feature_message_t engine_features[] = static void Host_MakeVersionString( char *out, size_t len ) { - Q_snprintf( out, len, XASH_ENGINE_NAME " %i/" XASH_VERSION " (%s-%s build %i)", PROTOCOL_VERSION, Q_buildos(), Q_buildarch(), Q_buildnum( )); + Q_snprintf( out, len, SWC_ENGINE_NAME " %i (web build %i, GPL, based on " XASH_ENGINE_NAME " " XASH_VERSION ")", PROTOCOL_VERSION, Q_buildnum( )); } static void Host_PrintUsage( const char *exename ) @@ -1176,6 +1176,24 @@ static void Sys_Quit_f( void ) Sys_Quit( Cmd_Argc() > 1 ? Cmd_Argv( 1 ) : "command" ); } +#if XASH_EMSCRIPTEN +static void Host_EmscriptenFrame( void *arg ) +{ + double *oldtime = arg; + double newtime; + + if( host.status == HOST_CRASHED ) + { + emscripten_cancel_main_loop(); + return; + } + + newtime = Platform_DoubleTime(); + COM_Frame( newtime - *oldtime ); + *oldtime = newtime; +} +#endif + /* ================= Host_Main @@ -1352,6 +1370,10 @@ int EXPORT Host_Main( int argc, char **argv, const char *progname, int bChangeGa PS4_AllowHideSplash( ); #endif +#if XASH_EMSCRIPTEN + // a browser tab can't block: run one frame per animation frame, main() returns to the page + emscripten_set_main_loop_arg( Host_EmscriptenFrame, &oldtime, 0, true ); +#else // main window message loop while( host.status != HOST_CRASHED ) { @@ -1359,6 +1381,7 @@ int EXPORT Host_Main( int argc, char **argv, const char *progname, int bChangeGa COM_Frame( newtime - oldtime ); oldtime = newtime; } +#endif return 0; } diff --git a/engine/common/net_ws.c b/engine/common/net_ws.c index 06fd730b..634f81b0 100644 --- a/engine/common/net_ws.c +++ b/engine/common/net_ws.c @@ -19,6 +19,9 @@ GNU General Public License for more details. #include "xash3d_mathlib.h" #include "ipv6text.h" #include "net_ws_private.h" +#if XASH_EMSCRIPTEN +#include "platform/emscripten/net_emscripten.h" +#endif #include "server.h" // sv_cheats #if XASH_SDL == 2 diff --git a/engine/platform/emscripten/library_xash.js b/engine/platform/emscripten/library_xash.js new file mode 100644 index 00000000..e6e7e8ab --- /dev/null +++ b/engine/platform/emscripten/library_xash.js @@ -0,0 +1,68 @@ +/* +library_xash.js - Emscripten JS library for the Xash3D FWGS web build +Copyright (C) 2026 SwedenCode + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +The game's UDP socket is not an Emscripten socket: every call is handed to the page's network object +(Module.net), which carries the datagrams (e.g. over a WebSocket relay). The page's object implements +socket/bind/sendto/recvfrom/closesocket/getsockname/gethostname/getaddrinfo with BSD argument order and +pointers into the wasm heap; a missing method makes the call fail with -1. +TCP (HTTP downloads) keeps using Emscripten's own WebSocket-backed sockets. +*/ + +addToLibrary({ + emscripten_net_socket: (family, type, protocol) => Module['net']?.['socket']?.(family, type, protocol) ?? -1, + emscripten_net_bind: (fd, sockaddr, socklen) => Module['net']?.['bind']?.(fd, sockaddr, socklen) ?? -1, + emscripten_net_closesocket: (fd) => Module['net']?.['closesocket']?.(fd) ?? -1, + emscripten_net_getsockname: (fd, sockaddr, socklen) => Module['net']?.['getsockname']?.(fd, sockaddr, socklen) ?? -1, + emscripten_net_gethostname: (name, namelen) => Module['net']?.['gethostname']?.(name, namelen) ?? -1, + emscripten_net_getaddrinfo: (host, service, hints, res) => Module['net']?.['getaddrinfo']?.(host, service, hints, res) ?? -1, + emscripten_net_sendto: (fd, buf, len, flags, sockaddr, socklen) => Module['net']?.['sendto']?.(fd, buf, len, flags, sockaddr, socklen) ?? -1, + emscripten_net_recvfrom: (fd, buf, len, flags, sockaddr, socklen) => Module['net']?.['recvfrom']?.(fd, buf, len, flags, sockaddr, socklen) ?? -1, + + // Web Audio buffer size multiplier for SDL audio (Module.audioBufferMultiplier, default 1) + emscripten_xash_audio_multiplier: () => { + var m = Module['audioBufferMultiplier'] | 0; + return m > 0 && m <= 16 ? m : 1; + }, + + // In-game menu: Module.onGameMenu() shows the page's own menu instead of the engine's; it returns true when it did + // Real disconnect (not a map change): Module.onDisconnect() shows the page's own screen; true = page took over + emscripten_xash_disconnected: () => { + try { return Module['onDisconnect'] && Module['onDisconnect']() ? 1 : 0; } catch (e) { return 0; } + }, + + emscripten_xash_game_menu: () => { + try { return Module['onGameMenu'] && Module['onGameMenu']() ? 1 : 0; } catch (e) { return 0; } + }, + + // Per-browser player key for ID_Init: Module.playerKey (32 lowercase hex digits) when the page gives one, + // otherwise a random key kept in localStorage. Writes a NUL terminated string, returns its length or 0. + emscripten_xash_player_key__deps: ['$stringToUTF8'], + emscripten_xash_player_key: (buf, size) => { + var ok = (k) => typeof k == 'string' && /^[0-9a-f]{32}$/.test(k); + var key = Module['playerKey']; + if (typeof key == 'function') key = key(); + if (!ok(key)) { + try { key = localStorage.getItem('xash3d-player-key'); } catch (e) { key = null; } + if (!ok(key)) { + var b = new Uint8Array(16); + crypto.getRandomValues(b); + key = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join(''); + try { localStorage.setItem('xash3d-player-key', key); } catch (e) {} + } + } + if (size < 33) return 0; + stringToUTF8(key, buf, size); + return 32; + }, +}); diff --git a/engine/platform/emscripten/net_emscripten.h b/engine/platform/emscripten/net_emscripten.h new file mode 100644 index 00000000..3f66f9ef --- /dev/null +++ b/engine/platform/emscripten/net_emscripten.h @@ -0,0 +1,76 @@ +/* +net_emscripten.h - the game's UDP socket in a web browser +Copyright (C) 2026 SwedenCode + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +Included by net_ws.c only. A browser has no UDP, so the socket calls of net_ws.c go to the page's network +object (Module.net, see library_xash.js), which carries the datagrams (e.g. over a WebSocket relay). +Only IPv4 datagram sockets exist. Socket options and non-blocking mode are accepted and ignored: the page's +socket never blocks. HTTP downloads (net_http_xash.c) are not affected and use Emscripten's sockets. +*/ +#ifndef NET_EMSCRIPTEN_H +#define NET_EMSCRIPTEN_H + +#include +#include + +int emscripten_net_socket( int family, int type, int protocol ); +int emscripten_net_bind( int fd, const struct sockaddr *addr, socklen_t len ); +int emscripten_net_closesocket( int fd ); +int emscripten_net_getsockname( int fd, struct sockaddr *addr, socklen_t *len ); +int emscripten_net_gethostname( char *name, size_t len ); +int emscripten_net_getaddrinfo( const char *host, const char *service, const struct addrinfo *hints, struct addrinfo **res ); +int emscripten_net_sendto( int fd, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen ); +int emscripten_net_recvfrom( int fd, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen ); + +static inline int Emscripten_NetSocket( int family, int type, int protocol ) +{ + if( family != AF_INET || type != SOCK_DGRAM ) + { + errno = EAFNOSUPPORT; // quietly skipped by NET_IPSocket + return -1; + } + return emscripten_net_socket( family, type, protocol ); +} + +static inline int Emscripten_NetIgnore( void ) +{ + return 0; +} + +// the page allocates the result with malloc: one addrinfo and one sockaddr per entry +static inline void Emscripten_NetFreeAddrInfo( struct addrinfo *ai ) +{ + while( ai ) + { + struct addrinfo *next = ai->ai_next; + free( ai->ai_addr ); + free( ai ); + ai = next; + } +} + +#undef closesocket +#undef ioctlsocket +#define socket( family, type, protocol ) Emscripten_NetSocket(( family ), ( type ), ( protocol )) +#define bind( fd, addr, len ) emscripten_net_bind(( fd ), ( addr ), ( len )) +#define closesocket( fd ) emscripten_net_closesocket(( fd )) +#define getsockname( fd, addr, len ) emscripten_net_getsockname(( fd ), ( addr ), ( len )) +#define gethostname( name, len ) emscripten_net_gethostname(( name ), ( len )) +#define getaddrinfo( h, s, hints, res ) emscripten_net_getaddrinfo(( h ), ( s ), ( hints ), ( res )) +#define freeaddrinfo( ai ) Emscripten_NetFreeAddrInfo(( ai )) +#define sendto( fd, b, l, f, to, tl ) emscripten_net_sendto(( fd ), ( b ), ( l ), ( f ), ( to ), ( tl )) +#define recvfrom( fd, b, l, f, from, fl ) emscripten_net_recvfrom(( fd ), ( b ), ( l ), ( f ), ( from ), ( fl )) +#define setsockopt( fd, lvl, opt, v, l ) (( void )( fd ), ( void )( v ), Emscripten_NetIgnore( )) +#define ioctlsocket( fd, req, arg ) (( void )( fd ), ( void )( arg ), Emscripten_NetIgnore( )) + +#endif // NET_EMSCRIPTEN_H diff --git a/engine/platform/emscripten/sys_emscripten.c b/engine/platform/emscripten/sys_emscripten.c new file mode 100644 index 00000000..fa320e47 --- /dev/null +++ b/engine/platform/emscripten/sys_emscripten.c @@ -0,0 +1,59 @@ +/* +sys_emscripten.c - web browser specific engine functions +Copyright (C) 2026 SwedenCode + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. +*/ +#include +#include +#include "common.h" +#include "platform/platform.h" + +int emscripten_xash_audio_multiplier( void ); +int emscripten_xash_player_key( char *buf, int size ); + +// the page's network object reports socket errors (EAGAIN) through errno +EMSCRIPTEN_KEEPALIVE int *getErrnoLocation( void ) +{ + return &errno; +} + +// SDL audio buffer = this x 1024 samples (Module.audioBufferMultiplier), a power of two +int Emscripten_AudioMultiplier( void ) +{ + int m = emscripten_xash_audio_multiplier( ), p = 1; + + while( p * 2 <= m && p < 16 ) + p *= 2; + + return p; +} + +int emscripten_xash_game_menu( void ); +int emscripten_xash_disconnected( void ); + +// the page's own "disconnected" screen, if it has one; true when the page took over +qboolean Emscripten_Disconnected( void ) +{ + return emscripten_xash_disconnected( ) != 0; +} + +// the page's own in-game menu, if it has one; true when the page took over +qboolean Emscripten_GameMenu( void ) +{ + return emscripten_xash_game_menu( ) != 0; +} + +// per-browser player key (32 lowercase hex digits), see identification.c +qboolean Emscripten_PlayerKey( char *key, size_t size ) +{ + return emscripten_xash_player_key( key, (int)size ) == 32; +} diff --git a/engine/platform/platform.h b/engine/platform/platform.h index 4b1e40c6..b43e7af4 100644 --- a/engine/platform/platform.h +++ b/engine/platform/platform.h @@ -152,6 +152,13 @@ static inline double Platform_GetCPUTime( void ) #endif } +#if XASH_EMSCRIPTEN +int Emscripten_AudioMultiplier( void ); +qboolean Emscripten_PlayerKey( char *key, size_t size ); +qboolean Emscripten_GameMenu( void ); +qboolean Emscripten_Disconnected( void ); +#endif + #if XASH_NSWITCH void NSwitch_Init( void ); void NSwitch_Shutdown( void ); diff --git a/engine/platform/sdl2/s_sdl2.c b/engine/platform/sdl2/s_sdl2.c index 51362471..3887dcc9 100644 --- a/engine/platform/sdl2/s_sdl2.c +++ b/engine/platform/sdl2/s_sdl2.c @@ -126,7 +126,11 @@ qboolean SNDDMA_Init( void ) { .freq = SOUND_DMA_SPEED, .format = AUDIO_S16SYS, +#if XASH_EMSCRIPTEN + .samples = 1024 * Emscripten_AudioMultiplier( ), +#else .samples = 1024, +#endif .channels = 2, .callback = SDL_SoundCallback, }; diff --git a/engine/wscript b/engine/wscript index dafbf490..501e1e28 100644 --- a/engine/wscript +++ b/engine/wscript @@ -326,14 +326,24 @@ def build(bld): linkflags = [] if bld.env.DEST_OS == 'emscripten': - linkflags = ['-sINITIAL_MEMORY=134217728', '-sALLOW_MEMORY_GROWTH=1', '-sSTACK_SIZE=16777216'] - - linkflags += ['-sASYNCIFY=1'] - - node = bld.srcnode.find_node('rodir') - if not node: - bld.fatal('Put game data into rodir folder in source tree root') - linkflags += ['--preload-file', '%s@/rodir' % node.path_from(bld.bldnode)] + # SwedenCode web build (2026-11): the engine is the MAIN_MODULE that the page loads with the + # filesystem, renderer and game libraries as side modules; the page supplies game data at run time. + # See platform/emscripten/README.md + jslib = bld.path.find_node('platform/emscripten/library_xash.js') + linkflags = [ + '-O3', + '-sMAIN_MODULE=1', + '-sMODULARIZE=1', '-sEXPORT_ES6=1', '-sEXPORT_NAME=Xash3D', '-sENVIRONMENT=web', + '-sINITIAL_MEMORY=134217728', '-sALLOW_MEMORY_GROWTH=1', '-sMAXIMUM_MEMORY=2147483648', + '-sSTACK_SIZE=16777216', + '-sMAX_WEBGL_VERSION=2', '-sMIN_WEBGL_VERSION=2', '-sFULL_ES3=1', '-sGL_ENABLE_GET_PROC_ADDRESS=1', + '-sEXPORTED_FUNCTIONS=_main,_Cmd_ExecuteString,_getErrnoLocation,_malloc,_free', + '-sEXPORTED_RUNTIME_METHODS=FS,ccall,cwrap,getValue,setValue,addFunction,removeFunction,writeArrayToMemory,intArrayFromString,AsciiToString,UTF8ToString,addRunDependency,removeRunDependency,stackSave,stackRestore', + '-sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=$writeSockaddr,$readSockaddr,$AsciiToString,$intArrayFromString,$writeArrayToMemory,$addFunction,$removeFunction', + '-sALLOW_TABLE_GROWTH=1', + '--profiling-funcs', + '--js-library', jslib.abspath(), + ] f(source = source, target = 'xash', diff --git a/ref/gl/gl2_shim/gl2_shim.c b/ref/gl/gl2_shim/gl2_shim.c index 91541c9b..ef4bdf7d 100644 --- a/ref/gl/gl2_shim/gl2_shim.c +++ b/ref/gl/gl2_shim/gl2_shim.c @@ -114,6 +114,7 @@ static struct qboolean force_flush; // enable MAP_FLUSH_EXPLICIT_BIT and FlushMappedBufferRange calls uint32_t cycle_buffers; // cycle N buffers during draw to reduce locking in non-incremental mode uint32_t version; // glsl version to use + qboolean stream; // WebGL vertex stream, see GL2_StreamInit } gl2wrap_config; static struct @@ -132,6 +133,23 @@ static struct GLuint tmu; } gl2wrap_state; +static struct +{ + qboolean enabled; + GLuint vao, vbo, ibo; + GLuint vbo_pos, ibo_pos; // write cursors in bytes + GLuint enabled_locs; // vertex attribute locations enabled in the vao + GLuint bound_abo; // real GL_ARRAY_BUFFER binding + qboolean vao_bound; + byte *vstage; + size_t vstage_size; + byte *istage; + size_t istage_size; +} gl2wrap_stream; +static void GL2_StreamFlushPrims( gl2wrap_prog_t *prog, GLint count ); +static qboolean GL2_StreamInit( void ); +static void GL2_StreamShutdown( void ); + //#define QUAD_BATCH #ifdef QUAD_BATCH @@ -172,6 +190,51 @@ static void (APIENTRY *rpglDrawElements )( GLenum mode, GLsizei count, GLenum ty static void (APIENTRY *rpglDrawArrays )( GLenum mode, GLint first, GLsizei count ); static void (APIENTRY *rpglDrawRangeElements )( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices ); static void (APIENTRY *rpglBindBufferARB)( GLenum buf, GLuint obj ); +static void (APIENTRY *rpglBufferDataARB)( GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage ); +static void (APIENTRY *rpglBufferSubDataARB)( GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data ); +static qboolean GL2_StreamActive( void ); +static void (APIENTRY *rpglBlendFunc)( GLenum sfactor, GLenum dfactor ); +static void (APIENTRY *rpglDepthMask)( GLboolean flag ); +static void (APIENTRY *rpglDepthFunc)( GLenum func ); +static void (APIENTRY *rpglCullFace)( GLenum mode ); + +/* +WebGL state cache (SwedenCode, 2026-11): the renderer sets the same blend/depth/cull state again for almost every +sprite, particle and HUD quad (hundreds of times per frame in crowded scenes). Each one is a WebGL call that Chrome +validates and sends to the GPU process. With the stream enabled, calls that would not change the state are dropped. +Every state change goes through these wrappers (the game modules have no GL access of their own), so the cache +stays exact; ~0 means "unknown" and always passes the first call through. +*/ +static struct +{ + GLenum blend_src, blend_dst; + int depth_mask; + GLenum depth_func; + GLenum cull_face; + signed char caps[8]; // -1 unknown, 0 disabled, 1 enabled +} gl2wrap_cache; + +static int GL2_CacheCapSlot( GLenum e ) +{ + switch( e ) + { + case GL_BLEND: return 0; + case GL_DEPTH_TEST: return 1; + case GL_CULL_FACE: return 2; + case GL_POLYGON_OFFSET_FILL: return 3; + case GL_SCISSOR_TEST: return 4; + case GL_STENCIL_TEST: return 5; + case GL_DITHER: return 6; + } + return -1; +} + +static void GL2_CacheReset( void ) +{ + memset( &gl2wrap_cache, 0, sizeof( gl2wrap_cache )); + gl2wrap_cache.depth_mask = -1; + memset( gl2wrap_cache.caps, -1, sizeof( gl2wrap_cache.caps )); +} static void GL2_FreeArrays( void ); @@ -368,7 +431,7 @@ static gl2wrap_prog_t *GL2_GetProg( const GLuint flags ) prog->ufog = pglGetUniformLocationARB( glprog, "uFog" ); prog->uMVP = pglGetUniformLocationARB( glprog, "uMVP" ); - if( gl2wrap_config.vao_mandatory ) + if( gl2wrap_config.vao_mandatory && !GL2_StreamActive( )) { prog->vao_begin = Mem_Calloc( r_temppool, gl2wrap_config.cycle_buffers * sizeof( GLuint )); pglGenVertexArrays( gl2wrap_config.cycle_buffers, prog->vao_begin ); @@ -378,7 +441,7 @@ static gl2wrap_prog_t *GL2_GetProg( const GLuint flags ) { if( prog->attridx[i] >= 0 ) { - if( gl2wrap_config.vao_mandatory || gl2wrap_config.incremental ) + if(( gl2wrap_config.vao_mandatory || gl2wrap_config.incremental ) && prog->vao_begin ) { for( int j = 0; j < gl2wrap_config.cycle_buffers; j++ ) { @@ -390,7 +453,7 @@ static gl2wrap_prog_t *GL2_GetProg( const GLuint flags ) } } } - if( gl2wrap_config.vao_mandatory ) + if( gl2wrap_config.vao_mandatory && prog->vao_begin ) pglBindVertexArray( 0 ); // these never change @@ -604,6 +667,14 @@ int GL2_ShimInit( void ) if( gEngfuncs.Sys_CheckParm( "-noincremental" )) gl2wrap_config.incremental = gl2wrap_config.buf_storage = false; +#if XASH_EMSCRIPTEN + // WebGL 2: vertex arrays always exist, buffer mapping never does (Emscripten only emulates it with copies) + gl2wrap_config.vao_mandatory = true; + gl2wrap_config.supports_mapbuffer = false; + gl2wrap_config.incremental = false; + gl2wrap_config.buf_storage = false; +#endif + gl2wrap_config.version = 310; if( gEngfuncs.Sys_CheckParm( "-minshaders" )) gl2wrap_config.version = 100; @@ -617,7 +688,11 @@ int GL2_ShimInit( void ) gl2wrap_config.cycle_buffers = 4; if( !gl2wrap_config.vao_mandatory ) gl2wrap_config.cycle_buffers = 1; - gEngfuncs.Con_Printf( S_NOTE "GL2_ShimInit: config: %s%s%s%s%s%s%sCYCLE=%d VER=%d\n", + // the WebGL stream replaces the cycled per-attribute buffers + gl2wrap_config.stream = gl2wrap_config.vao_mandatory && !gl2wrap_config.incremental && !gl2wrap_config.supports_mapbuffer && !gEngfuncs.Sys_CheckParm( "-noglstream" ); + if( gl2wrap_config.stream ) + gl2wrap_config.cycle_buffers = 1; + gEngfuncs.Con_Printf( S_NOTE "GL2_ShimInit: config: %s%s%s%s%s%s%s%sCYCLE=%d VER=%d\n", gl2wrap_config.buf_storage ? "BUF_STOR " : "", gl2wrap_config.buf_storage&&gl2wrap_config.coherent ? "COHERENT " : "", gl2wrap_config.async ? "ASYNC " : "", @@ -625,6 +700,7 @@ int GL2_ShimInit( void ) gl2wrap_config.force_flush ? "FLUSH " : "", gl2wrap_config.vao_mandatory ? "VAO " : "", gl2wrap_config.supports_mapbuffer ? "MAP " : "", + gl2wrap_config.stream ? "STREAM " : "", gl2wrap_config.cycle_buffers, gl2wrap_config.version ); memset( &gl2wrap, 0, sizeof( gl2wrap )); @@ -705,6 +781,13 @@ int GL2_ShimInit( void ) } } + GL2_CacheReset(); + if( gl2wrap_config.stream && !GL2_StreamInit( )) + { + gEngfuncs.Con_Printf( S_WARN "%s: WebGL stream unavailable\n", __func__ ); + GL2_StreamShutdown(); + } + gl2wrap_init = 1; return 0; } @@ -716,6 +799,7 @@ void GL2_ShimShutdown( void ) pglFinish(); pglUseProgramObjectARB( 0 ); + GL2_StreamShutdown(); GL2_FreeArrays(); pglDeleteBuffersARB(( !!pglDrawRangeElementsBaseVertex ? 1 : 4 ), gl2wrap.triquads_ibo ); @@ -898,6 +982,12 @@ static void GL2_FlushPrims( void ) goto leave_label; } + if( gl2wrap_stream.enabled ) + { + GL2_StreamFlushPrims( prog, count ); + goto stream_leave; + } + if( gl2wrap_config.incremental ) { GL2_UpdateIncrementalBuffer( prog, count ); @@ -991,12 +1081,13 @@ static void GL2_FlushPrims( void ) rpglDrawArrays( gl2wrap.prim, startindex, count ); leave_label: - if( gl2wrap_config.vao_mandatory ) + if( gl2wrap_config.vao_mandatory && !gl2wrap_stream.enabled ) // the stream keeps its vertex array bound { pglBindVertexArray( 0 ); pglBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); } +stream_leave: gl2wrap.prim = GL_NONE; gl2wrap.begin = gl2wrap.end; gl2wrap.cur_flags = 0; @@ -1137,11 +1228,14 @@ static void APIENTRY GL2_Color4f( GLfloat r, GLfloat g, GLfloat b, GLfloat a ) GL2_FlushPrims(); } #endif - gl2wrap.color[0] = r; - gl2wrap.color[1] = g; - gl2wrap.color[2] = b; - gl2wrap.color[3] = a; - gl2wrap.uchanged = GL_TRUE; + if( !GL2_StreamActive( ) || gl2wrap.color[0] != r || gl2wrap.color[1] != g || gl2wrap.color[2] != b || gl2wrap.color[3] != a ) + { + gl2wrap.color[0] = r; + gl2wrap.color[1] = g; + gl2wrap.color[2] = b; + gl2wrap.color[3] = a; + gl2wrap.uchanged = GL_TRUE; + } #ifdef QUAD_BATCH if( gl2wrap_quad.active ) return; @@ -1240,19 +1334,76 @@ static qboolean GL2_CatchEnable( GLenum e, qboolean enable ) return true; } +static qboolean GL2_CacheCap( GLenum e, int enable ) +{ + int slot; + + if( !GL2_StreamActive( ) || ( slot = GL2_CacheCapSlot( e )) < 0 ) + return false; + if( gl2wrap_cache.caps[slot] == enable ) + return true; // no change + gl2wrap_cache.caps[slot] = enable; + return false; +} + static void APIENTRY GL2_Enable( GLenum e ) { - if( !GL2_SkipEnable( e ) && !GL2_CatchEnable( e, true )) + if( !GL2_SkipEnable( e ) && !GL2_CatchEnable( e, true ) && !GL2_CacheCap( e, 1 )) rpglEnable( e ); } static void APIENTRY GL2_Disable( GLenum e ) { - if( !GL2_SkipEnable( e ) && !GL2_CatchEnable( e, false )) + if( !GL2_SkipEnable( e ) && !GL2_CatchEnable( e, false ) && !GL2_CacheCap( e, 0 )) rpglDisable( e ); } +static void APIENTRY GL2_BlendFunc( GLenum sfactor, GLenum dfactor ) +{ + if( GL2_StreamActive( )) + { + if( gl2wrap_cache.blend_src == sfactor && gl2wrap_cache.blend_dst == dfactor && sfactor ) + return; + gl2wrap_cache.blend_src = sfactor; + gl2wrap_cache.blend_dst = dfactor; + } + rpglBlendFunc( sfactor, dfactor ); +} + +static void APIENTRY GL2_DepthMask( GLboolean flag ) +{ + if( GL2_StreamActive( )) + { + if( gl2wrap_cache.depth_mask == !!flag ) + return; + gl2wrap_cache.depth_mask = !!flag; + } + rpglDepthMask( flag ); +} + +static void APIENTRY GL2_DepthFunc( GLenum func ) +{ + if( GL2_StreamActive( )) + { + if( gl2wrap_cache.depth_func == func && func ) + return; + gl2wrap_cache.depth_func = func; + } + rpglDepthFunc( func ); +} + +static void APIENTRY GL2_CullFace( GLenum mode ) +{ + if( GL2_StreamActive( )) + { + if( gl2wrap_cache.cull_face == mode && mode ) + return; + gl2wrap_cache.cull_face = mode; + } + rpglCullFace( mode ); +} + /* =========================== @@ -1592,6 +1743,444 @@ static void GL2_FreeArrays( void ) } +/* +====================== +WebGL vertex stream (SwedenCode, 2026-11) + +WebGL has no MapBufferRange/BufferStorage, so the generic paths above upload every draw's vertex data with +one bufferData() per attribute (re-allocating buffer storage each time, from vertex 0 up to the last vertex used) +and need Emscripten's client-side array emulation for the index data. With ~900 draws per frame in crowded +scenes the WebGL calls themselves became the frame cost. This stream instead keeps: +- one vertex array object, bound once, whose element buffer is a streaming index buffer; +- one streaming vertex buffer: every draw copies only the vertices it uses (start..end) for all of its + client-memory attributes into one contiguous block, uploaded with a single bufferSubData(); +- index data rebased to the uploaded block, uploaded with a single bufferSubData() into the index buffer; +- buffers are orphaned (bufferData with NULL) when they wrap, so a write never waits for an earlier draw. +A draw is now about 4 to 7 WebGL calls instead of 15 to 20. "-noglstream" disables it. +====================== +*/ +#define GL2_STREAM_VBO_SIZE ( 8 * 1024 * 1024 ) +#define GL2_STREAM_IBO_SIZE ( 2 * 1024 * 1024 ) + + +static void GL2_StreamBindArrayBuffer( GLuint obj ) +{ + if( gl2wrap_stream.bound_abo != obj ) + { + rpglBindBufferARB( GL_ARRAY_BUFFER_ARB, obj ); + gl2wrap_stream.bound_abo = obj; + } +} + +static void GL2_StreamBindVAO( void ) +{ + if( !gl2wrap_stream.vao_bound ) + { + pglBindVertexArray( gl2wrap_stream.vao ); + gl2wrap_stream.vao_bound = true; + } +} + +static qboolean GL2_StreamInit( void ) +{ + memset( &gl2wrap_stream, 0, sizeof( gl2wrap_stream )); + + pglGenVertexArrays( 1, &gl2wrap_stream.vao ); + pglGenBuffersARB( 1, &gl2wrap_stream.vbo ); + pglGenBuffersARB( 1, &gl2wrap_stream.ibo ); + if( !gl2wrap_stream.vao || !gl2wrap_stream.vbo || !gl2wrap_stream.ibo ) + return false; + + pglBindVertexArray( gl2wrap_stream.vao ); + rpglBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, gl2wrap_stream.ibo ); + rpglBufferDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB, GL2_STREAM_IBO_SIZE, NULL, GL_STREAM_DRAW_ARB ); + pglBindVertexArray( 0 ); + rpglBindBufferARB( GL_ARRAY_BUFFER_ARB, gl2wrap_stream.vbo ); + rpglBufferDataARB( GL_ARRAY_BUFFER_ARB, GL2_STREAM_VBO_SIZE, NULL, GL_STREAM_DRAW_ARB ); + rpglBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); + + gl2wrap_stream.vstage_size = 256 * 1024; + gl2wrap_stream.vstage = malloc( gl2wrap_stream.vstage_size ); + gl2wrap_stream.istage_size = 64 * 1024; + gl2wrap_stream.istage = malloc( gl2wrap_stream.istage_size ); + gl2wrap_stream.enabled = gl2wrap_stream.vstage && gl2wrap_stream.istage; + return gl2wrap_stream.enabled; +} + +static void GL2_StreamShutdown( void ) +{ + if( gl2wrap_stream.vao ) + pglDeleteVertexArrays( 1, &gl2wrap_stream.vao ); + if( gl2wrap_stream.vbo ) + pglDeleteBuffersARB( 1, &gl2wrap_stream.vbo ); + if( gl2wrap_stream.ibo ) + pglDeleteBuffersARB( 1, &gl2wrap_stream.ibo ); + free( gl2wrap_stream.vstage ); + free( gl2wrap_stream.istage ); + memset( &gl2wrap_stream, 0, sizeof( gl2wrap_stream )); +} + +static byte *GL2_StreamStage( byte **stage, size_t *stage_size, size_t size ) +{ + if( size > *stage_size ) + { + size_t newsize = *stage_size; + byte *p; + + while( newsize < size ) + newsize *= 2; + p = realloc( *stage, newsize ); + if( !p ) + return NULL; + *stage = p; + *stage_size = newsize; + } + return *stage; +} + +// upload size bytes into the vertex stream, returns the buffer offset; the stream vbo is left bound +static GLuint GL2_StreamUploadVertices( const void *data, GLuint size ) +{ + GLuint ofs; + + GL2_StreamBindArrayBuffer( gl2wrap_stream.vbo ); + if( gl2wrap_stream.vbo_pos + size > GL2_STREAM_VBO_SIZE ) + { + if( size > GL2_STREAM_VBO_SIZE ) + return 0xffffffff; + rpglBufferDataARB( GL_ARRAY_BUFFER_ARB, GL2_STREAM_VBO_SIZE, NULL, GL_STREAM_DRAW_ARB ); // orphan + gl2wrap_stream.vbo_pos = 0; + } + ofs = gl2wrap_stream.vbo_pos; + rpglBufferSubDataARB( GL_ARRAY_BUFFER_ARB, ofs, size, data ); + gl2wrap_stream.vbo_pos = ( ofs + size + 15 ) & ~15; + return ofs; +} + +// upload index data into the index stream (the vao must be bound), returns the buffer offset +static GLuint GL2_StreamUploadIndices( const void *data, GLuint size ) +{ + GLuint ofs; + + if( gl2wrap_stream.ibo_pos + size > GL2_STREAM_IBO_SIZE ) + { + if( size > GL2_STREAM_IBO_SIZE ) + return 0xffffffff; + rpglBufferDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB, GL2_STREAM_IBO_SIZE, NULL, GL_STREAM_DRAW_ARB ); // orphan + gl2wrap_stream.ibo_pos = 0; + } + ofs = gl2wrap_stream.ibo_pos; + rpglBufferSubDataARB( GL_ELEMENT_ARRAY_BUFFER_ARB, ofs, size, data ); + gl2wrap_stream.ibo_pos = ( ofs + size + 3 ) & ~3; + return ofs; +} + +static void GL2_StreamSetEnabled( GLuint want ) +{ + GLuint diff = gl2wrap_stream.enabled_locs ^ want; + int loc; + + for( loc = 0; diff; loc++, diff >>= 1 ) + { + if( !( diff & 1 )) + continue; + if( want & BIT( loc )) + pglEnableVertexAttribArrayARB( loc ); + else + pglDisableVertexAttribArrayARB( loc ); + } + gl2wrap_stream.enabled_locs = want; +} + +static int GL2_StreamArrayStride( int i ) +{ + int stride = gl2wrap_arrays.ptr[i].stride; + + if( stride == 0 ) + stride = gl2wrap_arrays.ptr[i].size * ( gl2wrap_arrays.ptr[i].type == GL_UNSIGNED_BYTE ? 1 : 4 ); + return stride; +} + +static int GL2_StreamArrayElementSize( int i ) +{ + return gl2wrap_arrays.ptr[i].size * ( gl2wrap_arrays.ptr[i].type == GL_UNSIGNED_BYTE ? 1 : 4 ); +} + +/* +====================== +StreamSetupArrays + +legacy client arrays (glVertexPointer & co) for vertices base..last: client memory attributes are copied +into the stream so that vertex "base" is at the start of the uploaded block (base = first vertex used, +or 0 when another attribute comes from a renderer VBO and indices must stay absolute) +====================== +*/ +static gl2wrap_prog_t *GL2_StreamSetupArrays( GLuint base, GLuint last ) +{ + unsigned int flags = gl2wrap_arrays.flags; + GLuint want = 0, total = 0, ofs[GL2_ATTR_MAX]; + gl2wrap_prog_t *prog; + byte *stage; + int i; + + if( gl2wrap_state.alpha_test ) + SetBits( flags, BIT( GL2_FLAG_ALPHA_TEST )); + if( gl2wrap_state.fog ) + SetBits( flags, BIT( GL2_FLAG_FOG )); + + prog = GL2_SetProg( flags ); + if( !prog ) + return NULL; + + GL2_StreamBindVAO( ); + + // gather the client memory attributes into one block + for( i = 0; i < GL2_ATTR_MAX; i++ ) + { + ofs[i] = 0; + if( prog->attridx[i] < 0 || !FBitSet( flags, BIT( i )) || gl2wrap_arrays.ptr[i].vbo ) + continue; + total = ( total + 15 ) & ~15; + ofs[i] = total; + total += ( last - base ) * GL2_StreamArrayStride( i ) + GL2_StreamArrayElementSize( i ); + } + + if( total ) + { + GLuint vofs; + + if( !( stage = GL2_StreamStage( &gl2wrap_stream.vstage, &gl2wrap_stream.vstage_size, total ))) + return NULL; + for( i = 0; i < GL2_ATTR_MAX; i++ ) + { + int stride; + + if( prog->attridx[i] < 0 || !FBitSet( flags, BIT( i )) || gl2wrap_arrays.ptr[i].vbo ) + continue; + stride = GL2_StreamArrayStride( i ); + memcpy( stage + ofs[i], (const byte *)gl2wrap_arrays.ptr[i].userptr + base * stride, + ( last - base ) * stride + GL2_StreamArrayElementSize( i )); + } + vofs = GL2_StreamUploadVertices( stage, total ); + if( vofs == 0xffffffff ) + return NULL; + for( i = 0; i < GL2_ATTR_MAX; i++ ) + ofs[i] += vofs; + } + + for( i = 0; i < GL2_ATTR_MAX; i++ ) + { + if( prog->attridx[i] < 0 || !FBitSet( flags, BIT( i ))) + continue; + + want |= BIT( prog->attridx[i] ); + if( gl2wrap_arrays.ptr[i].vbo ) + { + GL2_StreamBindArrayBuffer( gl2wrap_arrays.ptr[i].vbo ); + pglVertexAttribPointerARB( prog->attridx[i], gl2wrap_arrays.ptr[i].size, gl2wrap_arrays.ptr[i].type, i == GL2_ATTR_COLOR, gl2wrap_arrays.ptr[i].stride, gl2wrap_arrays.ptr[i].userptr ); + } + else + { + GL2_StreamBindArrayBuffer( gl2wrap_stream.vbo ); + pglVertexAttribPointerARB( prog->attridx[i], gl2wrap_arrays.ptr[i].size, gl2wrap_arrays.ptr[i].type, i == GL2_ATTR_COLOR, gl2wrap_arrays.ptr[i].stride, (void *)(size_t)ofs[i] ); + } + } + GL2_StreamSetEnabled( want ); + return prog; +} + +static void GL2_StreamArraySources( qboolean *client, qboolean *vbo ) +{ + *client = *vbo = false; + for( int i = 0; i < GL2_ATTR_MAX; i++ ) + { + if( !FBitSet( gl2wrap_arrays.flags, BIT( i ))) + continue; + if( gl2wrap_arrays.ptr[i].vbo ) + *vbo = true; + else + *client = true; + } +} + +static GLuint GL2_StreamIndex( const void *indices, int isize, GLuint i ) +{ + if( isize == 4 ) + return ((const GLuint *)indices)[i]; + if( isize == 2 ) + return ((const GLushort *)indices)[i]; + return ((const GLubyte *)indices)[i]; +} + +static void GL2_StreamDrawElements( GLenum mode, GLuint start, GLuint end, qboolean range, GLsizei count, GLenum type, const GLvoid *indices ) +{ + const int isize = type == GL_UNSIGNED_INT ? 4 : type == GL_UNSIGNED_SHORT ? 2 : 1; + qboolean client, vbo; + GLuint base = 0, i, iofs; + byte *stage; + + if( count <= 0 || !gl2wrap_arrays.flags || !indices ) + return; + + GL2_StreamArraySources( &client, &vbo ); + + if( client && ( !range || end < start )) + { + // the vertex range is needed to know what to upload + start = 0xffffffff; + end = 0; + for( i = 0; i < (GLuint)count; i++ ) + { + GLuint v = GL2_StreamIndex( indices, isize, i ); + if( v < start ) start = v; + if( v > end ) end = v; + } + } + else if( !client ) + start = end = 0; // all vertex data is in renderer VBOs + + // rebase to the uploaded block unless a renderer VBO needs absolute vertex numbers + if( client && !vbo ) + base = start; + + if( !GL2_StreamSetupArrays( base, end )) + return; + + if( base == 0 ) + { + iofs = GL2_StreamUploadIndices( indices, count * isize ); + if( iofs != 0xffffffff ) + rpglDrawElements( mode, count, type, (void *)(size_t)iofs ); + return; + } + + if( end - base < 65536 ) + { + GLushort *out; + + if( !( stage = GL2_StreamStage( &gl2wrap_stream.istage, &gl2wrap_stream.istage_size, count * 2 ))) + return; + out = (GLushort *)stage; + if( isize == 2 ) + { + const GLushort *in = indices; + for( i = 0; i < (GLuint)count; i++ ) + out[i] = in[i] - base; + } + else + { + for( i = 0; i < (GLuint)count; i++ ) + out[i] = GL2_StreamIndex( indices, isize, i ) - base; + } + iofs = GL2_StreamUploadIndices( out, count * 2 ); + if( iofs != 0xffffffff ) + rpglDrawElements( mode, count, GL_UNSIGNED_SHORT, (void *)(size_t)iofs ); + } + else + { + GLuint *out; + + if( !( stage = GL2_StreamStage( &gl2wrap_stream.istage, &gl2wrap_stream.istage_size, count * 4 ))) + return; + out = (GLuint *)stage; + for( i = 0; i < (GLuint)count; i++ ) + out[i] = GL2_StreamIndex( indices, isize, i ) - base; + iofs = GL2_StreamUploadIndices( out, count * 4 ); + if( iofs != 0xffffffff ) + rpglDrawElements( mode, count, GL_UNSIGNED_INT, (void *)(size_t)iofs ); + } +} + +static void GL2_StreamDrawArrays( GLenum mode, GLint first, GLsizei count ) +{ + qboolean client, vbo; + GLuint base = 0; + + if( count <= 0 || !gl2wrap_arrays.flags ) + return; + + GL2_StreamArraySources( &client, &vbo ); + if( client && !vbo ) + base = first; + + if( !GL2_StreamSetupArrays( base, first + count - 1 )) + return; + + rpglDrawArrays( mode, first - base, count ); +} + +/* +====================== +StreamFlushPrims + +glBegin/glEnd vertices [begin, begin + count) of the immediate mode buffers +====================== +*/ +static void GL2_StreamFlushPrims( gl2wrap_prog_t *prog, GLint count ) +{ + GLuint want = 0, total = 0, ofs[GL2_ATTR_MAX], vofs; + byte *stage; + int i; + + GL2_StreamBindVAO( ); + + for( i = 0; i < GL2_ATTR_MAX; i++ ) + { + ofs[i] = total; + if( prog->attridx[i] >= 0 ) + total += gl2wrap_attr_size[i] * 4 * count; + } + + if( !( stage = GL2_StreamStage( &gl2wrap_stream.vstage, &gl2wrap_stream.vstage_size, total ))) + return; + + for( i = 0; i < GL2_ATTR_MAX; i++ ) + { + if( prog->attridx[i] >= 0 ) + memcpy( stage + ofs[i], gl2wrap.attrbuf[i] + gl2wrap_attr_size[i] * gl2wrap.begin, gl2wrap_attr_size[i] * 4 * count ); + } + + vofs = GL2_StreamUploadVertices( stage, total ); + if( vofs == 0xffffffff ) + return; + + for( i = 0; i < GL2_ATTR_MAX; i++ ) + { + if( prog->attridx[i] < 0 ) + continue; + want |= BIT( prog->attridx[i] ); + pglVertexAttribPointerARB( prog->attridx[i], gl2wrap_attr_size[i], GL_FLOAT, GL_FALSE, 0, (void *)(size_t)( vofs + ofs[i] )); + } + GL2_StreamSetEnabled( want ); + + if( gl2wrap.prim == GL_QUADS && count > 4 ) + { + const int quads = count / 4; + GLushort *out; + GLuint iofs; + + if( !( stage = GL2_StreamStage( &gl2wrap_stream.istage, &gl2wrap_stream.istage_size, quads * 6 * 2 ))) + return; + out = (GLushort *)stage; + for( i = 0; i < quads; i++ ) + { + out[i * 6 + 0] = i * 4; + out[i * 6 + 1] = i * 4 + 1; + out[i * 6 + 2] = i * 4 + 2; + out[i * 6 + 3] = i * 4; + out[i * 6 + 4] = i * 4 + 2; + out[i * 6 + 5] = i * 4 + 3; + } + iofs = GL2_StreamUploadIndices( out, quads * 6 * 2 ); + if( iofs != 0xffffffff ) + rpglDrawElements( GL_TRIANGLES, quads * 6, GL_UNSIGNED_SHORT, (void *)(size_t)iofs ); + } + else if( gl2wrap.prim == GL_QUADS || gl2wrap.prim == GL_POLYGON ) + rpglDrawArrays( GL_TRIANGLE_FAN, 0, count ); + else + rpglDrawArrays( gl2wrap.prim, 0, count ); +} + /* ====================== SetupArrays @@ -1702,12 +2291,22 @@ static void GL2_SetupArrays( GLuint start, GLuint end ) static void APIENTRY GL2_DrawElements( GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ) { + if( gl2wrap_stream.enabled ) + { + GL2_StreamDrawElements( mode, 0, 0, false, count, type, indices ); + return; + } GL2_SetupArrays( 0, 0 ); rpglDrawElements( mode, count, type, indices ); } static void APIENTRY GL2_DrawRangeElements( GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices ) { + if( gl2wrap_stream.enabled ) + { + GL2_StreamDrawElements( mode, start, end, true, count, type, indices ); + return; + } GL2_SetupArrays( start, end ); if( rpglDrawRangeElements ) rpglDrawRangeElements( mode, start, end, count, type, indices ); @@ -1720,6 +2319,12 @@ static void APIENTRY GL2_DrawArrays( GLenum mode, GLint first, GLsizei count ) if( count <= 0 ) return; + if( gl2wrap_stream.enabled ) + { + GL2_StreamDrawArrays( mode, first, count ); + return; + } + // vertices referenced are [first, first + count - 1], and first may be nonzero GL2_SetupArrays( 0, first + count - 1 ); rpglDrawArrays( mode, first, count ); @@ -1728,10 +2333,37 @@ static void APIENTRY GL2_DrawArrays( GLenum mode, GLint first, GLsizei count ) static void APIENTRY GL2_BindBufferARB( GLenum buf, GLuint obj ) { if( buf == GL_ARRAY_BUFFER_ARB ) + { gl2wrap_state.vbo = obj; + if( gl2wrap_stream.enabled ) + { + GL2_StreamBindArrayBuffer( obj ); + return; + } + } rpglBindBufferARB( buf, obj ); } +// the stream changes the GL_ARRAY_BUFFER binding behind the renderer's back: restore it for the renderer's uploads +static void APIENTRY GL2_BufferDataARB( GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage ) +{ + if( gl2wrap_stream.enabled && target == GL_ARRAY_BUFFER_ARB ) + GL2_StreamBindArrayBuffer( gl2wrap_state.vbo ); + rpglBufferDataARB( target, size, data, usage ); +} + +static void APIENTRY GL2_BufferSubDataARB( GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data ) +{ + if( gl2wrap_stream.enabled && target == GL_ARRAY_BUFFER_ARB ) + GL2_StreamBindArrayBuffer( gl2wrap_state.vbo ); + rpglBufferSubDataARB( target, offset, size, data ); +} + +static qboolean GL2_StreamActive( void ) +{ + return gl2wrap_stream.enabled; +} + #if 0 static void APIENTRY GL2_ActiveTextureARB( GLenum tex ) { @@ -1857,13 +2489,22 @@ void GL2_ShimInstall( void ) GL2_OVERRIDE_PTR_B( TexParameteri ) } #if XASH_EMSCRIPTEN - GL2_OVERRIDE_PTR( PolygonOffset ) + // WebGL has polygonOffset: the stub (GL2_PolygonOffset, kept for reference) left decals - player sprays, blood, + // bullet holes - without their depth offset, so they z-fought with the surface and showed as stripes + // GL2_OVERRIDE_PTR( PolygonOffset ) + (void)GL2_PolygonOffset; #endif // XASH_EMSCRIPTEN GL2_OVERRIDE_PTR_B( IsEnabled ) GL2_OVERRIDE_PTR_B( DrawRangeElements ) GL2_OVERRIDE_PTR_B( DrawElements ) GL2_OVERRIDE_PTR_B( DrawArrays ) GL2_OVERRIDE_PTR_B( BindBufferARB ) + GL2_OVERRIDE_PTR_B( BufferDataARB ) + GL2_OVERRIDE_PTR_B( BufferSubDataARB ) + GL2_OVERRIDE_PTR_B( BlendFunc ) + GL2_OVERRIDE_PTR_B( DepthMask ) + GL2_OVERRIDE_PTR_B( DepthFunc ) + GL2_OVERRIDE_PTR_B( CullFace ) GL2_OVERRIDE_PTR( EnableClientState ) GL2_OVERRIDE_PTR( DisableClientState ) GL2_OVERRIDE_PTR( VertexPointer ) diff --git a/ref/gl/gl_image.c b/ref/gl/gl_image.c index d89c0896..7c900c29 100644 --- a/ref/gl/gl_image.c +++ b/ref/gl/gl_image.c @@ -460,6 +460,10 @@ static void GL_SetTextureDimensions( gl_texture_t *tex, int width, int height, i Assert( false ); } + // SwedenCode: phones get a smaller cap (gl_web_maxtex); never for lightmap atlas pages or fonts + if( gl_web_maxtex.value >= 64 && !IsLightMap( tex ) && !FBitSet( tex->flags, TF_FONT ) && maxTextureSize > (int)gl_web_maxtex.value ) + maxTextureSize = (int)gl_web_maxtex.value; + // store original sizes tex->srcWidth = width; tex->srcHeight = height; diff --git a/ref/gl/gl_local.h b/ref/gl/gl_local.h index 1a9b4392..a5807fae 100644 --- a/ref/gl/gl_local.h +++ b/ref/gl/gl_local.h @@ -783,6 +783,7 @@ extern convar_t gl_lightmap_nearest; extern convar_t gl_fbo_nearest; extern convar_t gl_keeptjunctions; extern convar_t gl_round_down; +extern convar_t gl_web_maxtex; extern convar_t gl_wireframe; extern convar_t gl_polyoffset; extern convar_t gl_polyoffset_bmodels; diff --git a/ref/gl/gl_opengl.c b/ref/gl/gl_opengl.c index 91631823..ceeb4415 100644 --- a/ref/gl/gl_opengl.c +++ b/ref/gl/gl_opengl.c @@ -32,6 +32,8 @@ CVAR_DEFINE_AUTO( r_lockpvs, "0", FCVAR_CHEAT, "lockpvs area at current point (p CVAR_DEFINE_AUTO( r_lockfrustum, "0", FCVAR_CHEAT, "lock frustrum area at current point (cull test)" ); CVAR_DEFINE_AUTO( r_traceglow, "0", FCVAR_GLCONFIG, "cull flares behind models" ); CVAR_DEFINE_AUTO( gl_round_down, "2", FCVAR_GLCONFIG|FCVAR_READ_ONLY, "round texture sizes to nearest POT value" ); +// SwedenCode: largest texture side for low-memory devices (phones), 0 = no cap; lightmaps and fonts never shrink +CVAR_DEFINE_AUTO( gl_web_maxtex, "0", 0, "max texture size on low-memory devices (0 = off)" ); CVAR_DEFINE( r_vbo, "gl_vbo", "0", FCVAR_GLCONFIG, "draw world using VBO (known to be glitchy)" ); CVAR_DEFINE( r_vbo_detail, "gl_vbo_detail", "0", FCVAR_GLCONFIG, "detail vbo mode (0: disable, 1: multipass, 2: singlepass, broken decal dlights)" ); CVAR_DEFINE( r_vbo_dlightmode, "gl_vbo_dlightmode", "1", FCVAR_GLCONFIG, "vbo dlight rendering mode (0-1)" ); @@ -1268,6 +1270,7 @@ static void GL_InitCommands( void ) gEngfuncs.Cvar_RegisterVariable( &gl_msaa ); gEngfuncs.Cvar_RegisterVariable( &gl_stencilbits ); gEngfuncs.Cvar_RegisterVariable( &gl_round_down ); + gEngfuncs.Cvar_RegisterVariable( &gl_web_maxtex ); gEngfuncs.Cvar_RegisterVariable( &gl_overbright ); gEngfuncs.Cvar_RegisterVariable( &gl_fog ); gEngfuncs.Cvar_RegisterVariable( &gl_litwater_force ); diff --git a/ref/soft/r_glblit.c b/ref/soft/r_glblit.c index 863d5b41..c5bfd2c3 100644 --- a/ref/soft/r_glblit.c +++ b/ref/soft/r_glblit.c @@ -424,9 +424,11 @@ static void R_BuildBlendMaps( void ) ASSERT( !vid.addmap[index2 | index1] ); vid.addmap[index2 | index1] = r << ( 2 + 3 ) | g << 2 | b; - r = r1 * r2 / MASK( 3 ); - g = g1 * g2 / MASK( 3 ); - b = b1 * b2 / MASK( 2 ); + // SwedenCode 2026-11-12: round instead of truncating, otherwise every tint loses green first and the + // CS HUD orange (255,160,0) is drawn red + r = ( r1 * r2 + MASK( 3 ) / 2 ) / MASK( 3 ); + g = ( g1 * g2 + MASK( 3 ) / 2 ) / MASK( 3 ); + b = ( b1 * b2 + MASK( 2 ) / 2 ) / MASK( 2 ); vid.modmap[index2 | index1] = r << ( 2 + 3 ) | g << 2 | b; } diff --git a/scripts/waifulib/xcompile.py b/scripts/waifulib/xcompile.py index 981b3baf..99dcfda2 100644 --- a/scripts/waifulib/xcompile.py +++ b/scripts/waifulib/xcompile.py @@ -910,6 +910,9 @@ def configure(conf): for k in c_config.MACRO_TO_DESTOS: MACRO_TO_DESTOS[k] = c_config.MACRO_TO_DESTOS[k] # ordering is important c_config.MACRO_TO_DESTOS = MACRO_TO_DESTOS + if '__wasm32__' not in c_config.MACRO_TO_DEST_CPU: + c_config.MACRO_TO_DEST_CPU['__wasm32__'] = 'wasm32' + c_config.MACRO_TO_DEST_CPU['__wasm64__'] = 'wasm64' def post_compiler_cxx_configure(conf): conf.msg('Target OS', conf.env.DEST_OS) diff --git a/wscript b/wscript index 155cb3c2..e8f4e511 100644 --- a/wscript +++ b/wscript @@ -444,6 +444,19 @@ def configure(conf): # Harbour validator only recognizes DT_RPATH linkflags.append('-Wl,--disable-new-dtags') + if conf.env.DEST_OS == 'emscripten': + # SwedenCode web build: every object is position independent, the engine is the MAIN_MODULE and + # every shared library (filesystem, renderer, game libraries) is an Emscripten SIDE_MODULE named *.wasm + cflags = [f for f in cflags if not f.startswith('-g')] + ['-fPIC'] + cxxflags = [f for f in cxxflags if not f.startswith('-g')] + ['-fPIC'] + conf.env.LINKFLAGS_cshlib = ['-sSIDE_MODULE=1', '-O3', '--profiling-funcs'] + conf.env.LINKFLAGS_cxxshlib = ['-sSIDE_MODULE=1', '-O3', '--profiling-funcs'] + conf.env.cshlib_PATTERN = conf.env.cxxshlib_PATTERN = 'lib%s.wasm' + try: + linkflags.remove('-Wl,--no-undefined') + except ValueError: + pass + if conf.env.DEST_OS == 'ps4': # fix broken struct sockaddr_storage in OpenOrbis headers fix = conf.path.find_node('3rdparty/ps4compat/ps4_sockaddr.h').abspath() diff --git a/3rdparty/library_suffix/include/build.h b/3rdparty/library_suffix/include/build.h index b92c51e..ad4ba14 100644 --- a/3rdparty/library_suffix/include/build.h +++ b/3rdparty/library_suffix/include/build.h @@ -76,6 +76,7 @@ Then you can use another oneliner to query all variables: #undef XASH_OPENBSD #undef XASH_OSX #undef XASH_POSIX +#undef XASH_EMSCRIPTEN #undef XASH_PPC #undef XASH_PS4 #undef XASH_PSP @@ -144,6 +145,8 @@ Then you can use another oneliner to query all variables: #define XASH_PSVITA 1 #elif defined __wasi__ #define XASH_WASI 1 + #elif defined __EMSCRIPTEN__ + #define XASH_EMSCRIPTEN 1 #elif defined __sun__ #define XASH_SUNOS 1 #elif defined __gnu_hurd__ diff --git a/3rdparty/library_suffix/include/buildenums.h b/3rdparty/library_suffix/include/buildenums.h index c91f5e6..fa58a35 100644 --- a/3rdparty/library_suffix/include/buildenums.h +++ b/3rdparty/library_suffix/include/buildenums.h @@ -61,6 +61,7 @@ For more information, please refer to #define PLATFORM_PSP 18 #define PLATFORM_IOS 19 #define PLATFORM_PS4 20 +#define PLATFORM_EMSCRIPTEN 21 #if XASH_WIN32 #define XASH_PLATFORM PLATFORM_WIN32 @@ -100,6 +101,8 @@ For more information, please refer to #define XASH_PLATFORM PLATFORM_PSP #elif XASH_PS4 #define XASH_PLATFORM PLATFORM_PS4 +#elif XASH_EMSCRIPTEN + #define XASH_PLATFORM PLATFORM_EMSCRIPTEN #else #error #endif diff --git a/3rdparty/library_suffix/include/library_suffix.h b/3rdparty/library_suffix/include/library_suffix.h index 68ec127..641ee0c 100644 --- a/3rdparty/library_suffix/include/library_suffix.h +++ b/3rdparty/library_suffix/include/library_suffix.h @@ -39,6 +39,8 @@ For more information, please refer to #define OS_LIB_EXT "dll" #elif XASH_PSP || XASH_PS4 #define OS_LIB_EXT "prx" +#elif XASH_EMSCRIPTEN + #define OS_LIB_EXT "wasm" #elif XASH_POSIX #define OS_LIB_EXT "so" #else diff --git a/3rdparty/library_suffix/src/library_suffix.c b/3rdparty/library_suffix/src/library_suffix.c index 8f2b21a..de40749 100644 --- a/3rdparty/library_suffix/src/library_suffix.c +++ b/3rdparty/library_suffix/src/library_suffix.c @@ -81,6 +81,8 @@ const char *Q_PlatformStringByID( const int platform ) return "psp"; case PLATFORM_PS4: return "ps4"; + case PLATFORM_EMSCRIPTEN: + return "emscripten"; } return "unknown"; diff --git a/3rdparty/mainui/sdk_includes/public/build.h b/3rdparty/mainui/sdk_includes/public/build.h index b92c51e..ad4ba14 100644 --- a/3rdparty/mainui/sdk_includes/public/build.h +++ b/3rdparty/mainui/sdk_includes/public/build.h @@ -76,6 +76,7 @@ Then you can use another oneliner to query all variables: #undef XASH_OPENBSD #undef XASH_OSX #undef XASH_POSIX +#undef XASH_EMSCRIPTEN #undef XASH_PPC #undef XASH_PS4 #undef XASH_PSP @@ -144,6 +145,8 @@ Then you can use another oneliner to query all variables: #define XASH_PSVITA 1 #elif defined __wasi__ #define XASH_WASI 1 + #elif defined __EMSCRIPTEN__ + #define XASH_EMSCRIPTEN 1 #elif defined __sun__ #define XASH_SUNOS 1 #elif defined __gnu_hurd__ diff --git a/3rdparty/mainui/sdk_includes/public/buildenums.h b/3rdparty/mainui/sdk_includes/public/buildenums.h index c91f5e6..fa58a35 100644 --- a/3rdparty/mainui/sdk_includes/public/buildenums.h +++ b/3rdparty/mainui/sdk_includes/public/buildenums.h @@ -61,6 +61,7 @@ For more information, please refer to #define PLATFORM_PSP 18 #define PLATFORM_IOS 19 #define PLATFORM_PS4 20 +#define PLATFORM_EMSCRIPTEN 21 #if XASH_WIN32 #define XASH_PLATFORM PLATFORM_WIN32 @@ -100,6 +101,8 @@ For more information, please refer to #define XASH_PLATFORM PLATFORM_PSP #elif XASH_PS4 #define XASH_PLATFORM PLATFORM_PS4 +#elif XASH_EMSCRIPTEN + #define XASH_PLATFORM PLATFORM_EMSCRIPTEN #else #error #endif