I thought I need every line to be measured before the \n code if it's necessary.
Yes, you'll need one X value per line.
I spent some time trying things out and came up with this:
Spoiler: plugin code
JavaScript:
/*:
* @target MZ
* @plugindesc Centre all Show Texts.
* @author Caethyril
* @url https://forums.rpgmakerweb.com/threads/161650/
* @help Free to use and/or modify for any project, no credit required.
*/
;void (() => {
"use strict";
/** Non-conflicting identifier for new "line widths" property on `Window_Message`. */
const SYM = Symbol();
/**
* @param {object} Stores text drawing info.
* @returns {string} Next/current line of text.
*/
const getLine = function(textState) {
const s = textState.text.slice(textState.index);
const r = /^\n?([^\n]*)\n/.exec(s);
return r ? r[1] : s;
};
// Patch - reset starting X value on new line.
void (alias => {
Window_Message.prototype.processNewLine = function(textState) {
delete textState[SYM];
textState.startX = this.newLineX(textState);
alias.call(this, textState);
};
})(Window_Message.prototype.processNewLine);
// Override - offset to centre by referencing line width.
Window_Message.prototype.newLineX = function(textState) {
// default
const faceExists = $gameMessage.faceName() !== "";
const faceWidth = ImageManager.faceWidth;
const spacing = 20;
const margin = faceExists ? faceWidth + spacing : 4;
// get next line's offset (lazy init)
const lw = textState[SYM] ??= this.textSizeEx(getLine(textState)).width;
const dx = Math.floor((this.innerWidth - margin - 4 - lw) / 2);
// text direction
if (textState.rtl)
return this.innerWidth - margin - dx;
return margin + dx;
};
})();
It did a few quick tests and it seemed OK for me, hopefully it does what you want (or points you in a helpful direction).
👋
(I also noticed that the core message-specific codes, e.g.
\! and
\$, process even during text measurement...probably an oversight. Could patch the
processEscapeCharacter method of
Window_Base Window_Message, if necessary, to ensure they only process when
textState.drawing is
true.)
Edit: here's a snippet to make
\! etc not process during Show Text measurement~
JavaScript:
void (alias => {
Window_Message.prototype.processEscapeCharacter = function(code, textState) {
if (textState.drawing)
alias.apply(this, arguments);
else
Window_Base.prototype.processEscapeCharacter.apply(this, arguments);
};
})(Window_Base.prototype.processEscapeCharacter);
You can just add it to the end of the code from the spoiler.
😮💨