Files
18xchat/assets/Scripts/chat18x/data/ChatModel.ts
T
2025-08-27 16:35:26 +08:00

718 lines
19 KiB
TypeScript

import { VideoEmotion, purchase } from "../../schema/schema";
import { Dialog } from "./DialogData";
import ConfigManager from "../manager/ConfigManager";
/**
* 单个角色的聊天数据结构
*/
export interface RoleChatData {
roleId: number;
roleData: any;
roleDetail: any;
dialogs: Dialog[];
currentEmotion: VideoEmotion;
commercialVideos: purchase.CommercialVideo[];
nameKey: string;
lastActiveTime: Date;
isInitialized: boolean;
chatCount: number;
maxChatCount: number;
}
/**
* 聊天数据模型类 (多角色管理器)
*
* 负责管理多个角色的聊天相关数据,包括:
* - 多个角色的数据和配置
* - 各角色独立的对话历史记录
* - 各角色独立的情绪状态
* - 视频配置管理
* - 角色切换和数据持久化
*
* 这是MVP架构中的Model层,专注于多角色数据管理和业务逻辑
*/
export class ChatModel {
// 存储所有角色的数据
private rolesData: Map<number, RoleChatData> = new Map();
// 当前活跃的角色ID
private currentRoleId: number | null = null;
// 最大缓存角色数量(内存管理)
private maxCachedRoles: number = 10;
/**
* 初始化或切换到指定角色
* @param roleId 角色ID
* @returns 是否成功
*/
public initializeRole(roleId: number): boolean {
if (roleId <= 0) {
console.error("ChatModel: Invalid roleId provided");
return false;
}
// 如果角色数据已存在,直接切换
if (this.rolesData.has(roleId)) {
this.currentRoleId = roleId;
this.updateLastActiveTime(roleId);
console.log(`ChatModel: Switched to existing role ${roleId}`);
return true;
}
// 创建新的角色数据
const newRoleData = this.createRoleData(roleId);
if (newRoleData) {
// 内存管理:如果超过最大缓存数量,清理最久未使用的角色
this.manageMemory();
this.rolesData.set(roleId, newRoleData);
this.currentRoleId = roleId;
console.log(`ChatModel: Initialized new role ${roleId}`);
return true;
}
return false;
}
/**
* 切换到指定角色(不存在则初始化)
* @param roleId 角色ID
* @returns 是否成功
*/
public switchToRole(roleId: number): boolean {
return this.initializeRole(roleId);
}
/**
* 创建新的角色数据
* @param roleId 角色ID
* @returns 角色数据对象
*/
private createRoleData(roleId: number): RoleChatData | null {
try {
// 加载角色基础数据
const roleData = ConfigManager.tables.TbGirls.get(roleId);
const roleDetail = ConfigManager.tables.TbGirlsDetail.get(roleId);
if (!roleData) {
console.error(`ChatModel: Role data not found for roleId ${roleId}`);
return null;
}
//Todo:未接入后端数据 待补充
// 创建角色数据对象
const newRoleData: RoleChatData = {
roleId: roleId,
roleData: roleData,
roleDetail: roleDetail,
nameKey: roleData.nameKey || "",
dialogs: [],
currentEmotion: VideoEmotion.calm_down,
commercialVideos:
roleDetail && roleDetail.commercialVideos
? roleDetail.commercialVideos
: [],
lastActiveTime: new Date(),
isInitialized: true,
chatCount: 0,
maxChatCount: this.getDefaultChatLimit(),
};
return newRoleData;
} catch (error) {
console.error(
`ChatModel: Failed to create role data for ${roleId}:`,
error
);
return null;
}
}
/**
* 内存管理:清理最久未使用的角色数据
*/
private manageMemory(): void {
if (this.rolesData.size < this.maxCachedRoles) {
return;
}
// 找出最久未使用的角色
let oldestRoleId: number | null = null;
let oldestTime: Date = new Date();
for (const [roleId, roleData] of this.rolesData.entries()) {
if (roleData.lastActiveTime < oldestTime) {
oldestTime = roleData.lastActiveTime;
oldestRoleId = roleId;
}
}
if (oldestRoleId !== null) {
this.rolesData.delete(oldestRoleId);
console.log(`ChatModel: Cleaned up unused role ${oldestRoleId} data`);
}
}
/**
* 更新角色最后活跃时间
* @param roleId 角色ID
*/
private updateLastActiveTime(roleId: number): void {
const roleData = this.rolesData.get(roleId);
if (roleData) {
roleData.lastActiveTime = new Date();
}
}
/**
* 获取当前活跃角色ID
*/
public getCurrentRoleId(): number | null {
return this.currentRoleId;
}
/**
* 获取当前角色数据
*/
public getCurrentRoleData(): RoleChatData | null {
if (!this.currentRoleId) {
return null;
}
return this.rolesData.get(this.currentRoleId) || null;
}
/**
* 获取指定角色数据
* @param roleId 角色ID,不传则使用当前角色
*/
public getRoleData(roleId?: number): any {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return null;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.roleData : null;
}
/**
* 获取指定角色详细数据
* @param roleId 角色ID,不传则使用当前角色
*/
public getRoleDetail(roleId?: number): any {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return null;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.roleDetail : null;
}
/**
* 获取角色名称键值
* @param roleId 角色ID,不传则使用当前角色
*/
public getNameKey(roleId?: number): string {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return "";
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.nameKey : "";
}
/**
* 检查是否有指定角色的数据
* @param roleId 角色ID
*/
public hasRoleData(roleId: number): boolean {
return this.rolesData.has(roleId);
}
/**
* 获取对话记录
* @param roleId 角色ID,不传则使用当前角色
*/
public getDialogs(roleId?: number): Dialog[] {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return [];
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? [...roleData.dialogs] : []; // 返回副本避免外部修改
}
/**
* 添加对话记录
* @param isPlayer 是否为玩家消息
* @param content 消息内容
* @param roleId 角色ID,不传则使用当前角色
*/
public addDialog(isPlayer: boolean, content: string, roleId?: number): void {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
console.warn("ChatModel: Cannot add dialog - no active role");
return;
}
if (!content || content.trim() === "") {
console.warn("ChatModel: Cannot add empty dialog content");
return;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
console.warn(`ChatModel: Role data not found for roleId ${targetRoleId}`);
return;
}
const dialog: Dialog = {
isPlayer: isPlayer,
content: content.trim(),
};
roleData.dialogs.push(dialog);
this.updateLastActiveTime(targetRoleId);
console.log(
`ChatModel: Dialog added for role ${targetRoleId} (isPlayer: ${isPlayer}, content length: ${content.length})`
);
}
/**
* 清空对话记录
* @param roleId 角色ID,不传则使用当前角色
*/
public clearDialogs(roleId?: number): void {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
console.warn("ChatModel: Cannot clear dialogs - no active role");
return;
}
const roleData = this.rolesData.get(targetRoleId);
if (roleData) {
roleData.dialogs = [];
this.updateLastActiveTime(targetRoleId);
console.log(`ChatModel: Dialogs cleared for role ${targetRoleId}`);
}
}
/**
* 获取当前情绪状态
* @param roleId 角色ID,不传则使用当前角色
*/
public getCurrentEmotion(roleId?: number): VideoEmotion {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return VideoEmotion.calm_down;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.currentEmotion : VideoEmotion.calm_down;
}
/**
* 设置当前情绪状态
* @param emotion 新的情绪状态
* @param roleId 角色ID,不传则使用当前角色
*/
public setCurrentEmotion(emotion: VideoEmotion, roleId?: number): void {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
console.warn("ChatModel: Cannot set emotion - no active role");
return;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
console.warn(`ChatModel: Role data not found for roleId ${targetRoleId}`);
return;
}
if (roleData.currentEmotion !== emotion) {
const oldEmotion = roleData.currentEmotion;
roleData.currentEmotion = emotion;
this.updateLastActiveTime(targetRoleId);
console.log(
`ChatModel: Role ${targetRoleId} emotion changed from ${VideoEmotion[oldEmotion]} to ${VideoEmotion[emotion]}`
);
}
}
/**
* 获取商业视频配置
* @param roleId 角色ID,不传则使用当前角色
*/
public getCommercialVideos(roleId?: number): purchase.CommercialVideo[] {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return [];
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? [...roleData.commercialVideos] : []; // 返回副本避免外部修改
}
/**
* 根据情绪获取对应的视频(如果有多个视频,随机返回一个)
* @param emotion 目标情绪
* @param roleId 角色ID,不传则使用当前角色
* @returns 匹配的视频对象,没找到则返回null
*/
public getVideoByEmotion(
emotion: VideoEmotion,
roleId?: number
): purchase.CommercialVideo | null {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return null;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
return null;
}
// 获取所有匹配该情绪的视频
const matchingVideos = roleData.commercialVideos.filter(
(video) => video.emotion === emotion
);
if (matchingVideos.length === 0) {
return null;
}
// 如果只有一个匹配的视频,直接返回
if (matchingVideos.length === 1) {
return matchingVideos[0];
}
// 如果有多个匹配的视频,随机选择一个
const randomIndex = Math.floor(Math.random() * matchingVideos.length);
return matchingVideos[randomIndex];
}
/**
* 获取默认视频(第一个视频或平静状态视频)
* @param roleId 角色ID,不传则使用当前角色
*/
public getDefaultVideo(roleId?: number): purchase.CommercialVideo | null {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return null;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData || roleData.commercialVideos.length === 0) {
return null;
}
// 优先返回平静状态的视频
const calmVideo = roleData.commercialVideos.find(
(video) => video.emotion === VideoEmotion.calm_down
);
return calmVideo || roleData.commercialVideos[0];
}
/**
* 获取对话数量
* @param roleId 角色ID,不传则使用当前角色
*/
public getDialogCount(roleId?: number): number {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return 0;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.dialogs.length : 0;
}
/**
* 获取最后一条对话
* @param roleId 角色ID,不传则使用当前角色
*/
public getLastDialog(roleId?: number): Dialog | null {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return null;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData || roleData.dialogs.length === 0) {
return null;
}
return roleData.dialogs[roleData.dialogs.length - 1];
}
/**
* 检查当前角色是否已初始化
* @param roleId 角色ID,不传则使用当前角色
*/
public isInitialized(roleId?: number): boolean {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return false;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.isInitialized : false;
}
/**
* 重置所有数据到初始状态
*/
public reset(): void {
this.rolesData.clear();
this.currentRoleId = null;
console.log(
"ChatModel: All role data cleared and model reset to initial state"
);
}
/**
* 重置指定角色的数据
* @param roleId 角色ID
*/
public resetRole(roleId: number): void {
if (this.rolesData.has(roleId)) {
this.rolesData.delete(roleId);
// 如果删除的是当前角色,清空当前角色ID
if (this.currentRoleId === roleId) {
this.currentRoleId = null;
}
console.log(`ChatModel: Role ${roleId} data cleared`);
}
}
/**
* 验证当前模型状态
* @param roleId 角色ID,不传则使用当前角色
*/
public validate(roleId?: number): boolean {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
console.error("ChatModel: No active role");
return false;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
console.error(`ChatModel: Role data not found for ${targetRoleId}`);
return false;
}
if (!roleData.isInitialized) {
console.error(`ChatModel: Role ${targetRoleId} not initialized`);
return false;
}
if (!roleData.roleData) {
console.error(`ChatModel: Role ${targetRoleId} data not loaded`);
return false;
}
return true;
}
/**
* 获取所有角色数据摘要
*/
public getAllRolesData(): Map<number, RoleChatData> {
return new Map(this.rolesData);
}
/**
* 获取缓存的角色数量
*/
public getCachedRoleCount(): number {
return this.rolesData.size;
}
/**
* 获取所有角色ID列表
*/
public getAllRoleIds(): number[] {
return Array.from(this.rolesData.keys());
}
/**
* 清除指定角色的数据(外部调用接口)
* @param roleId 角色ID
*/
public clearRoleData(roleId: number): void {
this.resetRole(roleId);
}
/**
* 设置最大缓存角色数量
* @param maxCount 最大缓存数量
*/
public setMaxCachedRoles(maxCount: number): void {
if (maxCount > 0) {
this.maxCachedRoles = maxCount;
console.log(`ChatModel: Max cached roles set to ${maxCount}`);
// 如果当前缓存超过新限制,清理多余的
this.manageMemory();
}
}
/**
* 获取模型状态摘要(用于调试)
* @param roleId 角色ID,不传则返回当前角色摘要
*/
public getStateSummary(roleId?: number): any {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return {
currentRoleId: null,
totalCachedRoles: this.rolesData.size,
maxCachedRoles: this.maxCachedRoles,
allRoleIds: this.getAllRoleIds(),
};
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
return {
roleId: targetRoleId,
error: "Role data not found",
};
}
return {
roleId: targetRoleId,
nameKey: roleData.nameKey,
dialogCount: roleData.dialogs.length,
currentEmotion: VideoEmotion[roleData.currentEmotion],
videoCount: roleData.commercialVideos.length,
lastActiveTime: roleData.lastActiveTime,
isInitialized: roleData.isInitialized,
chatCount: roleData.chatCount,
maxChatCount: roleData.maxChatCount,
remainingChats: roleData.maxChatCount - roleData.chatCount,
totalCachedRoles: this.rolesData.size,
};
}
/**
* 获取默认聊天次数限制
* TODO: 以后从后端获取,目前默认返回10
* @returns 默认聊天次数限制
*/
private getDefaultChatLimit(): number {
return 1;
}
/**
* 获取角色的聊天次数限制
* @param roleId 角色ID,不传则使用当前角色
* @returns 聊天次数限制,未找到角色则返回0
*/
public getRoleChatLimit(roleId?: number): number {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return 0;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.maxChatCount : 0;
}
/**
* 获取角色已使用的聊天次数
* @param roleId 角色ID,不传则使用当前角色
* @returns 已使用的聊天次数
*/
public getRoleChatCount(roleId?: number): number {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return 0;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData ? roleData.chatCount : 0;
}
/**
* 获取角色剩余聊天次数
* @param roleId 角色ID,不传则使用当前角色
* @returns 剩余聊天次数
*/
public getRemainingChatCount(roleId?: number): number {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
return 0;
}
const roleData = this.rolesData.get(targetRoleId);
return roleData
? Math.max(0, roleData.maxChatCount - roleData.chatCount)
: 0;
}
/**
* 检查角色是否还有剩余聊天次数
* @param roleId 角色ID,不传则使用当前角色
* @returns 是否可以继续聊天
*/
public canChat(roleId?: number): boolean {
return this.getRemainingChatCount(roleId) > 0;
}
/**
* 增加角色聊天次数计数
* @param roleId 角色ID,不传则使用当前角色
*/
public incrementChatCount(roleId?: number): void {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
console.warn("ChatModel: Cannot increment chat count - no active role");
return;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
console.warn(`ChatModel: Role data not found for roleId ${targetRoleId}`);
return;
}
roleData.chatCount++;
this.updateLastActiveTime(targetRoleId);
console.log(
`ChatModel: Chat count incremented for role ${targetRoleId}, current: ${roleData.chatCount}/${roleData.maxChatCount}`
);
}
/**
* 重置角色聊天次数
* @param roleId 角色ID,不传则使用当前角色
*/
public resetChatCount(roleId?: number): void {
const targetRoleId = roleId || this.currentRoleId;
if (!targetRoleId) {
console.warn("ChatModel: Cannot reset chat count - no active role");
return;
}
const roleData = this.rolesData.get(targetRoleId);
if (!roleData) {
console.warn(`ChatModel: Role data not found for roleId ${targetRoleId}`);
return;
}
roleData.chatCount = 0;
this.updateLastActiveTime(targetRoleId);
console.log(`ChatModel: Chat count reset for role ${targetRoleId}`);
}
}