world_music.lua 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. --[[
  2. Music of the world map. The data (tracks, overrides and conditions) is in world_settings.lua
  3. (WorldMapSettings.music); this has the logic that picks the track and plays it.
  4. WorldMusic.update is called by the module when a map starts, when the vehicle changes, and every half
  5. second (the story can change the music while the map is on).
  6. ]]
  7. WorldMusic = WorldMusic or {current = nil}
  8. --- Calls a function of the settings that can fail without stopping the game.
  9. local function safe(func, ...)
  10. if type(func) ~= "function" then return nil end
  11. local ok, result = pcall(func, ...)
  12. if ok then return result end
  13. return nil
  14. end
  15. --- Gets the track of a map and a vehicle.
  16. -- @param map_id 0 for WM0, 1 for WM2 (underwater), 2 for WM3 (snow).
  17. -- @param vehicle walk, chocobo, buggy, tiny_bronco, highwind or submarine.
  18. -- @return The track or nil.
  19. WorldMusic.choose = function(map_id, vehicle)
  20. local music = WorldMapSettings and WorldMapSettings.music
  21. if not music then return nil end
  22. if map_id == 1 then return music.underwater end
  23. if map_id == 2 then return music.snow end
  24. -- The Chocobo always has priority.
  25. if vehicle == "chocobo" and music.chocobo then return music.chocobo end
  26. -- Overrides of the story: the vehicles don't change them.
  27. for _, override in ipairs(music.overrides or {}) do
  28. if safe(override.when) then return override.track end
  29. end
  30. -- The vehicles with their own track.
  31. if vehicle == "highwind" and music.highwind and not safe(music.cloud_away) then
  32. return music.highwind
  33. end
  34. if vehicle ~= "walk" and vehicle ~= "highwind" and vehicle ~= "chocobo" and music[vehicle] then
  35. return music[vehicle]
  36. end
  37. -- The default one of the story.
  38. local from_story = music.danger_from_story
  39. if music.danger and from_story and ReadWord(0) >= from_story then return music.danger end
  40. return music.default
  41. end
  42. --- Plays the track of the moment if it is not the one that is playing.
  43. -- @param map_id Map of the module.
  44. -- @param vehicle Name of the vehicle.
  45. WorldMusic.update = function(map_id, vehicle)
  46. local track = WorldMusic.choose(map_id, vehicle)
  47. if track == nil or track == WorldMusic.current then return end
  48. WorldMusic.current = track
  49. audio_manager:play_music(tostring(track))
  50. end
  51. --- Forgets the track that was playing (the next update plays it again).
  52. WorldMusic.reset = function()
  53. WorldMusic.current = nil
  54. end