This commit is contained in:
CraftyBoss 2022-07-05 19:34:48 -07:00
commit 3ce0f03650
26 changed files with 156 additions and 93 deletions

View File

@ -32,9 +32,9 @@ class SocketBase {
const char *sock_ip;
u16 port;
u8 socket_log_state;
u8 socket_log_state = SOCKET_LOG_UNINITIALIZED;
s32 socket_log_socket;
int sock_flags;
};

View File

@ -488,6 +488,10 @@ namespace CaptureAnims {
}
static constexpr const char *FindStr(Type type) {
return s_Strs.at(ToValue(type));
const s16 type_ = (s16)type;
if (0 <= type_ && type_ < s_Strs.size())
return s_Strs[type_];
else
return "";
}
}

View File

@ -98,6 +98,10 @@ namespace CaptureTypes {
}
static constexpr const char *FindStr(Type type) {
return s_Strs.at(ToValue(type));
const s16 type_ = (s16)type;
if (0 <= type_ && type_ < s_Strs.size())
return s_Strs[type_];
else
return "";
}
}

View File

@ -1154,6 +1154,10 @@ namespace PlayerAnims {
}
static constexpr const char *FindStr(Type type) {
return s_Strs.at(ToValue(type));
const s16 type_ = (s16)type;
if (0 <= type_ && type_ < s_Strs.size())
return s_Strs[type_];
else
return "";
}
}

View File

@ -72,6 +72,10 @@ namespace WipeTypes {
}
static constexpr const char *FindStr(Type type) {
return s_Strs.at(ToValue(type));
const s16 type_ = (s16)type;
if (0 <= type_ && type_ < s_Strs.size())
return s_Strs[type_];
else
return "";
}
}

View File

@ -2,12 +2,12 @@
#include "Packet.h"
struct CaptureInf : Packet {
struct PACKED CaptureInf : Packet {
CaptureInf() : Packet() {
this->mType = PacketType::CAPTUREINF;
mPacketSize = sizeof(CaptureInf) - sizeof(Packet);
};
char hackName[0x20] = {};
};

View File

@ -2,7 +2,7 @@
#include "Packet.h"
struct ChangeStagePacket : Packet {
struct PACKED ChangeStagePacket : Packet {
ChangeStagePacket() : Packet() {
this->mType = PacketType::CHANGESTAGE;
mPacketSize = sizeof(ChangeStagePacket) - sizeof(Packet);

View File

@ -2,7 +2,7 @@
#include "Packet.h"
struct CostumeInf : Packet {
struct PACKED CostumeInf : Packet {
CostumeInf() : Packet() {this->mType = PacketType::COSTUMEINF; mPacketSize = sizeof(CostumeInf) - sizeof(Packet);};
CostumeInf(const char* body, const char* cap) : Packet() {
this->mType = PacketType::COSTUMEINF;

View File

@ -3,9 +3,9 @@
#include "Packet.h"
#include "al/util.hpp"
struct GameInf : Packet {
struct PACKED GameInf : Packet {
GameInf() : Packet() {this->mType = PacketType::GAMEINF; mPacketSize = sizeof(GameInf) - sizeof(Packet);};
bool is2D = false;
bool4 is2D = false;
u8 scenarioNo = -1;
char stageName[0x40] = {};

View File

@ -2,10 +2,10 @@
#include "Packet.h"
struct HackCapInf : Packet {
struct PACKED HackCapInf : Packet {
HackCapInf() : Packet() {this->mType = PacketType::HACKCAPINF; mPacketSize = sizeof(HackCapInf) - sizeof(Packet);};
sead::Vector3f capPos;
sead::Quatf capQuat;
bool isCapVisible = false;
bool4 isCapVisible = false;
char capAnim[PACKBUFSIZE] = {};
};

View File

@ -2,7 +2,7 @@
#include "Packet.h"
struct InitPacket : Packet {
struct PACKED InitPacket : Packet {
InitPacket() : Packet() {this->mType = PacketType::CLIENTINIT; mPacketSize = sizeof(InitPacket) - sizeof(Packet);};
u16 maxPlayers = 0;
};

View File

@ -5,6 +5,8 @@
#include "nn/account.h"
#include "types.h"
#define PACKBUFSIZE 0x30
#define COSTUMEBUFSIZE 0x20
@ -27,8 +29,9 @@ enum PacketType : short {
};
// attribute otherwise the build log is spammed with unused warnings
__attribute((used)) static const char *packetNames[] = {
USED static const char *packetNames[] = {
"Unknown",
"Client Initialization",
"Player Info",
"Player Cap Info",
"Game Info",
@ -38,6 +41,7 @@ __attribute((used)) static const char *packetNames[] = {
"Costume Info",
"Moon Collection",
"Capture Info",
"Change Stage",
"Server Command"
};
@ -59,7 +63,7 @@ static const char *senderNames[] = {
};
*/
struct Packet {
struct PACKED Packet {
nn::account::Uid mUserID; // User ID of the packet owner
PacketType mType = PacketType::UNKNOWN;
short mPacketSize = 0; // represents packet size without size of header

View File

@ -2,9 +2,11 @@
#include "Packet.h"
struct PlayerConnect : Packet {
#include <cstdint>
struct PACKED PlayerConnect : Packet {
PlayerConnect() : Packet() {this->mType = PacketType::PLAYERCON; mPacketSize = sizeof(PlayerConnect) - sizeof(Packet);};
ConnectionTypes conType;
u16 maxPlayerCount;
u16 maxPlayerCount = USHRT_MAX;
char clientName[COSTUMEBUFSIZE] = {};
};

View File

@ -2,6 +2,6 @@
#include "Packet.h"
struct PlayerDC : Packet {
struct PACKED PlayerDC : Packet {
PlayerDC() : Packet() {this->mType = PacketType::PLAYERDC; mPacketSize = sizeof(PlayerDC) - sizeof(Packet);};
};

View File

@ -4,9 +4,9 @@
#include "al/util.hpp"
#include "algorithms/PlayerAnims.h"
struct PlayerInf : Packet {
struct PACKED PlayerInf : Packet {
PlayerInf() : Packet() {mType = PacketType::PLAYERINF; mPacketSize = sizeof(PlayerInf) - sizeof(Packet);};
sead::Vector3f playerPos;
sead::Vector3f playerPos;
sead::Quatf playerRot;
float animBlendWeights[6];
PlayerAnims::Type actName;

View File

@ -2,7 +2,7 @@
#include "Packet.h"
struct ServerCommand : Packet {
struct PACKED ServerCommand : Packet {
ServerCommand(const char *command) : Packet() {this->mType = PacketType::CMD; strcpy(srvCmd, command); mPacketSize = sizeof(ServerCommand) - sizeof(Packet);};
char srvCmd[PACKBUFSIZE] = {};
};

View File

@ -2,8 +2,8 @@
#include "Packet.h"
struct ShineCollect : Packet {
struct PACKED ShineCollect : Packet {
ShineCollect() : Packet() {this->mType = PacketType::SHINECOLL; mPacketSize = sizeof(ShineCollect) - sizeof(Packet);};
int shineId = -1;
bool isGrand = false;
bool4 isGrand = false;
};

View File

@ -8,10 +8,10 @@ enum TagUpdateType : u8 {
STATE = 1 << 1
};
struct TagInf : Packet {
struct PACKED TagInf : Packet {
TagInf() : Packet() { this->mType = PacketType::TAGINF; mPacketSize = sizeof(TagInf) - sizeof(Packet);};
TagUpdateType updateType;
bool isIt = false;
bool4 isIt = false;
u8 seconds;
u16 minutes;
};

View File

@ -2,9 +2,9 @@
* @file server/Client.hpp
* @author CraftyBoss (https://github.com/CraftyBoss)
* @brief main class responsible for handing all client-server related communications, as well as any gamemodes.
*
*
* @copyright Copyright (c) 2022
*
*
*/
#pragma once
@ -95,7 +95,7 @@ class Client {
bool isShineCollected(int shineId);
static void initMode(GameModeInitInfo const &initInfo);
static void sendHackCapInfPacket(const HackCap *hackCap);
static void sendPlayerInfPacket(const PlayerActorHakoniwa *player);
static void sendGameInfPacket(const PlayerActorHakoniwa *player, GameDataHolderAccessor holder);
@ -194,7 +194,7 @@ class Client {
static void tryRestartCurrentMode();
static bool isModeActive() { return sInstance ? sInstance->mIsModeActive : false; }
static bool isSelectedMode(GameMode mode) { return sInstance ? sInstance->mCurMode->getMode() == mode: false; }
void resetCollectedShines();
@ -241,15 +241,15 @@ class Client {
// --- Server Syncing Members ---
// array of shine IDs for checking if multiple shines have been collected in quick sucession, all moons within the players stage that match the ID will be deleted
sead::SafeArray<int, 128> curCollectedShines;
sead::SafeArray<int, 128> curCollectedShines;
int collectedShineCount = 0;
int lastCollectedShine = -1;
PlayerInf lastPlayerInfPacket =
PlayerInf(); // Info struct for storing our currently logged player information
// Backups for our last player/game packets, used for example to re-send them for newly connected clients
PlayerInf lastPlayerInfPacket = PlayerInf();
GameInf lastGameInfPacket = GameInf();
CostumeInf lastCostumeInfPacket = CostumeInf();
Keyboard* mKeyboard = nullptr; // keyboard for setting server IP
@ -257,6 +257,7 @@ class Client {
int mServerPort = 0;
bool waitForGameInit = true;
bool isFirstConnect = true;
// --- Game Layouts ---

View File

@ -18,6 +18,8 @@ typedef signed int s32;
typedef int64_t s64;
typedef __int128_t s128;
typedef u32 bool4; // guaranteed to be 4 bytes, 'bool' is impl. defined
typedef float f32;
typedef double f64;
@ -76,3 +78,6 @@ struct Rect
float right;
float top;
};
#define PACKED __attribute__((packed))
#define USED __attribute__((used))

View File

@ -6,8 +6,12 @@ import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 3080
if len(sys.argv) == 3:
port = int(sys.argv[2])
# Bind the socket to the port
server_address = (sys.argv[1], 3080)
server_address = (sys.argv[1], port)
print(f"Starting TCP Server with IP {server_address[0]} and Port {server_address[1]}.")
sock.bind(server_address)
@ -22,12 +26,17 @@ while True:
print(f'Switch Connected! IP: {client_address[0]} Port: {client_address[1]}')
while True:
data = connection.recv(1024)
if data:
print(data.decode("utf-8"))
print(data.decode("utf-8"), end='', flush=True)
else:
print(f'Connection Terminated.')
break
except ConnectionResetError:
print("Connection reset")
finally:
# Clean up the connection
connection.close()
connection.close()

View File

@ -137,6 +137,7 @@ void drawMainHook(HakoniwaSequence *curSequence, sead::Viewport *viewport, sead:
gTextWriter->printf("Is in Capture: %s\n", curPupInfo->isCaptured ? "True" : "False");
gTextWriter->printf("Puppet Stage: %s\n", curPupInfo->stageName);
gTextWriter->printf("Puppet Scenario: %u\n", curPupInfo->scenarioNo);
gTextWriter->printf("Puppet Costume: H: %s B: %s\n", curPupInfo->costumeHead, curPupInfo->costumeBody);
//gTextWriter->printf("Packet Coords:\nX: %f\nY: %f\nZ: %f\n", curPupInfo->playerPos.x, curPupInfo->playerPos.y, curPupInfo->playerPos.z);
// if (curModel) {
// sead::Vector3f* pupPos = al::getTrans(curModel);
@ -165,7 +166,7 @@ void drawMainHook(HakoniwaSequence *curSequence, sead::Viewport *viewport, sead:
if (debugPuppet && debugInfo) {
al::LiveActor *curModel = debugPuppet->getCurrentModel();
gTextWriter->printf("Is Nametag Visible: %s\n", BTOC(debugPuppet->mNameTag->isVisible()));
gTextWriter->printf("Is Nametag Alive: %s\n", BTOC(debugPuppet->mNameTag->mIsAlive));
gTextWriter->printf("Nametag Normalized Dist: %f\n", debugPuppet->mNameTag->mNormalizedDist);
@ -178,14 +179,14 @@ void drawMainHook(HakoniwaSequence *curSequence, sead::Viewport *viewport, sead:
}
break;
case 2:
{
{
al::PlayerHolder *pHolder = al::getScenePlayerHolder(curScene);
PlayerActorHakoniwa *p1 = pHolder->tryGetPlayer(0);
if (p1->mHackKeeper && p1->mHackKeeper->currentHackActor) {
al::LiveActor *curHack = p1->mHackKeeper->currentHackActor;
gTextWriter->printf("Current Hack Animation: %s\n", al::getActionName(curHack));
gTextWriter->printf("Current Hack Name: %s\n",
p1->mHackKeeper->getCurrentHackName());
@ -209,14 +210,14 @@ void drawMainHook(HakoniwaSequence *curSequence, sead::Viewport *viewport, sead:
gTextWriter->printf("Cap Skew: %f\n", p1->mHackCap->mJointKeeper->mSkew);
}
}
}
}
break;
default:
break;
}
renderer->begin();
//sead::Matrix34f mat = sead::Matrix34f::ident;
//mat.setBase(3, sead::Vector3f::zero); // Sets the position of the matrix.
// For cubes, you need to put this at the location.
@ -244,7 +245,7 @@ void sendShinePacket(GameDataHolderWriter thisPtr, Shine* curShine) {
if (!curShine->isGot()) {
Client::sendShineCollectPacket(curShine->shineId);
}
GameDataFunction::setGotShine(thisPtr, curShine->curShineInfo);
}
@ -252,7 +253,7 @@ void stageInitHook(al::ActorInitInfo *info, StageScene *curScene, al::PlacementI
al::initActorInitInfo(info, curScene, placement, lytInfo, factory, sceneMsgCtrl,
dataHolder);
Client::clearArrays();
Client::setSceneInfo(*info, curScene);
@ -264,7 +265,7 @@ void stageInitHook(al::ActorInitInfo *info, StageScene *curScene, al::PlacementI
}
Client::sendGameInfPacket(info->mActorSceneInfo.mSceneObjHolder);
}
PlayerCostumeInfo *setPlayerModel(al::LiveActor *player, const al::ActorInitInfo &initInfo, const char *bodyModel, const char *capModel, al::AudioKeeper *keeper, bool isCloset) {
@ -281,7 +282,7 @@ ulong constructHook() { // hook for constructing anything we need to globally b
__asm("MOV %[result], X20"
: [result] "=r"(
initInfo)); // Save our scenes init info to a gloabl ptr so we can access it later
Client::sInstance = new Client(playBufSize);
return 0x20;
@ -311,7 +312,7 @@ bool hakoniwaSequenceHook(HakoniwaSequence* sequence) {
if (isFirstStep) {
Client::tryRestartCurrentMode();
}
isInGame = !stageScene->isPause();
Client::setGameActive(!stageScene->isPause());
@ -345,10 +346,10 @@ bool hakoniwaSequenceHook(HakoniwaSequence* sequence) {
if(debugPuppetIndex < 0) {
debugPuppetIndex = playBufSize - 2;
}
if (debugPuppetIndex >= playBufSize)
if (debugPuppetIndex >= playBufSize - 1)
debugPuppetIndex = 0;
}
} else if (al::isPadHoldL(-1)) {
if (al::isPadTriggerLeft(-1)) Client::toggleCurrentMode();
if (al::isPadTriggerRight(-1)) {
@ -389,7 +390,7 @@ bool hakoniwaSequenceHook(HakoniwaSequence* sequence) {
}
void seadPrintHook(const char *fmt, ...)
void seadPrintHook(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);

View File

@ -247,9 +247,7 @@ bool Client::startConnection() {
// wait for client init packet
while (true) {
if (mSocket->RECV()) {
Packet* curPacket = mSocket->mPacketQueue.popFront();
if (curPacket->mType == PacketType::CLIENTINIT) {
@ -258,8 +256,7 @@ bool Client::startConnection() {
Logger::log("Server Max Player Size: %d\n", initPacket->maxPlayers);
maxPuppets = initPacket->maxPlayers - 1;
}else {
} else {
Logger::log("First Packet was not Init!\n");
mIsConnectionActive = false;
}
@ -346,9 +343,10 @@ void Client::openKeyboardPort() {
*/
void Client::readFunc() {
if (isFirstConnect) {
if (waitForGameInit) {
nn::os::YieldThread(); // sleep the thread for the first thing we do so that game init can finish
nn::os::SleepThread(nn::TimeSpan::FromSeconds(2));
waitForGameInit = false;
}
// we can use the start of readFunc to display an al::WindowConfirmWait while the server
@ -414,9 +412,8 @@ void Client::readFunc() {
mSocket->SEND(&initPacket); // re-send init packet as reconnect packet
mConnectionWait->tryEnd();
continue;
} else {
Logger::log("Connection Failed! Retrying in 5 Seconds.\n");
Logger::log("%s: not reconnected\n", __func__);
}
nn::os::YieldThread(); // if we're currently waiting on the socket to be initialized, wait until it is
@ -448,15 +445,20 @@ void Client::readFunc() {
break;
case PacketType::PLAYERCON:
updatePlayerConnect((PlayerConnect*)curPacket);
// send game info packet when client recieves connection
if (lastGameInfPacket.mUserID != mUserID) {
// assume game info packet is empty from first connection
// Send relevant info packets when another client is connected
// Assume game packets are empty from first connection
if (lastGameInfPacket.mUserID != mUserID)
lastGameInfPacket.mUserID = mUserID;
// leave rest blank
}
mSocket->SEND(&lastGameInfPacket);
// No need to send player/costume packets if they're empty
if (lastPlayerInfPacket.mUserID == mUserID)
mSocket->SEND(&lastPlayerInfPacket);
if (lastCostumeInfPacket.mUserID == mUserID)
mSocket->SEND(&lastCostumeInfPacket);
break;
case PacketType::COSTUMEINF:
updateCostumeInfo((CostumeInf*)curPacket);
@ -465,7 +467,7 @@ void Client::readFunc() {
updateShineInfo((ShineCollect*)curPacket);
break;
case PacketType::PLAYERDC:
Logger::log("Recieved Player Disconnect!\n");
Logger::log("Received Player Disconnect!\n");
curPacket->mUserID.print();
disconnectPlayer((PlayerDC*)curPacket);
break;
@ -713,6 +715,7 @@ void Client::sendCostumeInfPacket(const char* body, const char* cap) {
CostumeInf packet = CostumeInf(body, cap);
packet.mUserID = sInstance->mUserID;
sInstance->mSocket->SEND(&packet);
sInstance->lastCostumeInfPacket = packet;
}
/**
@ -791,17 +794,21 @@ void Client::updatePlayerInfo(PlayerInf *packet) {
}
}
if (packet->actName != PlayerAnims::Type::Unknown) {
strcpy(curInfo->curAnimStr, PlayerAnims::FindStr(packet->actName));
} else {
strcpy(curInfo->curAnimStr, "Wait");
}
if (packet->actName != PlayerAnims::Type::Unknown) {
strcpy(curInfo->curAnimStr, PlayerAnims::FindStr(packet->actName));
if (curInfo->curAnimStr[0] == '\0')
Logger::log("[ERROR] %s: actName was out of bounds: %d\n", __func__, packet->actName);
} else {
strcpy(curInfo->curAnimStr, "Wait");
}
if(packet->subActName != PlayerAnims::Type::Unknown) {
strcpy(curInfo->curSubAnimStr, PlayerAnims::FindStr(packet->subActName));
} else {
strcpy(curInfo->curSubAnimStr, "");
}
if(packet->subActName != PlayerAnims::Type::Unknown) {
strcpy(curInfo->curSubAnimStr, PlayerAnims::FindStr(packet->subActName));
if (curInfo->curSubAnimStr[0] == '\0')
Logger::log("[ERROR] %s: subActName was out of bounds: %d\n", __func__, packet->subActName);
} else {
strcpy(curInfo->curSubAnimStr, "");
}
curInfo->curAnim = packet->actName;
curInfo->curSubAnim = packet->subActName;

View File

@ -79,6 +79,8 @@ bool SocketClient::SEND(Packet *packet) {
int valread = 0;
if (packet->mType != PLAYERINF && packet->mType != HACKCAPINF)
Logger::log("Sending packet: %s\n", packetNames[packet->mType]);
if ((valread = nn::socket::Send(this->socket_log_socket, buffer, packet->mPacketSize + sizeof(Packet), this->sock_flags) > 0)) {
return true;
@ -94,7 +96,7 @@ bool SocketClient::SEND(Packet *packet) {
bool SocketClient::RECV() {
if (this->socket_log_state != SOCKET_LOG_CONNECTED) {
Logger::log("Unable To Recieve! Socket Not Connected.\n");
Logger::log("Unable To Receive! Socket Not Connected.\n");
this->socket_errno = nn::socket::GetLastErrno();
return false;
}
@ -126,6 +128,10 @@ bool SocketClient::RECV() {
if (header->mType != PacketType::UNKNOWN && fullSize <= MAXPACKSIZE && fullSize > 0) {
if (header->mType != PLAYERINF && header->mType != HACKCAPINF)
Logger::log("Received packet (from %02X%02X): %s\n",
header->mUserID.data[0], header->mUserID.data[1], packetNames[header->mType]);
char* packetBuf = (char*)malloc(fullSize);
if (packetBuf) {

View File

@ -2,6 +2,10 @@
#include "helpers.hpp"
#include "nn/result.h"
// If connection fails, try X ports above the specified one
// Useful for debugging multple clients on the same machine
constexpr u32 ADDITIONAL_LOG_PORT_COUNT = 2;
Logger* Logger::sInstance = nullptr;
void Logger::createInstance() {
@ -15,9 +19,9 @@ void Logger::createInstance() {
nn::Result Logger::init(const char* ip, u16 port) {
sock_ip = ip;
this->port = port;
in_addr hostAddress = { 0 };
sockaddr serverAddress = { 0 };
@ -38,12 +42,12 @@ nn::Result Logger::init(const char* ip, u16 port) {
}
#endif
if ((this->socket_log_socket = nn::socket::Socket(2, 1, 0)) < 0) {
this->socket_log_state = SOCKET_LOG_UNAVAILABLE;
return -1;
}
nn::socket::InetAton(this->sock_ip, &hostAddress);
serverAddress.address = hostAddress;
@ -51,17 +55,25 @@ nn::Result Logger::init(const char* ip, u16 port) {
serverAddress.family = 2;
nn::Result result;
bool connected = false;
for (u32 i = 0; i < ADDITIONAL_LOG_PORT_COUNT + 1; ++i) {
result = nn::socket::Connect(this->socket_log_socket, &serverAddress, sizeof(serverAddress));
if (result.isSuccess()) {
connected = true;
break;
}
this->port++;
serverAddress.port = nn::socket::InetHtons(this->port);
}
if ((result = nn::socket::Connect(this->socket_log_socket, &serverAddress, sizeof(serverAddress))).isFailure()) {
if (connected) {
this->socket_log_state = SOCKET_LOG_CONNECTED;
this->isDisableName = false;
return 0;
} else {
this->socket_log_state = SOCKET_LOG_UNAVAILABLE;
return result;
}
this->socket_log_state = SOCKET_LOG_CONNECTED;
this->isDisableName = false;
return 0;
}
void Logger::log(const char *fmt, va_list args) { // impl for replacing seads system::print

View File

@ -81,7 +81,7 @@ StageSceneStateServerConfig::StageSceneStateServerConfig(const char *name, al::S
mCurrentMenu = mMainOptions;
}
void StageSceneStateServerConfig::init() {
void StageSceneStateServerConfig::init() {
initNerve(&nrvStageSceneStateServerConfigMainMenu, 0);
}
@ -196,10 +196,10 @@ void StageSceneStateServerConfig::exeRestartServer() {
Client::restartConnection();
}
//if (Client::isSocketActive()) {
if (Client::isSocketActive()) {
al::startHitReaction(mCurrentMenu, "リセット", 0);
al::setNerve(this, &nrvStageSceneStateServerConfigMainMenu);
//}
}
}
void StageSceneStateServerConfig::exeGamemodeConfig() {
@ -210,7 +210,7 @@ void StageSceneStateServerConfig::exeGamemodeConfig() {
}
subMenuUpdate();
if (mIsDecideConfig && mCurrentList->isDecideEnd()) {
if (mGamemodeConfigMenu->updateMenu(mCurrentList->mCurSelected)) {
endSubMenu();
@ -220,7 +220,7 @@ void StageSceneStateServerConfig::exeGamemodeConfig() {
void StageSceneStateServerConfig::exeGamemodeSelect() {
if (al::isFirstStep(this)) {
mCurrentList = mModeSelectList;
mCurrentMenu = mModeSelect;