(af16ecdfa) Merge branch 'dev' into human-ai

This commit is contained in:
Joonas Rikkonen
2019-05-16 05:14:00 +03:00
parent 8be0b0676e
commit bec7aadfa9
65 changed files with 1579 additions and 1449 deletions
@@ -303,7 +303,7 @@ namespace Barotrauma.Tutorials
yield return new WaitForSeconds(1.0f);
infoBox = CreateInfoFrame("Uh-oh... Something enormous just appeared on the sonar.");
infoBox = CreateInfoFrame("", "Uh-oh... Something enormous just appeared on the sonar.");
List<Structure> windows = new List<Structure>();
foreach (Structure s in Structure.WallList)
@@ -4,22 +4,12 @@ using System;
using Microsoft.Xna.Framework;
using Barotrauma.Items.Components;
using System.Linq;
using Microsoft.Xna.Framework.Input;
namespace Barotrauma.Tutorials
{
class ContextualTutorial : Tutorial
{
public static bool Selected = false;
public static bool ContentRunning = false;
public static bool Initialized = false;
private enum ContentTypes { None = 0, Video = 1, TextOnly = 2 };
private TutorialSegment activeSegment;
private List<TutorialSegment> segments;
private VideoPlayer videoPlayer;
private Steering navConsole;
private Reactor reactor;
@@ -33,83 +23,29 @@ namespace Barotrauma.Tutorials
private List<Pair<Character, float>> characterTimeOnSonar;
private float requiredTimeOnSonar = 5f;
private bool started = false;
private string playableContentPath;
private float tutorialTimer;
private bool disableTutorialOnDeficiencyFound = true;
private GUIFrame holderFrame, objectiveFrame;
private List<TutorialSegment> activeObjectives = new List<TutorialSegment>();
private string objectiveTranslated;
private float floodTutorialTimer = 0.0f;
private const float floodTutorialDelay = 2.0f;
private float medicalTutorialTimer = 0.0f;
private const float medicalTutorialDelay = 2.0f;
private Point screenResolution;
private float prevUIScale;
private class TutorialSegment
{
public string Id;
public string Objective;
public ContentTypes ContentType;
public XElement TextContent;
public XElement VideoContent;
public bool IsTriggered;
public GUIButton ReplayButton;
public GUITextBlock LinkedTitle, LinkedText;
public TutorialSegment(XElement config)
{
Id = config.GetAttributeString("id", "Missing ID");
Objective = TextManager.Get(config.GetAttributeString("objective", string.Empty), true);
Enum.TryParse(config.GetAttributeString("contenttype", "None"), true, out ContentType);
IsTriggered = config.GetAttributeBool("istriggered", false);
switch (ContentType)
{
case ContentTypes.None:
break;
case ContentTypes.Video:
VideoContent = config.Element("Video");
TextContent = config.Element("Text");
break;
case ContentTypes.TextOnly:
TextContent = config.Element("Text");
break;
}
}
}
public ContextualTutorial(XElement element) : base(element)
{
playableContentPath = element.GetAttributeString("playablecontentpath", "");
segments = new List<TutorialSegment>();
foreach (var segment in element.Elements("Segment"))
{
segments.Add(new TutorialSegment(segment));
}
Name = "ContextualTutorial";
}
public override void Initialize()
{
base.Initialize();
for (int i = 0; i < segments.Count; i++)
{
segments[i].IsTriggered = false;
}
if (Initialized) return;
Initialized = true;
base.Initialize();
videoPlayer = new VideoPlayer();
characterTimeOnSonar = new List<Pair<Character, float>>();
}
@@ -167,10 +103,7 @@ namespace Barotrauma.Tutorials
base.Start();
injuredMember = null;
activeObjectives.Clear();
objectiveTranslated = TextManager.Get("Objective");
CreateObjectiveFrame();
activeSegment = null;
activeContentSegment = null;
tutorialTimer = floodTutorialTimer = medicalTutorialTimer = 0.0f;
subStartingPosition = Vector2.Zero;
characterTimeOnSonar.Clear();
@@ -183,10 +116,10 @@ namespace Barotrauma.Tutorials
#if DEBUG
if (reactor == null || navConsole == null || sonar == null)
{
infoBox = CreateInfoFrame("Submarine not compatible with the tutorial:"
infoBox = CreateInfoFrame("Error", "Submarine not compatible with the tutorial:"
+ "\nReactor - " + (reactor != null ? "OK" : "Tag 'reactor' not found")
+ "\nNavigation Console - " + (navConsole != null ? "OK" : "Tag 'command' not found")
+ "\nSonar - " + (sonar != null ? "OK" : "Not found under Navigation Console"), true);
+ "\nSonar - " + (sonar != null ? "OK" : "Not found under Navigation Console"), hasButton: true);
CoroutineManager.StartCoroutine(WaitForErrorClosed());
return;
}
@@ -222,62 +155,15 @@ namespace Barotrauma.Tutorials
}
#endif
public void Stop()
public override void Stop()
{
started = ContentRunning = Initialized = false;
videoPlayer.Remove();
videoPlayer = null;
base.Stop();
characterTimeOnSonar = null;
}
private void CreateObjectiveFrame()
{
holderFrame = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center));
objectiveFrame = new GUIFrame(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ObjectiveAnchor, holderFrame.RectTransform), style: null);
for (int i = 0; i < activeObjectives.Count; i++)
{
CreateObjectiveGUI(activeObjectives[i], i);
}
screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight);
prevUIScale = GUI.Scale;
}
public override void AddToGUIUpdateList()
{
if (videoPlayer != null)
{
videoPlayer.AddToGUIUpdateList(order: 100);
}
if (GUI.DisableHUD) return;
if (GameMain.GraphicsWidth != screenResolution.X || GameMain.GraphicsHeight != screenResolution.Y || prevUIScale != GUI.Scale)
{
CreateObjectiveFrame();
}
if (objectiveFrame != null && activeObjectives.Count > 0)
{
objectiveFrame.AddToGUIUpdateList(order: -1);
}
base.AddToGUIUpdateList();
}
public override void Update(float deltaTime)
{
if (videoPlayer != null)
{
videoPlayer.Update();
}
if (infoBox != null)
{
if (PlayerInput.KeyHit(Keys.Enter) || PlayerInput.KeyHit(Keys.Escape))
{
CloseInfoFrame(null, null);
}
}
base.Update(deltaTime);
if (!started || ContentRunning) return;
@@ -285,93 +171,12 @@ namespace Barotrauma.Tutorials
for (int i = 0; i < segments.Count; i++)
{
if (segments[i].IsTriggered || activeObjectives.Contains(segments[i])) continue;
if (segments[i].IsTriggered || HasObjective(segments[i])) continue;
if (CheckContextualTutorials(i, deltaTime)) // Found a relevant tutorial, halt finding new ones
{
break;
}
}
for (int i = 0; i < activeObjectives.Count; i++)
{
CheckActiveObjectives(activeObjectives[i], deltaTime);
}
}
private void ClosePreTextAndTriggerVideoCallback()
{
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(activeSegment.VideoContent), new VideoPlayer.TextSettings(activeSegment.VideoContent), activeSegment.Id, true, activeSegment.Objective, CurrentSegmentStopCallback);
}
private void CurrentSegmentStopCallback()
{
if (!string.IsNullOrEmpty(activeSegment.Objective))
{
AddNewObjective(activeSegment);
}
activeSegment = null;
ContentRunning = false;
}
private void AddNewObjective(TutorialSegment segment)
{
activeObjectives.Add(segment);
CreateObjectiveGUI(segment, activeObjectives.Count - 1);
}
private void CreateObjectiveGUI(TutorialSegment segment, int index)
{
Point replayButtonSize = new Point((int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).X * GUI.Scale), (int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).Y * 1.45f * GUI.Scale));
segment.ReplayButton = new GUIButton(new RectTransform(replayButtonSize, objectiveFrame.RectTransform, Anchor.TopRight, Pivot.TopRight) { AbsoluteOffset = new Point(0, (replayButtonSize.Y + (int)(20f * GUI.Scale)) * index) }, style: null);
segment.ReplayButton.OnClicked += (GUIButton btn, object userdata) =>
{
ReplaySegmentVideo(segment);
return true;
};
int yOffset = (int)((GUI.ObjectiveNameFont.MeasureString(objectiveTranslated).Y / 2f + 5) * GUI.Scale);
segment.LinkedTitle = new GUITextBlock(new RectTransform(new Point(replayButtonSize.X, yOffset), segment.ReplayButton.RectTransform, Anchor.Center, Pivot.BottomCenter) { AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) }, objectiveTranslated, textColor: Color.White, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight);
segment.LinkedText = new GUITextBlock(new RectTransform(new Point(replayButtonSize.X, yOffset), segment.ReplayButton.RectTransform, Anchor.Center, Pivot.TopCenter) { AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) }, segment.Objective, textColor: new Color(4, 180, 108), font: GUI.ObjectiveNameFont, textAlignment: Alignment.CenterRight);
segment.LinkedTitle.TextScale = segment.LinkedText.TextScale = GUI.Scale;
segment.LinkedTitle.Color = segment.LinkedTitle.HoverColor = segment.LinkedTitle.PressedColor = segment.LinkedTitle.SelectedColor = Color.Transparent;
segment.LinkedText.Color = segment.LinkedText.HoverColor = segment.LinkedText.PressedColor = segment.LinkedText.SelectedColor = Color.Transparent;
segment.ReplayButton.Color = segment.ReplayButton.HoverColor = segment.ReplayButton.PressedColor = segment.ReplayButton.SelectedColor = Color.Transparent;
}
private void RemoveCompletedObjective(TutorialSegment objective)
{
objective.IsTriggered = true;
int checkMarkHeight = (int)(objective.ReplayButton.Rect.Height * 1.2f);
int checkMarkWidth = (int)(checkMarkHeight * 0.93f);
Color color = new Color(4, 180, 108);
RectTransform rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), objective.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - 5, 0);
GUIImage checkmark = new GUIImage(rectTA, "CheckMark");
checkmark.Color = color;
RectTransform rectTB = new RectTransform(new Vector2(1.1f, .8f), objective.LinkedText.RectTransform, Anchor.Center, Pivot.Center);
GUIImage stroke = new GUIImage(rectTB, "Stroke");
stroke.Color = color;
CoroutineManager.StartCoroutine(WaitForObjectiveEnd(objective));
}
private IEnumerable<object> WaitForObjectiveEnd(TutorialSegment objective)
{
yield return new WaitForSeconds(2.0f);
objectiveFrame.RemoveChild(objective.ReplayButton);
activeObjectives.Remove(objective);
for (int i = 0; i < activeObjectives.Count; i++)
{
activeObjectives[i].ReplayButton.RectTransform.AbsoluteOffset = new Point(0, (activeObjectives[i].ReplayButton.Rect.Height + 20) * i);
}
}
private bool CheckContextualTutorials(int index, float deltaTime)
@@ -526,17 +331,7 @@ namespace Barotrauma.Tutorials
return true;
}
private bool HasObjective(string objectiveName)
{
for (int i = 0; i < activeObjectives.Count; i++)
{
if (activeObjectives[i].Id == objectiveName) return true;
}
return false;
}
private void CheckActiveObjectives(TutorialSegment objective, float deltaTime)
protected override void CheckActiveObjectives(TutorialSegment objective, float deltaTime)
{
switch(objective.Id)
{
@@ -704,50 +499,9 @@ namespace Barotrauma.Tutorials
return characterTimeOnSonar.Find(ct => ct.Second >= requiredTimeOnSonar && !ct.First.IsDead) != null;
}
private void TriggerTutorialSegment(int index, params object[] args)
protected override void TriggerTutorialSegment(int index, params object[] args)
{
Inventory.draggingItem = null;
ContentRunning = true;
activeSegment = segments[index];
string tutorialText = TextManager.GetFormatted(activeSegment.TextContent.GetAttributeString("tag", ""), true, args);
string objectiveText = string.Empty;
if (!string.IsNullOrEmpty(activeSegment.Objective))
{
if (args.Length == 0)
{
objectiveText = activeSegment.Objective;
}
else
{
objectiveText = string.Format(activeSegment.Objective, args);
}
activeSegment.Objective = objectiveText;
}
else
{
activeSegment.IsTriggered = true; // Complete at this stage only if no related objective
}
switch (activeSegment.ContentType)
{
case ContentTypes.None:
break;
case ContentTypes.Video:
infoBox = CreateInfoFrame(TextManager.Get(activeSegment.Id), tutorialText,
activeSegment.TextContent.GetAttributeInt("width", 300),
activeSegment.TextContent.GetAttributeInt("height", 80),
activeSegment.TextContent.GetAttributeString("anchor", "Center"), true, ClosePreTextAndTriggerVideoCallback);
break;
case ContentTypes.TextOnly:
infoBox = CreateInfoFrame(TextManager.Get(activeSegment.Id), tutorialText,
activeSegment.TextContent.GetAttributeInt("width", 300),
activeSegment.TextContent.GetAttributeInt("height", 80),
activeSegment.TextContent.GetAttributeString("anchor", "Center"), true, CurrentSegmentStopCallback);
break;
}
base.TriggerTutorialSegment(index, args);
for (int i = 0; i < segments.Count; i++)
{
@@ -757,13 +511,6 @@ namespace Barotrauma.Tutorials
CoroutineManager.StartCoroutine(WaitToStop()); // Completed
}
private void ReplaySegmentVideo(TutorialSegment segment)
{
if (ContentRunning) return;
ContentRunning = true;
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), new VideoPlayer.TextSettings(segment.VideoContent), segment.Id, true, callback: () => ContentRunning = false);
}
private IEnumerable<object> WaitToStop()
{
while (ContentRunning) yield return null;
@@ -170,7 +170,7 @@ namespace Barotrauma.Tutorials
yield return new WaitForSeconds(2.0f);
}*/
TriggerTutorialSegment(0, GameMain.Config.KeyBind(InputType.Select), GameMain.Config.KeyBind(InputType.Deselect)); // Medical supplies objective
TriggerTutorialSegment(0, GameMain.Config.KeyBind(InputType.Use), GameMain.Config.KeyBind(InputType.Deselect)); // Medical supplies objective
do
{
@@ -508,7 +508,7 @@ namespace Barotrauma.Tutorials
mechanic.AddActiveObjectiveEntity(mechanic_brokenWall_2, mechanic_repairIcon, mechanic_repairIconColor);
do { yield return null; } while (WallHasDamagedSections(mechanic_brokenWall_2));
mechanic.RemoveActiveObjectiveEntity(mechanic_brokenWall_2);
TriggerTutorialSegment(9, GameMain.Config.KeyBind(InputType.Use)); // Repairing machinery (pump)
TriggerTutorialSegment(9, GameMain.Config.KeyBind(InputType.Select)); // Repairing machinery (pump)
SetHighlight(mechanic_brokenPump.Item, true);
Repairable repairablePumpComponent = mechanic_brokenPump.Item.GetComponent<Repairable>();
do
@@ -1,44 +1,118 @@
using System;
using Barotrauma.Items.Components;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Tutorials
{
class ScenarioTutorial : Tutorial
{
private CoroutineHandle tutorialCoroutine;
private Character character;
private string spawnSub;
private SpawnType spawnPointType;
private string submarinePath;
private string startOutpostPath;
private string endOutpostPath;
private string levelSeed;
private string levelParams;
private Submarine startOutpost = null;
private Submarine endOutpost = null;
private bool currentTutorialCompleted = false;
private float fadeOutTime = 3f;
protected float waitBeforeFade = 4f;
// Colors
protected Color highlightColor = Color.OrangeRed;
protected Color uiHighlightColor = new Color(150, 50, 0);
protected Color buttonHighlightColor = new Color(255, 100, 0);
protected Color inaccessibleColor = Color.Red;
protected Color accessibleColor = Color.Green;
public ScenarioTutorial(XElement element) : base(element)
{
submarinePath = element.GetAttributeString("submarinepath", "");
startOutpostPath = element.GetAttributeString("startoutpostpath", "");
endOutpostPath = element.GetAttributeString("endoutpostpath", "");
levelSeed = element.GetAttributeString("levelseed", "tuto");
Enum.TryParse(element.GetAttributeString("spawnpointtype", "Human"), true, out spawnPointType);
levelParams = element.GetAttributeString("levelparams", "");
spawnSub = element.GetAttributeString("spawnsub", "");
Enum.TryParse(element.GetAttributeString("spawnpointtype", "Human"), true, out spawnPointType);
}
public override void Initialize()
{
base.Initialize();
currentTutorialCompleted = false;
GameMain.Instance.ShowLoading(Loading());
}
private IEnumerable<object> Loading()
{
Submarine.MainSub = Submarine.Load(submarinePath, "", true);
LevelGenerationParams generationParams = LevelGenerationParams.LevelParams.Find(p => p.Name == levelParams);
yield return CoroutineStatus.Running;
GameMain.GameSession = new GameSession(Submarine.MainSub, "",
GameModePreset.List.Find(g => g.Identifier == "tutorial"));
(GameMain.GameSession.GameMode as TutorialMode).Tutorial = this;
if (generationParams != null)
{
Biome biome = LevelGenerationParams.GetBiomes().Find(b => generationParams.AllowedBiomes.Contains(b));
if (startOutpostPath != string.Empty)
{
startOutpost = Submarine.Load(startOutpostPath, "", false);
}
if (endOutpostPath != string.Empty)
{
endOutpost = Submarine.Load(endOutpostPath, "", false);
}
Level tutorialLevel = new Level(levelSeed, 0, 0, generationParams, biome, startOutpost, endOutpost);
GameMain.GameSession.StartRound(tutorialLevel);
}
else
{
GameMain.GameSession.StartRound(levelSeed);
}
GameMain.GameSession.EventManager.Events.Clear();
GameMain.GameSession.EventManager.Enabled = false;
GameMain.GameScreen.Select();
yield return CoroutineStatus.Success;
}
public override void Start()
{
base.Start();
WayPoint wayPoint = WayPoint.GetRandom(spawnPointType, null);
Submarine.MainSub.GodMode = true;
CharacterInfo charInfo = configElement.Element("Character") == null ?
new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "engineer")) :
new CharacterInfo(configElement.Element("Character"));
WayPoint wayPoint = GetSpawnPoint(charInfo);
if (wayPoint == null)
{
DebugConsole.ThrowError("A waypoint with the spawntype \"" + spawnPointType + "\" is required for the tutorial event");
return;
}
CharacterInfo charInfo = configElement.Element("Character") == null ?
new CharacterInfo(Character.HumanConfigFile, "", JobPrefab.List.Find(jp => jp.Identifier == "engineer")) :
new CharacterInfo(configElement.Element("Character"));
character = Character.Create(charInfo, wayPoint.WorldPosition, "", false, false);
Character.Controlled = character;
character.GiveJobItems(null);
@@ -52,22 +126,82 @@ namespace Barotrauma.Tutorials
idCard.AddTag("com");
idCard.AddTag("eng");
CoroutineManager.StartCoroutine(UpdateState());
tutorialCoroutine = CoroutineManager.StartCoroutine(UpdateState());
}
private IEnumerable<object> Loading()
public override void AddToGUIUpdateList()
{
Submarine.MainSub = Submarine.Load(submarinePath, "", true);
yield return CoroutineStatus.Running;
if (!currentTutorialCompleted)
{
base.AddToGUIUpdateList();
}
}
GameMain.GameSession = new GameSession(Submarine.MainSub, "",
GameModePreset.List.Find(g => g.Identifier == "tutorial"));
(GameMain.GameSession.GameMode as TutorialMode).tutorial = this;
GameMain.GameSession.StartRound(levelSeed);
GameMain.GameSession.EventManager.Events.Clear();
GameMain.GameScreen.Select();
private WayPoint GetSpawnPoint(CharacterInfo charInfo)
{
Submarine spawnSub = null;
yield return CoroutineStatus.Success;
if (this.spawnSub != string.Empty)
{
switch (this.spawnSub)
{
case "startoutpost":
spawnSub = startOutpost;
break;
case "endoutpost":
spawnSub = endOutpost;
break;
default:
spawnSub = Submarine.MainSub;
break;
}
}
return WayPoint.GetRandom(spawnPointType, charInfo.Job, spawnSub);
}
protected bool HasOrder(Character character, string aiTag, string option = null)
{
if (character.CurrentOrder?.AITag == aiTag)
{
if (option == null)
{
return true;
}
else
{
HumanAIController humanAI = character.AIController as HumanAIController;
return humanAI.CurrentOrderOption == option;
}
}
return false;
}
protected void SetHighlight(Item item, bool state)
{
if (item.ExternalHighlight == state) return;
item.SpriteColor = (state) ? highlightColor : Color.White;
item.ExternalHighlight = state;
}
protected void SetHighlight(Structure structure, bool state)
{
structure.SpriteColor = (state) ? highlightColor : Color.White;
structure.ExternalHighlight = state;
}
protected void SetHighlight(Character character, bool state)
{
character.ExternalHighlight = state;
}
protected void SetDoorAccess(Door door, LightComponent light, bool state)
{
if (state && door != null) door.requiredItems.Clear();
if (light != null) light.LightColor = (state) ? accessibleColor : inaccessibleColor;
}
public override void Update(float deltaTime)
@@ -75,27 +209,47 @@ namespace Barotrauma.Tutorials
base.Update(deltaTime);
if (character != null)
{
if (Character.Controlled == null)
if (character.Oxygen < 1)
{
CoroutineManager.StopCoroutines("TutorialMode.UpdateState");
character.Oxygen = 1;
}
if (character.IsDead)
{
CoroutineManager.StartCoroutine(Dead());
}
else if (Character.Controlled == null)
{
if (tutorialCoroutine != null)
{
CoroutineManager.StopCoroutines(tutorialCoroutine);
}
infoBox = null;
}
else if (Character.Controlled.IsDead)
{
Character.Controlled = null;
CoroutineManager.StopCoroutines("TutorialMode.UpdateState");
infoBox = null;
CoroutineManager.StartCoroutine(Dead());
}
}
}
public override void Stop()
{
if (tutorialCoroutine != null)
{
CoroutineManager.StopCoroutines(tutorialCoroutine);
}
base.Stop();
}
private IEnumerable<object> Dead()
{
GUI.PreventPauseMenuToggle = true;
Character.Controlled = character = null;
Stop();
yield return new WaitForSeconds(3.0f);
var messageBox = new GUIMessageBox("You have died", "Do you want to try again?", new string[] { "Yes", "No" });
var messageBox = new GUIMessageBox(TextManager.Get("Tutorial.TryAgainHeader"), TextManager.Get("Tutorial.TryAgain"), new string[] { TextManager.Get("Yes"), TextManager.Get("No") });
messageBox.Buttons[0].OnClicked += Restart;
messageBox.Buttons[0].OnClicked += messageBox.Close;
@@ -106,5 +260,29 @@ namespace Barotrauma.Tutorials
yield return CoroutineStatus.Success;
}
protected IEnumerable<object> TutorialCompleted()
{
GUI.PreventPauseMenuToggle = true;
Character.Controlled.ClearInputs();
Character.Controlled = null;
yield return new WaitForSeconds(waitBeforeFade);
var endCinematic = new RoundEndCinematic(Submarine.MainSub, GameMain.GameScreen.Cam, fadeOutTime);
currentTutorialCompleted = Completed = true;
while (endCinematic.Running) yield return null;
Stop();
GameMain.MainMenuScreen.ReturnToMainMenu(null, null);
}
protected void Heal(Character character)
{
character.SetAllDamage(0.0f, 0.0f, 0.0f);
character.Oxygen = 100.0f;
character.Bloodloss = 0.0f;
character.SetStun(0.0f, true);
}
}
}
@@ -1,15 +1,23 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Items.Components;
using Barotrauma.Extensions;
namespace Barotrauma.Tutorials
{
abstract class Tutorial
{
#region Tutorial variables
public static bool Initialized = false;
public static bool ContentRunning = false;
public static List<Tutorial> Tutorials;
protected bool started = false;
protected GUIComponent infoBox;
private Action infoBoxClosedCallback;
protected XElement configElement;
@@ -17,6 +25,54 @@ namespace Barotrauma.Tutorials
private enum TutorialType { None, Scenario, Contextual };
private TutorialType tutorialType = TutorialType.None;
protected VideoPlayer videoPlayer;
protected enum TutorialContentTypes { None = 0, Video = 1, ManualVideo = 2, TextOnly = 3 };
protected string playableContentPath;
protected Point screenResolution;
protected float prevUIScale;
private GUIFrame holderFrame, objectiveFrame;
private List<TutorialSegment> activeObjectives = new List<TutorialSegment>();
private string objectiveTranslated;
protected TutorialSegment activeContentSegment;
protected List<TutorialSegment> segments;
protected class TutorialSegment
{
public string Id;
public string Objective;
public TutorialContentTypes ContentType;
public XElement TextContent;
public XElement VideoContent;
public bool IsTriggered;
public GUIButton ReplayButton;
public GUITextBlock LinkedTitle, LinkedText;
public object[] Args;
public TutorialSegment(XElement config)
{
Id = config.GetAttributeString("id", "Missing ID");
Objective = TextManager.Get(config.GetAttributeString("objective", string.Empty), true);
Enum.TryParse(config.GetAttributeString("contenttype", "None"), true, out ContentType);
IsTriggered = config.GetAttributeBool("istriggered", false);
switch (ContentType)
{
case TutorialContentTypes.None:
break;
case TutorialContentTypes.Video:
case TutorialContentTypes.ManualVideo:
VideoContent = config.Element("Video");
TextContent = config.Element("Text");
break;
case TutorialContentTypes.TextOnly:
TextContent = config.Element("Text");
break;
}
}
}
public string Name
{
get;
@@ -34,7 +90,9 @@ namespace Barotrauma.Tutorials
GameMain.Config.SaveNewPlayerConfig();
}
}
#endregion
#region Tutorial Controls
public static void Init()
{
Tutorials = new List<Tutorial>();
@@ -107,26 +165,85 @@ namespace Barotrauma.Tutorials
Name = element.GetAttributeString("name", "Unnamed");
completed = GameMain.Config.CompletedTutorialNames.Contains(Name);
Enum.TryParse(element.GetAttributeString("tutorialtype", "Scenario"), true, out tutorialType);
playableContentPath = element.GetAttributeString("playablecontentpath", "");
segments = new List<TutorialSegment>();
foreach (var segment in element.Elements("Segment"))
{
segments.Add(new TutorialSegment(segment));
}
}
public virtual void Initialize()
{
if (Initialized) return;
Initialized = true;
videoPlayer = new VideoPlayer();
}
public virtual void Start()
{
activeObjectives.Clear();
objectiveTranslated = TextManager.Get("Tutorial.Objective");
CreateObjectiveFrame();
// Setup doors: Clear all requirements, unless the door is setup as locked.
foreach (var item in Item.ItemList)
{
var door = item.GetComponent<Door>();
if (door != null)
{
if (door.requiredItems.Values.None(ris => ris.None(ri => ri.Identifiers.None(i => i == "locked"))))
{
door.requiredItems.Clear();
}
}
}
}
public virtual void AddToGUIUpdateList()
{
if (GameMain.GraphicsWidth != screenResolution.X || GameMain.GraphicsHeight != screenResolution.Y || prevUIScale != GUI.Scale)
{
CreateObjectiveFrame();
}
if (objectiveFrame != null && activeObjectives.Count > 0)
{
objectiveFrame.AddToGUIUpdateList(order: -1);
}
if (infoBox != null) infoBox.AddToGUIUpdateList(order: 100);
if (videoPlayer != null) videoPlayer.AddToGUIUpdateList(order: 100);
}
public virtual void Update(float deltaTime)
{
if (videoPlayer != null)
{
videoPlayer.Update();
}
if (activeObjectives != null)
{
for (int i = 0; i < activeObjectives.Count; i++)
{
CheckActiveObjectives(activeObjectives[i], deltaTime);
}
}
}
public void CloseActiveContentGUI()
{
if (videoPlayer.IsPlaying)
{
videoPlayer.Stop();
}
else if (infoBox != null)
{
CloseInfoFrame(null, null);
}
}
public virtual IEnumerable<object> UpdateState()
@@ -134,6 +251,233 @@ namespace Barotrauma.Tutorials
yield return CoroutineStatus.Success;
}
protected bool Restart(GUIButton button, object obj)
{
GUI.PreventPauseMenuToggle = false;
TutorialMode.StartTutorial(this);
return true;
}
protected virtual void TriggerTutorialSegment(int index, params object[] args)
{
Inventory.draggingItem = null;
ContentRunning = true;
activeContentSegment = segments[index];
segments[index].Args = args;
string tutorialText = TextManager.GetFormatted(activeContentSegment.TextContent.GetAttributeString("tag", ""), true, args);
tutorialText = TextManager.ParseInputTypes(tutorialText);
string objectiveText = string.Empty;
if (!string.IsNullOrEmpty(activeContentSegment.Objective))
{
if (args.Length == 0)
{
objectiveText = activeContentSegment.Objective;
}
else
{
objectiveText = string.Format(activeContentSegment.Objective, args);
}
objectiveText = TextManager.ParseInputTypes(objectiveText);
activeContentSegment.Objective = objectiveText;
}
else
{
activeContentSegment.IsTriggered = true; // Complete at this stage only if no related objective
}
switch (activeContentSegment.ContentType)
{
case TutorialContentTypes.None:
break;
case TutorialContentTypes.Video:
infoBox = CreateInfoFrame(TextManager.Get(activeContentSegment.Id), tutorialText,
activeContentSegment.TextContent.GetAttributeInt("width", 300),
activeContentSegment.TextContent.GetAttributeInt("height", 80),
activeContentSegment.TextContent.GetAttributeString("anchor", "Center"), true, () => LoadVideo(activeContentSegment));
break;
case TutorialContentTypes.ManualVideo:
infoBox = CreateInfoFrame(TextManager.Get(activeContentSegment.Id), tutorialText,
activeContentSegment.TextContent.GetAttributeInt("width", 300),
activeContentSegment.TextContent.GetAttributeInt("height", 80),
activeContentSegment.TextContent.GetAttributeString("anchor", "Center"), true, StopCurrentContentSegment, () => LoadVideo(activeContentSegment, false));
break;
case TutorialContentTypes.TextOnly:
infoBox = CreateInfoFrame(TextManager.Get(activeContentSegment.Id), tutorialText,
activeContentSegment.TextContent.GetAttributeInt("width", 300),
activeContentSegment.TextContent.GetAttributeInt("height", 80),
activeContentSegment.TextContent.GetAttributeString("anchor", "Center"), true, StopCurrentContentSegment);
break;
}
}
public virtual void Stop()
{
started = ContentRunning = Initialized = false;
infoBox = null;
if (videoPlayer != null)
{
videoPlayer.Remove();
videoPlayer = null;
}
}
#endregion
#region Objectives
private void CreateObjectiveFrame()
{
holderFrame = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center));
objectiveFrame = new GUIFrame(HUDLayoutSettings.ToRectTransform(HUDLayoutSettings.ObjectiveAnchor, holderFrame.RectTransform), style: null);
for (int i = 0; i < activeObjectives.Count; i++)
{
CreateObjectiveGUI(activeObjectives[i], i, activeObjectives[i].ContentType);
}
screenResolution = new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight);
prevUIScale = GUI.Scale;
}
protected void StopCurrentContentSegment()
{
if (!string.IsNullOrEmpty(activeContentSegment.Objective))
{
AddNewObjective(activeContentSegment, activeContentSegment.ContentType);
}
activeContentSegment = null;
ContentRunning = false;
}
protected virtual void CheckActiveObjectives(TutorialSegment objective, float deltaTime)
{
}
protected bool HasObjective(TutorialSegment segment)
{
return activeObjectives.Contains(segment);
}
protected void AddNewObjective(TutorialSegment segment, TutorialContentTypes type)
{
activeObjectives.Add(segment);
CreateObjectiveGUI(segment, activeObjectives.Count - 1, type);
}
private void CreateObjectiveGUI(TutorialSegment segment, int index, TutorialContentTypes type)
{
Point replayButtonSize = new Point((int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).X * GUI.Scale), (int)(GUI.ObjectiveNameFont.MeasureString(segment.Objective).Y * 1.45f * GUI.Scale));
segment.ReplayButton = new GUIButton(new RectTransform(replayButtonSize, objectiveFrame.RectTransform, Anchor.TopRight, Pivot.TopRight) { AbsoluteOffset = new Point(0, (replayButtonSize.Y + (int)(20f * GUI.Scale)) * index) }, style: null);
segment.ReplayButton.OnClicked += (GUIButton btn, object userdata) =>
{
if (type == TutorialContentTypes.Video)
{
ReplaySegmentVideo(segment);
}
else
{
ShowSegmentText(segment);
}
return true;
};
string objectiveText = TextManager.ParseInputTypes(objectiveTranslated);
int yOffset = (int)((GUI.ObjectiveNameFont.MeasureString(objectiveText).Y / 2f + 5) * GUI.Scale);
segment.LinkedTitle = new GUITextBlock(new RectTransform(new Point((int)GUI.ObjectiveNameFont.MeasureString(objectiveText).X, yOffset), segment.ReplayButton.RectTransform, Anchor.CenterRight, Pivot.BottomRight) { AbsoluteOffset = new Point((int)(-10 * GUI.Scale), 0) },
objectiveText, textColor: Color.White, font: GUI.ObjectiveTitleFont, textAlignment: Alignment.CenterRight);
segment.LinkedText = new GUITextBlock(new RectTransform(new Point(replayButtonSize.X, yOffset), segment.ReplayButton.RectTransform, Anchor.Center, Pivot.TopCenter) { AbsoluteOffset = new Point((int)(10 * GUI.Scale), 0) },
TextManager.ParseInputTypes(segment.Objective), textColor: new Color(4, 180, 108), font: GUI.ObjectiveNameFont, textAlignment: Alignment.CenterRight);
segment.LinkedTitle.TextScale = segment.LinkedText.TextScale = GUI.Scale;
segment.LinkedTitle.Color = segment.LinkedTitle.HoverColor = segment.LinkedTitle.PressedColor = segment.LinkedTitle.SelectedColor = Color.Transparent;
segment.LinkedText.Color = segment.LinkedText.HoverColor = segment.LinkedText.PressedColor = segment.LinkedText.SelectedColor = Color.Transparent;
segment.ReplayButton.Color = segment.ReplayButton.HoverColor = segment.ReplayButton.PressedColor = segment.ReplayButton.SelectedColor = Color.Transparent;
}
private void ReplaySegmentVideo(TutorialSegment segment)
{
if (ContentRunning) return;
ContentRunning = true;
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), new VideoPlayer.TextSettings(segment.VideoContent), segment.Id, true, callback: () => ContentRunning = false);
}
private void ShowSegmentText(TutorialSegment segment)
{
if (ContentRunning) return;
Inventory.draggingItem = null;
ContentRunning = true;
string tutorialText = TextManager.GetFormatted(segment.TextContent.GetAttributeString("tag", ""), true, segment.Args);
Action videoAction = null;
if (segment.ContentType != TutorialContentTypes.TextOnly)
{
videoAction = () => LoadVideo(segment, false);
}
infoBox = CreateInfoFrame(TextManager.Get(segment.Id), tutorialText,
segment.TextContent.GetAttributeInt("width", 300),
segment.TextContent.GetAttributeInt("height", 80),
segment.TextContent.GetAttributeString("anchor", "Center"), true, () => ContentRunning = false, videoAction);
}
protected void RemoveCompletedObjective(TutorialSegment segment)
{
if (!HasObjective(segment)) return;
segment.IsTriggered = true;
segment.ReplayButton.OnClicked = null;
int checkMarkHeight = (int)(segment.ReplayButton.Rect.Height * 1.2f);
int checkMarkWidth = (int)(checkMarkHeight * 0.93f);
Color color = new Color(4, 180, 108);
int objectiveTextWidth = segment.LinkedText.Rect.Width;
int objectiveTitleWidth = segment.LinkedTitle.Rect.Width;
RectTransform rectTA;
if (objectiveTextWidth > objectiveTitleWidth)
{
rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - 5, 0);
}
else
{
rectTA = new RectTransform(new Point(checkMarkWidth, checkMarkHeight), segment.ReplayButton.RectTransform, Anchor.BottomLeft, Pivot.BottomLeft);
rectTA.AbsoluteOffset = new Point(-rectTA.Rect.Width - 5 - (objectiveTitleWidth), 0);
}
GUIImage checkmark = new GUIImage(rectTA, "CheckMark");
checkmark.Color = checkmark.SelectedColor = checkmark.HoverColor = checkmark.PressedColor = color;
RectTransform rectTB = new RectTransform(new Vector2(1.1f, .8f), segment.LinkedText.RectTransform, Anchor.Center, Pivot.Center);
GUIImage stroke = new GUIImage(rectTB, "Stroke");
stroke.Color = stroke.SelectedColor = stroke.HoverColor = stroke.PressedColor = color;
CoroutineManager.StartCoroutine(WaitForObjectiveEnd(segment));
}
private IEnumerable<object> WaitForObjectiveEnd(TutorialSegment objective)
{
yield return new WaitForSeconds(2.0f);
objectiveFrame.RemoveChild(objective.ReplayButton);
activeObjectives.Remove(objective);
for (int i = 0; i < activeObjectives.Count; i++)
{
activeObjectives[i].ReplayButton.RectTransform.AbsoluteOffset = new Point(0, (activeObjectives[i].ReplayButton.Rect.Height + 20) * i);
}
}
#endregion
#region InfoFrame
protected bool CloseInfoFrame(GUIButton button, object userData)
{
infoBox = null;
@@ -141,73 +485,71 @@ namespace Barotrauma.Tutorials
return true;
}
protected GUIComponent CreateInfoFrame(string text, bool hasButton = false, Action callback = null)
protected GUIComponent CreateInfoFrame(string title, string text, int width = 300, int height = 80, string anchorStr = "", bool hasButton = false, Action callback = null, Action showVideo = null)
{
int width = 300;
int height = hasButton ? 110 : 80;
if (hasButton) height += 60;
string wrappedText = ToolBox.WrapText(text, width, GUI.Font);
height += wrappedText.Split('\n').Length * 25;
var infoBlock = new GUIFrame(new RectTransform(new Point(width, height), GUI.Canvas, Anchor.TopRight) { AbsoluteOffset = new Point(20) });
infoBlock.Flash(Color.Green);
var textBlock = new GUITextBlock(new RectTransform(new Vector2(0.9f, 0.7f), infoBlock.RectTransform, Anchor.Center),
text, wrap: true);
infoBoxClosedCallback = callback;
if (hasButton)
{
var okButton = new GUIButton(new RectTransform(new Point(160, 50), infoBlock.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) { AbsoluteOffset = new Point(0, -10) },
TextManager.Get("OK"))
{
OnClicked = CloseInfoFrame
};
}
GUI.PlayUISound(GUISoundType.UIMessage);
return infoBlock;
}
protected GUIComponent CreateInfoFrame(string title, string text, int width, int height, string anchorStr, bool hasButton = false, Action callback = null)
{
if (hasButton) height += 30;
string wrappedText = ToolBox.WrapText(text, width, GUI.Font);
height += wrappedText.Split('\n').Length * 25;
float textScale = GUI.Scale;
string wrappedText = ToolBox.WrapText(text, width, GUI.Font, textScale);
height += (int)(GUI.Font.MeasureString(wrappedText).Y * textScale + 50);
if (title.Length > 0)
{
height += 35;
}
Anchor anchor = Anchor.TopRight;
Enum.TryParse(anchorStr, out anchor);
var infoBlock = new GUIFrame(new RectTransform(new Point((int)(width * GUI.Scale), (int)(height * GUI.Scale)), GUI.Canvas, anchor) { AbsoluteOffset = new Point(20) });
if (anchorStr != string.Empty)
{
Enum.TryParse(anchorStr, out anchor);
}
var background = new GUIFrame(new RectTransform(new Point(GameMain.GraphicsWidth, GameMain.GraphicsHeight), GUI.Canvas, Anchor.Center), "InnerFrame", new Color(0, 0, 0, 1f));
var infoBlock = new GUIFrame(new RectTransform(new Point((int)(width * GUI.Scale), (int)(height * GUI.Scale)), background.RectTransform, anchor) { AbsoluteOffset = new Point(20) });
infoBlock.Flash(Color.Green);
var infoContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), infoBlock.RectTransform, Anchor.Center))
{
Stretch = true,
RelativeSpacing = 0.02f
};
if (title.Length > 0)
{
var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1f, .35f), infoBlock.RectTransform, Anchor.TopCenter,
Pivot.TopCenter), title, font: GUI.VideoTitleFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0));
titleBlock.TextScale = GUI.Scale;
var titleBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.3f), infoContent.RectTransform),
title, font: GUI.VideoTitleFont, textAlignment: Alignment.Center, textColor: new Color(253, 174, 0));
titleBlock.TextScale = textScale;
}
var textBlock = new GUITextBlock(new RectTransform(new Vector2(0.9f, 1f), infoBlock.RectTransform, Anchor.BottomCenter),
text, wrap: true);
textBlock.TextScale = GUI.Scale;
var textBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), infoContent.RectTransform), text, wrap: true);
infoBoxClosedCallback = callback;
if (hasButton)
{
var okButton = new GUIButton(new RectTransform(new Point(160, 50), infoBlock.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) { AbsoluteOffset = new Point(0, -10) },
TextManager.Get("OK"))
var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.3f), infoContent.RectTransform) { MinSize = new Point(0, 30), MaxSize = new Point((int) infoContent.Rect.X, 60) }, isHorizontal: true)
{
Stretch = true,
RelativeSpacing = 0.1f
};
if (showVideo != null)
{
var videoButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonContainer.RectTransform),
TextManager.Get("Video"), style: "GUIButtonLarge")
{
OnClicked = (GUIButton button, object obj) =>
{
showVideo();
return true;
}
};
}
var okButton = new GUIButton(new RectTransform(new Vector2(0.6f, 1.0f), buttonContainer.RectTransform),
TextManager.Get("OK"), style: "GUIButtonLarge")
{
OnClicked = CloseInfoFrame
};
@@ -215,13 +557,55 @@ namespace Barotrauma.Tutorials
GUI.PlayUISound(GUISoundType.UIMessage);
return infoBlock;
return background;
}
#endregion
#region Video
protected void LoadVideo(TutorialSegment segment, bool showText = true)
{
if (videoPlayer == null) videoPlayer = new VideoPlayer();
if (showText)
{
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), new VideoPlayer.TextSettings(segment.VideoContent), segment.Id, true, segment.Objective, StopCurrentContentSegment);
}
else
{
videoPlayer.LoadContent(playableContentPath, new VideoPlayer.VideoSettings(segment.VideoContent), null, segment.Id, true, segment.Objective, null);
}
}
#endregion
#region Highlights
protected void HighlightInventorySlot(Inventory inventory, string identifier, Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount)
{
if (inventory.slots == null) { return; }
for (int i = 0; i < inventory.Items.Length; i++)
{
if (inventory.Items[i] != null && inventory.Items[i].Prefab.Identifier == identifier)
{
HighlightInventorySlot(inventory, i, color, fadeInDuration, fadeOutDuration, scaleUpAmount);
}
}
}
protected bool Restart(GUIButton button, object obj)
protected void HighlightInventorySlotWithTag(Inventory inventory, string tag, Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount)
{
TutorialMode.StartTutorial(this);
return true;
if (inventory.slots == null) { return; }
for (int i = 0; i < inventory.Items.Length; i++)
{
if (inventory.Items[i] != null && inventory.Items[i].HasTag(tag))
{
HighlightInventorySlot(inventory, i, color, fadeInDuration, fadeOutDuration, scaleUpAmount);
}
}
}
protected void HighlightInventorySlot(Inventory inventory, int index, Color color, float fadeInDuration, float fadeOutDuration, float scaleUpAmount)
{
if (inventory.slots == null || index < 0 || inventory.slots[index].HighlightTimer > 0) return;
inventory.slots[index].ShowBorderHighlight(color, fadeInDuration, fadeOutDuration, scaleUpAmount);
}
#endregion
}
}
@@ -4,7 +4,7 @@ namespace Barotrauma
{
class TutorialMode : GameMode
{
public Tutorial tutorial;
public Tutorial Tutorial;
public static void StartTutorial(Tutorial tutorial)
{
@@ -19,18 +19,20 @@ namespace Barotrauma
public override void Start()
{
base.Start();
tutorial.Start();
GameMain.GameSession.CrewManager = new CrewManager(true);
Tutorial.Start();
}
public override void AddToGUIUpdateList()
{
tutorial.AddToGUIUpdateList();
base.AddToGUIUpdateList();
Tutorial.AddToGUIUpdateList();
}
public override void Update(float deltaTime)
{
base.Update(deltaTime);
tutorial.Update(deltaTime);
Tutorial.Update(deltaTime);
}
}
}