Opening another scene mid-battle and saving mid-battle

This is less a request and more a thought experiment.

Say I want to open a shop or another scene during a battle, and, at the end of such scene, return to the ongoing battle. What do I need to do in order to do it? From what I understand, calling another scene through the SceneManager will first call the end of the current scene (calling pre_terminate then terminate) before calling the start and post_start methods from the new scene.

While for some scenes like Scene_Map or Scene_Menu, calling sub scenes seems okay, I am less sure about Scene_Battle which will probably break some properties (related to BattleManager or the $game_troop I expect). My ultimate goal would be to perform sub-scenes call during my TBS script which has a somewhat similar structure to Scene_Battle.

Ideally, I would like to be able to call a Scene_Shop menu during battle, and, with even more development, be able to save mid-battle, and when reloading a save to call back my battle scene.
Do you know if someone investigated saving mid-battle or calling other scenes in the middle of a Scene_Battle?
as you have guessed, calling another scene during battle takes a lot more.

If I remember correctly, both Victor and Yanfly made scripts for a "Battle Status", d.h. calling a status scene during battle. You might consider looking for them and see what you can learn. Just remember that for the Ace Engine, Victor's Scripts and Yanfly Scripts are often either incompatible or difficult to make work together.

Saving in Battle is even more problematic, because by default the engine does not store anything about a battle or battle turn, You would have to make sure that all of the battledata is stored into a permanent instead of temporary structure and that that data structure would be added to the savefile and loaded from there.
And I would strongly suggest doing that on the party menu level, NOT on the actor menu level - storing detailed turn data is worse than storing only between-turn-summaries.
So I did not find anything related to a status menu mid-battle, but, checking Yanfly's Equip Menu, you can actually handle a sub scene like this:
Ruby:
SceneManager.call(Scene_Equip)
SceneManager.scene.main #this one will loop until we leave the sub scene
SceneManager.force_recall(self)
The last command is just a failsafe to make sure the returned scene is the parent one but I think this is not necessary for most sub scenes as they should return to their parent.
It seems very simple and I will have to test it, but this would make sub-scenes calls much easier.

For saving a battle state, I will investigate it later but it doesn't seems that far away: by default the save already stores the $game_troop along with the party, meaning that almost all the data I need in my battle is stored (battlers involved, states, positions etc.). I just need to check if BattleManager stores some information, then if my battle scene stores some useful objects (it does like my turnwheel), and then when calling back the save, I should try to retrieve most data and skip the initialisation of some variables. It will require time and testing and I won't do it until my script has reached its 'full' released version but I think I know how to do it.

Thanks!
Hey,

As Andar said, the battle scene is a bit of a beast of its own.
Most scenes will set up graphics and determine which parts of the game get updated. The battle scene assumes that you enter it at the start of a battle and leave it at the end of it.

I could not find a working link for the Battle Status script right now for comparison, but assuming you want to switch to menus only through events and not in the middle of an action or during action selection or something, it might be enough to stop the battle scene from initiating a new battle when opened:
Ruby:
class Game_Temp
  attr_accessor :last_battle_subject
end

class Scene_Battle
 
  alias_method(:main_during_rememberLastSubject, :main)
  def main
    temp = $game_temp
    @subject = temp.last_battle_subject  if $game_party.in_battle
    main_during_rememberLastSubject
    temp.last_battle_subject = @subject  if $game_party.in_battle
  end
 
  # Redefined:
  def battle_start
    BattleManager.battle_start  if !$game_party.in_battle  # Stop new battle
    process_event
    if !BattleManager.in_turn?
      # If the battle is interrupted during action selection, make sure the
      # party constellation does not change and no members lose their actions.
      # Otherwise extra code will be needed to restore consistency.
      # (This also does not yet restore the exact menu position)
      if BattleManager.actor
        start_actor_command_selection
      else
        start_party_command_selection
      end
    end
  end
 
  alias_method(:terminate_before_MenuBackgroundSnapshot, :terminate)
  def terminate
    terminate_before_MenuBackgroundSnapshot
    SceneManager.snapshot_for_background
  end
end
Of course this assumes any other battle related scripts you use don't need their own adjustments for this. This should work in between actions or turns, but may cause issues if the BattleManager is in the "input" phase. Returning to the map screen mid-battle may also cause some issues.
Late Edit: Have not actually tested this, but as long as your action list does not change you should be able to return to the command selection too without too much extra code.
Late Edit 2: Changed the code to include saving the @subject variable of the battle scene (relevant if the scene is exited in between two actions by the same battler)

The subscene approach in your post is a good alternative though, since it allows the battle scene to just continue where it left off. It might be more difficult to preserve that status in a savefile though.


You mentioned you are good on the saving mid-battle part, but since it is already done in case you have use for it as a reference: (based on the default battle system and in addition to the script part above):
Spoiler
Ruby:
# Store/Load BattleManager Status in a savefile:
# - The @method_wait_for_message variable is incompatible, but will be updated
#   when entering the battle scene anyways.
# - The "Battle Processing..." event callback proc needs to be made compatible
# - The "@event_flags" from $game_troop need to be refreshed, since the troop
#   event page objects will be different
# - The @subject variable from the active battle scene is saved

class Scene_Load
 
  alias_method(:on_load_success_before_restoreBattleScene, :on_load_success)
  def on_load_success
    on_load_success_before_restoreBattleScene
    SceneManager.call(Scene_Battle)  if $game_party.in_battle
  end
end


class Game_Temp
 
  attr_accessor :current_battle_scene
 
  def battle_scene_subject
    scene = current_battle_scene
    return scene ? scene.instance_variable_get(:@subject) : last_battle_subject
  end
end

class Scene_Battle
 
  alias_method(:main_during_registerCurrentBattleScene, :main)
  def main
    temp = $game_temp
    temp.current_battle_scene = self
    main_during_registerCurrentBattleScene
    temp.current_battle_scene = nil
  end
end


class << DataManager
 
  alias_method(:make_save_contents_before_BattleState, :make_save_contents)
  def make_save_contents
    contents = make_save_contents_before_BattleState
    if $game_party.in_battle
      contents[:battle_state] = BattleManager.memorize_state
      contents[:troop_event_flags] = $game_troop.memorize_event_flags
      contents[:battle_subject] = $game_temp.battle_scene_subject
    end
    contents
  end
 
  alias_method(:extract_save_contents_before_BattleState, :extract_save_contents)
  def extract_save_contents(contents)
    extract_save_contents_before_BattleState(contents)
    if $game_party.in_battle
      BattleManager.restore_state(contents[:battle_state])
      $game_troop.restore_event_flags(contents[:troop_event_flags])
      $game_temp.last_battle_subject = contents[:battle_subject]
    end
  end
end


module BattleManager
 
  def self.memorize_state
    variables = instance_variables - [:@method_wait_for_message]
    return Hash[variables.map { |i| [i, instance_variable_get(i)] }]
  end
 
  def self.restore_state(contents)
    contents.each_pair { |key, value| instance_variable_set(key, value) }
  end
end


class Game_Troop
 
  def memorize_event_flags
    flags = Hash[@event_flags.map { |key, val| [troop.pages.index(key), val] }]
    raise "Page reassociation error!"  if flags.has_key?(nil)
    return flags
  end
 
  def restore_event_flags(contents)
    @event_flags.clear
    contents.each_pair { |id, value| @event_flags[troop.pages[id]] = value }
  end
end


class Game_Interpreter
 
  # ---
  # Modify the marshal data to only skip commands if the interpreter was started
  # ---
 
  alias_method(:clear_after_ResetStartedFlag, :clear)
  def clear
    @interpreter_started = false
    clear_after_ResetStartedFlag
  end
 
  # Note: If the game can be saved (again) while the interpreter is waiting
  # for the message window, additional safeguards will be needed.
  alias_method(:run_after_SetStartedFlag, :run)
  def run
    @interpreter_started = true
    run_after_SetStartedFlag
  end
 
  alias_method(:marshal_dump_before_StartedFlag, :marshal_dump)
  def marshal_dump
    result = marshal_dump_before_StartedFlag
    result.push(@interpreter_started ? nil : @index)
    return result
  end
 
  alias_method(:marshal_load_during_StartedFlag, :marshal_load)
  def marshal_load(obj)
    raise "Incompatible Save Data"  if obj.length < 7  # Basic Consistency Check
    idle_index = obj.pop
    marshal_load_during_StartedFlag(obj)
    @index = idle_index  if idle_index
    @interpreter_started = false
  end
 
  # ---
 
  # Marshal-compatible event callback for in-battle saves
  class Event_Proc
 
    def initialize(branch, indent)
      @branch = branch
      @indent = indent
    end
 
    def call(value)
      @branch[@indent] = value
    end
  end
 
  #--------------------------------------------------------------------------
  # * Battle Processing
  #--------------------------------------------------------------------------
  def command_301
    return if $game_party.in_battle
    if @params[0] == 0                      # Direct designation
      troop_id = @params[1]
    elsif @params[0] == 1                   # Designation with variables
      troop_id = $game_variables[@params[1]]
    else                                    # Map-designated troop
      troop_id = $game_player.make_encounter_troop_id
    end
    if $data_troops[troop_id]
      BattleManager.setup(troop_id, @params[2], @params[3])
      # --- Modified:
      BattleManager.event_proc = Event_Proc.new(@branch, @indent)
      #BattleManager.event_proc = Proc.new {|n| @branch[@indent] = n }
      # ---
      $game_player.make_encounter_count
      SceneManager.call(Scene_Battle)
    end
    Fiber.yield
  end
end
Late Edit: This code does now include the saved @subject variable. This is still more like a blueprint rather than an universally applicable script.
Late Edit3: Added code to hopefully not screw up map events if the game is saved and loaded during battle multiple times.
Sorry for the late reply and thank you!
You mentioned you are good on the saving mid-battle part, but since it is already done in case you have use for it as a reference: (based on the default battle system and in addition to the script part above)
I have not yet tested the save/load approach and probably won't for some time, but the script you provided will be very useful, do you know its source or did you write it?


Regarding sub-scene approach, I tested it with my tbs scene with event calls for the shop menu and the name menu, here is what I changed:
Ruby:
#goods and @params are in the context of command_302 from Game_Interpreter
SceneManager.snapshot_for_background #to freeze the previous scene graphic and blur them for background
SceneManager.call(Scene_Shop)
SceneManager.scene.prepare(goods, @params[4])
SceneManager.scene.main #will loop until we leave Scene_Shop
SceneManager.scene.perform_transition #updates the graphics back
Without the last command your graphics won't have been updated when leaving the shop x)
Note that you may need more things to change before calling the scene and when returning to it like hiding menus, Yanfly's Equip Menu for instance does a bit more preparations.
Hey,

Sorry for the, uh, late reply. The answer probably still fits better here than in the thread for your actual TBS script.

do you know its source or did you write it?
The code is written by me, but I also made a mistake and overlooked that the @subject variable from the battle scene would also need to be saved.
Although this is probably not important if you are making your own battle scene anyways.

Regarding sub-scene approach, I tested it with my tbs scene with event calls for the shop menu and the name menu, here is what I changed
I think the subscene approach is a convenient workaround for the battle scene, but it is not ideal. The graphics from your battle scene will still be rendered in the background.

If you are writing your own scene from scratch anyways, I think it might be worth designing it in a way so you can freely leave- and re-enter it without losing crucial data (most scenes will hold window- and sprite objects, and any game data will be kept in $game_... objects where it is not lost in case of a scene switch. In case of Scene_Map for instance you may be losing/canceling any ongoing animation effects, but most other data is stored elsewhere.)

Especially if you are planning to one day allow saving mid-fight, you will likely have to be able to recreate a new scene after loading.


(That said, I have not really looked into your TBS and don't know what you have written yet, and I cannot really tell why the event callback mix up would possibly happen. It did not happen whenever I tested it in the default battle system.)

Either way, best of luck with your TBS project, it looks interesting. 🙂
I think the subscene approach is a convenient workaround for the battle scene, but it is not ideal. The graphics from your battle scene will still be rendered in the background.
They will be rendered but will not be updated (since the update part is performed by the current scene only), so I think it is fine, especially if the background is blurred with snapshot_for_background. Though yes in general I should avoid this subscene approach as it will not work as intended if the subscene calls other scenes.

Especially if you are planning to one day allow saving mid-fight, you will likely have to be able to recreate a new scene after loading.
Actually I did implement it in v0.8 ahah (it is part of an addon script with all modifications to allow saving and loading mid tbs battle).

My approach was to save the battle data that was proper to the scene inside $game_temp (attribute is an hash table) such that saving would store the data from $game_temp (not $game_temp itself).
That way, when I load Scene_TBS_Battle (which is the case when loading a save with battle data), if the battle data is not empty, then it will get it and skip some initialization. Overall it seems to work fine, both for the placement phase and even mid battle (I assume though that the save was made during player's turn).

If I load a savefile mid battle, I have an attribute set to true such that terminating Scene_TBS_Battle will skip critical parts (mostly the loading of the original map as it was already changed by the save file loaded).

So I guess I have almost everything to deal with subscene approach in a cleaner way, I would just need to keep $game_temp non empty as long as Scene_TBS_Battle is not the current one (unless the battle ended properly). I do however have some problem if the other scenes are supposed to play with $game_map as it is used by my scene (it can be different from the map calling the battle) and should not be modified.

(That said, I have not really looked into your TBS and don't know what you have written yet, and I cannot really tell why the event callback mix up would possibly happen. It did not happen whenever I tested it in the default battle system.)
It might be an issue on my side, I encountered it once and I am unsure if it wasn't just a mistake from my part. I have trouble understanding how interpreter is handled, even more with save files. I haven't yet reproduced it so maybe I just read my event message poorly.

EDIT: I confirm that I have an issue but it is not consistent, here is my battle event triggering each turn:
1748438218456.png

(Translation: gives choice to win, end the battle through event calls, lose or continue the battle each turn)

And here is my event:
1748438308504.png

(translation: start battle with a troop, if victory cries "Victoire !", is escaped says "........", if defeat says "Défaite", and regardless will say "Combat Terminé" afterwards.)

All calls will end the battle, however I observed that sometimes (I will have to test all possibilities with or without scene reloading and exit and check whether it is consistent):
- win battle -> might skip "Victoire" message but still say "Combat Terminée"
- flee or lose -> might call "Victoire" and THEN their own message (.... or défaite) before saying "Combat terminé".

EDIT2:
I managed to isolate a save where this bug is consistently occurring (the victory message then other process):
-if victory -> normal behavior
-else -> victory message then normal process (escape/lose messages)
I checked and regardless: BattleManager.battle_end(result) is called once with the right parameter, so the victory branch appears for some other condition, it might be that I haven't initialize the value and it's the default behavior? But then why is it called once in the victory case...

EDIT3:
New test made, so actually my saves were bugged all along, though I don't know how. So here is my event in rough code:
Code:
cmd battle (301)
cmd victory? (601)
    cmd msg1
cmd escape? (602)
    cmd msg2
cmd defeat? (603)
    cmd msg3
cmd msg4
One of my save (the one calling the victory branch) has already successfully passed the cmd victory? and is at cmd msg1.
Meaning that when the battle has ended, the end value (0,1,2) will not be tested with command victory, which explains why it is skipped and why the escape and defeat branch are still happening.

For the other save, the command victory has already been skipped and the test is performed on the later two because they were not performed.
One of my save (the one calling the victory branch) has already successfully passed the cmd victory? and is at cmd msg1.
Ah, I have not used the VXAce in a while and did not think of this. It has a unique way to handle the event interpreter, which might be the culprit:

The interpreter utilizes a Fiber for progress which cannot be saved in a save file. Instead Game_Interpreter has a custom "marshal_dump" method, which skips the rest of the currently active command when the interpreter is loaded again.
However, if you save and load the game multiple times before the interpreter is allowed to update, then this would start skipping additional commands instead.

So... if that ends up being the issue this might be a bit clunky but workable solution:
Spoiler
Ruby:
class Game_Interpreter
 
  # ---
  # Modify the marshal data to only skip commands if the interpreter was started
  # ---
 
  alias_method(:clear_after_ResetStartedFlag, :clear)
  def clear
    @interpreter_started = false
    clear_after_ResetStartedFlag
  end
 
  # Note: If the game can be saved (again) while the interpreter is waiting
  # for the message window, additional safeguards will be needed.
  alias_method(:run_after_SetStartedFlag, :run)
  def run
    @interpreter_started = true
    run_after_SetStartedFlag
  end
 
  alias_method(:marshal_dump_before_StartedFlag, :marshal_dump)
  def marshal_dump
    result = marshal_dump_before_StartedFlag
    result.push(@interpreter_started ? nil : @index)
    return result
  end
 
  alias_method(:marshal_load_during_StartedFlag, :marshal_load)
  def marshal_load(obj)
    raise "Incompatible Save Data"  if obj.length < 7  # Basic Consistency Check
    idle_index = obj.pop
    marshal_load_during_StartedFlag(obj)
    @index = idle_index  if idle_index
    @interpreter_started = false
  end
end
Late Edit: Mostly-cosmetic code changes.
However, if you save and load the game multiple times before the interpreter is allowed to update, then this would start skipping additional commands instead.
This is exactly what happened, I did not realize it until your post so I tested it by saving and loading the same file in battle multiple times and observed that multiple commands of the event were skipped!

By adding your patch, the bug seems to have vanished, thank you!

The interpreter utilizes a Fiber for progress, which cannot be saved in a save file. Instead Game_Interpreter has a custom "marshal_dump" method, which skips the rest of the currently active command when the interpreter is loaded again.

I have a very shallow understanding of the Fiber notion, is it some sort of execution environment that we can leave and go back to to simulate parallel process?

So adding the +1 to the index when marshal dumping is some security measure to ensure the current command (usually the save menu command) is not executed once more uh...

Anyway, thank you very much! This issue was very troubling for me!
I have a very shallow understanding of the Fiber notion, is it some sort of execution environment that we can leave and go back to to simulate parallel process?
Pretty much what you said.
A Fiber can execute a block of code in multiple steps. Calling fibervariable.resume executes the code block until it is either finished or calls Fiber.yield. In the latter case, calling fibervariable.resume again will continue where the previous call has left off.

In Game_Interpreter, @fiber.resume is called with every update, so Fiber.yield in event commands (or any place the run method reaches) acts as a one frame wait.
Spoiler
This allows for interruptions in script commands
Ruby:
texts =
  ["Are you sure?",
   "Are you really, really sure?",
   "Last warning!?",
   "Fine then..."]
texts.each { |text|
  $game_message.add(text)
  setup_choices([["Yes!", "No..."], 2])
  wait_for_message
  break  if @branch[@indent] == 1
}
$game_message.add(@branch[@indent] == 1 ? "Okay... :(" : "Okay! :)")
wait_for_message
Edit2: fixed

As you said, most of the time the fiber will be paused at the very end of an event command, so the index is increased so a new fiber starting at the beginning of the run method would not repeat it.

Edit: Thinking about it I made a few mostly-cosmetic changes to the script:
- For the sake of fixing the bug, setting the flag at the beginning of the run method instead of every execute_command should be enough here (mostly cosmetic and not a noticeable performance gain).
- Setting the index instead of subtracting might make it less likely for the patch to conflict with other scripts that may attempt a similar fix.

The previous version should work just fine too though.
Thank you for the explanation!

I updated my script to integrate your new version of the Interpreter fix, it seems to work fine (at least I don't encounter the eating commands bug anymore).

I once again want to thank you for you help as it was critical for the save system of my script, I don't know if I could have reached the interpreter solution or the first version of the script you provided, especially in such a short time. So, thank you.



Unrelated but I noticed a random crash after leaving one of my battle and calling the save menu by events. Then I saw that my graphical object reference log was very long (Mithran's script is very useful), I guess it does not like at all the subscene approach from my earlier posts which is definitely understandable.
My hand is now forced to write the proper way of calling scenes mid TBS ahah

Edit: Well, that was shorter than I thought, now simply using SceneManager.call is enough ~

Original thread: https://forums.rpgmakerweb.com/threads/opening-another-scene-mid-battle-and-saving-mid-battle.177182/