File: InGameConsole.cpp

package info (click to toggle)
jazz2-native 3.5.0-1
  • links: PTS, VCS
  • area: contrib
  • in suites:
  • size: 16,836 kB
  • sloc: cpp: 172,557; xml: 113; python: 36; makefile: 5; sh: 2
file content (429 lines) | stat: -rw-r--r-- 13,275 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#include "InGameConsole.h"
#include "FormattedTextBlock.h"
#include "../ContentResolver.h"
#include "../LevelHandler.h"
#include "../PreferencesCache.h"

#include "../../nCine/Application.h"
#include "../../nCine/I18n.h"
#include "../../nCine/Graphics/RenderQueue.h"
#include "../../nCine/Input/IInputManager.h"

#include <Containers/StringConcatenable.h>
#include <Utf8.h>

namespace Jazz2::UI
{
	struct LogLine {
		MessageLevel Level;
		float TimeLeft;
		FormattedTextBlock Message;

		LogLine(MessageLevel level, String&& message, Font* font);
	};

	static SmallVector<LogLine, 0> _logHistory;
	static SmallVector<String, 0> _commandHistory;

	InGameConsole::InGameConsole(LevelHandler* levelHandler)
		: _levelHandler(levelHandler), _currentLine{}, _textCursor(0), _carretAnim(0.0f), _scrollPos(0), _isVisible(false)
	{
		PruneLogHistory();
		_historyIndex = _commandHistory.size();
	}

	InGameConsole::~InGameConsole()
	{
	}

	void InGameConsole::OnInitialized()
	{
		auto& resolver = ContentResolver::Get();
		_smallFont = resolver.GetFont(FontType::Small);

		for (auto& line : _logHistory) {
			line.Message.SetFont(_smallFont);
		}
	}

	void InGameConsole::OnUpdate(float timeMult)
	{
		Canvas::OnUpdate(timeMult);

		_carretAnim += timeMult;

		for (std::int32_t i = _logHistory.size() - 1; i >= 0; i--) {
			auto& line = _logHistory[i];
			if (line.TimeLeft <= 0.0f) {
				break;
			}
			line.TimeLeft -= timeMult;
		}
	}

	bool InGameConsole::OnDraw(RenderQueue& renderQueue)
	{
		Canvas::OnDraw(renderQueue);

		ViewSize = _levelHandler->GetViewSize();
		Vector2f currentLinePos = Vector2f(46.0f, ViewSize.Y - 60.0f);
		float width = ViewSize.X - currentLinePos.X - 24.0f;

		if (_isVisible) {
			DrawSolid(Vector2f(0.0f, 0.0f), 80, ViewSize.As<float>(), Colorf(0.0f, 0.0f, 0.0f, std::min(AnimTime * 5.0f, 0.6f)));

			Colorf color = (_currentLine[0] == '/' ? Colorf(0.38f, 0.48f, 0.69f, 0.5f) : Colorf(0.62f, 0.44f, 0.34f, 0.5f));

			// Current line
			std::int32_t charOffset = 0, charOffsetShadow = 0;
			_smallFont->DrawString(this, ">"_s, charOffsetShadow, currentLinePos.X - 16.0f + 1.0f, currentLinePos.Y + 2.0f, FontShadowLayer + 100,
				Alignment::Left, Colorf(0.0f, 0.0f, 0.0f, 0.3f), 0.8f, 0.0f, 0.0f, 0.0f);
			_smallFont->DrawString(this, ">"_s, charOffset, currentLinePos.X - 16.0f, currentLinePos.Y, FontLayer + 100,
				Alignment::Left, color, 0.8f, 0.0f, 0.0f, 0.0f);

			StringView currentLine = _currentLine;
			_smallFont->DrawString(this, currentLine, charOffsetShadow, currentLinePos.X + 1.0f, currentLinePos.Y + 2.0f, FontShadowLayer + 100,
				Alignment::Left, Colorf(0.0f, 0.0f, 0.0f, 0.3f), 0.8f, 0.0f, 0.0f, 0.0f);
			_smallFont->DrawString(this, currentLine, charOffset, currentLinePos.X, currentLinePos.Y, FontLayer + 100,
				Alignment::Left, color, 0.8f, 0.0f, 0.0f, 0.0f);

			// Carret
			Vector2f textToCursorSize = _smallFont->MeasureString(StringView{_currentLine, _textCursor}, 0.8f);
			DrawSolid(Vector2f(currentLinePos.X + textToCursorSize.X + 1.0f, currentLinePos.Y - 7.0f), FontLayer + 120, Vector2f(1.0f, 12.0f),
				Colorf(1.0f, 1.0f, 1.0f, std::clamp(sinf(_carretAnim * 0.1f) * 1.4f, 0.0f, 0.8f)), true);
		}

		// History
		if (_scrollPos > (std::int32_t)_logHistory.size() - 1) {
			_scrollPos = 0;
		}

		Vector2f historyLinePos = currentLinePos;
		historyLinePos.Y -= 4.0f;
		for (std::int32_t i = _logHistory.size() - 1 - _scrollPos; i >= 0; i--) {
			if (historyLinePos.Y < 50.0f) {
				break;
			}

			auto& line = _logHistory[i];
			if (line.Level == MessageLevel::Debug && !_isVisible) {
				continue;
			}
			float alpha = (_isVisible ? 1.0f : std::min(line.TimeLeft * 0.06f, 1.0f));
			if (alpha <= 0.0f) {
				break;
			}

			Colorf color;
			switch (line.Level) {
				default: color = Font::DefaultColor; color.A *= alpha; break;
				case MessageLevel::Echo: color = Font::DefaultColor; color.A *= alpha; break;
				case MessageLevel::Debug: color = Colorf(0.36f, 0.44f, 0.35f, 0.5f * sqrtf(alpha)); break;
				case MessageLevel::Error: color = Colorf(0.6f, 0.41f, 0.40f, 0.5f * sqrtf(alpha)); break;
				case MessageLevel::Fatal: color = Colorf(0.48f, 0.38f, 0.34f, 0.5f * sqrtf(alpha)); break;
			}

			std::int32_t charOffset = 0;
			line.Message.SetDefaultColor(color);

			Vector2f textSize = line.Message.MeasureSize(Vector2f(width, 400.0f));
			historyLinePos.Y -= textSize.Y;

			if (line.Level == MessageLevel::Echo) {
				std::int32_t charOffset = 0, charOffsetShadow = 0;
				_smallFont->DrawString(this, "›"_s, charOffsetShadow, historyLinePos.X - 13.0f, historyLinePos.Y + 2.0f, FontShadowLayer + 100,
							Alignment::Left, Colorf(0.0f, 0.0f, 0.0f, 0.3f * sqrtf(alpha)), 0.8f, 0.0f, 0.0f, 0.0f);
				_smallFont->DrawString(this, "›"_s, charOffset, historyLinePos.X - 13.0f, historyLinePos.Y, FontLayer + 100,
					Alignment::Left, color, 0.8f, 0.0f, 0.0f, 0.0f);
			}

			line.Message.Draw(this, Rectf(historyLinePos.X, historyLinePos.Y, width, 400.0f), FontLayer + 100, charOffset);
		}

		return true;
	}

	void InGameConsole::OnKeyPressed(const KeyboardEvent& event)
	{
		switch (event.sym) {
			case Keys::Return:
			case Keys::NumPadEnter: {
				ProcessCurrentLine();
				break;
			}
			case Keys::Tab: {
				// If the console is bound to Tab key, allow to toggle it off
				if (ControlScheme::ContainsTarget(PlayerAction::Console, ControlScheme::CreateTarget(Keys::Tab))) {
					Hide();
				}
				break;
			}
			case Keys::Backspace: {
				if (_textCursor > 0) {
					std::size_t lengthAfter = std::strlen(&_currentLine[_textCursor]);
					std::size_t startPos;
					if ((event.mod & KeyMod::Ctrl) != KeyMod::None) {
						auto found = StringView{_currentLine, _textCursor}.findLastOr(' ', _currentLine);
						startPos = found.begin() - _currentLine;
					} else {
						auto [_, prevPos] = Utf8::PrevChar(_currentLine, _textCursor);
						startPos = prevPos;
					}
					std::memmove(&_currentLine[startPos], &_currentLine[_textCursor], lengthAfter + 1);
					_textCursor = startPos;
					_carretAnim = 0.0f;
				}
				break;
			}
			case Keys::Delete: {
				if (_currentLine[_textCursor] != '\0') {
					std::size_t lengthAfter = std::strlen(&_currentLine[_textCursor]);
					std::size_t endPos;
					if ((event.mod & KeyMod::Ctrl) != KeyMod::None) {
						auto found = StringView{&_currentLine[_textCursor]}.findOr(' ', &_currentLine[_textCursor + lengthAfter]);
						endPos = found.end() - _currentLine;
					} else {
						auto [_, nextPos] = Utf8::NextChar(_currentLine, _textCursor);
						endPos = nextPos;
					}
					std::memmove(&_currentLine[_textCursor], &_currentLine[endPos], lengthAfter + 1);
					_carretAnim = 0.0f;
				}
				break;
			}
			case Keys::Left: {
				if (_textCursor > 0) {
					auto [c, prevPos] = Utf8::PrevChar(_currentLine, _textCursor);
					_textCursor = prevPos;
					_carretAnim = 0.0f;
				}
				break;
			}
			case Keys::Right: {
				if (_currentLine[_textCursor] != '\0') {
					auto [c, nextPos] = Utf8::NextChar(_currentLine, _textCursor);
					_textCursor = nextPos;
					_carretAnim = 0.0f;
				}
				break;
			}
			case Keys::Up: {
				if (event.mod & KeyMod::Ctrl) {
					ScrollUp(1);
				} else {
					GetPreviousCommandFromHistory();
				}
				break;
			}
			case Keys::Down: {
				if (event.mod & KeyMod::Ctrl) {
					ScrollDown(1);
				} else {
					GetNextCommandFromHistory();
				}
				break;
			}
			case Keys::PageUp: {
				ScrollUp(3);
				break;
			}
			case Keys::PageDown: {
				ScrollDown(3);
				break;
			}
			case Keys::K: { // Clear line
				if ((event.mod & KeyMod::Ctrl) != KeyMod::None && (event.mod & (KeyMod::Alt | KeyMod::Shift)) == KeyMod::None) {
					_currentLine[0] = '\0';
					_textCursor = 0;
					_carretAnim = 0.0f;
				}
				break;
			}
			case Keys::L: { // Clear history
				if ((event.mod & KeyMod::Ctrl) != KeyMod::None && (event.mod & (KeyMod::Alt | KeyMod::Shift)) == KeyMod::None) {
					_logHistory.clear();
				}
				break;
			}
			case Keys::V: { // Paste
				if ((event.mod & KeyMod::Ctrl) != KeyMod::None && (event.mod & (KeyMod::Alt | KeyMod::Shift)) == KeyMod::None) {
					auto text = theApplication().GetInputManager().getClipboardText();
					if (!text.empty()) {
						auto trimmedText = text.trimmedPrefix();
						if (auto firstNewLine = trimmedText.find('\n')) {
							trimmedText = trimmedText.prefix(firstNewLine.begin());
						}
						trimmedText = trimmedText.trimmedSuffix();

						std::size_t lengthTotal = std::strlen(_currentLine);
						if (lengthTotal + trimmedText.size() < MaxLineLength) {
							std::size_t lengthAfter = std::strlen(&_currentLine[_textCursor]);
							if (lengthAfter > 0) {
								std::memmove(&_currentLine[_textCursor + trimmedText.size()], &_currentLine[_textCursor], lengthAfter);
							}
							_currentLine[_textCursor + trimmedText.size() + lengthAfter] = '\0';
							std::memcpy(&_currentLine[_textCursor], trimmedText.data(), trimmedText.size());
							_textCursor += trimmedText.size();
							_carretAnim = 0.0f;
						}
					}
				}
				break;
			}
		}
	}

	void InGameConsole::OnTextInput(const TextInputEvent& event)
	{
		if (_textCursor + event.length < MaxLineLength) {
			std::size_t lengthAfter = std::strlen(&_currentLine[_textCursor]);
			if (lengthAfter > 0) {
				std::memmove(&_currentLine[_textCursor + event.length], &_currentLine[_textCursor], lengthAfter);
			}
			_currentLine[_textCursor + event.length + lengthAfter] = '\0';
			std::memcpy(&_currentLine[_textCursor], event.text, event.length);
			_textCursor += event.length;
			_carretAnim = 0.0f;
		}
	}

	void InGameConsole::Clear()
	{
		_logHistory.clear();
	}

	bool InGameConsole::IsVisible() const
	{
		return _isVisible;
	}

	void InGameConsole::Show()
	{
		// Don't allow to show the console if it was hidden in the last frame (mainly to fix toggling with Tab key)
		if (AnimTime <= AnimTimeMultiplier) {
			return;
		}

		_isVisible = true;

		_currentLine[0] = '\0';
		_textCursor = 0;
		_carretAnim = 0.0f;

		AnimTime = 0.0f;
	}

	void InGameConsole::Hide()
	{
		_isVisible = false;

		AnimTime = 0.0f;
	}

	void InGameConsole::WriteLine(MessageLevel level, String line)
	{
#if defined(DEATH_TRACE)
		switch (level) {
			//case MessageLevel::Info: is skipped, because these messages are usually written to the log separately
			case MessageLevel::Echo: __DEATH_TRACE(TraceLevel::Info, {}, "> │ {}", Font::StripFormatting(line)); break;
			case MessageLevel::Chat:
			case MessageLevel::Confirm: __DEATH_TRACE(TraceLevel::Info, {}, "< │ {}", Font::StripFormatting(line)); break;
			case MessageLevel::Warning: __DEATH_TRACE(TraceLevel::Warning, {}, "< │ {}", Font::StripFormatting(line)); break;
			case MessageLevel::Error: __DEATH_TRACE(TraceLevel::Error, {}, "< │ {}", Font::StripFormatting(line)); break;
			case MessageLevel::Assert: __DEATH_TRACE(TraceLevel::Assert, {}, "< │ {}", Font::StripFormatting(line)); break;
			case MessageLevel::Fatal: __DEATH_TRACE(TraceLevel::Fatal, {}, "< │ {}", Font::StripFormatting(line)); break;
		}
#endif
		_logHistory.emplace_back(level, std::move(line), _smallFont);
		_scrollPos = 0;
	}

	void InGameConsole::ProcessCurrentLine()
	{
		if (_currentLine[0] == '\0') {
			// Empty line
			return;
		}

		StringView line = _currentLine;
		if (_commandHistory.empty() || _commandHistory.back() != line) {
			_commandHistory.emplace_back(line);
		}
		_historyIndex = _commandHistory.size();

		if (line == "/clear"_s || line == "/cls"_s) {
			Clear();
		} else {
			if (!_levelHandler->OnConsoleCommand(line)) {
				WriteLine(MessageLevel::Echo, line);
				WriteLine(MessageLevel::Error, _("Unknown command"));
			}
		}

		_currentLine[0] = '\0';
		_textCursor = 0;
		_carretAnim = 0.0f;
	}

	void InGameConsole::PruneLogHistory()
	{
		constexpr std::int32_t MaxHistoryLines = 64;

		if (_logHistory.size() > MaxHistoryLines) {
			_logHistory.erase(&_logHistory[0], &_logHistory[_logHistory.size() - MaxHistoryLines]);
		}
	}

	void InGameConsole::GetPreviousCommandFromHistory()
	{
		if (_historyIndex > 0) {
			_historyIndex--;
			std::memcpy(_currentLine, _commandHistory[_historyIndex].data(), _commandHistory[_historyIndex].size() + 1);
			_textCursor = _commandHistory[_historyIndex].size();
			_carretAnim = 0.0f;
		}
	}

	void InGameConsole::GetNextCommandFromHistory()
	{
		if (_historyIndex < _commandHistory.size()) {
			_historyIndex++;
			if (_historyIndex == _commandHistory.size()) {
				_currentLine[0] = '\0';
				_textCursor = 0;
			} else {
				std::memcpy(_currentLine, _commandHistory[_historyIndex].data(), _commandHistory[_historyIndex].size() + 1);
				_textCursor = _commandHistory[_historyIndex].size();
			}
			_carretAnim = 0.0f;
		}
	}

	void InGameConsole::ScrollUp(std::int32_t amount)
	{
		_scrollPos += amount;

		if (_scrollPos > (std::int32_t)_logHistory.size() - 1) {
			_scrollPos = (std::int32_t)_logHistory.size() - 1;
		}
	}

	void InGameConsole::ScrollDown(std::int32_t amount)
	{
		_scrollPos -= amount;

		if (_scrollPos < 0) {
			_scrollPos = 0;
		}
	}

	LogLine::LogLine(MessageLevel level, String&& message, Font* font)
		: Level(level), TimeLeft(5.0f * FrameTimer::FramesPerSecond)
	{
		Message.SetText(std::move(message));
		Message.SetScale(0.8f);
		Message.SetFont(font);
		Message.SetMultiline(true);
		Message.SetWrapping(true);
	}
}