Debian Codegraph @

similar/main/morph.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Morphing code
23 *
24 */
25
26 #include "dxxsconf.h"
27 #include <algorithm>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <ranges>
32
33 #include "dxxerror.h"
34 #include "inferno.h"
35 #include "polyobj.h"
36 #include "game.h"
37 #include "lighting.h"
38 #include "newdemo.h"
39 #include "piggy.h"
40 #include "bm.h"
41 #include "interp.h"
42 #include "render.h"
43
44 #include "compiler-poison.h"
45 #include "compiler-range_for.h"
46 #include "d_enumerate.h"
47 #include "d_levelstate.h"
48 #include "d_range.h"
49 #include "d_zip.h"
50 #include "partial_range.h"
51
52 #if !DXX_USE_OGL
53 #include "texmap.h"
54 #endif
55
56 using std::max;
57
58 namespace dcx {
59
60 namespace {
61
62 constexpr vms_vector morph_rotvel{0x4000,0x2000,0x1000};
63
64 class invalid_morph_model_type : public std::runtime_error
65 {
66 dxx_compiler_attribute_cold
67 static std::string prepare_message(const unsigned type)
68 {
69 std::array<char, 32 + sizeof("4294967295")> buf;
70 const auto bufdata{std::data(buf)};
71 const auto bufsize{std::size(buf)};
72 const auto written{std::snprintf(bufdata, bufsize, "invalid morph model type: %u", type)};
73 return std::string{bufdata, written < 0 ? std::size_t{0} : std::min(bufsize, static_cast<std::size_t>(written))};
74 }
75 public:
76 invalid_morph_model_type(const unsigned type) :
77 runtime_error(prepare_message(type))
78 {
79 }
80 };
81
82 class invalid_morph_model_vertex_count : public std::runtime_error
83 {
84 dxx_compiler_attribute_cold
85 static std::string prepare_message(const unsigned count, const polygon_model_index idx, const unsigned submodel_num)
86 {
87 std::array<char, 68 + 3 * sizeof("4294967295")> buf;
88 const unsigned uidx{underlying_value(idx)};
89 const auto bufdata{std::data(buf)};
90 const auto bufsize{std::size(buf)};
91 const auto written{std::snprintf(bufdata, bufsize, "too many vertices in morph model: found %u in model %u, submodel %u", count, uidx, submodel_num)};
92 return std::string{bufdata, written < 0 ? std::size_t{0} : std::min(bufsize, static_cast<std::size_t>(written))};
93 }
94 public:
95 invalid_morph_model_vertex_count(const unsigned count, const polygon_model_index idx, const unsigned submodel_num) :
96 runtime_error(prepare_message(count, idx, submodel_num))
97 {
98 }
99 };
100
101 struct submodel_data
102 {
103 const uint16_t *body;
104 const unsigned type;
105 const unsigned nverts;
106 const unsigned startpoint;
107 };
108
109 submodel_data parse_model_data_header(const polymodel &pm, const unsigned submodel_num)
110 {
111 auto data{reinterpret_cast<const uint16_t *>(&pm.model_data[pm.submodel_ptrs[submodel_num]])};
112 const auto ptype{data++};
113 const uint16_t type{*ptype};
114 const auto pnverts{data++};
115
116 const uint16_t startpoint{(type == 7)
117 ? *std::exchange(data, data + 2) //get start point number, skip pad
118 : (type == 1)
119 ? uint16_t{0} //start at zero
120 : throw invalid_morph_model_type(type)
121 };
122 const uint16_t nverts{*pnverts};
123 return {data, type, nverts, startpoint};
124 }
125
126 std::size_t count_submodel_points(const polymodel &pm, const polygon_model_index model_idx, const unsigned submodel_num)
127 {
128 /* Return the minimum array size that will not cause this submodel
129 * to index past the end of the array.
130 */
131 const auto &&sd{parse_model_data_header(pm, submodel_num)};
132 const std::size_t count{sd.startpoint + sd.nverts};
133 if (count > morph_data::MAX_VECS)
134 throw invalid_morph_model_vertex_count(count, model_idx, submodel_num);
135 return count;
136 }
137
138 std::size_t count_model_points(const polymodel &pm, const polygon_model_index model_idx)
139 {
140 /* Return the minimum array size that will not cause any used
141 * submodel of this model to index past the end of the array.
142 *
143 * Unused submodels are not considered. A submodel is used if:
144 * - its index is not above pm.n_models
145 * - its parent index is valid
146 * - its parent index is a used submodel
147 *
148 * Submodel 0 is always used.
149 */
150 auto count{count_submodel_points(pm, model_idx, 0)};
151 unsigned visited_submodels{1};
152 const unsigned mask_all_enabled_models{(1u << pm.n_models) - 1};
153 for (const auto &&submodel_parents{enumerate(partial_range(pm.submodel_parents, pm.n_models))};;)
154 {
155 if (visited_submodels == mask_all_enabled_models)
156 /* Every submodel has been checked, so the next pass through
157 * the loop will ignore every element. Break out early to
158 * avoid the extra iteration.
159 */
160 break;
161 const auto previous_visited_submodels{visited_submodels};
162 for (const auto &&[idx, value] : submodel_parents)
163 {
164 const unsigned mask_this_submodel{1u << idx};
165 if (mask_this_submodel & visited_submodels)
166 /* Already tested on a prior iteration */
167 continue;
168 if (value >= pm.submodel_parents.size())
169 /* Ignore submodels with out-of-range parents. This
170 * avoids undefined behavior in the shift, since some
171 * submodels have a parent of 0xff.
172 */
173 continue;
174 const unsigned mask_parent_submodel{1u << value};
175 if (mask_parent_submodel & visited_submodels)
176 {
177 visited_submodels |= mask_this_submodel;
178 /* Parent is in use, so this submodel is also in use. */
179 const auto subcount{count_submodel_points(pm, model_idx, idx)};
180 count = std::max(count, subcount);
181 }
182 }
183 if (previous_visited_submodels == visited_submodels)
184 /* No changes on the most recent pass, so no changes will
185 * occur on any subsequent pass. Break out.
186 */
187 break;
188 }
189 return count;
190 }
191
192 }
193
194 void *morph_data::operator new(std::size_t, const max_vectors max_vecs)
195 {
196 return ::operator new(sizeof(morph_data) + (underlying_value(max_vecs) * (sizeof(fix) + sizeof(vms_vector) + sizeof(vms_vector))));
197 }
198
199 morph_data::ptr morph_data::create(object_base &o, const polymodel &pm, const polygon_model_index model_idx)
200 {
201 const max_vectors m{count_model_points(pm, model_idx)};
202 /* This is an unusual form of `new` overload. Although arguments to
203 * `new` are typically considered a use of `placement new`, this is
204 * not used to place the object. Instead, it is used to pass extra
205 * information to `operator new` so that the count of allocated
206 * bytes can be adjusted.
207 */
208 return ptr(new(m) morph_data(o, m));
209 }
210
211 morph_data::morph_data(object_base &o, const max_vectors m) :
212 obj(&o), Morph_sig(o.signature), max_vecs(m)
213 {
214 DXX_POISON_VAR(submodel_active, 0xcc);
215 const auto morph_times{get_morph_times()};
216 DXX_POISON_MEMORY(morph_times, 0xcc);
217 const auto morph_vecs{get_morph_times()};
218 DXX_POISON_MEMORY(morph_vecs, 0xcc);
219 const auto morph_deltas{get_morph_times()};
220 DXX_POISON_MEMORY(morph_deltas, 0xcc);
221 DXX_POISON_VAR(n_morphing_points, 0xcc);
222 DXX_POISON_VAR(submodel_startpoints, 0xcc);
223 }
224
225 std::span<fix> morph_data::get_morph_times()
226 {
227 return {reinterpret_cast<fix *>(this + 1), {underlying_value(max_vecs)}};
228 }
229
230 std::span<vms_vector> morph_data::get_morph_vecs()
231 {
232 const auto t{get_morph_times()};
233 return {reinterpret_cast<vms_vector *>(t.data() + t.size()), {underlying_value(max_vecs)}};
234 }
235
236 std::span<vms_vector> morph_data::get_morph_deltas()
237 {
238 const auto v{get_morph_vecs()};
239 return {v.data() + v.size(), {underlying_value(max_vecs)}};
240 }
241
242 d_level_unique_morph_object_state::~d_level_unique_morph_object_state() = default;
243
244 //returns ptr to data for this object, or NULL if none
245 morph_data::ptr *find_morph_data(d_level_unique_morph_object_state &LevelUniqueMorphObjectState, object_base &obj)
246 {
247 auto &morph_objects = LevelUniqueMorphObjectState.morph_objects;
248 if (Newdemo_state == ND_STATE_PLAYBACK) {
249 return nullptr;
250 }
251
252 range_for (auto &i, morph_objects)
253 if (i && i->obj == &obj)
254 return &i;
255 return nullptr;
256 }
257
258 namespace {
259
260 static void assign_max(fix &a, const fix &b)
261 {
262 a = std::max(a, b);
263 }
264
265 static void assign_min(fix &a, const fix &b)
266 {
267 a = std::min(a, b);
268 }
269
270 static void update_bounds(std::ranges::min_max_result<vms_vector> &minmaxv, const vms_vector &v, fix vms_vector::*const p)
271 {
272 assign_max(minmaxv.max.*p, v.*p);
273 assign_min(minmaxv.min.*p, v.*p);
274 }
275
276 /* Take a `polymodel` as input. Return both the minimum and maximum extents of
277 * the `vms_vector` members that make up the `polymodel`.
278 */
279 [[nodiscard]]
280 static std::ranges::min_max_result<vms_vector> find_min_max(const polymodel &pm, const unsigned submodel_num)
281 {
282 const auto &&sd{parse_model_data_header(pm, submodel_num)};
283 std::ranges::min_max_result<vms_vector> result{};
284 const auto nverts{sd.nverts};
285 if (!nverts)
286 {
287 [[unlikely]];
288 return result;
289 }
290 const auto vp{reinterpret_cast<const vms_vector *>(sd.body)};
291
292 result = {
293 .min = *vp,
294 .max = *vp
295 };
296
297 for (auto &v : std::span(vp, nverts).template subspan<1>())
298 {
299 update_bounds(result, v, &vms_vector::x);
300 update_bounds(result, v, &vms_vector::y);
301 update_bounds(result, v, &vms_vector::z);
302 }
303 return result;
304 }
305
306 constexpr fix morph_rate{F1_0 * 3};
307 constexpr fix indeterminate_box_extent{INT32_MAX};
308
309 static fix update_bounding_box_extent(const vms_vector &vp, const vms_vector &box_size, fix vms_vector::*const p, const fix entry_extent)
310 {
311 if (!(vp.*p))
312 return entry_extent;
313 const auto box_size_p{box_size.*p};
314 const auto abs_vp_p{abs(vp.*p)};
315 if (f2i(box_size_p) >= abs_vp_p / 2)
316 return entry_extent;
317 return std::min(entry_extent, fixdiv(box_size_p, abs_vp_p));
318 }
319
320 static fix compute_bounding_box_extents(const vms_vector &vp, const vms_vector *const box_size)
321 {
322 return box_size
323 ? update_bounding_box_extent(
324 vp, *box_size, &vms_vector::z,
325 update_bounding_box_extent(
326 vp, *box_size, &vms_vector::y,
327 update_bounding_box_extent(
328 vp, *box_size, &vms_vector::x, indeterminate_box_extent
329 )
330 )
331 )
332 : indeterminate_box_extent;
333 }
334
335 static void init_points(const polymodel &pm, const vms_vector *const box_size, const unsigned submodel_num, morph_data *const md)
336 {
337 const auto &&sd{parse_model_data_header(pm, submodel_num)};
338 const unsigned startpoint{sd.startpoint};
339 const unsigned endpoint{sd.startpoint + sd.nverts};
340
341 md->submodel_active[submodel_num] = morph_data::submodel_state::animating;
342 md->n_morphing_points[submodel_num] = 0;
343 md->submodel_startpoints[submodel_num] = startpoint;
344
345 for (auto &&[vp, morph_vec, morph_delta, morph_time] : zip(
346 unchecked_partial_range(reinterpret_cast<const vms_vector *>(sd.body), sd.nverts),
347 partial_range(md->get_morph_vecs(), startpoint, endpoint),
348 partial_range(md->get_morph_deltas(), startpoint, endpoint),
349 partial_range(md->get_morph_times(), startpoint, endpoint)
350 ))
351 {
352 if (const fix k{compute_bounding_box_extents(vp, box_size)}; k != indeterminate_box_extent)
353 morph_vec = vm_vec_copy_scale(vp, k);
354 else
355 morph_vec = {};
356
357 const auto dist{vm_vec_normalized_dir_quick(morph_delta, vp, morph_vec)};
358 morph_time = fixdiv(dist, morph_rate);
359
360 if (morph_time != 0)
361 md->n_morphing_points[submodel_num]++;
362
363 vm_vec_scale(morph_delta, morph_rate);
364 }
365 }
366
367 static void update_points(const polymodel &pm, const unsigned submodel_num, morph_data *const md)
368 {
369 const auto &&sd{parse_model_data_header(pm, submodel_num)};
370 const unsigned startpoint{sd.startpoint};
371 const unsigned endpoint{startpoint + sd.nverts};
372
373 for (auto &&[vp, morph_vec, morph_delta, morph_time] : zip(
374 unchecked_partial_range(reinterpret_cast<const vms_vector *>(sd.body), sd.nverts),
375 partial_range(md->get_morph_vecs(), startpoint, endpoint),
376 partial_range(md->get_morph_deltas(), startpoint, endpoint),
377 partial_range(md->get_morph_times(), startpoint, endpoint)
378 ))
379 {
380 if (morph_time) //not done yet
381 {
382 if ((morph_time -= FrameTime) <= 0) {
383 morph_vec = vp;
384 morph_time = 0;
385 md->n_morphing_points[submodel_num]--;
386 }
387 else
388 vm_vec_scale_add2(morph_vec, morph_delta, FrameTime);
389 }
390 }
391 }
392
393 }
394
395 }
396
397 namespace dsx {
398
399 //process the morphing object for one frame
400 void do_morph_frame(object &obj)
401 {
402 auto &LevelUniqueMorphObjectState{LevelUniqueObjectState.MorphObjectState};
403 const auto umd{find_morph_data(LevelUniqueMorphObjectState, obj)};
404
405 if (!umd) { //maybe loaded half-morphed from disk
406 obj.flags |= OF_SHOULD_BE_DEAD; //..so kill it
407 return;
408 }
409 const auto md{umd->get()};
410 assert(md->obj == &obj);
411
412 auto &Polygon_models{LevelSharedPolygonModelState.Polygon_models};
413 const polymodel &pm{Polygon_models[obj.rtype.pobj_info.model_num]};
414
415 const auto n_models{pm.n_models};
416 for (auto &&[i, submodel_active, n_morphing_points] : enumerate(zip(unchecked_partial_range(md->submodel_active, n_models), md->n_morphing_points)))
417 {
418 if (submodel_active == morph_data::submodel_state::animating)
419 {
420 update_points(pm,i,md);
421 if (n_morphing_points == 0) { //maybe start submodel
422 submodel_active = morph_data::submodel_state::visible; //not animating, just visible
423 md->n_submodels_active--; //this one done animating
424 for (auto &&[t, submodel_parents] : enumerate(unchecked_partial_range(pm.submodel_parents, n_models)))
425 {
426 if (submodel_parents == i)
427 { //start this one
428 init_points(pm,nullptr,t,md);
429 md->n_submodels_active++;
430 }
431 }
432 }
433 }
434 }
435
436 if (!md->n_submodels_active) { //done morphing!
437
438 obj.control_source = md->morph_save_control_type;
439 obj.movement_source = md->morph_save_movement_type;
440 obj.render_type = render_type::RT_POLYOBJ;
441
442 obj.mtype.phys_info = md->morph_save_phys_info;
443 umd->reset();
444 }
445 }
446
447 void init_morphs(d_level_unique_morph_object_state &LevelUniqueMorphObjectState)
448 {
449 auto &morph_objects{LevelUniqueMorphObjectState.morph_objects};
450 morph_objects = {};
451 }
452
453 //make the object morph
454 void morph_start(d_level_unique_morph_object_state &LevelUniqueMorphObjectState, d_level_shared_polygon_model_state &LevelSharedPolygonModelState, object_base &obj)
455 {
456 auto &morph_objects{LevelUniqueMorphObjectState.morph_objects};
457 const auto mob{morph_objects.begin()};
458 const auto moe{morph_objects.end()};
459 const auto mop{[](const morph_data::ptr &pmo) {
460 if (!pmo)
461 return true;
462 auto &mo{*pmo.get()};
463 return mo.obj->type == OBJ_NONE || mo.obj->signature != mo.Morph_sig;
464 }};
465 const auto moi{std::ranges::find_if(mob, moe, mop)};
466
467 if (moi == moe) //no free slots
468 return;
469
470 auto &Polygon_models{LevelSharedPolygonModelState.Polygon_models};
471 const auto pmi{obj.rtype.pobj_info.model_num};
472 auto &pm{Polygon_models[pmi]};
473
474 *moi = morph_data::create(obj, pm, pmi);
475 morph_data *const md{moi->get()};
476
477 assert(obj.render_type == render_type::RT_POLYOBJ);
478
479 md->morph_save_control_type = obj.control_source;
480 md->morph_save_movement_type = obj.movement_source;
481 md->morph_save_phys_info = obj.mtype.phys_info;
482
483 assert(obj.control_source == object::control_type::ai); //morph objects are also AI objects
484
485 obj.control_source = object::control_type::morph;
486 obj.render_type = render_type::RT_MORPH;
487 obj.movement_source = object::movement_type::physics; //RT_NONE;
488
489 obj.mtype.phys_info.rotvel = morph_rotvel;
490
491 const auto &&[pmmin, pmmax] = find_min_max(pm, 0);
492
493 const vms_vector box_size{
494 .x = max(-pmmin.x, pmmax.x) / 2,
495 .y = max(-pmmin.y, pmmax.y) / 2,
496 .z = max(-pmmin.z, pmmax.z) / 2
497 };
498
499 //clear all points
500 const auto morph_times{md->get_morph_times()};
501 std::fill(morph_times.begin(), morph_times.end(), fix{});
502 //clear all parts
503 md->submodel_active = {};
504
505 md->n_submodels_active = 1;
506
507 //now, project points onto surface of box
508
509 init_points(pm,&box_size,0,md);
510 }
511
512 }
513
514 namespace {
515
516 static void draw_model(grs_canvas &canvas, polygon_model_points &robot_points, polymodel *const pm, const unsigned submodel_num, const submodel_angles anim_angles, g3s_lrgb light, morph_data *const md)
517 {
518 std::array<unsigned, MAX_SUBMODELS> sort_list;
519 //first, sort the submodels
520 sort_list[0] = submodel_num;
521 unsigned sort_n{1};
522
523 const uint_fast32_t n_models{pm->n_models};
524 range_for (const uint_fast32_t i, xrange(n_models))
525 if (md->submodel_active[i] != morph_data::submodel_state::invisible && pm->submodel_parents[i] == submodel_num)
526 {
527 const auto facing{g3_check_normal_facing(pm->submodel_pnts[i],pm->submodel_norms[i])};
528 if (!facing)
529 sort_list[sort_n] = i;
530 else { //put at start
531 const auto b{sort_list.begin()};
532 const auto e{std::next(b, sort_n)};
533 std::move_backward(b, e, std::next(e));
534 sort_list[0] = i;
535 }
536 ++sort_n;
537 }
538
539 //now draw everything
540
541 range_for (const auto mn, partial_const_range(sort_list, sort_n))
542 {
543 if (mn == submodel_num) {
544 std::array<bitmap_index, MAX_POLYOBJ_TEXTURES> texture_list_index;
545 std::array<grs_bitmap *, MAX_POLYOBJ_TEXTURES> texture_list;
546 for (unsigned i{0}; i < pm->n_textures; ++i)
547 {
548 const auto ptr{ObjBitmapPtrs[pm->first_texture + i]};
549 const auto &bmp{ObjBitmaps[ptr]};
550 texture_list_index[i] = bmp;
551 texture_list[i] = &GameBitmaps[bmp];
552 }
553
554 // Make sure the textures for this object are paged in...
555 range_for (auto &j, partial_const_range(texture_list_index, pm->n_textures))
556 PIGGY_PAGE_IN(j);
557 // Hmmm... cache got flushed in the middle of paging all these in,
558 // so we need to reread them all in.
559 // Make sure that they can all fit in memory.
560 const auto morph_vecs{md->get_morph_vecs()};
561 g3_draw_morphing_model(canvas, draw_tmap, &pm->model_data[pm->submodel_ptrs[submodel_num]], texture_list.data(), anim_angles, light, &morph_vecs[md->submodel_startpoints[submodel_num]], robot_points);
562 }
563 else {
564 const auto &&orient{vm_angles_2_matrix(anim_angles[mn])};
565 auto &&ctx{g3_start_instance_matrix(pm->submodel_offsets[mn], orient)};
566 draw_model(canvas, robot_points,pm,mn,anim_angles,light,md);
567 g3_done_instance(ctx);
568 }
569 }
570
571 }
572
573 }
574
575 namespace dsx {
576
577 void draw_morph_object(grs_canvas &canvas, const d_level_unique_light_state &LevelUniqueLightState, const vmobjptridx_t obj)
578 {
579 if (Newdemo_state == ND_STATE_PLAYBACK)
580 return;
581
582 auto &LevelUniqueMorphObjectState{LevelUniqueObjectState.MorphObjectState};
583 const auto umd{find_morph_data(LevelUniqueMorphObjectState, obj)};
584 if (!umd)
585 throw std::runtime_error("missing morph data");
586 const auto md{umd->get()};
587
588 auto &Polygon_models{LevelSharedPolygonModelState.Polygon_models};
589 polymodel *const po{&Polygon_models[obj->rtype.pobj_info.model_num]};
590
591 const auto light{compute_object_light(LevelUniqueLightState, obj)};
592
593 {
594 auto &&ctx{g3_start_instance_matrix(obj->pos, obj->orient)};
595 polygon_model_points robot_points;
596 draw_model(canvas, robot_points, po, 0, obj->rtype.pobj_info.anim_angles, light, md);
597 g3_done_instance(ctx);
598 }
599
600 if (Newdemo_state == ND_STATE_RECORDING)
601 newdemo_record_morph_frame(obj);
602 }
603
604 }