Update assets, working save kerfuffle

This commit is contained in:
Michal Pikulski
2025-11-17 14:30:07 +01:00
parent ee07d89d3e
commit c6f635f871
30 changed files with 44358 additions and 462 deletions

View File

@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Linq;
using AppleHills.Data.CardSystem;
using Core;
using Data.CardSystem;
@@ -25,8 +24,7 @@ namespace UI.CardSystem
[Header("Zone Navigation")]
[SerializeField] private Transform tabContainer; // Container holding all BookTabButton children
private BookTabButton[] zoneTabs; // Discovered zone tab buttons
private BookTabButton[] _zoneTabs; // Discovered zone tab buttons
[Header("Album Card Reveal")]
[SerializeField] private SlotContainer bottomRightSlots;
@@ -42,10 +40,13 @@ namespace UI.CardSystem
[SerializeField] private BoosterOpeningPage boosterOpeningPage;
private Input.InputMode _previousInputMode;
private List<StateMachine.Card> _activeCards = new List<StateMachine.Card>();
private const int MAX_VISIBLE_CARDS = 3;
private List<StateMachine.Card> _pendingCornerCards = new List<StateMachine.Card>();
private const int MAX_PENDING_CORNER = 3;
private const int MaxPendingCorner = 3;
// Pending card placement coordination
private StateMachine.Card _pendingPlacementCard;
private bool _waitingForPageFlip;
private bool _cardDragReleased;
internal override void OnManagedStart()
{
@@ -108,22 +109,22 @@ namespace UI.CardSystem
if (tabContainer == null)
{
Debug.LogError("[AlbumViewPage] Tab container is not assigned! Cannot discover zone tabs.");
zoneTabs = new BookTabButton[0];
_zoneTabs = new BookTabButton[0];
return;
}
// Get all BookTabButton components from children
zoneTabs = tabContainer.GetComponentsInChildren<BookTabButton>(includeInactive: false);
_zoneTabs = tabContainer.GetComponentsInChildren<BookTabButton>(includeInactive: false);
if (zoneTabs == null || zoneTabs.Length == 0)
if (_zoneTabs == null || _zoneTabs.Length == 0)
{
Logging.Warning($"[AlbumViewPage] No BookTabButton components found in tab container '{tabContainer.name}'!");
zoneTabs = new BookTabButton[0];
_zoneTabs = new BookTabButton[0];
}
else
{
Logging.Debug($"[AlbumViewPage] Discovered {zoneTabs.Length} zone tabs from container '{tabContainer.name}'");
foreach (var tab in zoneTabs)
Logging.Debug($"[AlbumViewPage] Discovered {_zoneTabs.Length} zone tabs from container '{tabContainer.name}'");
foreach (var tab in _zoneTabs)
{
Logging.Debug($" - Tab: {tab.name}, Zone: {tab.Zone}, TargetPage: {tab.TargetPage}");
}
@@ -159,7 +160,6 @@ namespace UI.CardSystem
if (CardSystemManager.Instance != null)
{
CardSystemManager.Instance.OnBoosterCountChanged -= OnBoosterCountChanged;
// NOTE: OnPendingCardAdded is unsubscribed in TransitionOut
}
// Clean up exit button
@@ -253,7 +253,6 @@ namespace UI.CardSystem
public override void TransitionIn()
{
// Only store and switch input mode if this is the first time entering
// (when _previousInputMode hasn't been set yet)
if (Input.InputManager.Instance != null)
{
// Store the current input mode before switching
@@ -262,12 +261,6 @@ namespace UI.CardSystem
Logging.Debug("[AlbumViewPage] Switched to UI-only input mode on first entry");
}
// Subscribe to pending card events while page is active
if (CardSystemManager.Instance != null)
{
CardSystemManager.Instance.OnPendingCardAdded += OnPendingCardAdded;
}
// Only spawn pending cards if we're already on an album page (not the menu)
if (IsInAlbumProper())
{
@@ -284,12 +277,6 @@ namespace UI.CardSystem
public override void TransitionOut()
{
// Unsubscribe from pending card events when page closes
if (CardSystemManager.Instance != null)
{
CardSystemManager.Instance.OnPendingCardAdded -= OnPendingCardAdded;
}
// Clean up active pending cards to prevent duplicates on next opening
CleanupPendingCornerCards();
@@ -402,165 +389,6 @@ namespace UI.CardSystem
}
}
#region Album Card Reveal System
/// <summary>
/// Spawn pending cards from CardSystemManager
/// Only spawns unique cards (one per definition+rarity, not one per copy)
/// </summary>
private void SpawnPendingCards()
{
if (CardSystemManager.Instance == null || bottomRightSlots == null || cardPrefab == null)
return;
var pending = CardSystemManager.Instance.GetPendingRevealCards();
var uniquePending = pending
.Where(c => c.CopiesOwned > 0)
.GroupBy(c => new { c.DefinitionId, c.Rarity })
.Select(g => g.First())
.ToList();
int spawnCount = Mathf.Min(uniquePending.Count, MAX_VISIBLE_CARDS);
Logging.Debug($"[AlbumViewPage] Spawning {spawnCount} unique pending cards (total pending: {pending.Count})");
for (int i = 0; i < spawnCount; i++)
{
SpawnCardInSlot(i, uniquePending[i]);
}
}
/// <summary>
/// Spawn a card in a specific slot using the new Card prefab
/// </summary>
private void SpawnCardInSlot(int slotIndex, CardData cardData)
{
if (cardData.CopiesOwned <= 0)
{
Logging.Warning($"[AlbumViewPage] Skipping spawn of card '{cardData.Name}' with {cardData.CopiesOwned} copies");
return;
}
DraggableSlot slot = FindSlotByIndex(slotIndex);
if (slot == null)
{
Logging.Warning($"[AlbumViewPage] Could not find slot with SlotIndex {slotIndex}");
return;
}
GameObject cardObj = Instantiate(cardPrefab, bottomRightSlots.transform);
var card = cardObj.GetComponent<StateMachine.Card>();
if (card != null)
{
// Cards spawned here are already revealed and can be dragged into album
card.SetupForAlbumPlacement(cardData);
// Assign to slot with animation (will apply size/position)
card.AssignToSlot(slot, true);
// Track placement completion to clean up
card.OnPlacedInAlbumSlot += OnCardPlacedInAlbum;
_activeCards.Add(card);
Logging.Debug($"[AlbumViewPage] Spawned pending card '{cardData.Name}' in slot {slotIndex}");
}
else
{
Logging.Warning($"[AlbumViewPage] Spawned card prefab missing Card component!");
Destroy(cardObj);
}
}
/// <summary>
/// Handle when a card is placed in an album slot from the pending list
/// Moves from pending to inventory, shuffles remaining, and spawns the next unique card.
/// </summary>
private void OnCardPlacedInAlbum(StateMachine.Card card, AlbumCardSlot slot)
{
if (card == null) return;
var data = card.CardData;
Logging.Debug($"[AlbumViewPage] Card placed in album slot: {data?.Name}");
// Move card from pending to inventory now
if (data != null && CardSystemManager.Instance != null)
{
CardSystemManager.Instance.MarkCardAsPlaced(data);
}
// Stop tracking and unsubscribe
card.OnPlacedInAlbumSlot -= OnCardPlacedInAlbum;
_activeCards.Remove(card);
// Shuffle remaining cards to front and spawn next
ShuffleCardsToFront();
TrySpawnNextCard();
}
/// <summary>
/// Shuffle active cards to occupy front slots
/// </summary>
private void ShuffleCardsToFront()
{
if (bottomRightSlots == null || _activeCards.Count == 0)
return;
List<DraggableObject> draggableList = _activeCards.Cast<DraggableObject>().ToList();
SlotContainerHelper.ShuffleToFront(bottomRightSlots, draggableList, animate: true);
}
/// <summary>
/// Try to spawn the next pending unique card
/// </summary>
private void TrySpawnNextCard()
{
if (CardSystemManager.Instance == null)
return;
if (_activeCards.Count >= MAX_VISIBLE_CARDS)
return;
var pending = CardSystemManager.Instance.GetPendingRevealCards();
var uniquePending = pending
.Where(c => c.CopiesOwned > 0)
.GroupBy(c => new { c.DefinitionId, c.Rarity })
.Select(g => g.First())
.ToList();
foreach (var cardData in uniquePending)
{
bool alreadySpawned = _activeCards.Any(c =>
c.CardData.DefinitionId == cardData.DefinitionId &&
c.CardData.Rarity == cardData.Rarity);
if (!alreadySpawned)
{
int nextSlotIndex = _activeCards.Count;
SpawnCardInSlot(nextSlotIndex, cardData);
break;
}
}
}
/// <summary>
/// Clean up all active pending cards
/// </summary>
private void CleanupActiveCards()
{
foreach (var card in _activeCards)
{
if (card != null && card.gameObject != null)
{
card.OnPlacedInAlbumSlot -= OnCardPlacedInAlbum;
Destroy(card.gameObject);
}
}
_activeCards.Clear();
}
#endregion
#region Card Enlarge System (Album Slots)
/// <summary>
@@ -633,37 +461,7 @@ namespace UI.CardSystem
#endregion
/// <summary>
/// Handle when a new card is added to pending queue
/// Only spawn if this unique card isn't already visualized
/// </summary>
private void OnPendingCardAdded(CardData card)
{
// Guard: Don't spawn cards with zero copies
if (card.CopiesOwned <= 0)
{
Logging.Warning($"[AlbumViewPage] Ignoring pending card '{card.Name}' with {card.CopiesOwned} copies");
return;
}
// Check if we already have a card with this definition + rarity spawned
bool alreadySpawned = _activeCards.Any(c =>
c.CardData.DefinitionId == card.DefinitionId &&
c.CardData.Rarity == card.Rarity);
if (alreadySpawned)
{
Logging.Debug($"[AlbumViewPage] Card '{card.Name}' already spawned, skipping duplicate spawn");
return; // Don't spawn duplicates
}
// Try to spawn if we have space
if (_activeCards.Count < MAX_VISIBLE_CARDS)
{
int nextSlotIndex = _activeCards.Count;
SpawnCardInSlot(nextSlotIndex, card);
}
}
#region New Pending Corner Card System
/// <summary>
/// Find a slot by its SlotIndex property
@@ -687,17 +485,36 @@ namespace UI.CardSystem
{
if (cardPrefab == null || bottomRightSlots == null) return;
CleanupPendingCornerCards();
for (int i = 0; i < MAX_PENDING_CORNER; i++)
// Get unique pending cards
var uniquePending = GetUniquePendingCards();
if (uniquePending.Count == 0)
{
Logging.Debug("[AlbumViewPage] No pending cards to spawn");
return;
}
// Spawn min(unique count, MaxPendingCorner)
int spawnCount = Mathf.Min(uniquePending.Count, MaxPendingCorner);
Logging.Debug($"[AlbumViewPage] Spawning {spawnCount} pending corner cards (out of {uniquePending.Count} unique pending)");
for (int i = 0; i < spawnCount; i++)
{
var slot = FindSlotByIndex(i);
if (slot == null) break;
GameObject cardObj = Instantiate(cardPrefab, bottomRightSlots.transform);
var card = cardObj.GetComponent<StateMachine.Card>();
if (card != null)
{
card.SetupForAlbumPending();
card.AssignToSlot(slot, true);
// Subscribe to both drag events
card.Context.OnDragStarted += OnCardDragStarted;
card.Context.OnDragEnded += OnCardDragEnded;
_pendingCornerCards.Add(card);
}
else
@@ -707,6 +524,40 @@ namespace UI.CardSystem
}
}
/// <summary>
/// Get unique pending cards (one per definition+rarity combo)
/// </summary>
private List<CardData> GetUniquePendingCards()
{
if (CardSystemManager.Instance == null) return new List<CardData>();
var pending = CardSystemManager.Instance.GetPendingRevealCards();
// Group by definition+rarity, take first of each group
var uniqueDict = new Dictionary<string, CardData>();
int duplicateCount = 0;
foreach (var card in pending)
{
string key = $"{card.DefinitionId}_{card.Rarity}";
if (!uniqueDict.ContainsKey(key))
{
uniqueDict[key] = card;
}
else
{
duplicateCount++;
}
}
if (duplicateCount > 0)
{
Logging.Warning($"[AlbumViewPage] Found {duplicateCount} duplicate pending cards (same definition+rarity combo)");
}
return new List<CardData>(uniqueDict.Values);
}
private void CleanupPendingCornerCards()
{
foreach (var c in _pendingCornerCards)
@@ -716,6 +567,7 @@ namespace UI.CardSystem
if (c.Context != null)
{
c.Context.OnDragStarted -= OnCardDragStarted;
c.Context.OnDragEnded -= OnCardDragEnded;
}
Destroy(c.gameObject);
}
@@ -732,24 +584,202 @@ namespace UI.CardSystem
if (card == null) return;
string stateName = card.GetCurrentStateName();
Logging.Debug($"[AlbumViewPage] OnCardDragStarted - Card state: {stateName}");
if (stateName != "PendingFaceDownState") return;
// Select smart pending card data
var selected = SelectSmartPendingCard();
if (selected == null)
{
Logging.Warning("[AlbumViewPage] No pending card data available!");
return; // no pending data
}
Logging.Debug($"[AlbumViewPage] Selected card: {selected.Name} ({selected.DefinitionId}), Zone: {selected.Zone}");
context.SetupCard(selected);
// Navigate album to page
int targetPage = FindPageForCard(selected);
// Find target page based on card's zone using BookTabButtons
int targetPage = FindPageForZone(selected.Zone);
Logging.Debug($"[AlbumViewPage] Target page for zone {selected.Zone}: {targetPage}");
if (targetPage >= 0)
{
NavigateToAlbumPage(targetPage);
// Always flip to the zone's page (even if already there, for consistency)
Logging.Debug($"[AlbumViewPage] Flipping to page {targetPage} for zone {selected.Zone}");
_waitingForPageFlip = true;
_cardDragReleased = false;
_pendingPlacementCard = card;
NavigateToAlbumPage(targetPage, OnPageFlipComplete);
}
else
{
// No valid page found for zone - don't wait for flip
Logging.Warning($"[AlbumViewPage] No BookTabButton found for zone {selected.Zone}");
_waitingForPageFlip = false;
_cardDragReleased = false;
_pendingPlacementCard = card;
}
}
private void OnCardDragEnded(StateMachine.CardContext context)
{
if (context == null) return;
var card = context.GetComponent<StateMachine.Card>();
if (card == null) return;
// Only handle if this is the pending placement card
if (card != _pendingPlacementCard) return;
Logging.Debug($"[AlbumViewPage] Card drag released for: {card.CardData?.Name}");
// Mark drag as released - don't capture slot yet (pages may still be flipping)
_cardDragReleased = true;
// Try to place card (will check if flip is also complete)
TryPlaceCard();
}
private void OnPageFlipComplete()
{
Logging.Debug("[AlbumViewPage] Page flip complete");
_waitingForPageFlip = false;
// Try to place card (will check if drag is also released)
TryPlaceCard();
}
private void TryPlaceCard()
{
// Check if BOTH conditions are met:
// 1. Card has been drag-released
// 2. Page flip is complete (or wasn't needed)
if (_cardDragReleased && !_waitingForPageFlip)
{
if (_pendingPlacementCard == null || _pendingPlacementCard.CardData == null)
{
Logging.Warning("[AlbumViewPage] TryPlaceCard - No pending card or card data");
ResetPlacementState();
return;
}
// Find the correct slot for this card (AFTER pages have flipped)
var targetSlot = FindTargetSlotForCard(_pendingPlacementCard.CardData);
if (targetSlot == null)
{
Logging.Warning($"[AlbumViewPage] No slot found for card {_pendingPlacementCard.CardData.DefinitionId}");
// TODO: Return card to corner
ResetPlacementState();
return;
}
// Both conditions met and slot found - perform placement
PlaceCardInSlot(_pendingPlacementCard, targetSlot);
}
}
/// <summary>
/// Find the AlbumCardSlot that accepts this card based on DefinitionId
/// </summary>
private AlbumCardSlot FindTargetSlotForCard(CardData cardData)
{
if (cardData == null) return null;
var allSlots = FindObjectsByType<AlbumCardSlot>(FindObjectsSortMode.None);
foreach (var slot in allSlots)
{
if (slot.TargetCardDefinition != null &&
slot.TargetCardDefinition.Id == cardData.DefinitionId)
{
Logging.Debug($"[AlbumViewPage] Found target slot for {cardData.DefinitionId}, slot: {slot}");
return slot;
}
}
// State will handle transition to FlippingPendingState
return null;
}
private void PlaceCardInSlot(StateMachine.Card card, AlbumCardSlot slot)
{
if (card == null || slot == null) return;
Logging.Debug($"[AlbumViewPage] Placing card '{card.CardData?.Name}' in slot - starting tween");
// Reparent to slot immediately, keeping world position (card stays visible where it is)
card.transform.SetParent(slot.transform, true);
// Tween local position and scale simultaneously
float tweenDuration = 0.4f;
// Tween position to center of slot
Tween.LocalPosition(card.transform, Vector3.zero, tweenDuration, 0f, Tween.EaseOutBack);
// Tween scale to normal (same duration and easing)
Tween.LocalScale(card.transform, Vector3.one, tweenDuration, 0f, Tween.EaseOutBack);
// Tween rotation to identity (use this for the completion callback since all tweens are synchronized)
Tween.LocalRotation(card.transform, Quaternion.identity, tweenDuration, 0f, Tween.EaseOutBack,
completeCallback: () =>
{
// After tween completes, finalize
card.transform.localPosition = Vector3.zero;
card.transform.localRotation = Quaternion.identity;
// Resize to match slot
RectTransform cardRect = card.transform as RectTransform;
RectTransform slotRect = slot.transform as RectTransform;
if (cardRect != null && slotRect != null)
{
float targetHeight = slotRect.rect.height;
cardRect.sizeDelta = new Vector2(cardRect.sizeDelta.x, targetHeight);
}
// Transition to placed state
var placedState = card.GetStateComponent<StateMachine.States.CardPlacedInSlotState>("PlacedInSlotState");
if (placedState != null)
{
placedState.SetParentSlot(slot);
}
card.ChangeState("PlacedInSlotState");
// Assign card to slot (so slot remembers it has a card)
slot.AssignCard(card);
// Mark as placed in inventory
if (CardSystemManager.Instance != null)
{
CardSystemManager.Instance.MarkCardAsPlaced(card.CardData);
}
// Unsubscribe from drag events - card is now placed, shouldn't respond to future drags
if (card.Context != null)
{
card.Context.OnDragStarted -= OnCardDragStarted;
card.Context.OnDragEnded -= OnCardDragEnded;
}
// Remove from pending corner cards list
_pendingCornerCards.Remove(card);
// Register with album page for enlarge system
RegisterCardInAlbum(card);
Logging.Debug($"[AlbumViewPage] Card placement complete and unsubscribed from drag events");
// Reset state for next card
ResetPlacementState();
});
}
private void ResetPlacementState()
{
_pendingPlacementCard = null;
_waitingForPageFlip = false;
_cardDragReleased = false;
}
private CardData SelectSmartPendingCard()
@@ -766,6 +796,29 @@ namespace UI.CardSystem
return pending[idx];
}
/// <summary>
/// Find the target page for a card zone using BookTabButtons
/// </summary>
private int FindPageForZone(CardZone zone)
{
if (_zoneTabs == null || _zoneTabs.Length == 0)
{
Logging.Warning("[AlbumViewPage] No zone tabs discovered!");
return -1;
}
foreach (var tab in _zoneTabs)
{
if (tab.Zone == zone)
{
return tab.TargetPage;
}
}
Logging.Warning($"[AlbumViewPage] No BookTabButton found for zone {zone}");
return -1;
}
private List<string> GetDefinitionsOnCurrentPage()
{
var result = new List<string>();
@@ -811,32 +864,7 @@ namespace UI.CardSystem
return false;
}
private int FindPageForCard(CardData data)
{
if (data == null || book == null || book.papers == null) return -1;
// Find all AlbumCardSlot in scene
var allSlots = FindObjectsByType<AlbumCardSlot>(FindObjectsSortMode.None);
foreach (var slot in allSlots)
{
if (slot.TargetCardDefinition != null && slot.TargetCardDefinition.Id == data.DefinitionId)
{
// Found matching slot, now find which page it's on
for (int i = 0; i < book.papers.Length; i++)
{
if (IsSlotOnPage(slot.transform, i))
{
return i;
}
}
}
}
return -1;
}
private void NavigateToAlbumPage(int pageIndex)
private void NavigateToAlbumPage(int pageIndex, UnityEngine.Events.UnityAction onComplete = null)
{
if (book == null || pageIndex < 0) return;
@@ -847,9 +875,18 @@ namespace UI.CardSystem
autoFlip = book.gameObject.AddComponent<BookCurlPro.AutoFlip>();
}
// Start flipping to target page
// Start flipping to target page with callback
autoFlip.enabled = true;
autoFlip.StartFlipping(pageIndex);
if (onComplete != null)
{
autoFlip.StartFlipping(pageIndex, onComplete);
}
else
{
autoFlip.StartFlipping(pageIndex);
}
}
#endregion
}
}