Debian Codegraph @

CorsixTH/Src/th_gfx.cpp

raw
1 /*
2 Copyright (c) 2009 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "th_gfx.h"
24
25 #include "config.h"
26
27 #include <algorithm>
28 #include <cassert>
29 #include <climits>
30 #include <cstdlib>
31 #include <cstring>
32 #include <memory>
33 #include <new>
34
35 #include "persist_lua.h"
36 #include "th_gfx_sdl.h"
37 #include "th_lua.h"
38 #include "th_map.h"
39 #include "th_sound.h"
40
41 /** Data retrieval class, simulating sequential access to the data, keeping
42 * track of available length. */
43 class memory_reader {
44 public:
45 memory_reader(const uint8_t* pData, const size_t iLength)
46 : data(pData), remaining_bytes(iLength) {}
47
48 const uint8_t* data; ///< Pointer to the remaining data.
49 size_t remaining_bytes; ///< Remaining number of bytes.
50
51 //! Can \a iSize bytes be read from the file?
52 /*!
53 @param iSize Number of bytes that are queried.
54 @return Whether the requested number of bytes is still available.
55 */
56 bool are_bytes_available(size_t iSize) const {
57 return iSize <= remaining_bytes;
58 }
59
60 //! Is EOF reached?
61 /*!
62 @return Whether EOF has been reached.
63 */
64 bool is_at_end_of_file() const { return remaining_bytes == 0; }
65
66 //! Get an 8 bit value from the file.
67 /*!
68 @return Read 8 bit value.
69 @pre There should be at least a byte available for reading.
70 */
71 uint8_t read_uint8() {
72 assert(remaining_bytes > 0);
73
74 uint8_t iVal = *data;
75 data++;
76 remaining_bytes--;
77 return iVal;
78 }
79
80 //! Get a 16 bit value from the file.
81 /*!
82 @return Read 16 bit value.
83 @pre There should be at least 2 bytes available for reading.
84 */
85 uint16_t read_uint16() {
86 uint16_t iVal = read_uint8();
87 uint16_t iVal2 = read_uint8();
88 return static_cast<uint16_t>(iVal | (iVal2 << 8));
89 }
90
91 //! Get a signed 16 bit value from the file.
92 /*!
93 @return The read signed 16 bit value.
94 @pre There should be at least 2 bytes available for reading.
95 */
96 int read_int16() {
97 int val = read_uint16();
98 if (val < 0x7FFF) return val;
99
100 int ret = -1;
101 return (ret & ~0xFFFF) | val;
102 }
103
104 //! Get a 32 bit value from the file.
105 /*!
106 @return Read 32 bit value.
107 @pre There should be at least 4 bytes available for reading.
108 */
109 uint32_t read_uint32() {
110 uint32_t iVal = read_uint16();
111 uint32_t iVal2 = read_uint16();
112 return iVal | (iVal2 << 16);
113 }
114
115 //! Load string from the memory_reader.
116 /*!
117 @param [out] pStr String to load.
118 @return Whether the string could be loaded.
119 */
120 bool read_string(std::string* pStr) {
121 char buff[256];
122
123 if (is_at_end_of_file()) {
124 return false;
125 }
126
127 size_t iLength = read_uint8();
128 if (!are_bytes_available(iLength)) {
129 return false;
130 }
131
132 size_t idx;
133 for (idx = 0; idx < iLength; idx++) {
134 buff[idx] = read_uint8();
135 }
136 buff[idx] = '\0';
137 *pStr = std::string(buff);
138
139 return true;
140 }
141 };
142
143 void animation_manager::set_sprite_sheet(sprite_sheet* pSpriteSheet) {
144 sheet = pSpriteSheet;
145 }
146
147 constexpr size_t bytes_per_animation_property = 4;
148
149 // Frame information structure reinterpreted from Theme Hospital data.
150 // https://github.com/CorsixTH/theme-hospital-spec/blob/master/format-specification.md#frame
151 struct th_frame_properties {
152 constexpr static size_t size = 10;
153
154 explicit th_frame_properties(const uint8_t* pData)
155 : list_index{bytes_to_uint32_le(pData)},
156 // skipping width and height (1 byte each)
157 sound{pData[6]},
158 flags{pData[7]},
159 next{bytes_to_uint16_le(pData + 8)} {}
160
161 uint32_t list_index;
162 uint8_t sound;
163 uint8_t flags;
164 uint16_t next;
165 };
166
167 // Structure reinterpreted from Theme Hospital data.
168 // https://github.com/CorsixTH/theme-hospital-spec/blob/master/format-specification.md#spriteelement
169 struct th_element_properties {
170 constexpr static size_t size = 6;
171
172 explicit th_element_properties(const uint8_t* pData)
173 : table_position{bytes_to_uint16_le(pData)},
174 offset_x{pData[2]},
175 offset_y{pData[3]},
176 layer{static_cast<uint8_t>(pData[4] >> 4)},
177 flags{static_cast<uint8_t>(pData[4] & 0xF)},
178 layer_id{pData[5]} {}
179
180 uint16_t table_position;
181 uint8_t offset_x;
182 uint8_t offset_y;
183 uint8_t layer; // High nibble of byte 4
184 uint8_t flags; // Low nibble of byte 4
185 uint8_t layer_id;
186 };
187
188 bool animation_manager::load_from_th_file(
189 const uint8_t* pStartData, size_t iStartDataLength,
190 const uint8_t* pFrameData, size_t iFrameDataLength,
191 const uint8_t* pListData, size_t iListDataLength,
192 const uint8_t* pElementData, size_t iElementDataLength) {
193 size_t iAnimationCount = iStartDataLength / bytes_per_animation_property;
194 size_t iFrameCount = iFrameDataLength / th_frame_properties::size;
195 size_t iListCount = iListDataLength / 2;
196 size_t iElementCount = iElementDataLength / th_element_properties::size;
197
198 if (iAnimationCount == 0 || iFrameCount == 0 || iListCount == 0 ||
199 iElementCount == 0) {
200 return false;
201 }
202
203 // Start offset of the file data into the vectors.
204 size_t iAnimationStart = animation_count;
205 size_t iFrameStart = frame_count;
206 size_t iListStart = element_list_count;
207 size_t iElementStart = element_count;
208
209 // Original data file must start at offset 0 due to the hard-coded animation
210 // numbers in the Lua code.
211 if (iAnimationStart > 0 || iFrameStart > 0 || iListStart > 0 ||
212 iElementStart > 0) {
213 return false;
214 }
215
216 // Overflow of list elements.
217 if (iElementStart + iElementCount >= 0xFFFF) {
218 return false;
219 }
220
221 // Create new space for the data.
222 first_frames.reserve(iAnimationStart + iAnimationCount);
223 frames.reserve(iFrameStart + iFrameCount);
224 element_list.reserve(iListStart + iListCount + 1);
225 elements.reserve(iElementStart + iElementCount);
226
227 // Read animations.
228 for (size_t i = 0; i < iAnimationCount; ++i) {
229 size_t iFirstFrame =
230 bytes_to_uint16_le(pStartData + i * bytes_per_animation_property);
231 if (iFirstFrame > iFrameCount) {
232 iFirstFrame = 0;
233 }
234
235 iFirstFrame += iFrameStart;
236 first_frames.push_back(iFirstFrame);
237 }
238
239 // Read frames.
240 for (size_t i = 0; i < iFrameCount; ++i) {
241 const th_frame_properties thFrame(pFrameData +
242 i * th_frame_properties::size);
243
244 frame oFrame;
245 oFrame.list_index =
246 iListStart + (thFrame.list_index < iListCount ? thFrame.list_index : 0);
247 oFrame.next_frame =
248 iFrameStart + (thFrame.next < iFrameCount ? thFrame.next : 0);
249 oFrame.sound = thFrame.sound;
250 oFrame.flags = thFrame.flags;
251 // Bounding box fields initialised later
252 oFrame.primary_marker_x = 0;
253 oFrame.primary_marker_y = 0;
254 oFrame.secondary_marker_x = 0;
255 oFrame.secondary_marker_y = 0;
256
257 frames.push_back(oFrame);
258 }
259
260 // Read the element list.
261 for (size_t i = 0; i < iListCount; ++i) {
262 uint16_t iElmNumber = bytes_to_uint16_le(pListData + i * 2);
263 if (iElmNumber >= iElementCount) {
264 iElmNumber = 0xFFFF;
265 } else {
266 iElmNumber = static_cast<uint16_t>(iElmNumber + iElementStart);
267 }
268
269 element_list.push_back(iElmNumber);
270 }
271 element_list.push_back(0xFFFF);
272
273 // Read elements.
274 size_t iSpriteCount = sheet->get_sprite_count();
275 for (size_t i = 0; i < iElementCount; ++i) {
276 const th_element_properties thElement(pElementData +
277 i * th_element_properties::size);
278
279 element oElement;
280 oElement.sprite =
281 thElement.table_position / 6; // sprite table entries are 6 bytes
282 oElement.flags = thElement.flags;
283 oElement.x = static_cast<int>(thElement.offset_x) - 141;
284 oElement.y = static_cast<int>(thElement.offset_y) - 186;
285 oElement.layer = thElement.layer;
286
287 if (oElement.layer >= max_number_of_layers) {
288 // Nothing lives on layer 6
289 oElement.layer = 6;
290 }
291 oElement.layer_id = thElement.layer_id;
292 if (oElement.sprite < iSpriteCount) {
293 oElement.element_sprite_sheet = sheet;
294 } else {
295 oElement.element_sprite_sheet = nullptr;
296 }
297
298 elements.push_back(oElement);
299 }
300
301 // Compute bounding box of the animations using the sprite sheet.
302 for (size_t i = 0; i < iFrameCount; ++i) {
303 set_bounding_box(frames[iFrameStart + i]);
304 }
305
306 animation_count += iAnimationCount;
307 frame_count += iFrameCount;
308 element_list_count += iListCount + 1;
309 element_count += iElementCount;
310
311 assert(first_frames.size() == animation_count);
312 assert(frames.size() == frame_count);
313 assert(element_list.size() == element_list_count);
314 assert(elements.size() == element_count);
315
316 return true;
317 }
318
319 namespace {
320
321 //! Update \a iLeft with the smallest of both values.
322 /*!
323 @param [inout] iLeft Left value to check and update.
324 @param iRight Second value to check.
325 */
326 void set_left_to_min(int& iLeft, int iRight) {
327 if (iRight < iLeft) iLeft = iRight;
328 }
329
330 //! Update \a iLeft with the biggest of both values.
331 /*!
332 @param [inout] iLeft Left value to check and update.
333 @param iRight Second value to check.
334 */
335 void set_left_to_max(int& iLeft, int iRight) {
336 if (iRight > iLeft) iLeft = iRight;
337 }
338
339 } // namespace
340
341 void animation_manager::set_bounding_box(frame& oFrame) {
342 oFrame.bounding_left = INT_MAX;
343 oFrame.bounding_right = INT_MIN;
344 oFrame.bounding_top = INT_MAX;
345 oFrame.bounding_bottom = INT_MIN;
346
347 size_t iListIndex = oFrame.list_index;
348 for (;; ++iListIndex) {
349 uint16_t iElement = element_list[iListIndex];
350 if (iElement >= elements.size()) {
351 break;
352 }
353
354 element& oElement = elements[iElement];
355 if (oElement.element_sprite_sheet == nullptr) {
356 continue;
357 }
358
359 int iWidth;
360 int iHeight;
361 oElement.element_sprite_sheet->get_sprite_size_unchecked(oElement.sprite,
362 &iWidth, &iHeight);
363 set_left_to_min(oFrame.bounding_left, oElement.x);
364 set_left_to_min(oFrame.bounding_top, oElement.y);
365 set_left_to_max(oFrame.bounding_right, oElement.x - 1 + (int)iWidth);
366 set_left_to_max(oFrame.bounding_bottom, oElement.y - 1 + (int)iHeight);
367 }
368 }
369
370 void animation_manager::set_canvas(render_target* pCanvas) { canvas = pCanvas; }
371
372 namespace {
373
374 //! Load the header.
375 /*!
376 @param [inout] input Data to read.
377 @return Number of consumed bytes, a negative number indicates an error.
378 */
379 int load_header(memory_reader& input) {
380 static const uint8_t aHdr[] = {'C', 'T', 'H', 'G', 1, 2};
381
382 if (!input.are_bytes_available(6)) {
383 return false;
384 }
385
386 for (int i = 0; i < 6; i++) {
387 if (input.read_uint8() != aHdr[i]) {
388 return false;
389 }
390 }
391 return true;
392 }
393
394 } // namespace
395
396 size_t animation_manager::load_elements(
397 memory_reader& input, sprite_sheet* pSpriteSheet, size_t iNumElements,
398 size_t& iLoadedElements, size_t iElementStart, size_t iElementCount) {
399 size_t iFirst = iLoadedElements + iElementStart;
400
401 size_t iSpriteCount = pSpriteSheet->get_sprite_count();
402 while (iNumElements > 0) {
403 if (iLoadedElements >= iElementCount || !input.are_bytes_available(12)) {
404 return SIZE_MAX;
405 }
406
407 size_t iSprite = input.read_uint32();
408 int iX = input.read_int16();
409 int iY = input.read_int16();
410 uint8_t iLayerClass = input.read_uint8();
411 uint8_t iLayerId = input.read_uint8();
412 uint32_t iFlags = input.read_uint16();
413
414 if (iLayerClass >= max_number_of_layers) {
415 // Nothing lives on layer 6
416 iLayerClass = 6;
417 }
418
419 element oElement;
420 oElement.sprite = iSprite;
421 oElement.flags = iFlags;
422 oElement.x = iX;
423 oElement.y = iY;
424 oElement.layer = iLayerClass;
425 oElement.layer_id = iLayerId;
426 if (oElement.sprite >= iSpriteCount)
427 oElement.element_sprite_sheet = nullptr;
428 else
429 oElement.element_sprite_sheet = pSpriteSheet;
430
431 elements.push_back(oElement);
432 iLoadedElements++;
433 iNumElements--;
434 }
435 return iFirst;
436 }
437
438 size_t animation_manager::make_list_elements(size_t iFirstElement,
439 size_t iNumElements,
440 size_t& iLoadedListElements,
441 size_t iListStart,
442 size_t iListCount) {
443 size_t iFirst = iLoadedListElements + iListStart;
444
445 // Verify there is enough room for all list elements + 0xFFFF
446 if (iLoadedListElements + iNumElements + 1 > iListCount) {
447 return SIZE_MAX;
448 }
449
450 // Overflow for list elements.
451 assert(iFirstElement + iNumElements < 0xFFFF);
452
453 while (iNumElements > 0) {
454 element_list.push_back(static_cast<uint16_t>(iFirstElement));
455 iLoadedListElements++;
456 iFirstElement++;
457 iNumElements--;
458 }
459 // Add 0xFFFF.
460 element_list.push_back(0xFFFF);
461 iLoadedListElements++;
462
463 return iFirst;
464 }
465
466 namespace {
467
468 //! Shift the first frame if all frames are available.
469 /*!
470 @param iFirst First frame number, or 0xFFFFFFFFu if no animation.
471 @param iLength Number of frames in the animation.
472 @param iStart Start of the frames for this file.
473 @param iLoaded Number of loaded frames.
474 @return The shifted first frame, or 0xFFFFFFFFu.
475 */
476 uint32_t shift_first(uint32_t iFirst, size_t iLength, size_t iStart,
477 size_t iLoaded) {
478 if (iFirst == 0xFFFFFFFFu || iFirst + iLength > iLoaded) {
479 return 0xFFFFFFFFu;
480 }
481 return iFirst + static_cast<uint32_t>(iStart);
482 }
483
484 } // namespace
485
486 void animation_manager::fix_next_frame(uint32_t iFirst, size_t iLength) {
487 if (iFirst == 0xFFFFFFFFu) {
488 return;
489 }
490
491 frame& oFirst = frames[iFirst];
492 oFirst.flags |= 0x1; // Start of animation flag.
493
494 frame& oLast = frames[iFirst + iLength - 1];
495 oLast.next_frame = iFirst; // Loop last frame back to the first.
496 }
497
498 bool animation_manager::load_custom_animations(const uint8_t* pData,
499 size_t iDataLength) {
500 memory_reader input(pData, iDataLength);
501
502 if (!load_header(input)) {
503 return false;
504 }
505
506 if (!input.are_bytes_available(5 * 4)) {
507 return false;
508 }
509
510 size_t iAnimationCount = input.read_uint32();
511 size_t iFrameCount = input.read_uint32();
512 size_t iElementCount = input.read_uint32();
513 size_t iSpriteCount = input.read_uint32();
514 input.read_uint32(); // Total number of bytes sprite data is not used.
515
516 // Every element is referenced once, and one 0xFFFF for every frame.
517 size_t iListCount = iElementCount + iFrameCount;
518
519 size_t iFrameStart = frame_count;
520 size_t iListStart = element_list_count;
521 size_t iElementStart = element_count;
522
523 if (iAnimationCount == 0 || iFrameCount == 0 || iElementCount == 0 ||
524 iSpriteCount == 0) {
525 return false;
526 }
527
528 // Overflow of list elements.
529 if (iElementStart + iElementCount >= 0xFFFF) {
530 return false;
531 }
532
533 // Create new space for the elements.
534 // Be optimistic in reservation.
535 first_frames.reserve(first_frames.size() + iAnimationCount * 4);
536 frames.reserve(iFrameStart + iFrameCount);
537 element_list.reserve(iListStart + iListCount);
538 elements.reserve(iElementStart + iElementCount);
539
540 // Construct a sprite sheet for the sprites to be loaded.
541 sprite_sheet pSheet;
542 pSheet.set_sprite_count(iSpriteCount, canvas);
543 custom_sheets.push_back(pSheet);
544
545 size_t iLoadedFrames = 0;
546 size_t iLoadedListElements = 0;
547 size_t iLoadedElements = 0;
548 size_t iLoadedSprites = 0;
549
550 // Read the blocks of the file, until hitting EOF.
551 for (;;) {
552 if (input.is_at_end_of_file()) break;
553
554 // Read identification bytes at the start of each block, and dispatch
555 // loading.
556 if (!input.are_bytes_available(2)) return false;
557 int first = input.read_uint8();
558 int second = input.read_uint8();
559
560 // Recognized a grouped animation block, load it.
561 if (first == 'C' && second == 'A') {
562 animation_key oKey;
563
564 if (!input.are_bytes_available(2 + 4)) {
565 return false;
566 }
567
568 oKey.tile_size = input.read_uint16();
569 size_t iNumFrames = input.read_uint32();
570 if (iNumFrames == 0) {
571 return false;
572 }
573
574 if (!input.read_string(&oKey.name)) {
575 return false;
576 }
577
578 if (!input.are_bytes_available(4 * 4)) {
579 return false;
580 }
581
582 uint32_t iNorthFirst = input.read_uint32();
583 uint32_t iEastFirst = input.read_uint32();
584 uint32_t iSouthFirst = input.read_uint32();
585 uint32_t iWestFirst = input.read_uint32();
586
587 iNorthFirst =
588 shift_first(iNorthFirst, iNumFrames, iFrameStart, iLoadedFrames);
589 iEastFirst =
590 shift_first(iEastFirst, iNumFrames, iFrameStart, iLoadedFrames);
591 iSouthFirst =
592 shift_first(iSouthFirst, iNumFrames, iFrameStart, iLoadedFrames);
593 iWestFirst =
594 shift_first(iWestFirst, iNumFrames, iFrameStart, iLoadedFrames);
595
596 animation_start_frames oFrames;
597 if (iNorthFirst != 0xFFFFFFFFu) {
598 fix_next_frame(iNorthFirst, iNumFrames);
599 oFrames.north = static_cast<long>(first_frames.size());
600 first_frames.push_back(iNorthFirst);
601 }
602 if (iEastFirst != 0xFFFFFFFFu) {
603 fix_next_frame(iEastFirst, iNumFrames);
604 oFrames.east = static_cast<long>(first_frames.size());
605 first_frames.push_back(iEastFirst);
606 }
607 if (iSouthFirst != 0xFFFFFFFFu) {
608 fix_next_frame(iSouthFirst, iNumFrames);
609 oFrames.south = static_cast<long>(first_frames.size());
610 first_frames.push_back(iSouthFirst);
611 }
612 if (iWestFirst != 0xFFFFFFFFu) {
613 fix_next_frame(iWestFirst, iNumFrames);
614 oFrames.west = static_cast<long>(first_frames.size());
615 first_frames.push_back(iWestFirst);
616 }
617
618 named_animation_pair p(oKey, oFrames);
619 named_animations.insert(p);
620 continue;
621 } else if (first == 'F' && second == 'R') {
622 // Recognized a frame block, load it.
623
624 if (iLoadedFrames >= iFrameCount) {
625 return false;
626 }
627
628 if (!input.are_bytes_available(2 + 2)) {
629 return false;
630 }
631
632 int iSound = input.read_uint16();
633 size_t iNumElements = input.read_uint16();
634
635 size_t iElm = load_elements(input, &pSheet, iNumElements, iLoadedElements,
636 iElementStart, iElementCount);
637 if (iElm == SIZE_MAX) {
638 return false;
639 }
640
641 size_t iListElm = make_list_elements(
642 iElm, iNumElements, iLoadedListElements, iListStart, iListCount);
643 if (iListElm == SIZE_MAX) {
644 return false;
645 }
646
647 frame oFrame;
648 oFrame.list_index = iListElm;
649
650 // Point to next frame.
651 // Last frame of each animation corrected later.
652 oFrame.next_frame = iFrameStart + iLoadedFrames + 1;
653
654 oFrame.sound = iSound;
655
656 // Set later
657 oFrame.flags = 0;
658 oFrame.primary_marker_x = 0;
659 oFrame.primary_marker_y = 0;
660 oFrame.secondary_marker_x = 0;
661 oFrame.secondary_marker_y = 0;
662
663 set_bounding_box(oFrame);
664
665 frames.push_back(oFrame);
666 iLoadedFrames++;
667 continue;
668 } else if (first == 'S' && second == 'P') {
669 // Recognized a Sprite block, load it.
670
671 if (iLoadedSprites >= iSpriteCount) {
672 return false;
673 }
674
675 if (!input.are_bytes_available(2 + 2 + 4)) {
676 return false;
677 }
678
679 int iWidth = input.read_uint16();
680 int iHeight = input.read_uint16();
681 uint32_t iSize = input.read_uint32();
682
683 // Check it is safe to use as 'int'
684 if (iSize > INT_MAX) {
685 return false;
686 }
687
688 // Load data.
689 uint8_t* pData = new (std::nothrow) uint8_t[iSize];
690 if (pData == nullptr) {
691 return false;
692 }
693
694 if (!input.are_bytes_available(iSize)) {
695 delete[] pData;
696 return false;
697 }
698
699 for (uint32_t i = 0; i < iSize; i++) {
700 pData[i] = input.read_uint8();
701 }
702
703 if (!pSheet.set_sprite_data(iLoadedSprites, pData, true, iSize, iWidth,
704 iHeight)) {
705 return false;
706 }
707
708 iLoadedSprites++;
709 continue;
710 } else {
711 // Unrecognized block, fail.
712 return false;
713 }
714 }
715
716 assert(iLoadedFrames == iFrameCount);
717 assert(iLoadedListElements == iListCount);
718 assert(iLoadedElements == iElementCount);
719 assert(iLoadedSprites == iSpriteCount);
720
721 // Fix the next pointer of the last frame in case it points to non-existing
722 // frames.
723 frame& oFrame = frames[iFrameStart + iFrameCount - 1];
724 if (iFrameCount > 0 && oFrame.next_frame >= iFrameStart + iFrameCount) {
725 // Useless, but maybe less crashy.
726 oFrame.next_frame = iFrameStart;
727 }
728
729 animation_count = first_frames.size();
730 frame_count += iFrameCount;
731 element_list_count += iListCount;
732 element_count += iElementCount;
733 assert(frames.size() == frame_count);
734 assert(element_list.size() == element_list_count);
735 assert(elements.size() == element_count);
736
737 return true;
738 }
739
740 const animation_start_frames& animation_manager::get_named_animations(
741 const std::string_view sName, const int iTilesize) const {
742 static const animation_start_frames oNoneAnimations = {-1, -1, -1, -1};
743
744 animation_key oKey;
745 oKey.name = sName;
746 oKey.tile_size = iTilesize;
747
748 named_animations_map::const_iterator iter = named_animations.find(oKey);
749 if (iter == named_animations.end()) {
750 return oNoneAnimations;
751 }
752 return (*iter).second;
753 }
754
755 size_t animation_manager::get_animation_count() const {
756 return animation_count;
757 }
758
759 size_t animation_manager::get_frame_count() const { return frame_count; }
760
761 size_t animation_manager::get_first_frame(size_t iAnimation) const {
762 if (iAnimation < animation_count) {
763 return first_frames[iAnimation];
764 } else {
765 return 0;
766 }
767 }
768
769 size_t animation_manager::get_next_frame(size_t iFrame) const {
770 if (iFrame < frame_count) {
771 return frames[iFrame].next_frame;
772 } else {
773 return iFrame;
774 }
775 }
776
777 void animation_manager::set_animation_alt_palette_map(size_t iAnimation,
778 const uint8_t* pMap,
779 uint32_t iAlt32) {
780 if (iAnimation >= animation_count) {
781 return;
782 }
783
784 size_t iFrame = first_frames[iAnimation];
785 size_t iFirstFrame = iFrame;
786 do {
787 size_t iListIndex = frames[iFrame].list_index;
788 for (;; ++iListIndex) {
789 uint16_t iElement = element_list[iListIndex];
790 if (iElement >= element_count) {
791 break;
792 }
793
794 element& oElement = elements[iElement];
795 if (oElement.element_sprite_sheet != nullptr) {
796 oElement.element_sprite_sheet->set_sprite_alt_palette_map(
797 oElement.sprite, pMap, iAlt32);
798 }
799 }
800 iFrame = frames[iFrame].next_frame;
801 } while (iFrame != iFirstFrame);
802 }
803
804 bool animation_manager::set_frame_primary_marker(size_t iFrame, int iX,
805 int iY) {
806 if (iFrame >= frame_count) {
807 return false;
808 }
809
810 frames[iFrame].primary_marker_x = iX;
811 frames[iFrame].primary_marker_y = iY;
812 return true;
813 }
814
815 bool animation_manager::set_frame_secondary_marker(size_t iFrame, int iX,
816 int iY) {
817 if (iFrame >= frame_count) {
818 return false;
819 }
820
821 frames[iFrame].secondary_marker_x = iX;
822 frames[iFrame].secondary_marker_y = iY;
823 return true;
824 }
825
826 bool animation_manager::get_frame_primary_marker(size_t iFrame, int* pX,
827 int* pY) {
828 if (iFrame >= frame_count) {
829 return false;
830 }
831
832 *pX = frames[iFrame].primary_marker_x;
833 *pY = frames[iFrame].primary_marker_y;
834 return true;
835 }
836
837 bool animation_manager::get_frame_secondary_marker(size_t iFrame, int* pX,
838 int* pY) {
839 if (iFrame >= frame_count) {
840 return false;
841 }
842
843 *pX = frames[iFrame].secondary_marker_x;
844 *pY = frames[iFrame].secondary_marker_y;
845 return true;
846 }
847
848 void animation_manager::tick() { ++game_ticks; }
849
850 bool animation_manager::hit_test(size_t iFrame, const ::layers& oLayers, int iX,
851 int iY, uint32_t iFlags, int iTestX,
852 int iTestY) const {
853 if (iFrame >= frame_count) {
854 return false;
855 }
856
857 const frame& oFrame = frames[iFrame];
858 iTestX -= iX;
859 iTestY -= iY;
860
861 if (iFlags & thdf_flip_horizontal) {
862 iTestX = -iTestX;
863 }
864
865 if (iTestX < oFrame.bounding_left || iTestX > oFrame.bounding_right) {
866 return false;
867 }
868
869 if (iFlags & thdf_flip_vertical) {
870 if (-iTestY < oFrame.bounding_top || -iTestY > oFrame.bounding_bottom) {
871 return false;
872 }
873 } else {
874 if (iTestY < oFrame.bounding_top || iTestY > oFrame.bounding_bottom) {
875 return false;
876 }
877 }
878
879 if (iFlags & thdf_bound_box_hit_test) {
880 return true;
881 }
882
883 size_t iListIndex = oFrame.list_index;
884 for (;; ++iListIndex) {
885 uint16_t iElement = element_list[iListIndex];
886 if (iElement >= element_count) {
887 break;
888 }
889
890 const element& oElement = elements[iElement];
891 if ((oElement.layer_id != 0 &&
892 oLayers.layer_contents[oElement.layer] != oElement.layer_id) ||
893 oElement.element_sprite_sheet == nullptr) {
894 continue;
895 }
896
897 if (iFlags & thdf_flip_horizontal) {
898 int iWidth;
899 int iHeight;
900 oElement.element_sprite_sheet->get_sprite_size_unchecked(
901 oElement.sprite, &iWidth, &iHeight);
902 if (oElement.element_sprite_sheet->hit_test_sprite(
903 oElement.sprite, oElement.x + iWidth - iTestX,
904 iTestY - oElement.y, oElement.flags ^ thdf_flip_horizontal)) {
905 return true;
906 }
907 } else {
908 if (oElement.element_sprite_sheet->hit_test_sprite(
909 oElement.sprite, iTestX - oElement.x, iTestY - oElement.y,
910 oElement.flags)) {
911 return true;
912 }
913 }
914 }
915
916 return false;
917 }
918
919 void animation_manager::draw_frame(render_target* pCanvas, size_t iFrame,
920 const ::layers& oLayers, int iX, int iY,
921 uint32_t iFlags,
922 animation_effect patient_effect,
923 size_t patient_effect_offset,
924 int scale_factor) const {
925 if (iFrame >= frame_count) {
926 return;
927 }
928
929 uint32_t iPassOnFlags = iFlags & (thdf_alt_palette | thdf_nearest);
930
931 size_t iListIndex = frames[iFrame].list_index;
932 for (;; ++iListIndex) {
933 uint16_t iElement = element_list[iListIndex];
934 if (iElement >= element_count) {
935 break;
936 }
937
938 const element& oElement = elements[iElement];
939 if (oElement.element_sprite_sheet == nullptr) {
940 continue;
941 }
942
943 if (oElement.layer_id != 0 &&
944 oLayers.layer_contents[oElement.layer] != oElement.layer_id) {
945 // Some animations involving doctors (i.e. #72, #74, maybe others)
946 // only provide versions for heads W1 and B1, not W2 and B2. The
947 // quickest way to fix this is this dirty hack here, which draws
948 // the W1 layer as well as W2 if W2 is being used, and similarly
949 // for B1 / B2. A better fix would be to go into each animation
950 // which needs it, and duplicate the W1 / B1 layers to W2 / B2.
951 if (oElement.layer == 5 &&
952 oLayers.layer_contents[5] - 4 == oElement.layer_id) {
953 /* don't skip */;
954 } else {
955 continue;
956 }
957 }
958
959 // Only apply patient animation effect to patient sprites. Layer 0, 0
960 // represents non-patient sprites such as doors, benches, etc.
961 // TODO: Some animations such as leaving radiation chamber have part of
962 // patient in layer 0, 0, so this condition is not quite correct.
963 animation_effect render_effect =
964 (oElement.layer > 0 || oElement.layer_id > 0) ? patient_effect
965 : animation_effect::none;
966 size_t effect_ticks = game_ticks + patient_effect_offset;
967 int oex = oElement.x * scale_factor;
968 int oey = oElement.y * scale_factor;
969 if (iFlags & thdf_flip_horizontal) {
970 int iWidth;
971 int iHeight;
972 oElement.element_sprite_sheet->get_sprite_size_unchecked(
973 oElement.sprite, &iWidth, &iHeight);
974 iWidth *= scale_factor;
975 iHeight *= scale_factor;
976
977 oElement.element_sprite_sheet->draw_sprite(
978 pCanvas, oElement.sprite, iX - oex - iWidth, iY + oey,
979 iPassOnFlags | (oElement.flags ^ thdf_flip_horizontal), effect_ticks,
980 render_effect, scale_factor);
981 } else {
982 oElement.element_sprite_sheet->draw_sprite(
983 pCanvas, oElement.sprite, iX + oex, iY + oey,
984 iPassOnFlags | oElement.flags, effect_ticks, render_effect,
985 scale_factor);
986 }
987 }
988 }
989
990 size_t animation_manager::get_frame_sound(size_t iFrame) {
991 if (iFrame < frame_count) {
992 return frames[iFrame].sound;
993 } else {
994 return 0;
995 }
996 }
997
998 void animation_manager::get_frame_extent(size_t iFrame, const ::layers& oLayers,
999 int* pMinX, int* pMaxX, int* pMinY,
1000 int* pMaxY, uint32_t iFlags) const {
1001 int iMinX = INT_MAX;
1002 int iMaxX = INT_MIN;
1003 int iMinY = INT_MAX;
1004 int iMaxY = INT_MIN;
1005 if (iFrame < frame_count) {
1006 size_t iListIndex = frames[iFrame].list_index;
1007
1008 for (;; ++iListIndex) {
1009 uint16_t iElement = element_list[iListIndex];
1010 if (iElement >= element_count) {
1011 break;
1012 }
1013
1014 const element& oElement = elements[iElement];
1015 if ((oElement.layer_id != 0 &&
1016 oLayers.layer_contents[oElement.layer] != oElement.layer_id) ||
1017 oElement.element_sprite_sheet == nullptr) {
1018 continue;
1019 }
1020
1021 int iX = oElement.x;
1022 int iY = oElement.y;
1023 int iWidth;
1024 int iHeight;
1025 oElement.element_sprite_sheet->get_sprite_size_unchecked(
1026 oElement.sprite, &iWidth, &iHeight);
1027 if (iFlags & thdf_flip_horizontal) iX = -(iX + iWidth);
1028 if (iX < iMinX) iMinX = iX;
1029 if (iY < iMinY) iMinY = iY;
1030 if (iX + iWidth + 1 > iMaxX) iMaxX = iX + iWidth + 1;
1031 if (iY + iHeight + 1 > iMaxY) iMaxY = iY + iHeight + 1;
1032 }
1033 }
1034 if (pMinX) *pMinX = iMinX;
1035 if (pMaxX) *pMaxX = iMaxX;
1036 if (pMinY) *pMinY = iMinY;
1037 if (pMaxY) *pMaxY = iMaxY;
1038 }
1039
1040 chunk_renderer::chunk_renderer(const int width, const int height,
1041 std::vector<uint8_t>::iterator start)
1042 : ptr(start), end(start + (width * height)), width(width), height(height) {}
1043
1044 void chunk_renderer::chunk_fill_to_end_of_line(uint8_t value) {
1045 if (x != 0 || !skip_eol) {
1046 chunk_fill(width - x, value);
1047 }
1048 skip_eol = false;
1049 }
1050
1051 void chunk_renderer::chunk_finish(uint8_t value) {
1052 chunk_fill(static_cast<int>(end - ptr), value);
1053 }
1054
1055 void chunk_renderer::chunk_fill(int npixels, uint8_t value) {
1056 fix_n_pixels(npixels);
1057 if (npixels > 0) {
1058 std::fill_n(ptr, npixels, value);
1059 increment_position(npixels);
1060 }
1061 }
1062
1063 void chunk_renderer::chunk_copy(int npixels, const uint8_t* in_data) {
1064 fix_n_pixels(npixels);
1065 if (npixels > 0) {
1066 std::copy_n(in_data, npixels, ptr);
1067 increment_position(npixels);
1068 }
1069 }
1070
1071 void chunk_renderer::fix_n_pixels(int& npixels) const {
1072 if (ptr + npixels > end) {
1073 npixels = static_cast<int>(end - ptr);
1074 }
1075 }
1076
1077 void chunk_renderer::increment_position(int npixels) {
1078 ptr += npixels;
1079 x += npixels;
1080 y += x / width;
1081 x = x % width;
1082 skip_eol = true;
1083 }
1084
1085 void chunk_renderer::decode_chunks(const uint8_t* data, int datalen,
1086 bool complex) {
1087 if (complex) {
1088 while (!is_done() && datalen > 0) {
1089 uint8_t b = *data;
1090 --datalen;
1091 ++data;
1092 if (b == 0) {
1093 chunk_fill_to_end_of_line(0xFF);
1094 } else if (b < 0x40) {
1095 int amt = b;
1096 if (datalen < amt) amt = datalen;
1097 chunk_copy(amt, data);
1098 data += amt;
1099 datalen -= amt;
1100 } else if ((b & 0xC0) == 0x80) {
1101 chunk_fill(b - 0x80, 0xFF);
1102 } else {
1103 int amt;
1104 uint8_t colour = 0;
1105 if (b == 0xFF) {
1106 if (datalen < 2) {
1107 break;
1108 }
1109 amt = (int)data[0];
1110 colour = data[1];
1111 data += 2;
1112 datalen -= 2;
1113 } else {
1114 amt = b - 60 - (b & 0x80) / 2;
1115 if (datalen > 0) {
1116 colour = *data;
1117 ++data;
1118 --datalen;
1119 }
1120 }
1121 chunk_fill(amt, colour);
1122 }
1123 }
1124 } else {
1125 while (!is_done() && datalen > 0) {
1126 uint8_t b = *data;
1127 --datalen;
1128 ++data;
1129 if (b == 0) {
1130 chunk_fill_to_end_of_line(0xFF);
1131 } else if (b < 0x80) {
1132 int amt = b;
1133 if (datalen < amt) amt = datalen;
1134 chunk_copy(amt, data);
1135 data += amt;
1136 datalen -= amt;
1137 } else {
1138 chunk_fill(0x100 - b, 0xFF);
1139 }
1140 }
1141 }
1142 chunk_finish(0xFF);
1143 }
1144
1145 animation_base::animation_base() : drawable() {}
1146
1147 void animation_base::remove_from_tile() {
1148 link_list::remove_from_list();
1149 tile = {-1, -1};
1150 }
1151
1152 void animation_base::attach_to_tile(const xy_pair& tile_pos, map_tile* node,
1153 int layer) {
1154 remove_from_tile();
1155 link_list* pList;
1156 if (flags & thdf_early_list) {
1157 pList = &node->oEarlyEntities;
1158 } else {
1159 pList = &node->entities;
1160 }
1161
1162 this->set_drawing_layer(layer);
1163 this->set_tile(tile_pos);
1164
1165 while (pList->next &&
1166 static_cast<drawable*>(pList->next)->get_drawing_layer() < layer) {
1167 pList = pList->next;
1168 }
1169
1170 prev = pList;
1171 if (pList->next != nullptr) {
1172 pList->next->prev = this;
1173 this->next = pList->next;
1174 } else {
1175 next = nullptr;
1176 }
1177 pList->next = this;
1178 }
1179
1180 void animation_base::set_layer(int iLayer, int iId) {
1181 if (0 <= iLayer && iLayer < max_number_of_layers) {
1182 layers.layer_contents[iLayer] = static_cast<uint8_t>(iId);
1183 }
1184 }
1185
1186 namespace {
1187
1188 bool are_flags_set(uint32_t val, uint32_t flags) {
1189 return (val & flags) == flags;
1190 }
1191
1192 } // namespace
1193
1194 animation::animation() { patient_effect_offset = rand(); }
1195
1196 void animation::draw(render_target* canvas, const xy_pair& draw_pos) {
1197 if (are_flags_set(flags, thdf_alpha_50 | thdf_alpha_75)) return;
1198
1199 int x = draw_pos.x + pixel_offset.x * scale_factor;
1200 int y = draw_pos.y + pixel_offset.y * scale_factor;
1201 if (sound_to_play) {
1202 sound_player* pSounds = sound_player::get_singleton();
1203 if (pSounds) pSounds->play_at(sound_to_play, x, y, 0);
1204 sound_to_play = 0;
1205 }
1206 if (manager) {
1207 if (flags & thdf_crop) {
1208 clip_rect rcNew;
1209 rcNew.y = 0;
1210 rcNew.h = canvas->get_height();
1211 rcNew.x = x + (crop_column - 1) * 32 * scale_factor;
1212 rcNew.w = 64 * scale_factor;
1213 render_target::scoped_clip clip(canvas, &rcNew);
1214 manager->draw_frame(canvas, frame_index, layers, x, y, flags,
1215 patient_effect, patient_effect_offset, scale_factor);
1216 } else
1217 manager->draw_frame(canvas, frame_index, layers, x, y, flags,
1218 patient_effect, patient_effect_offset, scale_factor);
1219 }
1220 }
1221
1222 void animation::draw_child(render_target* canvas, const xy_pair& draw_pos,
1223 bool use_primary) {
1224 if (are_flags_set(flags, thdf_alpha_50 | thdf_alpha_75)) return;
1225 if (are_flags_set(parent->flags, thdf_alpha_50 | thdf_alpha_75)) return;
1226 int x = 0, y = 0;
1227 if (use_primary)
1228 parent->get_primary_marker(&x, &y);
1229 else
1230 parent->get_secondary_marker(&x, &y);
1231
1232 x += pixel_offset.x * scale_factor + draw_pos.x;
1233 y += pixel_offset.y * scale_factor + draw_pos.y;
1234 if (sound_to_play) {
1235 sound_player* pSounds = sound_player::get_singleton();
1236 if (pSounds) pSounds->play_at(sound_to_play, x, y, 0);
1237 sound_to_play = 0;
1238 }
1239 if (manager)
1240 manager->draw_frame(canvas, frame_index, layers, x, y, flags,
1241 animation_effect::none, 0, scale_factor);
1242 }
1243
1244 bool animation::hit_test_child(const xy_pair& draw_pos,
1245 const xy_pair& obj_pos) {
1246 // TODO
1247 return false;
1248 }
1249
1250 void animation::draw_morph(render_target* canvas, const xy_pair& draw_pos) {
1251 if (are_flags_set(flags, thdf_alpha_50 | thdf_alpha_75)) return;
1252
1253 if (!manager) return;
1254
1255 int x = draw_pos.x + pixel_offset.x * scale_factor;
1256 int y = draw_pos.y + pixel_offset.y * scale_factor;
1257 if (sound_to_play) {
1258 sound_player* pSounds = sound_player::get_singleton();
1259 if (pSounds) pSounds->play_at(sound_to_play, x, y, 0);
1260 sound_to_play = 0;
1261 }
1262
1263 clip_rect oMorphRect;
1264 // We set the morph rect x and w clip to the entire canvas, so that only
1265 // vertical clipping is applied.
1266 oMorphRect.x = 0;
1267 oMorphRect.w = canvas->get_width();
1268 oMorphRect.y = y + morph_target->pixel_offset.x * scale_factor;
1269 oMorphRect.h = (morph_target->pixel_offset.y - morph_target->pixel_offset.x) *
1270 scale_factor;
1271 {
1272 render_target::scoped_clip clip(canvas, &oMorphRect);
1273 manager->draw_frame(canvas, frame_index, layers, x, y, flags,
1274 animation_effect::none, 0, scale_factor);
1275 }
1276 oMorphRect.y = y + morph_target->pixel_offset.y * scale_factor;
1277 oMorphRect.h =
1278 (morph_target->speed.x - morph_target->pixel_offset.y) * scale_factor;
1279 {
1280 render_target::scoped_clip clip(canvas, &oMorphRect);
1281 manager->draw_frame(canvas, morph_target->frame_index, morph_target->layers,
1282 x, y, morph_target->flags, animation_effect::none, 0,
1283 scale_factor);
1284 }
1285 }
1286
1287 bool animation::hit_test(const xy_pair& draw_pos, const xy_pair& obj_pos) {
1288 if (are_flags_set(flags, thdf_alpha_50 | thdf_alpha_75)) {
1289 return false;
1290 }
1291
1292 if (manager == nullptr) {
1293 return false;
1294 }
1295
1296 return manager->hit_test(frame_index, layers, pixel_offset.x + draw_pos.x,
1297 pixel_offset.y + draw_pos.y, flags, obj_pos.x,
1298 obj_pos.y);
1299 }
1300
1301 bool animation::hit_test_morph(const xy_pair& draw_pos,
1302 const xy_pair& obj_pos) {
1303 if (are_flags_set(flags, thdf_alpha_50 | thdf_alpha_75)) {
1304 return false;
1305 }
1306
1307 if (manager == nullptr) {
1308 return false;
1309 }
1310
1311 return manager->hit_test(frame_index, layers, pixel_offset.x + draw_pos.x,
1312 pixel_offset.y + draw_pos.y, flags, obj_pos.x,
1313 obj_pos.y) ||
1314 morph_target->hit_test(draw_pos, obj_pos);
1315 }
1316
1317 void animation::persist(lua_persist_writer* writer) const {
1318 lua_State* L = writer->get_stack();
1319
1320 // Write the next chained thing
1321 lua_rawgeti(L, luaT_environindex, 2);
1322 void* np = dynamic_cast<animation*>(next);
1323 if (np == nullptr) {
1324 np = dynamic_cast<sprite_render_list*>(next);
1325 }
1326 lua_pushlightuserdata(L, np);
1327 lua_rawget(L, -2);
1328 writer->fast_write_stack_object(-1);
1329 lua_pop(L, 2);
1330
1331 // Write the drawable fields
1332 writer->write_uint(flags);
1333
1334 if (anim_kind == animation_kind::normal) {
1335 writer->write_uint(1);
1336 } else if (anim_kind == animation_kind::primary_child) {
1337 writer->write_uint(2);
1338 } else if (anim_kind == animation_kind::morph) {
1339 // NB: Prior version of code used the number 3 here, and forgot
1340 // to persist the morph target.
1341 writer->write_uint(4);
1342 lua_rawgeti(L, luaT_environindex, 2);
1343 lua_pushlightuserdata(L, morph_target);
1344 lua_rawget(L, -2);
1345 writer->write_stack_object(-1);
1346 lua_pop(L, 2);
1347 } else if (anim_kind == animation_kind::secondary_child) {
1348 writer->write_uint(5);
1349 } else {
1350 writer->write_uint(0);
1351 }
1352
1353 // Write the simple fields
1354 writer->write_uint(animation_index);
1355 writer->write_uint(frame_index);
1356 writer->write_int(pixel_offset.x);
1357 writer->write_int(pixel_offset.y);
1358
1359 // Not a uint, for compatibility
1360 writer->write_int((int)sound_to_play);
1361
1362 writer->write_int(static_cast<int>(patient_effect));
1363
1364 if (flags & thdf_crop) {
1365 writer->write_int(crop_column);
1366 }
1367
1368 // Write the unioned fields
1369 if (anim_kind != animation_kind::primary_child &&
1370 anim_kind != animation_kind::secondary_child) {
1371 writer->write_int(speed.x);
1372 writer->write_int(speed.y);
1373 } else {
1374 lua_rawgeti(L, luaT_environindex, 2);
1375 lua_pushlightuserdata(L, parent);
1376 lua_rawget(L, -2);
1377 writer->write_stack_object(-1);
1378 lua_pop(L, 2);
1379 }
1380
1381 // Write the layers
1382 int iNumLayers = max_number_of_layers;
1383 for (; iNumLayers >= 1; --iNumLayers) {
1384 if (layers.layer_contents[iNumLayers - 1] != 0) break;
1385 }
1386 writer->write_uint(iNumLayers);
1387 writer->write_byte_stream(layers.layer_contents, iNumLayers);
1388 }
1389
1390 void animation::depersist(lua_persist_reader* reader) {
1391 lua_State* L = reader->get_stack();
1392
1393 do {
1394 // Read the chain
1395 if (!reader->read_stack_object()) break;
1396
1397 next = luaT_toanimationbase(L, -1);
1398 if (next) next->prev = this;
1399 lua_pop(L, 1);
1400
1401 // Read drawable fields
1402 if (!reader->read_uint(flags)) break;
1403 int iFunctionSet;
1404 if (!reader->read_uint(iFunctionSet)) break;
1405 switch (iFunctionSet) {
1406 case 3:
1407 // 3 should be the morph set, but the actual morph target is
1408 // missing, so settle for a graphical bug rather than a segfault
1409 // by reverting to the normal function set.
1410 case 1:
1411 set_animation_kind(animation_kind::normal);
1412 break;
1413 case 2:
1414 set_animation_kind(animation_kind::primary_child);
1415 break;
1416 case 4:
1417 set_animation_kind(animation_kind::morph);
1418 reader->read_stack_object();
1419 morph_target = static_cast<animation*>(lua_touserdata(L, -1));
1420 lua_pop(L, 1);
1421 break;
1422 case 5:
1423 set_animation_kind(animation_kind::secondary_child);
1424 break;
1425 default:
1426 reader->set_error(lua_pushfstring(
1427 L, "Unknown animation function set #%i", iFunctionSet));
1428 return;
1429 }
1430
1431 // Read the simple fields
1432 if (!reader->read_uint(animation_index)) break;
1433 if (!reader->read_uint(frame_index)) break;
1434 if (!reader->read_int(pixel_offset.x)) break;
1435 if (!reader->read_int(pixel_offset.y)) break;
1436 int iDummy;
1437 if (!reader->read_int(iDummy)) break;
1438 if (iDummy >= 0) sound_to_play = (unsigned int)iDummy;
1439 if (!reader->read_int(iDummy)) break;
1440 patient_effect = static_cast<animation_effect>(iDummy);
1441 if (flags & thdf_crop) {
1442 if (!reader->read_int(crop_column)) {
1443 break;
1444 }
1445 } else {
1446 crop_column = 0;
1447 }
1448
1449 // Read the unioned fields
1450 if (anim_kind != animation_kind::primary_child &&
1451 anim_kind != animation_kind::secondary_child) {
1452 if (!reader->read_int(speed.x)) break;
1453 if (!reader->read_int(speed.y)) break;
1454 } else {
1455 if (!reader->read_stack_object()) break;
1456 parent = static_cast<animation*>(lua_touserdata(L, -1));
1457 lua_pop(L, 1);
1458 }
1459
1460 // Read the layers
1461 std::memset(layers.layer_contents, 0, sizeof(layers.layer_contents));
1462 int iNumLayers;
1463 if (!reader->read_uint(iNumLayers)) {
1464 break;
1465 }
1466
1467 if (iNumLayers > max_number_of_layers) {
1468 if (!reader->read_byte_stream(layers.layer_contents,
1469 max_number_of_layers)) {
1470 break;
1471 }
1472 if (!reader->read_byte_stream(nullptr,
1473 iNumLayers - max_number_of_layers)) {
1474 break;
1475 }
1476 } else {
1477 if (!reader->read_byte_stream(layers.layer_contents, iNumLayers)) break;
1478 }
1479
1480 // Fix the m_pAnimator field
1481 luaT_getenvfield(L, 2, "animator");
1482 manager = static_cast<animation_manager*>(lua_touserdata(L, -1));
1483 lua_pop(L, 1);
1484
1485 return;
1486 } while (false);
1487
1488 reader->set_error("Cannot depersist animation instance");
1489 }
1490
1491 void animation::set_patient_effect(animation_effect patient_effect) {
1492 this->patient_effect = patient_effect;
1493 }
1494
1495 void animation::set_animation_kind(animation_kind anim_kind) {
1496 this->anim_kind = anim_kind;
1497 }
1498
1499 namespace {
1500 //! Storage of one or two sounds. If two sounds are stored, both are selected in
1501 //! 50% of the cases.
1502 struct sound_pair {
1503 sound_pair(int16_t sound) : soundA(sound), soundB(-1) {}
1504 sound_pair(int16_t soundA, int16_t soundB) : soundA(soundA), soundB(soundB) {}
1505
1506 int16_t get_sound() const {
1507 if (soundB < 0) {
1508 return soundA;
1509 } else {
1510 int value = rand();
1511 int counter = 0;
1512 for (int i = 0; i < 7; i++) {
1513 counter = counter + (value & 1);
1514 value >>= 1;
1515 }
1516 return (counter < 4) ? soundA : soundB;
1517 }
1518 }
1519
1520 private:
1521 const int16_t soundA; //!< First available sound.
1522 const int16_t soundB; //!< If non-negative, the second available sound.
1523 };
1524
1525 typedef std::map<size_t, sound_pair> sound_replacement_map;
1526
1527 // Map of frame numbers to sounds to play.
1528 const sound_replacement_map frame_sound_replacements{
1529 // Female flying to heaven (anim 3220)
1530 {6987, sound_pair(123)},
1531
1532 // Using Computer (anim 2098)
1533 {4213, sound_pair(35)},
1534 {4215, sound_pair(35)},
1535 {4224, sound_pair(35)},
1536 {4230, sound_pair(35)},
1537
1538 // Vomit sounds.
1539 {1902, sound_pair(58, 114)}, // Animation 1034
1540 {4149, sound_pair(58, 114)}, // Animation 2056
1541 {6901, sound_pair(58, 114)}, // Animation 3184
1542 {8819, sound_pair(58, 114)}, // Animation 4138
1543 {9105, sound_pair(58, 114)}, // Animation 4204
1544 {9565, sound_pair(58, 114)}, // Animation 4324
1545 {9654, sound_pair(58, 114)}, // Animation 4384
1546 {9944, sound_pair(58, 114)}, // Animation 4452
1547 {10007, sound_pair(58, 114)}, // Animation 4476
1548 {10989, sound_pair(58, 114)}, // Animation 4792
1549
1550 // Using Atom Analyser. Actually a generic animation of Researcher pushing
1551 // buttons (anim 4878)
1552 {11136, sound_pair(35)},
1553 {11138, sound_pair(35)},
1554 {11147, sound_pair(35)},
1555 {11152, sound_pair(35)},
1556 {11153, sound_pair(35)},
1557 {11154, sound_pair(35)}};
1558 } // Namespace
1559
1560 void animation::tick() {
1561 frame_index = manager->get_next_frame(frame_index);
1562 if (anim_kind != animation_kind::primary_child &&
1563 anim_kind != animation_kind::secondary_child) {
1564 pixel_offset.x += speed.x;
1565 pixel_offset.y += speed.y;
1566 }
1567
1568 if (morph_target) {
1569 morph_target->pixel_offset.y += morph_target->speed.y;
1570 if (morph_target->pixel_offset.y < morph_target->pixel_offset.x) {
1571 morph_target->pixel_offset.y = morph_target->pixel_offset.x;
1572 }
1573 }
1574
1575 // Decide sound to play.
1576 sound_replacement_map::const_iterator pos =
1577 frame_sound_replacements.find(frame_index);
1578 if (pos == frame_sound_replacements.end()) {
1579 sound_to_play = manager->get_frame_sound(frame_index);
1580 } else {
1581 sound_to_play = pos->second.get_sound();
1582 }
1583 }
1584
1585 void animation::set_parent(animation* parent_anim, bool use_primary) {
1586 remove_from_tile();
1587 if (parent_anim == nullptr) {
1588 set_animation_kind(animation_kind::normal);
1589 speed = {0, 0};
1590 } else {
1591 set_animation_kind(use_primary ? animation_kind::primary_child
1592 : animation_kind::secondary_child);
1593 parent = parent_anim;
1594 next = parent->next;
1595 if (next) next->prev = this;
1596 prev = parent;
1597 parent->next = this;
1598 }
1599 }
1600
1601 void animation::set_animation(animation_manager* mgr, size_t anim) {
1602 manager = mgr;
1603 animation_index = anim;
1604 frame_index = mgr->get_first_frame(anim);
1605
1606 if (morph_target) {
1607 morph_target = nullptr;
1608 set_animation_kind(animation_kind::normal);
1609 }
1610 }
1611
1612 bool animation::get_primary_marker(int* pX, int* pY) {
1613 if (!manager || !manager->get_frame_primary_marker(frame_index, pX, pY)) {
1614 return false;
1615 }
1616
1617 if (flags & thdf_flip_horizontal) {
1618 *pX = -*pX;
1619 }
1620
1621 *pX += pixel_offset.x;
1622 *pY += pixel_offset.y + 16;
1623 return true;
1624 }
1625
1626 bool animation::get_secondary_marker(int* pX, int* pY) {
1627 if (!manager || !manager->get_frame_secondary_marker(frame_index, pX, pY)) {
1628 return false;
1629 }
1630
1631 if (flags & thdf_flip_horizontal) {
1632 *pX = -*pX;
1633 }
1634
1635 *pX += pixel_offset.x;
1636 *pY += pixel_offset.y + 16;
1637 return true;
1638 }
1639
1640 namespace {
1641
1642 int GetAnimationDurationAndExtent(animation_manager* pManager, size_t iFrame,
1643 const ::layers& oLayers, int* pMinY,
1644 int* pMaxY, uint32_t iFlags) {
1645 int iMinY = INT_MAX;
1646 int iMaxY = INT_MIN;
1647 int iDuration = 0;
1648 size_t iCurFrame = iFrame;
1649 do {
1650 int iFrameMinY;
1651 int iFrameMaxY;
1652 pManager->get_frame_extent(iCurFrame, oLayers, nullptr, nullptr,
1653 &iFrameMinY, &iFrameMaxY, iFlags);
1654 if (iFrameMinY < iMinY) iMinY = iFrameMinY;
1655 if (iFrameMaxY > iMaxY) iMaxY = iFrameMaxY;
1656 iCurFrame = pManager->get_next_frame(iCurFrame);
1657 ++iDuration;
1658 } while (iCurFrame != iFrame);
1659
1660 if (pMinY) {
1661 *pMinY = iMinY;
1662 }
1663 if (pMaxY) {
1664 *pMaxY = iMaxY;
1665 }
1666 return iDuration;
1667 }
1668
1669 } // namespace
1670
1671 void animation::set_morph_target(animation* target, int duration) {
1672 morph_target = target;
1673 set_animation_kind(animation_kind::morph);
1674
1675 /* Morphing is the process by which two animations are combined to give a
1676 single animation of one animation turning into another. At the moment,
1677 morphing is done by having a y value, above which the original animation is
1678 rendered, and below which the new animation is rendered, and having the y
1679 value move upward a bit each frame.
1680 One example of where this is used is when transparent or invisible patients
1681 are cured at the pharmacy cabinet.
1682 The process of morphing requires four state variables, which are stored in
1683 the morph target animation:
1684 * The y value top limit - morph_target->x
1685 * The y value threshold - morph_target->y
1686 * The y value bottom limit - morph_target->speed.x
1687 * The y value increment per frame - morph_target->speed.y
1688 This obviously means that the morph target should not be ticked or rendered
1689 as it's position and speed contain other values.
1690 */
1691
1692 int iOrigMinY, iOrigMaxY;
1693 int iMorphMinY, iMorphMaxY;
1694
1695 int iOriginalDuration = GetAnimationDurationAndExtent(
1696 manager, frame_index, layers, &iOrigMinY, &iOrigMaxY, flags);
1697 int iMorphDuration = GetAnimationDurationAndExtent(
1698 morph_target->manager, morph_target->frame_index, morph_target->layers,
1699 &iMorphMinY, &iMorphMaxY, morph_target->flags);
1700 if (iMorphDuration > iOriginalDuration) {
1701 iMorphDuration = iOriginalDuration;
1702 }
1703
1704 iMorphDuration *= duration;
1705 if (iOrigMinY < iMorphMinY) {
1706 morph_target->pixel_offset.x = iOrigMinY;
1707 } else {
1708 morph_target->pixel_offset.x = iMorphMinY;
1709 }
1710
1711 if (iOrigMaxY > iMorphMaxY) {
1712 morph_target->speed.x = iOrigMaxY;
1713 } else {
1714 morph_target->speed.x = iMorphMaxY;
1715 }
1716
1717 int iDist = morph_target->pixel_offset.x - morph_target->speed.x;
1718 morph_target->speed.y = (iDist - iMorphDuration + 1) / iMorphDuration;
1719 morph_target->pixel_offset.y = morph_target->speed.x;
1720 }
1721
1722 void animation::set_frame(size_t new_frame) { frame_index = new_frame; }
1723
1724 void sprite_render_list::tick() {
1725 pixel_offset.x += dx_per_tick;
1726 pixel_offset.y += dy_per_tick;
1727 if (lifetime > 0) {
1728 --lifetime;
1729 }
1730 }
1731
1732 void sprite_render_list::draw(render_target* canvas, const xy_pair& draw_pos) {
1733 if (!sheet || sprites.empty()) {
1734 return;
1735 }
1736
1737 int x = draw_pos.x + pixel_offset.x * scale_factor;
1738 int y = draw_pos.y + pixel_offset.y * scale_factor;
1739
1740 std::unique_ptr<render_target::scoped_buffer> intermediate_buffer;
1741 if (use_intermediate_buffer) {
1742 int minX = INT_MAX, minY = INT_MAX, maxX = INT_MIN, maxY = INT_MIN;
1743 for (const sprite& pSprite : sprites) {
1744 int spriteX = x + pSprite.x * scale_factor;
1745 int spriteY = y + pSprite.y * scale_factor;
1746 int spriteWidth, spriteHeight;
1747 sheet->get_sprite_size_unchecked(pSprite.index, &spriteWidth,
1748 &spriteHeight);
1749 minX = std::min(minX, spriteX);
1750 minY = std::min(minY, spriteY);
1751 maxX = std::max(maxX, spriteX + spriteWidth * scale_factor);
1752 maxY = std::max(maxY, spriteY + spriteHeight * scale_factor);
1753 }
1754 intermediate_buffer = canvas->begin_intermediate_drawing(
1755 minX, minY, maxX - minX, maxY - minY);
1756 }
1757
1758 for (const sprite& pSprite : sprites) {
1759 sheet->draw_sprite(canvas, pSprite.index, x + pSprite.x * scale_factor,
1760 y + pSprite.y * scale_factor, flags, 0,
1761 animation_effect::none, scale_factor);
1762 }
1763 }
1764
1765 bool sprite_render_list::hit_test(const xy_pair& draw_pos,
1766 const xy_pair& obj_pos) {
1767 // TODO
1768 return false;
1769 }
1770
1771 void sprite_render_list::set_lifetime(int life_time) {
1772 if (life_time < 0) {
1773 life_time = -1;
1774 }
1775 lifetime = life_time;
1776 }
1777
1778 void sprite_render_list::set_use_intermediate_buffer() {
1779 use_intermediate_buffer = true;
1780 }
1781
1782 void sprite_render_list::append_sprite(size_t spr_num, int xpos, int ypos) {
1783 sprite s{spr_num, xpos, ypos};
1784 sprites.push_back(s);
1785 }
1786
1787 void sprite_render_list::persist(lua_persist_writer* writer) const {
1788 lua_State* L = writer->get_stack();
1789
1790 writer->write_uint(sprites.size());
1791 writer->write_uint(flags);
1792 writer->write_int(pixel_offset.x);
1793 writer->write_int(pixel_offset.y);
1794 writer->write_int(dx_per_tick);
1795 writer->write_int(dy_per_tick);
1796 writer->write_int(lifetime);
1797
1798 for (const sprite& pSprite : sprites) {
1799 writer->write_uint(pSprite.index);
1800 writer->write_int(pSprite.x);
1801 writer->write_int(pSprite.y);
1802 }
1803
1804 // Write the layers
1805 int iNumLayers = max_number_of_layers;
1806 for (; iNumLayers >= 1; --iNumLayers) {
1807 if (layers.layer_contents[iNumLayers - 1] != 0) {
1808 break;
1809 }
1810 }
1811 writer->write_uint(iNumLayers);
1812 writer->write_byte_stream(layers.layer_contents, iNumLayers);
1813
1814 // Write the next chained thing
1815 lua_rawgeti(L, luaT_environindex, 2);
1816 void* np = dynamic_cast<animation*>(next);
1817 if (np == nullptr) {
1818 np = dynamic_cast<sprite_render_list*>(next);
1819 }
1820 lua_pushlightuserdata(L, np);
1821 lua_rawget(L, -2);
1822 writer->fast_write_stack_object(-1);
1823 lua_pop(L, 2);
1824 }
1825
1826 void sprite_render_list::depersist(lua_persist_reader* reader) {
1827 lua_State* L = reader->get_stack();
1828
1829 uint32_t sprite_count;
1830 if (!reader->read_uint(sprite_count)) return;
1831 sprites.resize(sprite_count);
1832
1833 if (!reader->read_uint(flags)) return;
1834 if (!reader->read_int(pixel_offset.x)) return;
1835 if (!reader->read_int(pixel_offset.y)) return;
1836 if (!reader->read_int(dx_per_tick)) return;
1837 if (!reader->read_int(dy_per_tick)) return;
1838 if (!reader->read_int(lifetime)) return;
1839 for (sprite& pSprite : sprites) {
1840 if (!reader->read_uint(pSprite.index)) return;
1841 if (!reader->read_int(pSprite.x)) return;
1842 if (!reader->read_int(pSprite.y)) return;
1843 }
1844
1845 // Read the layers
1846 std::memset(layers.layer_contents, 0, sizeof(layers.layer_contents));
1847 int iNumLayers;
1848 if (!reader->read_uint(iNumLayers)) {
1849 return;
1850 }
1851
1852 if (iNumLayers > max_number_of_layers) {
1853 if (!reader->read_byte_stream(layers.layer_contents,
1854 max_number_of_layers)) {
1855 return;
1856 }
1857
1858 if (!reader->read_byte_stream(nullptr, iNumLayers - max_number_of_layers)) {
1859 return;
1860 }
1861 } else {
1862 if (!reader->read_byte_stream(layers.layer_contents, iNumLayers)) {
1863 return;
1864 }
1865 }
1866
1867 // Read the chain
1868 if (!reader->read_stack_object()) {
1869 return;
1870 }
1871
1872 next = luaT_toanimationbase(L, -1);
1873 if (next) {
1874 next->prev = this;
1875 }
1876 lua_pop(L, 1);
1877
1878 // Fix the sheet field
1879 luaT_getenvfield(L, 2, "sheet");
1880 sheet = static_cast<sprite_sheet*>(lua_touserdata(L, -1));
1881 lua_pop(L, 1);
1882 }