Files
CalamityModPublic/UI/DialogueDisplay/DialogueDisplayUI.cs
T

1179 lines
45 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using CalamityMod.Fonts;
using CalamityMod.UI.DialogueDisplay.DialogueEvents;
using CalamityMod.UI.DialogueDisplay.DisplayEffects;
using CalamityMod.UI.DialogueDisplay.TextEffects;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ReLogic.Graphics;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.UI;
using Terraria.UI.Chat;
using static ReLogic.Graphics.DynamicSpriteFont;
namespace CalamityMod.UI.DialogueDisplay
{
internal class DialogueDisplayUI : UIState
{
internal static readonly Dictionary<string, (DialogueDisplay ui, DialogueTextData data)> Dialogues = [];
internal static readonly Dictionary<string, Entity> DialogueEntities = [];
internal static readonly Dictionary<string, int> DialogueUptimes = [];
internal static readonly List<string> DialoguesToRemove = [];
public override void Update(GameTime gameTime)
{
foreach (string key in DialoguesToRemove)
{
RemoveChild(Dialogues[key].ui);
Dialogues.Remove(key);
DialogueEntities.Remove(key);
DialogueUptimes.Remove(key);
}
DialoguesToRemove.Clear();
foreach (var pair in DialogueEntities)
{
if (pair.Value != null && pair.Value.active)
Dialogues[pair.Key].ui.Position = pair.Value.Center;
else
Dialogues[pair.Key].ui.ClosingDialogue = true;
}
foreach (var pair in DialogueUptimes)
{
if (Dialogues[pair.Key].ui.Uptime >= pair.Value)
{
if (Dialogues[pair.Key].ui.ProgressDialogue)
Dialogues[pair.Key].ui.SwitchingPage = true;
else
Dialogues[pair.Key].ui.ClosingDialogue = true;
}
}
foreach (var pair in Dialogues)
{
float distFromSource = 0;
DialogueDisplay dialogue = pair.Value.ui;
DialogueTextData data = pair.Value.data;
if (dialogue.DisplayEffects.FadeWhenTooFar)
{
distFromSource = Vector2.Distance(Main.LocalPlayer.Center, dialogue.Position);
// If the player is too far, cancel the dialogue
if (distFromSource > dialogue.DisplayEffects.FadeBuffer + dialogue.DisplayEffects.FadeDistance)
{
DialoguesToRemove.Add(pair.Key);
continue;
}
}
if (dialogue.DialoguePage.Event != null)
{
if (dialogue.DialoguePage.Event.IsOver)
{
if (!dialogue.ProgressDialogue)
DialoguesToRemove.Add(pair.Key);
else
{
if (++data.Page >= data.PageCount)
DialoguesToRemove.Add(pair.Key);
else
{
dialogue.DialoguePage = data.Pages[data.Page];
dialogue.SwitchingPage = false;
dialogue.SwitchCounter = 0;
Activate();
}
}
return;
}
}
if (dialogue.Switching)
{
if (dialogue.SwitchCounter >= dialogue.DisplayEffects.TimeToDisappear)
{
if (dialogue.ClosingDialogue || !dialogue.ProgressDialogue)
DialoguesToRemove.Add(pair.Key);
else
{
if (++data.Page >= data.PageCount)
DialoguesToRemove.Add(pair.Key);
else
{
dialogue.DialoguePage = data.Pages[data.Page];
dialogue.SwitchingPage = false;
dialogue.SwitchCounter = 0;
Activate();
}
}
continue;
}
dialogue.SwitchCounter++;
}
}
base.Update(gameTime);
}
}
public class DialogueDisplay : UIElement
{
public static readonly Dictionary<string, SoundStyle> DialogueSounds = new()
{
{ "Amidias", SoundID.NPCHit1 },
{ "Otonilou", SoundID.NPCHit25 }
};
/// <summary>
/// How long this dialogue has existed
/// </summary>
public int DialogueTimer = 0;
/// <summary>
/// Which page are we reading?
/// </summary>
//public int currentPage;
/// <summary>
/// The position from which the text originates
/// </summary>
public Vector2 Position = Vector2.Zero;
/// <summary>
/// How many page there are
/// </summary>
//public int pageCount => DialogueData.Length;
public bool SwitchingPage = false;
public bool ProgressDialogue = true;
public bool ClosingDialogue = false;
public bool ScreenLocked;
public Vector2 TextSize { get; private set; }
public Vector2 SizeOffsetFromStart { get; private set; }
public bool Switching => SwitchingPage || ClosingDialogue;
internal int SwitchCounter = 0;
internal DialoguePage DialoguePage;
internal DisplayEffect DisplayEffects;
internal string Text = "";
private int TextTimer = 0;
internal int textIndex = 0;
internal int Uptime = 0;
internal string FontKey;
//Effects
internal Dictionary<int, (float IndexOffset, string[] hexcodes)> UniqueColors = [];
internal Dictionary<int, (float IndexOffset, string[] hexcodes)> UniqueBorderColors = [];
internal Dictionary<int, float> Pauses = [];
internal Dictionary<int, List<(TextEffect Effect, float[] args)>> TextEffects = [];
internal Dictionary<int, Vector2> UniqueScales = [];
internal List<int> LineBreakIndexes = [];
private DialogueCharacterData[] CharacterData;
private Color BaseColor = Color.White;
private Color BaseBorderColor = Color.Black;
internal bool Crawling = true;
private int storedDelay = 0;
private bool lockDelay = false;
private float WrapWidth = -1;
public DialogueDisplay(DialoguePage textData, DisplayEffect displayEffects, int startPage = 0, bool screenLocked = false, float wrapWidth = -1, string font = "MouseText")
{
DisplayEffects = displayEffects;
ScreenLocked = screenLocked;
DialoguePage = textData;
DisplayEffects = displayEffects;
FontKey = font;
WrapWidth = wrapWidth;
}
public override void OnActivate()
{
Text = "";
UniqueColors = [];
UniqueBorderColors = [];
Pauses = [];
TextEffects = [];
UniqueScales = [];
if (DialoguePage.Event != null)
return;
int fullLength = 0;
List<string> lines = [];
for (int i = 0; i < DialoguePage.Lines.Length; i++)
{
string fullLine = DialoguePage.Lines[i];
FindEffects(ref fullLine, fullLength);
if (fullLine[^1] != ' ')
fullLine += ' ';
lines.Add(fullLine);
fullLength += fullLine.Length;
}
if (WrapWidth != -1)
{
for (int i = 0; i < lines.Count; i++)
{
string line = lines[i];
int finalIndex = 0;
float width = MeasureString(line, FontAssetSystem.Fonts[FontKey]).X;
if (width > WrapWidth)
{
string yoinked = "";
do
{
finalIndex = line.LastIndexOf(' ');
if (finalIndex < line.Length - 1)
finalIndex++;
yoinked = line.Substring(finalIndex) + yoinked;
line = line.Remove(finalIndex);
} while (MeasureString(line, FontAssetSystem.Fonts[FontKey]).X > WrapWidth);
lines[i] = line;
if (i >= lines.Count - 1)
lines.Add(yoinked);
else
lines[i + 1] = yoinked + lines[i + 1];
}
}
}
fullLength = 0;
int[] lineLengths = new int[lines.Count];
LineBreakIndexes.Clear();
for (int i = 0; i < lines.Count; i++)
{
lineLengths[i] = lines[i].Length;
Text += lines[i];
fullLength += lines[i].Length;
LineBreakIndexes.Add(fullLength);
}
if (DialoguePage.BaseColor != null)
BaseColor = DialogueDisplaySystem.GetColorFromHex(DialoguePage.BaseColor);
if (DialoguePage.BaseBorderColor != null)
BaseBorderColor = DialogueDisplaySystem.GetColorFromHex(DialoguePage.BaseBorderColor);
else
{
BaseBorderColor = BaseColor * DialoguePage.BorderDarkening;
BaseBorderColor.A = 255;
}
CharacterData = new DialogueCharacterData[Text.Length];
for (int i = 0; i < Text.Length; i++)
{
int j = 0;
int summedLength = 0;
for (; j < lineLengths.Length; j++)
{
summedLength += lineLengths[j];
if (i < summedLength)
break;
}
CharacterData[i] = new(i, Text.Length, j);
}
textIndex = 0;
Crawling = true;
TextTimer = -30;
storedDelay = 0;
lockDelay = false;
DialogueTimer = 0;
Uptime = 0;
Vector2 zero = Vector2.Zero;
bool newLine = true;
float textWidth = 0f;
float highestFirstLineYScale = 1f;
for (int j = 0; j < Text.Length; j++)
{
if (Text[j] == '\n')
break;
if (UniqueScales.TryGetValue(j, out Vector2 uniqueScale) && uniqueScale.Y > highestFirstLineYScale)
highestFirstLineYScale = uniqueScale.Y;
}
SizeOffsetFromStart = new(8, 16 * highestFirstLineYScale);
for (int i = 0; i < Text.Length; i++)
{
char c = Text[i];
#region Positioning
Vector2 scale = Vector2.One;
if (UniqueScales.TryGetValue(i, out Vector2 result))
scale = result;
else if (DialoguePage.TextScale != -1)
scale *= DialoguePage.TextScale;
//Checks for Special Characters, and handles Line Breaks
switch (c)
{
case '\n':
if (zero.X > textWidth)
textWidth = zero.X;
zero.X = 0;
float highestYscale = 1f;
for (int j = i + 1; j < Text.Length; j++)
{
if (Text[j] == '\n')
break;
if (UniqueScales.TryGetValue(j, out Vector2 uniqueScale) && uniqueScale.Y > highestYscale)
highestYscale = uniqueScale.Y;
}
zero.Y += FontAssetSystem.Fonts[FontKey].LineSpacing * highestYscale;
newLine = true;
continue;
case '\r':
continue;
}
if (LineBreakIndexes.Contains(i))
{
if (zero.X > textWidth)
textWidth = zero.X;
zero.X = 0;
float highestYscale = 1f;
for (int j = i + 1; j < Text.Length; j++)
{
if (Text[j] == '\n')
break;
if (UniqueScales.TryGetValue(j, out Vector2 uniqueScale) && uniqueScale.Y > highestYscale)
highestYscale = uniqueScale.Y;
}
zero.Y += FontAssetSystem.Fonts[FontKey].LineSpacing * highestYscale;
newLine = true;
}
//Sets the character's position within the full text
SpriteCharacterData spriteData = FontAssetSystem.Fonts[FontKey].SpriteCharacters[c];
Vector3 kerning = spriteData.Kerning;
Rectangle padding = spriteData.Padding;
if (newLine)
kerning.X = Math.Max(kerning.X, 0f);
else
zero.X += FontAssetSystem.Fonts[FontKey].CharacterSpacing * scale.X;
zero.X += kerning.X * scale.X;
Vector2 position = zero + spriteData.Glyph.Size() * 0.5f;
position.X += padding.X * scale.X;
position.Y += padding.Y * scale.Y;
CharacterData[i].TextPosition = position - (Vector2.UnitY * scale.Y * FontAssetSystem.Fonts[FontKey].LineSpacing * 0.5f);
zero.X += (kerning.Y + kerning.Z) * scale.X;
newLine = false;
#endregion
}
if (zero.X > textWidth)
textWidth = zero.X;
float textHeight = zero.Y;
if (DialoguePage.AlignType != Alignment.Left)
{
for (int i = 0; i < lineLengths.Length; i++)
{
DialogueCharacterData furthestChar = CharacterData.Last(d => d.LineNumber == i && Text[d.Index] != '\n');
float xPos = furthestChar.TextPosition.X;
float dif = textWidth - xPos;
if (DialoguePage.AlignType == Alignment.Center)
foreach (var c in CharacterData.Where(c => c.LineNumber == i))
c.TextPosition.X += dif / 2f;
else
foreach (var c in CharacterData.Where(c => c.LineNumber == i))
c.TextPosition.X += dif;
}
}
TextSize = new Vector2(textWidth + 8, textHeight + 12) + SizeOffsetFromStart;
}
private void FindEffects(ref string fullLine, int fullLength)
{
Stack<int> returnPoints = [];
Stack<string> returnString = [];
for (int j = 0; j < fullLine.Length; j++)
{
char c = fullLine[j];
if (c == '[')
{
int k = j + 1;
string currentData = "[";
bool readingData = true;
for (k = j + 1; k < fullLine.Length; k++)
{
if (fullLine[k] == ']')
break;
if (fullLine[k] == '[')
{
returnPoints.Push(j);
returnString.Push(currentData);
currentData = "[";
c = fullLine[k];
j = k;
readingData = true;
}
else if (readingData)
{
currentData += fullLine[k];
if (fullLine[k] == ':')
readingData = false;
}
}
if (fullLine[k] != ']')
throw new Exception("[ was found without a ] after it.");
string effect = fullLine[j..k];
string ID = "";
string Text = "";
List<float> Params = [];
List<string> ColorParams = [];
List<string> BorderColorParams = [];
string Param = "";
bool readingText = false;
bool readingParams = false;
for (int l = 1; l < effect.Length; l++)
{
char ch = effect[l];
if (ch == '(')
{
readingParams = true;
continue;
}
else if (ch == ':')
{
readingText = true;
continue;
}
else if (ch == ']')
break;
if (readingText)
Text += ch;
else if (readingParams)
{
if (ch == ',' || ch == ')')
{
if (ID == "Colors")
{
if (float.TryParse(Param, out float result))
Params.Add(result);
else
ColorParams.Add(Param);
}
if (ID == "BorderColors")
{
if (float.TryParse(Param, out float result))
Params.Add(result);
else
BorderColorParams.Add(Param);
}
else
{
if (float.TryParse(Param, out float result))
Params.Add(result);
else
throw new Exception("Invalid Parameter found");
}
Param = "";
}
else if (ch == ' ')
continue;
else
Param += ch;
}
else
ID += ch;
}
fullLine = fullLine.Remove(j, k - j + 1);
fullLine = fullLine.Insert(j, Text);
if (ID == "Pause")
{
Pauses.Add(j - 1 + fullLength - ID.Length - Params[0].ToString().Length, Params[0]);
}
else
{
for (int i = 0; i < Text.Length; i++)
{
int index = j + i + fullLength;
if (ID == "Colors")
{
int storedLen = 0;
foreach (string s in returnString)
storedLen += s.Length;
UniqueColors.Add(index - storedLen, (Params.Count == 0 ? 0 : Params[0], [.. ColorParams]));
}
else if (ID == "BorderColors")
{
int storedLen = 0;
foreach (string s in returnString)
storedLen += s.Length;
UniqueBorderColors.Add(index - storedLen, (Params.Count == 0 ? 0 : Params[0], [.. BorderColorParams]));
}
else if (ID == "Scale")
{
int storedLen = 0;
foreach (string s in returnString)
storedLen += s.Length;
Vector2 scale;
if (Params.Count == 0)
scale = Vector2.One;
else if (Params.Count == 1)
scale = new(Params[0], Params[0]);
else
scale = new(Params[0], Params[1]);
UniqueScales.Add(index - storedLen, scale);
}
else
{
int storedLen = 0;
foreach (string s in returnString)
storedLen += s.Length;
string path = "CalamityMod.UI.DialogueDisplay.TextEffects.";
Type t = Type.GetType(path + ID) ?? throw new Exception("Invalid text effect ID found");
TextEffect te = (TextEffect)Activator.CreateInstance(t);
if (TextEffects.TryGetValue(index - storedLen, out var value))
value.Add(new(te, [.. Params]));
else
TextEffects.Add(index - storedLen, [new(te, [.. Params])]);
}
}
}
if (returnPoints.Count > 0)
{
j = returnPoints.Pop() - 1;
returnString.Pop();
}
}
}
}
private Vector2 MeasureString(string text, DynamicSpriteFont font)
{
if (text.Length == 0)
return Vector2.Zero;
Vector2 zero = Vector2.Zero;
zero.Y = font.LineSpacing;
float val = 0f;
int num = 0;
float num2 = 0f;
bool newLine = true;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
Vector2 scale = Vector2.One;
if (UniqueScales.TryGetValue(i, out Vector2 result))
scale = result;
else if (DialoguePage.TextScale != -1)
scale *= DialoguePage.TextScale;
//Checks for Special Characters, and handles Line Breaks
switch (c)
{
case '\n':
zero.X = 0;
float highestYscale = 1f;
for (int j = i + 1; j < text.Length; j++)
{
if (text[j] == '\n')
break;
if (UniqueScales.TryGetValue(j, out Vector2 uniqueScale) && uniqueScale.Y > highestYscale)
highestYscale = uniqueScale.Y;
}
zero.Y += font.LineSpacing * highestYscale;
newLine = true;
continue;
case '\r':
continue;
}
//Sets the character's position within the full text
SpriteCharacterData spriteData = font.SpriteCharacters[c];
Vector3 kerning = spriteData.Kerning;
Rectangle padding = spriteData.Padding;
if (newLine)
kerning.X = Math.Max(kerning.X, 0f);
else
zero.X += font.CharacterSpacing * scale.X;
zero.X += kerning.X * scale.X;
Vector2 position = zero + spriteData.Glyph.Size() * 0.5f;
position.X += padding.X * scale.X;
position.Y += padding.Y * scale.Y;
zero.X += (kerning.Y + kerning.Z) * scale.X;
newLine = false;
}
zero.X += Math.Max(num2, 0f);
zero.Y += num * font.LineSpacing;
zero.X = Math.Max(zero.X, val);
return zero;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (DialoguePage.Event != null)
DialoguePage.Event.UpdateEvent();
else if (!Switching)
{
if (DisplayEffects.FadeWhenTooFar)
{
float distFromSource = Vector2.Distance(Main.LocalPlayer.Center, Position);
SwitchCounter = (int)(MathHelper.Clamp((distFromSource - DisplayEffects.FadeBuffer) / DisplayEffects.FadeDistance, 0f, 1f) * DisplayEffects.TimeToDisappear);
}
int textDelay = DialoguePage.TextDelay;
if (DialoguePage.TextDelay != -1)
textDelay = DialoguePage.TextDelay;
if (DialoguePage.Event != null && !DialoguePage.Event.IsOver)
{
DialoguePage.Event.UpdateEvent();
}
if (textIndex < Text.Length)
{
if (TextTimer == 0)
{
if (!lockDelay)
{
PunctuationData data = new();
if (DialoguePage.BasePunctuationDelay != null)
data = DialoguePage.BasePunctuationDelay;
if (DialoguePage.PunctuationDelays != null)
{
if (DialoguePage.PunctuationDelays.TryGetValue(Text[textIndex].ToString(), out var value))
data = value;
else if (DialoguePage.PunctuationDelays.TryGetValue(Text[textIndex].ToString(), out value))
data = value;
}
switch (Text[textIndex])
{
case '.':
case '?':
case '!':
case ';':
case ':':
case ',':
if (data.ForceSet)
storedDelay = data.Delay;
else
storedDelay += data.Delay;
break;
case '-':
if (textIndex == Text.Length - 1 || Text[textIndex + 1] == ' ')
{
if (data.ForceSet)
storedDelay = data.Delay;
else
storedDelay += data.Delay;
}
break;
}
if (data.Locks)
lockDelay = true;
}
if (Pauses.TryGetValue(textIndex, out float pause))
storedDelay = (int)(pause * 60);
}
if (++TextTimer % ((Text[textIndex] == ' ' || Text[textIndex] == '\n') && storedDelay > 0 ? textDelay + storedDelay : textDelay) == 0 && TextTimer >= 0)
{
if (Text[textIndex] == ' ')
{
storedDelay = 0;
lockDelay = false;
}
else
{
string speaker = null;
if (DialoguePage.Speaker != null)
speaker = DialoguePage.Speaker;
if (speaker != null)
SoundEngine.PlaySound(DialogueSounds[speaker]);
}
TextTimer = 0;
++textIndex;
}
}
else
Crawling = false;
}
if (!Crawling)
Uptime++;
DialogueTimer++;
}
protected override void DrawSelf(SpriteBatch spriteBatch)
{
Vector2 textTop = DisplayEffects.TextOffsetFromStart(Position, TextSize);
Vector2 pageTop = textTop - SizeOffsetFromStart;
DisplayEffects.PreDraw(spriteBatch, pageTop, TextSize, DialogueTimer, SwitchCounter);
#region Shadow Drawing
for (int i = 0; i < textIndex; i++)
{
char c = Text[i];
if (c == '\r' || c == '\n')
continue;
if (CharacterData == null)
Activate();
Vector2 drawPos;
float rotation = 0f;
float opacity = 1f;
Vector2 scale = Vector2.One;
if (UniqueScales.TryGetValue(i, out Vector2 result))
scale = result;
Color color;
if (UniqueColors.TryGetValue(i, out var textColors))
{
Color[] colors = new Color[textColors.hexcodes.Length];
for (int j = 0; j < colors.Length; j++)
colors[j] = DialogueDisplaySystem.GetColorFromHex(textColors.hexcodes[j]);
color = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly + (i * textColors.IndexOffset), colors);
}
else
color = BaseColor;
Color borderColor;
if (UniqueBorderColors.TryGetValue(i, out var borderColors))
{
Color[] colors = new Color[borderColors.hexcodes.Length];
for (int j = 0; j < colors.Length; j++)
colors[j] = DialogueDisplaySystem.GetColorFromHex(borderColors.hexcodes[j]);
borderColor = CalamityUtils.MulticolorLerp(Main.GlobalTimeWrappedHourly + (i * borderColors.IndexOffset), colors);
}
else
borderColor = BaseBorderColor;
if (CharacterData[i].Timer < DisplayEffects.TimeToAppear)
{
drawPos = DisplayEffects.AppearPositioning(Position, textTop + CharacterData[i].TextPosition, CharacterData[i].Timer, CharacterData[i]);
opacity = DisplayEffects.AppearOpacity(opacity, CharacterData[i].Timer, CharacterData[i]);
color = DisplayEffects.AppearColoring(color, CharacterData[i].Timer, CharacterData[i]);
rotation = DisplayEffects.AppearRotation(rotation, CharacterData[i].Timer, CharacterData[i]);
scale = DisplayEffects.AppearScale(scale, CharacterData[i].Timer, CharacterData[i]);
}
else
drawPos = textTop + CharacterData[i].TextPosition;
if (SwitchCounter > 0)
{
drawPos = DisplayEffects.DisappearPositioning(drawPos, SwitchCounter, CharacterData[i]);
opacity = DisplayEffects.DisappearOpacity(opacity, SwitchCounter, CharacterData[i]);
color = DisplayEffects.DisappearColoring(color, SwitchCounter, CharacterData[i]);
rotation = DisplayEffects.DisappearRotation(rotation, SwitchCounter, CharacterData[i]);
scale = DisplayEffects.DisappearScale(scale, SwitchCounter, CharacterData[i]);
}
if (!ScreenLocked)
drawPos -= Main.screenPosition;
foreach (var l in TextEffects.Where(v => v.Key == i))
foreach ((TextEffect Effect, float[] args) in l.Value)
{
drawPos = Effect.ModifyPos(drawPos, CharacterData[i], args);
rotation = Effect.ModifyRot(rotation, CharacterData[i], args);
color = Effect.ModifyColor(color, CharacterData[i], args);
scale = Effect.ModifyScale(scale, CharacterData[i], args);
}
SpriteCharacterData spriteData = FontAssetSystem.Fonts[FontKey].SpriteCharacters[c];
Vector2 origin = spriteData.Glyph.Size() * 0.5f;
CharacterData[i].SetDrawInfo(drawPos, spriteData.Glyph, color * opacity, rotation, scale);
foreach (var l in TextEffects.Where(v => v.Key == i))
foreach ((TextEffect Effect, float[] args) in l.Value)
Effect.PreDraw(spriteBatch, spriteData.Texture, CharacterData[i]);
for (int j = 0; j < ChatManager.ShadowDirections.Length; j++)
spriteBatch.Draw(spriteData.Texture, drawPos + (ChatManager.ShadowDirections[j] * 2), spriteData.Glyph, borderColor * opacity, rotation, origin, scale, SpriteEffects.None, 0);
}
#endregion
#region Character Drawing
for (int i = 0; i < textIndex; i++)
{
char c = Text[i];
if (c == '\r' || c == '\n')
continue;
if (CharacterData == null)
Activate();
SpriteCharacterData spriteData = FontAssetSystem.Fonts[FontKey].SpriteCharacters[c];
Vector2 origin = spriteData.Glyph.Size() * 0.5f;
spriteBatch.Draw(spriteData.Texture, CharacterData[i].DrawPosition, spriteData.Glyph, CharacterData[i].DrawColor, CharacterData[i].Rotation, origin, CharacterData[i].Scale, SpriteEffects.None, 0);
foreach (var l in TextEffects.Where(v => v.Key == i))
foreach ((TextEffect Effect, float[] args) in l.Value)
Effect.PostDraw(spriteBatch, spriteData.Texture, CharacterData[i]);
CharacterData[i].Timer++;
}
#endregion
DisplayEffects.PostDraw(spriteBatch, pageTop, TextSize, DialogueTimer, SwitchCounter);
}
}
public class DialogueDisplaySystem : ModSystem
{
internal static DialogueDisplayUI State;
internal static UserInterface UI;
public override void Load()
{
if (!Main.dedServ)
{
UI = new();
State = new();
State.Activate();
}
}
public override void ModifyInterfaceLayers(List<GameInterfaceLayer> layers)
{
int preInventory = layers.FindIndex(layer => layer.Name == "Vanilla: Interface Logic 2");
if (preInventory != -1)
{
layers.Insert(preInventory, new LegacyGameInterfaceLayer("Dialogue Display", () =>
{
UI.Draw(Main.spriteBatch, new());
return true;
}, InterfaceScaleType.Game));
}
}
public override void UpdateUI(GameTime gameTime)
{
if (UI?.CurrentState != null)
UI?.Update(gameTime);
}
public static readonly JsonSerializerOptions stringEnumOptions = new()
{
Converters = { new JsonStringEnumConverter() }
};
public static DialogueTextData Deserialize(string key)
{
string activeExtension = LanguageManager.Instance.ActiveCulture.Name;
string path = "UI/DialogueDisplay/" + activeExtension + "/" + key + ".json";
// Fall back to english if not found
if (!CalamityMod.Instance.FileExists(path))
path = "UI/DialogueDisplay/en-US/" + key + ".json";
// Throw if we cant find english either
if (!CalamityMod.Instance.FileExists(path))
throw new FileNotFoundException($"Could not find the dialog file {path}.");
Stream stream = CalamityMod.Instance.GetFileStream(path);
DialogueTextData data = JsonSerializer.Deserialize<DialogueTextData>(stream, stringEnumOptions);
stream.Close();
return data;
}
public static Color GetColorFromHex(string hex)
{
System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml('#' + hex);
int r = Convert.ToInt16(color.R);
int g = Convert.ToInt16(color.G);
int b = Convert.ToInt16(color.B);
return new Color(r, g, b);
}
/// <summary>
/// Manually progresses dialogue
/// </summary>
public static void ProgressDialogue(string pearlKey)
{
if (DialogueDisplayUI.Dialogues.TryGetValue(pearlKey, out var val))
{
DialogueDisplay display = val.ui;
if (display.SwitchingPage)
return;
// If the text crawl hasnt finished, finish it instantly
if (display.textIndex < display.Text.Length - 1)
display.textIndex = display.Text.Length - 1;
// If the text crawl has finished, progress to the next page or finish if we're out of pages
else
display.SwitchingPage = true;
}
}
/// <summary>
/// Ends the dialogue if it exists in the world
/// </summary>
/// <param name="key">The name of the dialogue's localization key</param>
public static void EndDialogue(string key)
{
if (DialogueDisplayUI.Dialogues.TryGetValue(key, out var val))
val.ui.ClosingDialogue = true;
}
public static void RemoveDialogue(string key)
{
DialogueDisplayUI.DialoguesToRemove.Add(key);
}
/// <summary>
/// Creates a dialogue instance in the world
/// </summary>
/// <param name="key">The name of the dialogue's localization key</param>
/// <param name="startPosition">The position of the text in the world</param>
public static void StartDialogue(string key, Vector2 startPosition, int Uptime = -1, bool progressDialogue = true, DisplayEffect effects = null, float wrapWidth = -1)
{
UI ??= new();
State ??= new();
effects ??= new DisplayEffect();
DialogueTextData textData = Deserialize(key);
DialogueDisplay display = new(textData.Pages[0], effects, wrapWidth: wrapWidth)
{
Position = startPosition,
ProgressDialogue = progressDialogue,
};
DialogueDisplayUI.Dialogues.Add(key, (display, textData));
if (Uptime != -1)
DialogueDisplayUI.DialogueUptimes.Add(key, Uptime);
State.Append(display);
display.Activate();
if (UI.CurrentState != State)
UI?.SetState(State);
}
/// <summary>
/// Creates a dialogue instance in the world
/// </summary>
/// <param name="key">The name of the dialogue's localization key</param>
/// <param name="entity">The entity this dialogue will appear with</param>
/// <param name="Uptime">The entity this dialogue will appear with</param>
public static void StartDialogue(string key, Entity entity, int Uptime = -1, DisplayEffect effects = null, float wrapWidth = -1)
{
UI ??= new();
State ??= new();
effects ??= new DisplayEffect();
DialogueTextData textData = Deserialize(key);
DialogueDisplay display = new(textData[0], effects, wrapWidth: wrapWidth)
{
Position = entity.Center
};
DialogueDisplayUI.Dialogues.Add(key, (display, textData));
DialogueDisplayUI.DialogueEntities.Add(key, entity);
if (Uptime != -1)
DialogueDisplayUI.DialogueUptimes.Add(key, Uptime);
State.Append(display);
display.Activate();
if (UI.CurrentState != State)
UI?.SetState(State);
}
/// <summary>
/// Resets all of the dialogue's variables
/// </summary>
public static void EndAllDialogue()
{
DialogueDisplayUI.Dialogues.Clear();
State.RemoveAllChildren();
UI?.SetState(null);
}
}
public enum Alignment
{
None = -1,
Left,
Center,
Right
}
public class DialogueTextData
{
public DialoguePage[] Pages { get; init; }
public DialoguePage this[int index] { get => Pages[index]; set => Pages[index] = value; }
public int Page { get; set; }
public int PageCount => Pages.Length;
public string DefaultColor { get; init; }
public string DefaultSpeaker { get; init; }
public int DefaultScale { get; init; }
public Alignment AlignType { get; init; }
public int TextDelay { get; init; }
public PunctuationData BasePunctuationDelay { get; init; }
public int PunctuationDelayCap { get; init; }
public Dictionary<string, PunctuationData> PunctuationDelays { get; init; }
[JsonConstructor]
public DialogueTextData(DialoguePage[] pages, int page = 0, string defaultColor = null, string defaultSpeaker = null, int defaultScale = 1, Alignment alignType = Alignment.Left, int textDelay = 3, PunctuationData basePunctuationDelay = null, int punctuationDelayCap = 60, Dictionary<string, PunctuationData> punctuationDelays = null)
{
Pages = pages;
Page = page;
DefaultColor = defaultColor;
DefaultSpeaker = defaultSpeaker;
DefaultScale = defaultScale;
TextDelay = textDelay;
BasePunctuationDelay = basePunctuationDelay ?? new();
PunctuationDelayCap = punctuationDelayCap;
PunctuationDelays = punctuationDelays ?? [];
AlignType = alignType;
foreach (DialoguePage p in Pages)
{
p.BaseColor ??= defaultColor;
p.Speaker ??= defaultSpeaker;
if (p.TextScale == -1)
p.TextScale = DefaultScale;
if (p.TextDelay == -1)
p.TextDelay = TextDelay;
if (p.AlignType == Alignment.None)
p.AlignType = AlignType;
p.BasePunctuationDelay ??= BasePunctuationDelay;
if (p.PunctuationDelayCap == -1)
p.PunctuationDelayCap = PunctuationDelayCap;
p.PunctuationDelays ??= PunctuationDelays;
}
}
}
public class DialoguePage
{
public string[] Lines { get; set; }
public string BaseColor { get; set; } = null;
public string BaseBorderColor { get; set; } = null;
public float BorderDarkening { get; set; } = 0.33f;
public string Speaker { get; set; } = null;
public int TextScale { get; set; } = -1;
public Alignment AlignType { get; set; } = Alignment.Left;
public int TextDelay { get; set; } = -1;
public PunctuationData BasePunctuationDelay { get; set; } = null;
public int PunctuationDelayCap { get; set; } = -1;
public Dictionary<string, PunctuationData> PunctuationDelays { get; set; } = null;
public DialogueEvent Event { get; set; } = null;
}
public class PunctuationData
{
public int Delay { get; set; } = 10;
public bool ForceSet { get; set; } = false;
public bool Locks { get; set; } = false;
}
public class DialogueCharacterData(int index, int textLength, int lineNumber)
{
public int Timer = 0;
#region Text Info
public int Index = index;
public int TextLength = textLength;
public int LineNumber = lineNumber;
public float CompletionRatio => Index / (float)TextLength;
public Vector2 TextPosition = Vector2.Zero;
#endregion
#region Draw Info
public Vector2 DrawPosition;
public Rectangle Frame;
public Color DrawColor;
public float Rotation;
public Vector2 Scale;
internal void SetDrawInfo(Vector2 drawPos, Rectangle frame, Color color, float rotation, Vector2 scale)
{
DrawPosition = drawPos;
Frame = frame;
DrawColor = color;
Rotation = rotation;
Scale = scale;
}
#endregion
}
}