diff --git a/CMakeLists.txt b/CMakeLists.txt index 27509c2..a974f97 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -104,7 +104,7 @@ if(EMSCRIPTEN) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -sUSE_SDL=2 -fwasm-exceptions -sSUPPORT_LONGJMP=wasm -pthread") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -sUSE_SDL=2 -fwasm-exceptions -sSUPPORT_LONGJMP=wasm -pthread") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L${CMAKE_SOURCE_DIR}/wasm/prefix/lib/ -sENVIRONMENT=web,worker -lidbfs.js -lwebsocket.js -sASSERTIONS=1 -sSTACK_SIZE=30000000 -sMIN_WEBGL_VERSION=2 -sFULL_ES2 -sFULL_ES3 -sGL_FFP_ONLY -sUSE_SDL_MIXER=2 -lopenal -sINITIAL_MEMORY=768MB -sWASM_BIGINT -lcrypto -fwasm-exceptions") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L${CMAKE_SOURCE_DIR}/wasm/prefix/lib/ -sENVIRONMENT=web,worker -lidbfs.js -lwebsocket.js -sASSERTIONS=0 -sSTACK_SIZE=30000000 -sMIN_WEBGL_VERSION=2 -sFULL_ES2 -sFULL_ES3 -sGL_FFP_ONLY -sUSE_SDL_MIXER=2 -lopenal -sINITIAL_MEMORY=768MB --profiling-funcs -sFORCE_FILESYSTEM=1 -sEXPORTED_RUNTIME_METHODS=FS,ENV,IDBFS,ccall -lcrypto -fwasm-exceptions") if(CMAKE_BUILD_TYPE MATCHES Debug) set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --profiling") diff --git a/lib/irrlicht/source/Irrlicht/CAnimatedMeshSceneNode.cpp b/lib/irrlicht/source/Irrlicht/CAnimatedMeshSceneNode.cpp index 9977e66..ee666e1 100644 --- a/lib/irrlicht/source/Irrlicht/CAnimatedMeshSceneNode.cpp +++ b/lib/irrlicht/source/Irrlicht/CAnimatedMeshSceneNode.cpp @@ -48,6 +48,11 @@ CAnimatedMeshSceneNode::CAnimatedMeshSceneNode(IAnimatedMesh* mesh, //! destructor CAnimatedMeshSceneNode::~CAnimatedMeshSceneNode() { +#ifdef __EMSCRIPTEN__ + if (Mesh && Mesh->getMeshType() == EAMT_SKINNED && + reinterpret_cast(Mesh)->SkinnedBy == this) + reinterpret_cast(Mesh)->SkinnedBy = 0; +#endif if (Mesh) Mesh->drop(); @@ -200,6 +205,17 @@ IMesh * CAnimatedMeshSceneNode::getMeshForCurrentFrame() CSkinnedMesh* skinnedMesh = reinterpret_cast(Mesh); +#ifdef __EMSCRIPTEN__ + // The scene is animated and drawn once per camera (drawAll -> OnAnimate, then + // render): with split screen the same pose was skinned on the CPU and re-uploaded + // up to eight times per frame. Skip it when this node already skinned this mesh + // at this frame (nobody else touched the shared mesh in between). + if (JointMode != EJUOR_CONTROL && Transiting == 0.0f && + skinnedMesh->SkinnedBy == this && skinnedMesh->SkinnedFrame == getFrameNr() && + skinnedMesh->SkinnedStrength == AnimationStrength) + return skinnedMesh; +#endif + if (JointMode == EJUOR_CONTROL)//write to mesh skinnedMesh->transferJointsToMesh(JointChildSceneNodes); else @@ -226,6 +242,12 @@ IMesh * CAnimatedMeshSceneNode::getMeshForCurrentFrame() skinnedMesh->updateBoundingBox(); } +#ifdef __EMSCRIPTEN__ + // Set after the work: animateMesh/skinMesh from anywhere else clear it. + skinnedMesh->SkinnedBy = JointMode == EJUOR_CONTROL ? 0 : this; + skinnedMesh->SkinnedFrame = getFrameNr(); + skinnedMesh->SkinnedStrength = AnimationStrength; +#endif return skinnedMesh; #endif } diff --git a/lib/irrlicht/source/Irrlicht/CNullDriver.cpp b/lib/irrlicht/source/Irrlicht/CNullDriver.cpp index 20490c5..913b56b 100644 --- a/lib/irrlicht/source/Irrlicht/CNullDriver.cpp +++ b/lib/irrlicht/source/Irrlicht/CNullDriver.cpp @@ -1609,8 +1609,17 @@ void CNullDriver::removeAllHardwareBuffers() bool CNullDriver::isHardwareBufferRecommend(const scene::IMeshBuffer* mb) { +#ifdef __EMSCRIPTEN__ + // PadConsole: WebGL has no client-side arrays; Emscripten emulates them by + // re-uploading every draw (bufferSubData was ~90% of a race frame). Keep + // hint-less meshes in VBOs too; changes still re-upload via ChangedID. + if (!mb) + return false; + return true; +#else if (!mb || (mb->getHardwareMappingHint_Index()==scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex()==scene::EHM_NEVER)) return false; +#endif if (mb->getVertexCount()getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) return 0; +#endif SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); @@ -693,6 +698,12 @@ namespace video HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); +#ifdef __EMSCRIPTEN__ + if (HWBuffer->Mapped_Vertex == scene::EHM_NEVER) + HWBuffer->Mapped_Vertex = scene::EHM_STATIC; + if (HWBuffer->Mapped_Index == scene::EHM_NEVER) + HWBuffer->Mapped_Index = scene::EHM_STATIC; +#endif HWBuffer->LastUsed = 0; HWBuffer->vbo_verticesID = 0; HWBuffer->vbo_indicesID = 0; @@ -725,6 +736,13 @@ namespace video glDeleteBuffers(1, &HWBuffer->vbo_indicesID); HWBuffer->vbo_indicesID = 0; } +#ifdef __EMSCRIPTEN__ + if (HWBuffer->vaoID) + { + glDeleteVertexArrays(1, &HWBuffer->vaoID); + HWBuffer->vaoID = 0; + } +#endif CNullDriver::deleteHardwareBuffer(_HWBuffer); } @@ -746,6 +764,30 @@ namespace video const void *vertices = mb->getVertices(); const void *indexList = mb->getIndices(); +#ifdef __EMSCRIPTEN__ + // WebGL: every GL call is a validated browser call, and this is the hot path of the + // legacy renderer (one call per mesh buffer). A VAO per buffer turns the two buffer + // binds, four to six attribute pointers and their enables into one bind. + if (HWBuffer->vbo_verticesID && HWBuffer->vbo_indicesID && + HWBuffer->Mapped_Vertex != scene::EHM_NEVER && HWBuffer->Mapped_Index != scene::EHM_NEVER) + { + const u32 primitiveCount = mb->getIndexCount() / 3; + if (!primitiveCount || !mb->getVertexCount() || !checkPrimitiveCount(primitiveCount)) + return; + setRenderStates3DMode(); + CNullDriver::drawVertexPrimitiveList(0, mb->getVertexCount(), 0, primitiveCount, + mb->getVertexType(), scene::EPT_TRIANGLES, mb->getIndexType()); + bindHardwareBufferVAO(HWBuffer); + GLenum indexSize = GL_UNSIGNED_SHORT; + if (mb->getIndexType() == EIT_32BIT && FeatureAvailable[IRR_OES_element_index_uint]) + indexSize = GL_UNSIGNED_INT; + glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, + primitiveCount * 3, indexSize, 0); + glBindVertexArray(0); + return; + } +#endif + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) { glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); @@ -778,6 +820,46 @@ namespace video return ((u8*)0 + offset); } +#ifdef __EMSCRIPTEN__ + //! Binds (creating or refreshing) the VAO of a VBO-backed mesh buffer. + void COGLES2Driver::bindHardwareBufferVAO(SHWBufferLink_opengl* HWBuffer) + { + const E_VERTEX_TYPE vType = HWBuffer->MeshBuffer->getVertexType(); + if (HWBuffer->vaoID && HWBuffer->vaoVertices == HWBuffer->vbo_verticesID && + HWBuffer->vaoIndices == HWBuffer->vbo_indicesID && HWBuffer->vaoType == vType) + { + glBindVertexArray(HWBuffer->vaoID); + return; + } + if (!HWBuffer->vaoID) + glGenVertexArrays(1, &HWBuffer->vaoID); + glBindVertexArray(HWBuffer->vaoID); + glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); + const GLsizei pitch = getVertexPitchFromType(vType); + // Same layout as drawVertexPrimitiveList2d3d's VBO branch. + glEnableVertexAttribArray(EVA_POSITION); + glEnableVertexAttribArray(EVA_NORMAL); + glEnableVertexAttribArray(EVA_COLOR); + glEnableVertexAttribArray(EVA_TCOORD0); + glVertexAttribPointer(EVA_POSITION, 3, GL_FLOAT, false, pitch, buffer_offset(0)); + glVertexAttribPointer(EVA_NORMAL, 3, GL_FLOAT, false, pitch, buffer_offset(12)); + glVertexAttribPointer(EVA_COLOR, 4, GL_UNSIGNED_BYTE, true, pitch, buffer_offset(24)); + glVertexAttribPointer(EVA_TCOORD0, 2, GL_FLOAT, false, pitch, buffer_offset(28)); + if (vType == EVT_TANGENTS) + { + glEnableVertexAttribArray(EVA_TANGENT); + glEnableVertexAttribArray(EVA_BINORMAL); + glVertexAttribPointer(EVA_TANGENT, 3, GL_FLOAT, false, pitch, buffer_offset(36)); + glVertexAttribPointer(EVA_BINORMAL, 3, GL_FLOAT, false, pitch, buffer_offset(48)); + } + glBindBuffer(GL_ARRAY_BUFFER, 0); + HWBuffer->vaoVertices = HWBuffer->vbo_verticesID; + HWBuffer->vaoIndices = HWBuffer->vbo_indicesID; + HWBuffer->vaoType = vType; + } +#endif + //! draws a vertex primitive list void COGLES2Driver::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, diff --git a/lib/irrlicht/source/Irrlicht/COGLES2Driver.h b/lib/irrlicht/source/Irrlicht/COGLES2Driver.h index eb1f9f7..f88c721 100644 --- a/lib/irrlicht/source/Irrlicht/COGLES2Driver.h +++ b/lib/irrlicht/source/Irrlicht/COGLES2Driver.h @@ -110,13 +110,24 @@ namespace video struct SHWBufferLink_opengl : public SHWBufferLink { - SHWBufferLink_opengl(const scene::IMeshBuffer *meshBuffer): SHWBufferLink(meshBuffer), vbo_verticesID(0), vbo_indicesID(0) {} + SHWBufferLink_opengl(const scene::IMeshBuffer *meshBuffer): SHWBufferLink(meshBuffer), vbo_verticesID(0), vbo_indicesID(0) +#ifdef __EMSCRIPTEN__ + , vaoID(0), vaoVertices(0), vaoIndices(0), vaoType(EVT_STANDARD) +#endif + {} u32 vbo_verticesID; //tmp u32 vbo_indicesID; //tmp u32 vbo_verticesSize; //tmp u32 vbo_indicesSize; //tmp +#ifdef __EMSCRIPTEN__ + // WebGL: VAO holding this buffer's bindings and attribute layout. + u32 vaoID; + u32 vaoVertices; + u32 vaoIndices; + E_VERTEX_TYPE vaoType; +#endif }; bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); @@ -133,6 +144,9 @@ namespace video //! Draw hardware buffer virtual void drawHardwareBuffer(SHWBufferLink *HWBuffer); +#ifdef __EMSCRIPTEN__ + void bindHardwareBufferVAO(SHWBufferLink_opengl* HWBuffer); +#endif //! draws a vertex primitive list virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, diff --git a/lib/irrlicht/source/Irrlicht/CSkinnedMesh.cpp b/lib/irrlicht/source/Irrlicht/CSkinnedMesh.cpp index 0c74553..40d45a0 100644 --- a/lib/irrlicht/source/Irrlicht/CSkinnedMesh.cpp +++ b/lib/irrlicht/source/Irrlicht/CSkinnedMesh.cpp @@ -25,6 +25,11 @@ CSkinnedMesh::CSkinnedMesh() HasAnimation(false), PreparedForSkinning(false), AnimateNormals(true), m_deleted_vertex_buffer(false) { +#ifdef __EMSCRIPTEN__ + SkinnedBy = 0; + SkinnedFrame = -1.f; + SkinnedStrength = 0.f; +#endif #ifdef _DEBUG setDebugName("CSkinnedMesh"); #endif @@ -96,6 +101,9 @@ IMesh* CSkinnedMesh::getMesh(s32 frame, s32 detailLevel, s32 startFrameLoop, s32 //! blend: {0-old position, 1-New position} void CSkinnedMesh::animateMesh(f32 frame, f32 blend) { +#ifdef __EMSCRIPTEN__ + SkinnedBy = 0; +#endif if (LastAnimatedFrame==frame) { SkinnedLastFrame=false; @@ -456,6 +464,9 @@ void CSkinnedMesh::getFrameData(f32 frame, SJoint *joint, //! Preforms a software skin on this mesh based of joint positions void CSkinnedMesh::skinMesh(f32 strength) { +#ifdef __EMSCRIPTEN__ + SkinnedBy = 0; +#endif if (!HasAnimation || SkinnedLastFrame) return; diff --git a/lib/irrlicht/source/Irrlicht/CSkinnedMesh.h b/lib/irrlicht/source/Irrlicht/CSkinnedMesh.h index 3958015..5973cef 100644 --- a/lib/irrlicht/source/Irrlicht/CSkinnedMesh.h +++ b/lib/irrlicht/source/Irrlicht/CSkinnedMesh.h @@ -38,6 +38,14 @@ namespace scene //! constructor CSkinnedMesh(); +#ifdef __EMSCRIPTEN__ + //! Who skinned this mesh last, at which frame and strength (see + //! CAnimatedMeshSceneNode::getMeshForCurrentFrame). + const void* SkinnedBy; + f32 SkinnedFrame; + f32 SkinnedStrength; +#endif + //! destructor virtual ~CSkinnedMesh(); diff --git a/src/input/device_manager.hpp b/src/input/device_manager.hpp index b6ca036..785c982 100644 --- a/src/input/device_manager.hpp +++ b/src/input/device_manager.hpp @@ -168,6 +168,8 @@ public: void clearLatestUsedDevice(); InputDevice* getLatestUsedDevice(); + /** PadConsole: story mode starts on the phone that picked it. */ + void setLatestUsedDevice(InputDevice* device) { m_latest_used_device = device; } bool initialize(); void save(); diff --git a/src/karts/controller/player_controller.cpp b/src/karts/controller/player_controller.cpp index 7117d7e..96cdb10 100644 --- a/src/karts/controller/player_controller.cpp +++ b/src/karts/controller/player_controller.cpp @@ -336,11 +336,15 @@ void PlayerController::update(int ticks) // Only give penalty time in READY_PHASE. // Penalty time check makes sure it doesn't get rendered on every // update. +#ifndef __EMSCRIPTEN__ + // PadConsole: no early-start penalty; phones show the gas pedal + // while "Ready" is up and a held pedal must work at "Go". if (m_penalty_ticks == 0 && World::getWorld()->getPhase() == WorldStatus::READY_PHASE) { displayPenaltyWarning(); } // if penalty_time = 0 +#endif m_controls->setBrake(false); } // if key pressed diff --git a/src/karts/kart.cpp b/src/karts/kart.cpp index 1efa7fe..57425c1 100644 --- a/src/karts/kart.cpp +++ b/src/karts/kart.cpp @@ -2246,7 +2246,14 @@ void Kart::updateNitro(int ticks) { m_min_nitro_ticks = m_kart_properties->getNitroMinConsumptionTicks(); float min_consumption = m_min_nitro_ticks * m_consumption_per_tick; +#ifdef __EMSCRIPTEN__ + // PadConsole: any collected nitro gives a full-length boost on a tap + // (stock STK shortens the boost to the collected share of a minimum use). + (void)min_consumption; + m_energy_to_min_ratio = 1.0f; +#else m_energy_to_min_ratio = std::min(1, m_collected_energy/min_consumption); +#endif } if (m_min_nitro_ticks > 0) { diff --git a/src/karts/kart_model.cpp b/src/karts/kart_model.cpp index ccc4632..37ffa96 100644 --- a/src/karts/kart_model.cpp +++ b/src/karts/kart_model.cpp @@ -873,6 +873,12 @@ void KartModel::loadHeadlights(const XMLNode &node) const XMLNode* child = node.getNode(i); if (child->getName() == "object") { + // PadConsole: 1.5 assets add light-only headlight objects + // (type="spot"/"point") without a mesh; only meshes are loaded here. + std::string object_type; + child->get("type", &object_type); + if (!object_type.empty() && object_type != "mesh") + continue; core::vector3df position, rotation, scale; child->get("position", &position); child->get("rotation", &rotation); diff --git a/src/modes/cutscene_world.cpp b/src/modes/cutscene_world.cpp index d702df7..bbd160e 100644 --- a/src/modes/cutscene_world.cpp +++ b/src/modes/cutscene_world.cpp @@ -565,10 +565,15 @@ void CutsceneWorld::enterRaceOverState() StateManager::get()->resetAndGoToScreen(MainMenuScreen::getInstance()); player->setFirstTime(false); PlayerManager::get()->save(); +#ifdef __EMSCRIPTEN__ + // PadConsole: the kart was picked on the phone before the story started. + OverWorld::enterOverWorld(); +#else KartSelectionScreen* s = OfflineKartSelectionScreen::getInstance(); s->setMultiplayer(false); s->setGoToOverworldNext(); s->push(); +#endif } else { RaceManager::get()->exitRace(); diff --git a/src/padconsole_bridge.cpp b/src/padconsole_bridge.cpp new file mode 100644 index 0000000..21fc551 --- /dev/null +++ b/src/padconsole_bridge.cpp @@ -0,0 +1,440 @@ +// PadConsole bridge (WASM only): the PadConsole screen draws its own menus and +// drives STK through these exported functions (Module.ccall from loader.js). +// Called between frames on the browser main thread, like the STK main loop. +// SuperTuxKart is GPL-3.0-or-later; this file is part of the PadConsole patch. + +#ifdef __EMSCRIPTEN__ + +#include + +#include "challenges/story_mode_timer.hpp" +#include "audio/music_manager.hpp" +#include "config/player_manager.hpp" +#include "config/player_profile.hpp" +#include "config/stk_config.hpp" +#include "config/user_config.hpp" +#include "graphics/camera/camera.hpp" +#include "guiengine/engine.hpp" +#include "guiengine/modaldialog.hpp" +#include "input/device_manager.hpp" +#include "input/gamepad_device.hpp" +#include "input/input_manager.hpp" +#include "input/keyboard_device.hpp" +#include "karts/abstract_kart.hpp" +#include "karts/controller/controller.hpp" +#include "karts/controller/end_controller.hpp" +#include "karts/controller/skidding_ai.hpp" +#include "karts/kart_properties.hpp" +#include "karts/kart_properties_manager.hpp" +#include "modes/cutscene_world.hpp" +#include "modes/overworld.hpp" +#include "modes/world.hpp" +#include "network/network_config.hpp" +#include "network/remote_kart_info.hpp" +#include "race/race_manager.hpp" +#include "states_screens/cutscene_general.hpp" +#include "states_screens/main_menu_screen.hpp" +#include "states_screens/race_gui_base.hpp" +#include "states_screens/race_result_gui.hpp" +#include "states_screens/state_manager.hpp" +#include "tracks/track.hpp" +#include "tracks/track_manager.hpp" +#include "utils/string_utils.hpp" + +#include +#include +#include +#include +#include +#include + +namespace +{ +std::string g_out; + +std::string json(const std::string& text) +{ + std::string out = "\""; + for (unsigned char c : text) + { + if (c == '"' || c == '\\') { out += '\\'; out += (char)c; } + else if (c < 0x20) { char buf[8]; snprintf(buf, sizeof(buf), "\\u%04x", c); out += buf; } + else out += (char)c; + } + return out + "\""; +} + +std::string json(const irr::core::stringw& text) +{ + return json(StringUtils::wideToUtf8(text.c_str())); +} + +std::vector lines(const char* text) +{ + std::vector out; + std::stringstream stream(text ? text : ""); + std::string line; + while (std::getline(stream, line)) out.push_back(line); + return out; +} + +/** pad-bridge.js names phone N "PadConsole Phone N (...)"; SDL keeps that name. */ +InputDevice* padForSlot(int slot) +{ + DeviceManager* devices = input_manager->getDeviceManager(); + const std::string tag = "PadConsole Phone " + std::to_string(slot + 1) + " "; + for (int i = 0; i < devices->getGamePadAmount(); i++) + { + GamePadDevice* pad = devices->getGamePad(i); + if (pad && pad->isConnected() && StringUtils::startsWith(pad->getName(), tag)) + return pad; + } + return devices->getKeyboard(0); +} + +PlayerProfile* profileNamed(const std::string& name) +{ + PlayerProfile* profile = + PlayerManager::get()->getPlayer(StringUtils::utf8ToWide(name)); + return profile ? profile : PlayerManager::getCurrentPlayer(); +} + +bool atMainMenu() +{ + return StateManager::get()->getGameState() == GUIEngine::MENU && + GUIEngine::getCurrentScreen() == MainMenuScreen::getInstance() && + !GUIEngine::ModalDialog::isADialogActive(); +} + +void leaveRace() +{ + if (GUIEngine::ModalDialog::isADialogActive()) + GUIEngine::ModalDialog::dismiss(); + const bool story = RaceManager::get()->getMinorMode() == + RaceManager::MINOR_MODE_OVERWORLD || + RaceManager::get()->raceWasStartedFromOverworld(); + if (World::getWorld()) + { + RaceManager::get()->exitRace(); + RaceManager::get()->setAIKartOverride(""); + } + StateManager::get()->resetAndGoToScreen(MainMenuScreen::getInstance()); + if (story) + story_mode_timer->pauseTimer(/*loading screen*/ false); +} +} // namespace + +extern "C" { + +/** Karts and race tracks with translated names, for the PadConsole menus. */ +EMSCRIPTEN_KEEPALIVE const char* pc_catalog() +{ + std::string out = "{\"karts\":["; + bool first = true; + for (unsigned int i = 0; i < kart_properties_manager->getNumberOfKarts(); i++) + { + const KartProperties* kart = kart_properties_manager->getKartById(i); + if (!kart || kart->isAddon()) continue; + out += first ? "" : ","; + first = false; + out += "{\"id\":" + json(kart->getIdent()) + ",\"name\":" + json(kart->getName()) + + ",\"icon\":" + json(kart->getAbsoluteIconFile()) + + ",\"locked\":" + (PlayerManager::getCurrentPlayer()->isLocked(kart->getIdent()) ? "true" : "false") + "}"; + } + out += "],\"tracks\":["; + first = true; + for (unsigned int i = 0; i < track_manager->getNumberOfTracks(); i++) + { + const Track* track = track_manager->getTrack(i); + if (!track || !track->isRaceTrack() || track->isInternal() || track->isAddon()) + continue; + out += first ? "" : ","; + first = false; + out += "{\"id\":" + json(track->getIdent()) + ",\"name\":" + json(track->getName()) + + ",\"laps\":" + std::to_string(track->getDefaultNumberOfLaps()) + + ",\"reverse\":" + (track->reverseAvailable() ? "true" : "false") + + ",\"screenshot\":" + json(track->getScreenshotFile()) + "}"; + } + out += "]}"; + g_out = out; + return g_out.c_str(); +} + +/** Where STK is, polled by loader.js. "results" only for STK's result screen. */ +EMSCRIPTEN_KEEPALIVE const char* pc_status() +{ + const GUIEngine::GameState state = StateManager::get()->getGameState(); + GUIEngine::Screen* screen = GUIEngine::getCurrentScreen(); + World* world = World::getWorld(); + RaceManager* race = RaceManager::get(); + + std::string mode = "none"; + if (world) + { + switch (race->getMinorMode()) + { + case RaceManager::MINOR_MODE_OVERWORLD: mode = "overworld"; break; + case RaceManager::MINOR_MODE_CUTSCENE: mode = "cutscene"; break; + default: mode = "race"; break; + } + } + const bool results = world && screen && screen == RaceResultGUI::getInstance() && + state != GUIEngine::GAME; + std::string out = "{\"state\":"; + out += state == GUIEngine::MENU ? "\"menu\"" : state == GUIEngine::GAME ? "\"game\"" : "\"ingame\""; + out += ",\"main\":"; + out += atMainMenu() ? "true" : "false"; + out += ",\"mode\":" + json(mode); + out += ",\"story\":"; + out += (world && (mode == "overworld" || race->raceWasStartedFromOverworld())) ? "true" : "false"; + out += ",\"phase\":" + std::to_string(world ? (int)world->getPhase() : -1); + out += ",\"paused\":"; + out += (world && world->getPhase() == WorldStatus::IN_GAME_MENU_PHASE) ? "true" : "false"; + out += ",\"dialog\":"; + out += GUIEngine::ModalDialog::isADialogActive() ? "true" : "false"; + out += ",\"results\":"; + if (results) + { + // getKartInfo() holds only the player karts (index = local player), not world + // kart ids: indexing it with a world id read past the vector and allocated + // garbage-sized names until the fixed WASM heap ran out at the result screen. + out += "["; + for (unsigned int i = 0; i < world->getNumKarts(); i++) + { + AbstractKart* kart = world->getKart(i); + int player = -1; + for (unsigned int n = 0; n < race->getNumLocalPlayers(); n++) + { + if (world->getLocalPlayerKart(n) == kart) { player = (int)n; break; } + } + const bool local = player >= 0 && (unsigned int)player < race->getNumPlayers(); + out += i ? "," : ""; + out += "{\"kart\":" + json(kart->getIdent()) + + ",\"name\":" + json(local ? race->getKartInfo(player).getPlayerName() + : kart->getKartProperties()->getName()) + + ",\"pos\":" + std::to_string(kart->getPosition()) + + ",\"time\":" + std::to_string(kart->getFinishTime()) + + ",\"local\":" + (local ? "true" : "false") + + ",\"slot\":" + std::to_string(local ? player : -1) + "}"; + } + out += "]"; + } + else out += "null"; + out += "}"; + g_out = out; + return g_out.c_str(); +} + +/** One local player per phone slot, karts in the same order. Lists are newline separated. */ +EMSCRIPTEN_KEEPALIVE int pc_start_race(const char* slots_text, const char* names_text, + const char* karts_text, const char* track_id, + int laps, int difficulty, int num_ai, int reverse) +{ + if (!atMainMenu()) return 0; + Track* track = track_manager->getTrack(track_id ? track_id : ""); + const std::vector slots = lines(slots_text); + const std::vector names = lines(names_text); + const std::vector karts = lines(karts_text); + const unsigned int players = (unsigned int)karts.size(); + if (!track || players < 1 || players > 4 || slots.size() != players || names.size() != players) + return 0; + + NetworkConfig::get()->unsetNetworking(); + StateManager::get()->resetActivePlayers(); + RaceManager* race = RaceManager::get(); + race->setMajorMode(RaceManager::MAJOR_MODE_SINGLE); + race->setMinorMode(RaceManager::MINOR_MODE_NORMAL_RACE); + race->setDifficulty((RaceManager::Difficulty)std::max(0, std::min(difficulty, 3))); + for (unsigned int n = 0; n < players; n++) + { + PlayerProfile* profile = profileNamed(names[n]); + StateManager::get()->createActivePlayer(profile, padForSlot(atoi(slots[n].c_str()))); + profile->incrementUseFrequency(); + } + race->setNumPlayers(players); + for (unsigned int n = 0; n < players; n++) + { + const std::string kart = kart_properties_manager->getKart(karts[n]) ? karts[n] + : UserConfigParams::m_default_kart.getDefaultValue(); + race->setPlayerKart(n, kart); + } + input_manager->getDeviceManager()->setAssignMode(ASSIGN); + input_manager->getDeviceManager()->setSinglePlayer( + players == 1 ? StateManager::get()->getActivePlayer(0) : NULL); + + const int ai = std::max(0, std::min(num_ai, (int)stk_config->m_max_karts - (int)players)); + const int lap_count = std::max(1, std::min(laps, 20)); + track->setActualNumberOfLaps(lap_count); + race->setReverseTrack(reverse != 0 && track->reverseAvailable()); + race->setRecordRace(false); + PlayerManager::getCurrentPlayer()->setCurrentChallenge(""); + race->setNumKarts(players + ai); + race->startSingleRace(track->getIdent(), lap_count, false); + return 1; +} + +/** Story mode for one phone: its profile owns the story progress. */ +EMSCRIPTEN_KEEPALIVE int pc_start_story(int slot, const char* name, const char* kart) +{ + if (!atMainMenu()) return 0; + NetworkConfig::get()->unsetNetworking(); + PlayerProfile* profile = profileNamed(name ? name : ""); + if (profile != PlayerManager::getCurrentPlayer()) + PlayerManager::get()->setCurrentPlayer(profile); + InputDevice* device = padForSlot(slot); + input_manager->getDeviceManager()->setAssignMode(NO_ASSIGN); + input_manager->getDeviceManager()->setLatestUsedDevice(device); + + if (kart && kart_properties_manager->getKart(kart) && !profile->isLocked(kart)) + UserConfigParams::m_default_kart = std::string(kart); + story_mode_timer->startTimer(); + if (profile->isFirstTime()) + { + CutsceneWorld::setUseDuration(true); + StateManager::get()->enterGameState(); + RaceManager::get()->setMinorMode(RaceManager::MINOR_MODE_CUTSCENE); + RaceManager::get()->setNumKarts(0); + RaceManager::get()->setNumPlayers(0); + RaceManager::get()->startSingleRace("introcutscene", 999, false); + std::vector parts; + parts.push_back("introcutscene"); + parts.push_back("introcutscene2"); + ((CutsceneWorld*)World::getWorld())->setParts(parts); + CutSceneGeneral::getInstance()->push(); + return 1; + } + story_mode_timer->unpauseTimer(/*exit loading pause*/ false); + if (profile->isLocked(UserConfigParams::m_default_kart)) + UserConfigParams::m_default_kart.revertToDefaults(); + OverWorld::enterOverWorld(); + return 1; +} + +EMSCRIPTEN_KEEPALIVE void pc_pause(int on) +{ + World* world = World::getWorld(); + if (!world || GUIEngine::ModalDialog::isADialogActive()) return; + const bool paused = world->getPhase() == WorldStatus::IN_GAME_MENU_PHASE; + if (on && !paused && StateManager::get()->getGameState() == GUIEngine::GAME) + world->schedulePause(WorldStatus::IN_GAME_MENU_PHASE); + else if (!on && paused) + world->scheduleUnpause(); +} + +EMSCRIPTEN_KEEPALIVE void pc_restart() +{ + World* world = World::getWorld(); + if (!world || RaceManager::get()->getMinorMode() == RaceManager::MINOR_MODE_OVERWORLD) + return; + if (GUIEngine::getCurrentScreen() == RaceResultGUI::getInstance() && + StateManager::get()->getGameState() != GUIEngine::GAME) + StateManager::get()->popMenu(); + else if (world->getPhase() == WorldStatus::IN_GAME_MENU_PHASE) + world->scheduleUnpause(); + RaceManager::get()->rerunRace(); +} + +/** Pause menu "finish race": AI karts get estimated times, players are placed last. */ +EMSCRIPTEN_KEEPALIVE void pc_end_race() +{ + World* world = World::getWorld(); + if (!world || RaceManager::get()->getMinorMode() == RaceManager::MINOR_MODE_OVERWORLD || + RaceManager::get()->getMinorMode() == RaceManager::MINOR_MODE_CUTSCENE) + return; + if (world->getPhase() == WorldStatus::IN_GAME_MENU_PHASE) + world->scheduleUnpause(); + if (world->getRaceGUI()) world->getRaceGUI()->removeReferee(); + world->endRaceEarly(); +} + +/** Graphics preset chosen in the PadConsole menu ("smooth" / "high"), at STK's main menu. + * The WASM build always runs the legacy (fixed pipeline) renderer, so the advanced-pipeline + * effects do nothing here; the cost that varies is how much of the track is drawn. + * detail 0: STK's shortest LOD distances (geometry_level 2) and only important particles; + * 1: geometry_level 1; 2: STK's default. Applies to the next race. Returns 1, or 0 when + * STK is not at its main menu. */ +EMSCRIPTEN_KEEPALIVE int pc_graphics(int detail) +{ + if (!atMainMenu()) return 0; + detail = std::max(0, std::min(detail, 2)); + UserConfigParams::m_particles_effects = detail != 0 ? 2 : 1; + UserConfigParams::m_geometry_level = 2 - detail; + user_config->saveConfig(); + return 1; +} + +/** Heap use for tests and the memory budget: in use, free inside the heap, heap top. */ +EMSCRIPTEN_KEEPALIVE const char* pc_memory() +{ + struct mallinfo info = mallinfo(); + g_out = "{\"used\":" + std::to_string(info.uordblks) + ",\"free\":" + std::to_string(info.fordblks) + + ",\"top\":" + std::to_string((size_t)sbrk(0)) + "}"; + return g_out.c_str(); +} + +/** Tests only: local player karts drive themselves (the controller STK uses after the finish line). */ +EMSCRIPTEN_KEEPALIVE void pc_test_autopilot() +{ + World* world = World::getWorld(); + if (!world) return; + for (unsigned int i = 0; i < world->getNumKarts(); i++) + { + AbstractKart* kart = world->getKart(i); + Controller* controller = kart->getController(); + if (controller->isLocalPlayerController() && !dynamic_cast(controller)) + kart->setController(new EndController(kart, controller)); + } +} + +/** Lobby trailer capture only (games/supertuxkart/tests/catalog-film.mjs). + * 0: local karts drive with STK's full race AI (items, nitro, skids); + * 1/2/3: camera 0 normal / close-up / looking back; 4: camera 0 becomes the end + * (track-side) camera; 5: music off; 6: no race HUD (countdown included); 100+n: camera 0 follows kart n; + * 200+p: camera 0 follows the kart in race position p. */ +EMSCRIPTEN_KEEPALIVE void pc_film(int command) +{ + World* world = World::getWorld(); + if (command == 5) + { + if (music_manager) music_manager->setMasterMusicVolume(0.0f); + return; + } + if (!world || Camera::getNumCameras() == 0) return; + Camera* camera = Camera::getCamera(0); + if (command == 0) + { + for (unsigned int i = 0; i < world->getNumKarts(); i++) + { + AbstractKart* kart = world->getKart(i); + if (kart->getController()->isLocalPlayerController()) + kart->setController(new SkiddingAI(kart)); + } + } + else if (command >= 1 && command <= 3) + { + if (!camera->isNormal()) Camera::changeCamera(0, Camera::CM_TYPE_NORMAL); + Camera::getCamera(0)->setMode(command == 1 ? Camera::CM_NORMAL + : command == 2 ? Camera::CM_CLOSEUP : Camera::CM_REVERSE); + } + else if (command == 4) + Camera::changeCamera(0, Camera::CM_TYPE_END); + else if (command == 6 && world->getRaceGUI()) + world->getRaceGUI()->m_enabled = false; + else if (command >= 100 && command - 100 < (int)world->getNumKarts()) + camera->setKart(world->getKart(command - 100)); + else if (command >= 200) + { + for (unsigned int i = 0; i < world->getNumKarts(); i++) + if (world->getKart(i)->getPosition() == command - 200) + camera->setKart(world->getKart(i)); + } +} + +EMSCRIPTEN_KEEPALIVE void pc_to_menu() +{ + leaveRace(); +} + +} // extern "C" + +#endif diff --git a/src/states_screens/dialogs/select_challenge.cpp b/src/states_screens/dialogs/select_challenge.cpp index 9c342a4..d81a26a 100644 --- a/src/states_screens/dialogs/select_challenge.cpp +++ b/src/states_screens/dialogs/select_challenge.cpp @@ -38,6 +38,10 @@ #include "utils/string_utils.hpp" #include "utils/translation.hpp" +#ifdef __EMSCRIPTEN__ +#include +#endif + using namespace GUIEngine; // ---------------------------------------------------------------------------- @@ -267,6 +271,21 @@ GUIEngine::EventPropagation SelectChallengeDialog::processEvent(const std::strin m_challenge_id.c_str()); return GUIEngine::EVENT_LET; } +#ifdef __EMSCRIPTEN__ + // PadConsole: race tracks arrive as on-demand data packs. When a pack is + // missing the loader downloads it and shows progress; start again after. + std::string tracks = c_data->getTrackId(); + const GrandPrixData* gp = c_data->isGrandPrix() + ? grand_prix_manager->getGrandPrix(c_data->getGPId()) : NULL; + if (gp) + { + for (const std::string& track : gp->getTrackNames(true)) + tracks += "\n" + track; + } + if (!EM_ASM_INT({ return globalThis.pcTracksReady ? globalThis.pcTracksReady(UTF8ToString($0)) : 1; }, + tracks.c_str())) + return GUIEngine::EVENT_BLOCK; +#endif PlayerManager::getCurrentPlayer()->setCurrentChallenge(m_challenge_id); diff --git a/src/states_screens/kart_selection.cpp b/src/states_screens/kart_selection.cpp index 9f4e7f7..661fa00 100644 --- a/src/states_screens/kart_selection.cpp +++ b/src/states_screens/kart_selection.cpp @@ -592,6 +592,25 @@ bool KartSelectionScreen::joinPlayer(InputDevice* device, PlayerProfile* p) // Give each player a different start profile const int num_active_players = StateManager::get()->activePlayerCount(); profile_to_use = PlayerManager::get()->getPlayer(num_active_players); + // PadConsole: profiles are sorted by use frequency, so the n-th one + // may already be taken; give the joiner the first free profile. + for (unsigned int i = 0; i < PlayerManager::get()->getNumPlayers(); i++) + { + PlayerProfile* candidate = PlayerManager::get()->getPlayer(i); + bool taken = false; + for (int a = 0; a < num_active_players; a++) + { + StateManager::ActivePlayer* active = + StateManager::get()->getActivePlayer(a); + if (active && active->getProfile() == candidate) + taken = true; + } + if (!taken) + { + profile_to_use = candidate; + break; + } + } removeMultiplayerMessage(); } diff --git a/src/states_screens/race_gui.cpp b/src/states_screens/race_gui.cpp index 0f692d7..27aaca2 100644 --- a/src/states_screens/race_gui.cpp +++ b/src/states_screens/race_gui.cpp @@ -289,7 +289,8 @@ void RaceGUI::renderGlobal(float dt) World *world = World::getWorld(); assert(world != NULL); - if(world->getPhase() >= WorldStatus::WAIT_FOR_SERVER_PHASE && + if(m_enabled && + world->getPhase() >= WorldStatus::WAIT_FOR_SERVER_PHASE && world->getPhase() <= WorldStatus::GO_PHASE ) { drawGlobalReadySetGo(); diff --git a/wasm/build.sh b/wasm/build.sh index 92858ed..91293bd 100755 --- a/wasm/build.sh +++ b/wasm/build.sh @@ -16,7 +16,7 @@ mkdir -p $BUILD_DIR cd $BUILD_DIR source "$EMSDK_DIR/emsdk_env.sh" -embuilder build sdl2 sdl2_ttf sdl2_image sdl2_image_jpg sdl2_image_png +embuilder build sdl2 sdl2_ttf sdl2_mixer emcmake cmake "$SRC_DIR" -DNO_SHADERC=on -DCMAKE_BUILD_TYPE=$BUILD_TYPE make -j$CORE_COUNT diff --git a/wasm/build_deps.sh b/wasm/build_deps.sh index 89468ef..43d7463 100755 --- a/wasm/build_deps.sh +++ b/wasm/build_deps.sh @@ -65,7 +65,7 @@ build_zlib() { clone_repo "https://github.com/madler/zlib" v1.3.1 "$SRC_DIR" cd "$SRC_DIR" - emconfigure ./configure --prefix="$PREFIX" --static + CHOST=wasm32-unknown-emscripten emconfigure ./configure --prefix="$PREFIX" --static emmake make -j$CORE_COUNT make install }