package dnfbridge import ( "context" "encoding/binary" "fmt" "reflect" "strconv" dnfcompanion "longheng.io/server/internal/modules/dnf/companion" dnfrepo "longheng.io/server/internal/modules/dnf/repository" "longheng.io/server/internal/platform/eventloop" ) const currentDungeonCompanionProjectionFlagProgression = byte(2) // EXP owners can hold dungeon.mu. Post to the existing character event owner // so the refresh runs immediately after that transaction/death notification, // with the lock released and without waiting for a room change or dungeon exit. func (s *Service) queueCurrentDungeonCompanionProgressionRefresh(session *gameSession, sourceID string) { runtime := session.dungeon.runtime if runtime == nil || runtime.Companion == nil || !runtime.Companion.Ready { return } // Direct owner calls (also used by focused tests) have no event queue and // already own the session; they can be inside the dungeon lock. if session.events == nil || session.events.loop == nil { if err := s.refreshCurrentDungeonCompanionProgression(context.Background(), session, runtime, sourceID); err != nil { s.logGameEvent(session, "game-dungeon-companion-live-refresh-failed", "source_character_id", sourceID, "error", err) } return } // Submission originates inside this same event owner: it must not block // on a full queue. A later committed EXP event can retry a failed enqueue. err := session.events.loop.Submit(eventloop.Event{Type: "companion-progression-refresh", Priority: eventloop.PriorityHigh, Data: gameSessionEventTask{source: "companion-progression-refresh", characterID: session.selectedCharacterID, characterGeneration: session.characterGeneration, async: true, run: func() error { session.dungeon.mu.Lock() defer session.dungeon.mu.Unlock() if session.dungeon.runtime != runtime || !dungeonRuntimeOwnsCharacter(runtime, session.selectedCharacterID) { return nil } if err := s.refreshCurrentDungeonCompanionProgression(context.Background(), session, runtime, sourceID); err != nil { s.logGameEvent(session, "game-dungeon-companion-live-refresh-failed", "source_character_id", sourceID, "error", err) } return nil }}}) if err != nil { s.logGameEvent(session, "game-dungeon-companion-live-refresh-failed", "source_character_id", sourceID, "error", err) } } // Called under dungeon.mu. Keep this run's selection and equipment; only the // committed progression and the balance owner's current level/stats can change. func (s *Service) refreshCurrentDungeonCompanionProgression(ctx context.Context, session *gameSession, runtime *runtimeDungeonState, sourceID string) error { run := runtime.Companion if run == nil || !run.Ready { return nil } repos, ok := s.repositoryGroup() if !ok { return dnfrepo.ErrCompanionReadUnavailable } reader, ok := repos.Character.(dnfrepo.CompanionSourceReader) if !ok { return dnfrepo.ErrCompanionReadUnavailable } for i := range run.Sources { entry := &run.Sources[i] if !entry.Ready || strconv.Itoa(int(entry.SourceCharacterID)) != sourceID { continue } old := entry.ProgressionSnapshot if old.Source.CharacterID == "" || len(entry.Body) < currentDungeonCompanionProjectionHeaderSize { return fmt.Errorf("companion progression snapshot missing: source=%s", sourceID) } state, err := reader.ReadCompanionSource(ctx, old.Owner.AccountID, old.Owner.CharacterID, sourceID) if err != nil { return err } if state.Source.Level == old.Source.Level && (!entry.BalanceEnabled || state.Owner.Level == old.Owner.Level) && state.Source.Stats["grow_type"] == old.Source.Stats["grow_type"] && state.Source.Stats["ex_equip_slot_stat"] == old.Source.Stats["ex_equip_slot_stat"] && reflect.DeepEqual(state.Skill.Skills, old.Skill.Skills) && reflect.DeepEqual(state.Skill.Layouts, old.Skill.Layouts) { return nil } state.Equipment = dnfrepo.CloneEquipment(old.Equipment) state.HasEquipment = old.HasEquipment option := currentDungeonCompanionProjectionOptions{AIProfile: entry.AIProfile} if entry.BalanceEnabled { option.EffectiveLevel, option.Mode1, _, err = s.buildCurrentDungeonCompanionBalanceMode1(ctx, session, state) } else { stats, found := s.characterPVFStatsForUserInfo(ctx, session, state.Source, true) if !found { return fmt.Errorf("companion progression PVF stats unavailable: source=%s", sourceID) } character := dnfrepo.CloneCharacter(state.Source) if character.Stats == nil { character.Stats = make(map[string]int64) } for key, value := range characterPVFStatValues(stats) { character.Stats[key] = value } r := csharpLegacyUserInfoReader{ctx: ctx, characterID: sourceID, service: s, session: session, suppressActorSkillResources: true, equipmentSnapshot: &state.Equipment} // Keep the embedded APC owner paired with its 0/0 mode0 template. option.Mode1 = r.buildCurrentUserInfoMode1WithEquipmentForOwner(character, true, currentDungeonCompanionProjectionObjectKey, true, 0, currentSceneObjectRoute, currentSceneObjectContext) } if err != nil { return err } selection := dnfcompanion.Selection{AccountID: state.Owner.AccountID, OwnerCharacterID: state.Owner.CharacterID, SourceCharacterID: sourceID, OnlineStateKnown: true} projection, body, err := buildCurrentDungeonCompanionProjectionEnvelope(state, selection, s.gameplayNow(), option) if err != nil { return err } // Bind to the exact spawn packet, not an actor key inferred from combat. // A distinct flag never enters the client's summon queue. copy(body[8:16], entry.Body[8:16]) live := append([]byte(nil), body...) // Creation carries the AI plan in this word; a live progression packet // carries EXP there. Keep the two packet kinds mutually exclusive. live[5] = currentDungeonCompanionProjectionFlagPresent | currentDungeonCompanionProjectionFlagProgression binary.LittleEndian.PutUint32(live[68:72], statU32(state.Source, "exp", 0)) if err := s.sendGameUpperRawClass(session, currentDungeonCompanionProjectionOpcode, live, 0); err != nil { return err } previousLevel := entry.Projection.Level entry.Projection, entry.Body, entry.ProgressionSnapshot = projection.Clone(), body, state entry.EffectiveLevel, entry.SnapshotAt, entry.SnapshotFingerprint = projection.Level, s.gameplayNow(), projection.Fingerprint() if run.SourceCharacterID == entry.SourceCharacterID { run.Projection, run.Body = projection.Clone(), append([]byte(nil), body...) run.SnapshotAt, run.SnapshotFingerprint = entry.SnapshotAt, entry.SnapshotFingerprint } s.logGameEvent(session, "game-dungeon-companion-live-refresh-send", "source_character_id", sourceID, "previous_level", previousLevel, "level", projection.Level, "learned_skills", len(state.Skill.Skills), "dungeon_id", runtime.Dungeon.ID, "current_dungeon", true) } return nil }