Commit 37de4dfc by Jonathan Thomas

Broadcast ALL player friendships with each message update (to keep client in…

Broadcast ALL player friendships with each message update (to keep client in sync with server). Also updated many log statements, to improve debug output.
parent 1ab9273a
Pipeline #13212 passed with stages
in 2 minutes 13 seconds
......@@ -25,6 +25,7 @@ All notable changes to **CreatureChat** are documented in this file. The format
- Seperated `generateCharacter()` and `generateMessage()` functions for simplicity
- Fixing PACKET_S2C_MESSAGE from crashing a newly logging on player, if they receive that message first.
- Added NULL checks on client message listeners (to prevent crashes for invalid or uninitialized clients)
- Broadcast ALL player friendships with each message update (to keep client in sync with server)
### Fixed
- Fixed a regression caused by adding a "-forge" suffix to one of our builds
......
......@@ -22,10 +22,7 @@ import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
......@@ -96,6 +93,19 @@ public class ClientPackets {
ClientPlayNetworking.send(ServerPackets.PACKET_C2S_SEND_CHAT, buf);
}
// Reading a Map<String, PlayerData> from the buffer
public static Map<String, PlayerData> readPlayerDataMap(PacketByteBuf buffer) {
int size = buffer.readInt(); // Read the size of the map
Map<String, PlayerData> map = new HashMap<>();
for (int i = 0; i < size; i++) {
String key = buffer.readString(); // Read the key (playerName)
PlayerData data = new PlayerData();
data.friendship = buffer.readInt(); // Read PlayerData field(s)
map.put(key, data); // Add to the map
}
return map;
}
public static void register() {
// Client-side packet handler, message sync
ClientPlayNetworking.registerGlobalReceiver(ServerPackets.PACKET_S2C_MESSAGE, (client, handler, buffer, responseSender) -> {
......@@ -115,7 +125,7 @@ public class ClientPackets {
ChatDataManager.ChatStatus status = ChatDataManager.ChatStatus.valueOf(status_name);
String sender_name = buffer.readString(32767);
ChatDataManager.ChatSender sender = ChatDataManager.ChatSender.valueOf(sender_name);
int friendship = buffer.readInt();
Map<String, PlayerData> players = readPlayerDataMap(buffer);
// Update the chat data manager on the client-side
client.execute(() -> { // Make sure to run on the client thread
......@@ -150,11 +160,7 @@ public class ClientPackets {
chatData.currentLineNumber = line;
chatData.status = status;
chatData.sender = sender;
if (senderPlayerId != null) {
PlayerData playerData = chatData.getPlayerData(senderPlayerName);
playerData.friendship = friendship;
}
chatData.players = players; // friendships
}
// Play sound with volume based on distance (from player or entity)
......
......@@ -213,7 +213,6 @@ public class ChatGPTRequest {
ChatGPTResponse chatGPTResponse = gsonOutput.fromJson(response.toString(), ChatGPTResponse.class);
if (chatGPTResponse != null && chatGPTResponse.choices != null && !chatGPTResponse.choices.isEmpty()) {
String content = chatGPTResponse.choices.get(0).message.content;
LOGGER.info("Generated message: " + content);
return content;
}
}
......
......@@ -580,12 +580,20 @@ public class EntityChatData {
? "<returning player: " + playerName + " resumes the conversation>"
: "<a new player has joined the conversation: " + playerName + ">";
previousMessages.add(new ChatMessage(note, sender, playerName));
// Log context-switching message
LOGGER.info("Conversation-switching message: status=PENDING, sender={}, message={}, player={}, entity={}",
ChatDataManager.ChatStatus.PENDING, note, playerName, entityId);
}
}
// Add message to history
previousMessages.add(new ChatMessage(truncatedMessage, sender, playerName));
// Log regular message addition
LOGGER.info("Message added: status={}, sender={}, message={}, player={}, entity={}",
status.toString(), sender.toString(), truncatedMessage, playerName, entityId);
// Update current message and reset line number of displayed text
this.currentMessage = truncatedMessage;
this.currentLineNumber = 0;
......
......@@ -16,7 +16,7 @@ public class MessageParser {
public static final Logger LOGGER = LoggerFactory.getLogger("creaturechat");
public static ParsedMessage parseMessage(String input) {
LOGGER.info("Parsing message: {}", input);
LOGGER.debug("Parsing message: {}", input);
StringBuilder cleanedMessage = new StringBuilder();
List<Behavior> behaviors = new ArrayList<>();
Pattern pattern = Pattern.compile("[<*](FOLLOW|LEAD|FLEE|ATTACK|PROTECT|FRIENDSHIP|UNFOLLOW|UNLEAD|UNPROTECT|UNFLEE)[:\\s]*(\\s*[+-]?\\d+)?[>*]", Pattern.CASE_INSENSITIVE);
......@@ -29,7 +29,7 @@ public class MessageParser {
argument = Integer.valueOf(matcher.group(2));
}
behaviors.add(new Behavior(behaviorName, argument));
LOGGER.info("Found behavior: {} with argument: {}", behaviorName, argument);
LOGGER.debug("Found behavior: {} with argument: {}", behaviorName, argument);
matcher.appendReplacement(cleanedMessage, "");
}
......@@ -40,7 +40,7 @@ public class MessageParser {
// Remove all occurrences of "<>" and "**" (if any)
displayMessage = displayMessage.replaceAll("<>", "").replaceAll("\\*\\*", "").trim();
LOGGER.info("Cleaned message: {}", displayMessage);
LOGGER.debug("Cleaned message: {}", displayMessage);
return new ParsedMessage(displayMessage, input.trim(), behaviors);
}
......
......@@ -39,6 +39,7 @@ import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
......@@ -281,7 +282,6 @@ public class ServerPackets {
} else {
// Iterate over all players and send the packet
for (ServerPlayerEntity serverPlayer : serverInstance.getPlayerManager().getPlayerList()) {
LOGGER.info("Broadcast whitelist / blacklist packet to player: " + serverPlayer.getName().getString());
ServerPlayNetworking.send(serverPlayer, PACKET_S2C_WHITELIST, buffer);
}
}
......@@ -314,7 +314,7 @@ public class ServerPackets {
}
userMessageBuilder.append("They speak in '").append(userLanguage).append("' with a ").append(randomSpeakingStyle).append(" style.");
LOGGER.info(userMessageBuilder.toString());
// Generate new character
chatData.generateCharacter(userLanguage, player, userMessageBuilder.toString(), false);
}
......@@ -324,12 +324,30 @@ public class ServerPackets {
EntityBehaviorManager.addGoal(entity, talkGoal, GoalPriority.TALK_PLAYER);
// Add new message
LOGGER.info("Player message received: " + message + " | Entity: " + entity.getType().toString());
chatData.generateMessage(userLanguage, player, message, is_auto_message);
}
// Writing a Map<String, PlayerData> to the buffer
public static void writePlayerDataMap(PacketByteBuf buffer, Map<String, PlayerData> map) {
buffer.writeInt(map.size()); // Write the size of the map
for (Map.Entry<String, PlayerData> entry : map.entrySet()) {
buffer.writeString(entry.getKey()); // Write the key (playerName)
PlayerData data = entry.getValue();
buffer.writeInt(data.friendship); // Write PlayerData field(s)
}
}
// Send new message to all connected players
public static void BroadcastPacketMessage(EntityChatData chatData, ServerPlayerEntity sender) {
// Log useful information before looping through all players
LOGGER.info("Broadcasting message: sender={}, entityId={}, status={}, currentMessage={}, currentLineNumber={}, senderType={}",
sender != null ? sender.getDisplayName().getString() : "Unknown",
chatData.entityId,
chatData.status,
chatData.currentMessage.length() > 24 ? chatData.currentMessage.substring(0, 24) + "..." : chatData.currentMessage,
chatData.currentLineNumber,
chatData.sender);
for (ServerWorld world : serverInstance.getWorlds()) {
UUID entityId = UUID.fromString(chatData.entityId);
MobEntity entity = (MobEntity)ServerEntityFinder.getEntityByUUID(world, entityId);
......@@ -337,7 +355,7 @@ public class ServerPackets {
// Set custom name (if null)
String characterName = chatData.getCharacterProp("name");
if (!characterName.isEmpty() && !characterName.equals("N/A") && entity.getCustomName() == null) {
LOGGER.debug("Setting entity name to " + characterName + " for " + chatData.entityId);
LOGGER.info("Setting entity name to " + characterName + " for " + chatData.entityId);
entity.setCustomName(Text.literal(characterName));
entity.setCustomNameVisible(true);
entity.setPersistent();
......@@ -345,8 +363,6 @@ public class ServerPackets {
// Iterate over all players and send the packet
for (ServerPlayerEntity player : serverInstance.getPlayerManager().getPlayerList()) {
PlayerData playerData = chatData.getPlayerData(player.getDisplayName().getString());
PacketByteBuf buffer = new PacketByteBuf(Unpooled.buffer());
// Write the entity's chat updated data
......@@ -362,9 +378,9 @@ public class ServerPackets {
buffer.writeInt(chatData.currentLineNumber);
buffer.writeString(chatData.status.toString());
buffer.writeString(chatData.sender.toString());
buffer.writeInt(playerData.friendship);
writePlayerDataMap(buffer, chatData.players);
LOGGER.debug("Server broadcast message to client: " + player.getName().getString() + " | Status: " + chatData.status.toString() + " | Message: " + chatData.currentMessage);
// Send message to player
ServerPlayNetworking.send(player, PACKET_S2C_MESSAGE, buffer);
}
break;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment