OSDN Git Service

[Implement] ウサウサストライカー召喚処理を追加
[hengbandforosx/hengbandosx.git] / src / grid / grid.cpp
1 /*!
2  * @brief グリッドの実装 / low level dungeon routines -BEN-
3  * @date 2013/12/30
4  * @author
5  * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke\n
6  *\n
7  * This software may be copied and distributed for educational, research,\n
8  * and not for profit purposes provided that this copyright and statement\n
9  * are included in all such copies.  Other copyrights may also apply.\n
10  * \n
11  * Support for Adam Bolt's tileset, lighting and transparency effects\n
12  * by Robert Ruehlmann (rr9@angband.org)\n
13  * \n
14  * 2013 Deskull Doxygen向けのコメント整理\n
15  */
16
17 #include "grid/grid.h"
18 #include "core/window-redrawer.h"
19 #include "dungeon/dungeon-flag-types.h"
20 #include "dungeon/quest.h"
21 #include "effect/attribute-types.h"
22 #include "effect/effect-characteristics.h"
23 #include "effect/effect-processor.h"
24 #include "floor/cave.h"
25 #include "floor/floor-generator.h"
26 #include "floor/geometry.h"
27 #include "game-option/game-play-options.h"
28 #include "game-option/map-screen-options.h"
29 #include "game-option/special-options.h"
30 #include "grid/feature-action-flags.h"
31 #include "grid/feature.h"
32 #include "grid/object-placer.h"
33 #include "grid/trap.h"
34 #include "io/screen-util.h"
35 #include "monster-floor/monster-remover.h"
36 #include "monster-race/monster-race.h"
37 #include "monster-race/race-flags2.h"
38 #include "monster-race/race-flags7.h"
39 #include "monster/monster-info.h"
40 #include "monster/monster-status.h"
41 #include "monster/monster-update.h"
42 #include "object/item-tester-hooker.h"
43 #include "object/object-mark-types.h"
44 #include "player-info/class-info.h"
45 #include "player/player-status-flags.h"
46 #include "player/player-status.h"
47 #include "room/rooms-builder.h"
48 #include "system/dungeon-info.h"
49 #include "system/floor-type-definition.h"
50 #include "system/grid-type-definition.h"
51 #include "system/item-entity.h"
52 #include "system/monster-entity.h"
53 #include "system/monster-race-info.h"
54 #include "system/player-type-definition.h"
55 #include "system/redrawing-flags-updater.h"
56 #include "system/terrain-type-definition.h"
57 #include "term/gameterm.h"
58 #include "term/term-color-types.h"
59 #include "timed-effect/player-blindness.h"
60 #include "timed-effect/timed-effects.h"
61 #include "util/bit-flags-calculator.h"
62 #include "util/enum-converter.h"
63 #include "util/point-2d.h"
64 #include "view/display-map.h"
65 #include "view/display-messages.h"
66 #include "window/main-window-util.h"
67 #include "world/world.h"
68 #include <queue>
69
70 /*!
71  * @brief 新規フロアに入りたてのプレイヤーをランダムな場所に配置する / Returns random co-ordinates for player/monster/object
72  * @param player_ptr プレイヤーへの参照ポインタ
73  * @return 配置に成功したらTRUEを返す
74  */
75 bool new_player_spot(PlayerType *player_ptr)
76 {
77     auto max_attempts = 10000;
78     auto y = 0;
79     auto x = 0;
80     auto &floor = *player_ptr->current_floor_ptr;
81     while (max_attempts--) {
82         /* Pick a legal spot */
83         y = (POSITION)rand_range(1, floor.height - 2);
84         x = (POSITION)rand_range(1, floor.width - 2);
85
86         const auto &grid = player_ptr->current_floor_ptr->get_grid({ y, x });
87
88         /* Must be a "naked" floor grid */
89         if (grid.m_idx) {
90             continue;
91         }
92         if (floor.is_in_dungeon()) {
93             const auto &terrain = grid.get_terrain();
94
95             if (max_attempts > 5000) /* Rule 1 */
96             {
97                 if (terrain.flags.has_not(TerrainCharacteristics::FLOOR)) {
98                     continue;
99                 }
100             } else /* Rule 2 */
101             {
102                 if (terrain.flags.has_not(TerrainCharacteristics::MOVE)) {
103                     continue;
104                 }
105                 if (terrain.flags.has(TerrainCharacteristics::HIT_TRAP)) {
106                     continue;
107                 }
108             }
109
110             /* Refuse to start on anti-teleport grids in dungeon */
111             if (terrain.flags.has_not(TerrainCharacteristics::TELEPORTABLE)) {
112                 continue;
113             }
114         }
115         if (!player_can_enter(player_ptr, grid.feat, 0)) {
116             continue;
117         }
118         if (!in_bounds(&floor, y, x)) {
119             continue;
120         }
121
122         /* Refuse to start on anti-teleport grids */
123         if (grid.is_icky()) {
124             continue;
125         }
126
127         break;
128     }
129
130     if (max_attempts < 1) { /* Should be -1, actually if we failed... */
131         return false;
132     }
133
134     /* Save the new player grid */
135     player_ptr->y = y;
136     player_ptr->x = x;
137
138     return true;
139 }
140
141 /*!
142  * @brief マスに隠されたドアがあるかの判定を行う。 / Return TRUE if the given grid is a hidden closed door
143  * @param player_ptr プレイヤーへの参照ポインタ
144  * @param grid マス構造体の参照ポインタ
145  * @return 隠されたドアがあるならTRUEを返す。
146  */
147 bool is_hidden_door(PlayerType *player_ptr, const Grid &grid)
148 {
149     return (grid.mimic || grid.cave_has_flag(TerrainCharacteristics::SECRET)) && is_closed_door(player_ptr, grid.feat);
150 }
151
152 /*!
153  * @brief 指定された座標のマスが現在照らされているかを返す。 / Check for "local" illumination
154  * @param y y座標
155  * @param x x座標
156  * @return 指定された座標に照明がかかっているならTRUEを返す。。
157  */
158 bool check_local_illumination(PlayerType *player_ptr, POSITION y, POSITION x)
159 {
160     const auto yy = (y < player_ptr->y) ? (y + 1) : (y > player_ptr->y) ? (y - 1)
161                                                                         : y;
162     const auto xx = (x < player_ptr->x) ? (x + 1) : (x > player_ptr->x) ? (x - 1)
163                                                                         : x;
164     const auto *floor_ptr = player_ptr->current_floor_ptr;
165     const auto &grid_yyxx = floor_ptr->grid_array[yy][xx];
166     const auto &grid_yxx = floor_ptr->grid_array[y][xx];
167     const auto &grid_yyx = floor_ptr->grid_array[yy][x];
168     auto is_illuminated = feat_supports_los(grid_yyxx.get_feat_mimic()) && (grid_yyxx.info & CAVE_GLOW);
169     is_illuminated |= feat_supports_los(grid_yxx.get_feat_mimic()) && (grid_yxx.info & CAVE_GLOW);
170     is_illuminated |= feat_supports_los(grid_yyx.get_feat_mimic()) && (grid_yyx.info & CAVE_GLOW);
171     return is_illuminated;
172 }
173
174 /*!
175  * @brief 対象座標のマスの照明状態を更新する
176  * @param player_ptr プレイヤーへの参照ポインタ
177  * @param y 更新したいマスのY座標
178  * @param x 更新したいマスのX座標
179  */
180 static void update_local_illumination_aux(PlayerType *player_ptr, int y, int x)
181 {
182     const auto &floor = *player_ptr->current_floor_ptr;
183     const Pos2D pos(y, x);
184     const auto &grid = floor.get_grid(pos);
185     if (!grid.has_los()) {
186         return;
187     }
188
189     if (grid.m_idx > 0) {
190         update_monster(player_ptr, grid.m_idx, false);
191     }
192
193     note_spot(player_ptr, y, x);
194     lite_spot(player_ptr, y, x);
195 }
196
197 /*!
198  * @brief 指定された座標の照明状態を更新する / Update "local" illumination
199  * @param player_ptr プレイヤーへの参照ポインタ
200  * @param y 視界先y座標
201  * @param x 視界先x座標
202  */
203 void update_local_illumination(PlayerType *player_ptr, POSITION y, POSITION x)
204 {
205     int i;
206     POSITION yy, xx;
207
208     if (!in_bounds(player_ptr->current_floor_ptr, y, x)) {
209         return;
210     }
211
212     if ((y != player_ptr->y) && (x != player_ptr->x)) {
213         yy = (y < player_ptr->y) ? (y - 1) : (y + 1);
214         xx = (x < player_ptr->x) ? (x - 1) : (x + 1);
215         update_local_illumination_aux(player_ptr, yy, xx);
216         update_local_illumination_aux(player_ptr, y, xx);
217         update_local_illumination_aux(player_ptr, yy, x);
218     } else if (x != player_ptr->x) /* y == player_ptr->y */
219     {
220         xx = (x < player_ptr->x) ? (x - 1) : (x + 1);
221         for (i = -1; i <= 1; i++) {
222             yy = y + i;
223             update_local_illumination_aux(player_ptr, yy, xx);
224         }
225         yy = y - 1;
226         update_local_illumination_aux(player_ptr, yy, x);
227         yy = y + 1;
228         update_local_illumination_aux(player_ptr, yy, x);
229     } else if (y != player_ptr->y) /* x == player_ptr->x */
230     {
231         yy = (y < player_ptr->y) ? (y - 1) : (y + 1);
232         for (i = -1; i <= 1; i++) {
233             xx = x + i;
234             update_local_illumination_aux(player_ptr, yy, xx);
235         }
236         xx = x - 1;
237         update_local_illumination_aux(player_ptr, y, xx);
238         xx = x + 1;
239         update_local_illumination_aux(player_ptr, y, xx);
240     } else /* Player's grid */
241     {
242         for (i = 0; i < 8; i++) {
243             yy = y + ddy_cdd[i];
244             xx = x + ddx_cdd[i];
245             update_local_illumination_aux(player_ptr, yy, xx);
246         }
247     }
248 }
249
250 /*!
251  * @brief 指定された座標をプレイヤー収められていない状態かどうか / Returns true if the player's grid is dark
252  * @return 視覚に収められていないならTRUEを返す
253  * @details player_can_see_bold()関数の返り値の否定を返している。
254  */
255 bool no_lite(PlayerType *player_ptr)
256 {
257     return !player_can_see_bold(player_ptr, player_ptr->y, player_ptr->x);
258 }
259
260 /*
261  * Place an attr/char pair at the given map coordinate, if legal.
262  */
263 void print_rel(PlayerType *player_ptr, char c, TERM_COLOR a, POSITION y, POSITION x)
264 {
265     /* Only do "legal" locations */
266     if (panel_contains(y, x)) {
267         /* Hack -- fake monochrome */
268         if (!use_graphics) {
269             if (w_ptr->timewalk_m_idx) {
270                 a = TERM_DARK;
271             } else if (is_invuln(player_ptr) || player_ptr->timewalk) {
272                 a = TERM_WHITE;
273             } else if (player_ptr->wraith_form) {
274                 a = TERM_L_DARK;
275             }
276         }
277
278         /* Draw the char using the attr */
279         term_queue_bigchar(panel_col_of(x), y - panel_row_prt, a, c, 0, 0);
280     }
281 }
282
283 void print_bolt_pict(PlayerType *player_ptr, POSITION y, POSITION x, POSITION ny, POSITION nx, AttributeType typ)
284 {
285     const auto &[a, c] = bolt_pict(y, x, ny, nx, typ);
286     print_rel(player_ptr, c, a, ny, nx);
287 }
288
289 /*!
290  * Memorize interesting viewable object/features in the given grid
291  *
292  * This function should only be called on "legal" grids.
293  *
294  * This function will memorize the object and/or feature in the given
295  * grid, if they are (1) viewable and (2) interesting.  Note that all
296  * objects are interesting, all terrain features except floors (and
297  * invisible traps) are interesting, and floors (and invisible traps)
298  * are interesting sometimes (depending on various options involving
299  * the illumination of floor grids).
300  *
301  * The automatic memorization of all objects and non-floor terrain
302  * features as soon as they are displayed allows incredible amounts
303  * of optimization in various places, especially "map_info()".
304  *
305  * Note that the memorization of objects is completely separate from
306  * the memorization of terrain features, preventing annoying floor
307  * memorization when a detected object is picked up from a dark floor,
308  * and object memorization when an object is dropped into a floor grid
309  * which is memorized but out-of-sight.
310  *
311  * This function should be called every time the "memorization" of
312  * a grid (or the object in a grid) is called into question, such
313  * as when an object is created in a grid, when a terrain feature
314  * "changes" from "floor" to "non-floor", when any grid becomes
315  * "illuminated" or "viewable", and when a "floor" grid becomes
316  * "torch-lit".
317  *
318  * Note the relatively efficient use of this function by the various
319  * "update_view()" and "update_lite()" calls, to allow objects and
320  * terrain features to be memorized (and drawn) whenever they become
321  * viewable or illuminated in any way, but not when they "maintain"
322  * or "lose" their previous viewability or illumination.
323  *
324  * Note the butchered "internal" version of "player_can_see_bold()",
325  * optimized primarily for the most common cases, that is, for the
326  * non-marked floor grids.
327  */
328 void note_spot(PlayerType *player_ptr, POSITION y, POSITION x)
329 {
330     const Pos2D pos(y, x);
331     auto &floor = *player_ptr->current_floor_ptr;
332     auto &grid = floor.get_grid(pos);
333
334     /* Blind players see nothing */
335     if (player_ptr->effects()->blindness()->is_blind()) {
336         return;
337     }
338
339     /* Analyze non-torch-lit grids */
340     if (!(grid.info & (CAVE_LITE | CAVE_MNLT))) {
341         /* Require line of sight to the grid */
342         if (!(grid.info & (CAVE_VIEW))) {
343             return;
344         }
345
346         /* Require "perma-lite" of the grid */
347         if ((grid.info & (CAVE_GLOW | CAVE_MNDK)) != CAVE_GLOW) {
348             /* Not Ninja */
349             if (!player_ptr->see_nocto) {
350                 return;
351             }
352         }
353     }
354
355     /* Hack -- memorize objects */
356     for (const auto this_o_idx : grid.o_idx_list) {
357         auto &item = floor.o_list[this_o_idx];
358         item.marked.set(OmType::FOUND);
359         RedrawingFlagsUpdater::get_instance().set_flag(SubWindowRedrawingFlag::FOUND_ITEMS);
360     }
361
362     /* Hack -- memorize grids */
363     if (!grid.is_mark()) {
364         /* Feature code (applying "mimic" field) */
365         const auto &terrain = grid.get_terrain_mimic();
366
367         /* Memorize some "boring" grids */
368         if (terrain.flags.has_not(TerrainCharacteristics::REMEMBER)) {
369             /* Option -- memorize all torch-lit floors */
370             if (view_torch_grids && ((grid.info & (CAVE_LITE | CAVE_MNLT)) || player_ptr->see_nocto)) {
371                 grid.info |= (CAVE_MARK);
372             }
373
374             /* Option -- memorize all perma-lit floors */
375             else if (view_perma_grids && ((grid.info & (CAVE_GLOW | CAVE_MNDK)) == CAVE_GLOW)) {
376                 grid.info |= (CAVE_MARK);
377             }
378         }
379
380         /* Memorize normal grids */
381         else if (terrain.flags.has(TerrainCharacteristics::LOS)) {
382             grid.info |= (CAVE_MARK);
383         }
384
385         /* Memorize torch-lit walls */
386         else if (grid.info & (CAVE_LITE | CAVE_MNLT)) {
387             grid.info |= (CAVE_MARK);
388         }
389
390         /* Memorize walls seen by noctovision of Ninja */
391         else if (player_ptr->see_nocto) {
392             grid.info |= (CAVE_MARK);
393         }
394
395         /* Memorize certain non-torch-lit wall grids */
396         else if (check_local_illumination(player_ptr, y, x)) {
397             grid.info |= (CAVE_MARK);
398         }
399     }
400
401     /* Memorize terrain of the grid */
402     grid.info |= (CAVE_KNOWN);
403 }
404
405 /*
406  * Redraw (on the screen) a given MAP location
407  *
408  * This function should only be called on "legal" grids
409  */
410 void lite_spot(PlayerType *player_ptr, POSITION y, POSITION x)
411 {
412     if (panel_contains(y, x) && in_bounds2(player_ptr->current_floor_ptr, y, x)) {
413         TERM_COLOR a;
414         char c;
415         TERM_COLOR ta;
416         char tc;
417
418         map_info(player_ptr, y, x, &a, &c, &ta, &tc);
419         if (!use_graphics) {
420             if (w_ptr->timewalk_m_idx) {
421                 a = TERM_DARK;
422             } else if (is_invuln(player_ptr) || player_ptr->timewalk) {
423                 a = TERM_WHITE;
424             } else if (player_ptr->wraith_form) {
425                 a = TERM_L_DARK;
426             }
427         }
428
429         term_queue_bigchar(panel_col_of(x), y - panel_row_prt, a, c, ta, tc);
430         static constexpr auto flags = {
431             SubWindowRedrawingFlag::OVERHEAD,
432             SubWindowRedrawingFlag::DUNGEON,
433         };
434         RedrawingFlagsUpdater::get_instance().set_flags(flags);
435     }
436 }
437
438 /*
439  * Some comments on the grid flags.  -BEN-
440  *
441  *
442  * One of the major bottlenecks in previous versions of Angband was in
443  * the calculation of "line of sight" from the player to various grids,
444  * such as monsters.  This was such a nasty bottleneck that a lot of
445  * silly things were done to reduce the dependancy on "line of sight",
446  * for example, you could not "see" any grids in a lit room until you
447  * actually entered the room, and there were all kinds of bizarre grid
448  * flags to enable this behavior.  This is also why the "call light"
449  * spells always lit an entire room.
450  *
451  * The code below provides functions to calculate the "field of view"
452  * for the player, which, once calculated, provides extremely fast
453  * calculation of "line of sight from the player", and to calculate
454  * the "field of torch lite", which, again, once calculated, provides
455  * extremely fast calculation of "which grids are lit by the player's
456  * lite source".  In addition to marking grids as "GRID_VIEW" and/or
457  * "GRID_LITE", as appropriate, these functions maintain an array for
458  * each of these two flags, each array containing the locations of all
459  * of the grids marked with the appropriate flag, which can be used to
460  * very quickly scan through all of the grids in a given set.
461  *
462  * To allow more "semantically valid" field of view semantics, whenever
463  * the field of view (or the set of torch lit grids) changes, all of the
464  * grids in the field of view (or the set of torch lit grids) are "drawn"
465  * so that changes in the world will become apparent as soon as possible.
466  * This has been optimized so that only grids which actually "change" are
467  * redrawn, using the "temp" array and the "GRID_TEMP" flag to keep track
468  * of the grids which are entering or leaving the relevent set of grids.
469  *
470  * These new methods are so efficient that the old nasty code was removed.
471  *
472  * Note that there is no reason to "update" the "viewable space" unless
473  * the player "moves", or walls/doors are created/destroyed, and there
474  * is no reason to "update" the "torch lit grids" unless the field of
475  * view changes, or the "light radius" changes.  This means that when
476  * the player is resting, or digging, or doing anything that does not
477  * involve movement or changing the state of the dungeon, there is no
478  * need to update the "view" or the "lite" regions, which is nice.
479  *
480  * Note that the calls to the nasty "los()" function have been reduced
481  * to a bare minimum by the use of the new "field of view" calculations.
482  *
483  * I wouldn't be surprised if slight modifications to the "update_view()"
484  * function would allow us to determine "reverse line-of-sight" as well
485  * as "normal line-of-sight", which would allow monsters to use a more
486  * "correct" calculation to determine if they can "see" the player.  For
487  * now, monsters simply "cheat" somewhat and assume that if the player
488  * has "line of sight" to the monster, then the monster can "pretend"
489  * that it has "line of sight" to the player.
490  *
491  *
492  * The "update_lite()" function maintains the "CAVE_LITE" flag for each
493  * grid and maintains an array of all "CAVE_LITE" grids.
494  *
495  * This set of grids is the complete set of all grids which are lit by
496  * the players light source, which allows the "player_can_see_bold()"
497  * function to work very quickly.
498  *
499  * Note that every "CAVE_LITE" grid is also a "CAVE_VIEW" grid, and in
500  * fact, the player (unless blind) can always "see" all grids which are
501  * marked as "CAVE_LITE", unless they are "off screen".
502  *
503  *
504  * The "update_view()" function maintains the "CAVE_VIEW" flag for each
505  * grid and maintains an array of all "CAVE_VIEW" grids.
506  *
507  * This set of grids is the complete set of all grids within line of sight
508  * of the player, allowing the "player_has_los_bold()" macro to work very
509  * quickly.
510  *
511  *
512  * The current "update_view()" algorithm uses the "CAVE_XTRA" flag as a
513  * temporary internal flag to mark those grids which are not only in view,
514  * but which are also "easily" in line of sight of the player.  This flag
515  * is always cleared when we are done.
516  *
517  *
518  * The current "update_lite()" and "update_view()" algorithms use the
519  * "CAVE_TEMP" flag, and the array of grids which are marked as "CAVE_TEMP",
520  * to keep track of which grids were previously marked as "CAVE_LITE" or
521  * "CAVE_VIEW", which allows us to optimize the "screen updates".
522  *
523  * The "CAVE_TEMP" flag, and the array of "CAVE_TEMP" grids, is also used
524  * for various other purposes, such as spreading lite or darkness during
525  * "lite_room()" / "unlite_room()", and for calculating monster flow.
526  *
527  *
528  * Any grid can be marked as "CAVE_GLOW" which means that the grid itself is
529  * in some way permanently lit.  However, for the player to "see" anything
530  * in the grid, as determined by "player_can_see()", the player must not be
531  * blind, the grid must be marked as "CAVE_VIEW", and, in addition, "wall"
532  * grids, even if marked as "perma lit", are only illuminated if they touch
533  * a grid which is not a wall and is marked both "CAVE_GLOW" and "CAVE_VIEW".
534  *
535  *
536  * To simplify various things, a grid may be marked as "CAVE_MARK", meaning
537  * that even if the player cannot "see" the grid, he "knows" the terrain in
538  * that grid.  This is used to "remember" walls/doors/stairs/floors when they
539  * are "seen" or "detected", and also to "memorize" floors, after "wiz_lite()",
540  * or when one of the "memorize floor grids" options induces memorization.
541  *
542  * Objects are "memorized" in a different way, using a special "marked" flag
543  * on the object itself, which is set when an object is observed or detected.
544  *
545  *
546  * A grid may be marked as "CAVE_ROOM" which means that it is part of a "room",
547  * and should be illuminated by "lite room" and "darkness" spells.
548  *
549  *
550  * A grid may be marked as "CAVE_ICKY" which means it is part of a "vault",
551  * and should be unavailable for "teleportation" destinations.
552  *
553  *
554  * The "view_perma_grids" allows the player to "memorize" every perma-lit grid
555  * which is observed, and the "view_torch_grids" allows the player to memorize
556  * every torch-lit grid.  The player will always memorize important walls,
557  * doors, stairs, and other terrain features, as well as any "detected" grids.
558  *
559  * Note that the new "update_view()" method allows, among other things, a room
560  * to be "partially" seen as the player approaches it, with a growing cone of
561  * floor appearing as the player gets closer to the door.  Also, by not turning
562  * on the "memorize perma-lit grids" option, the player will only "see" those
563  * floor grids which are actually in line of sight.
564  *
565  * And my favorite "plus" is that you can now use a special option to draw the
566  * "floors" in the "viewable region" brightly (actually, to draw the *other*
567  * grids dimly), providing a "pretty" effect as the player runs around, and
568  * to efficiently display the "torch lite" in a special color.
569  *
570  *
571  * Some comments on the "update_view()" algorithm...
572  *
573  * The algorithm is very fast, since it spreads "obvious" grids very quickly,
574  * and only has to call "los()" on the borderline cases.  The major axes/diags
575  * even terminate early when they hit walls.  I need to find a quick way
576  * to "terminate" the other scans.
577  *
578  * Note that in the worst case (a big empty area with say 5% scattered walls),
579  * each of the 1500 or so nearby grids is checked once, most of them getting
580  * an "instant" rating, and only a small portion requiring a call to "los()".
581  *
582  * The only time that the algorithm appears to be "noticeably" too slow is
583  * when running, and this is usually only important in town, since the town
584  * provides about the worst scenario possible, with large open regions and
585  * a few scattered obstructions.  There is a special "efficiency" option to
586  * allow the player to reduce his field of view in town, if needed.
587  *
588  * In the "best" case (say, a normal stretch of corridor), the algorithm
589  * makes one check for each viewable grid, and makes no calls to "los()".
590  * So running in corridors is very fast, and if a lot of monsters are
591  * nearby, it is much faster than the old methods.
592  *
593  * Note that resting, most normal commands, and several forms of running,
594  * plus all commands executed near large groups of monsters, are strictly
595  * more efficient with "update_view()" that with the old "compute los() on
596  * demand" method, primarily because once the "field of view" has been
597  * calculated, it does not have to be recalculated until the player moves
598  * (or a wall or door is created or destroyed).
599  *
600  * Note that we no longer have to do as many "los()" checks, since once the
601  * "view" region has been built, very few things cause it to be "changed"
602  * (player movement, and the opening/closing of doors, changes in wall status).
603  * Note that door/wall changes are only relevant when the door/wall itself is
604  * in the "view" region.
605  *
606  * The algorithm seems to only call "los()" from zero to ten times, usually
607  * only when coming down a corridor into a room, or standing in a room, just
608  * misaligned with a corridor.  So if, say, there are five "nearby" monsters,
609  * we will be reducing the calls to "los()".
610  *
611  * I am thinking in terms of an algorithm that "walks" from the central point
612  * out to the maximal "distance", at each point, determining the "view" code
613  * (above).  For each grid not on a major axis or diagonal, the "view" code
614  * depends on the "cave_los_bold()" and "view" of exactly two other grids
615  * (the one along the nearest diagonal, and the one next to that one, see
616  * "update_view_aux()"...).
617  *
618  * We "memorize" the viewable space array, so that at the cost of under 3000
619  * bytes, we reduce the time taken by "forget_view()" to one assignment for
620  * each grid actually in the "viewable space".  And for another 3000 bytes,
621  * we prevent "erase + redraw" ineffiencies via the "seen" set.  These bytes
622  * are also used by other routines, thus reducing the cost to almost nothing.
623  *
624  * A similar thing is done for "forget_lite()" in which case the savings are
625  * much less, but save us from doing bizarre maintenance checking.
626  *
627  * In the worst "normal" case (in the middle of the town), the reachable space
628  * actually reaches to more than half of the largest possible "circle" of view,
629  * or about 800 grids, and in the worse case (in the middle of a dungeon level
630  * where all the walls have been removed), the reachable space actually reaches
631  * the theoretical maximum size of just under 1500 grids.
632  *
633  * Each grid G examines the "state" of two (?) other (adjacent) grids, G1 & G2.
634  * If G1 is lite, G is lite.  Else if G2 is lite, G is half.  Else if G1 and G2
635  * are both half, G is half.  Else G is dark.  It only takes 2 (or 4) bits to
636  * "name" a grid, so (for MAX_RAD of 20) we could use 1600 bytes, and scan the
637  * entire possible space (including initialization) in one step per grid.  If
638  * we do the "clearing" as a separate step (and use an array of "view" grids),
639  * then the clearing will take as many steps as grids that were viewed, and the
640  * algorithm will be able to "stop" scanning at various points.
641  * Oh, and outside of the "torch radius", only "lite" grids need to be scanned.
642  */
643
644 /*
645  * Hack - speed up the update_flow algorithm by only doing
646  * it everytime the player moves out of LOS of the last
647  * "way-point".
648  */
649 static POSITION flow_x = 0;
650 static POSITION flow_y = 0;
651
652 /*
653  * Hack -- fill in the "cost" field of every grid that the player
654  * can "reach" with the number of steps needed to reach that grid.
655  * This also yields the "distance" of the player from every grid.
656  *
657  * In addition, mark the "when" of the grids that can reach
658  * the player with the incremented value of "flow_n".
659  *
660  * Hack -- use the "seen" array as a "circular queue".
661  *
662  * We do not need a priority queue because the cost from grid
663  * to grid is always "one" and we process them in order.
664  */
665 void update_flow(PlayerType *player_ptr)
666 {
667     auto &floor = *player_ptr->current_floor_ptr;
668
669     /* The last way-point is on the map */
670     if (player_ptr->running && in_bounds(&floor, flow_y, flow_x)) {
671         /* The way point is in sight - do not update.  (Speedup) */
672         if (floor.grid_array[flow_y][flow_x].info & CAVE_VIEW) {
673             return;
674         }
675     }
676
677     /* Erase all of the current flow information */
678     for (auto y = 0; y < floor.height; y++) {
679         for (auto x = 0; x < floor.width; x++) {
680             auto &grid = floor.grid_array[y][x];
681             grid.reset_costs();
682             grid.reset_dists();
683         }
684     }
685
686     /* Save player position */
687     flow_y = player_ptr->y;
688     flow_x = player_ptr->x;
689
690     for (auto i = 0; i < FLOW_MAX; i++) {
691         // 幅優先探索用のキュー。
692         std::queue<Pos2D> que;
693         que.emplace(player_ptr->y, player_ptr->x);
694
695         /* Now process the queue */
696         while (!que.empty()) {
697             const Pos2D pos = std::move(que.front());
698             que.pop();
699             const auto &grid = floor.get_grid(pos);
700
701             /* Add the "children" */
702             for (auto d = 0; d < 8; d++) {
703                 byte m = grid.costs[i] + 1;
704                 byte n = grid.dists[i] + 1;
705                 const Pos2D pos_neighbor(pos.y + ddy_ddd[d], pos.x + ddx_ddd[d]);
706
707                 /* Ignore player's grid */
708                 if (player_ptr->is_located_at(pos_neighbor)) {
709                     continue;
710                 }
711
712                 auto &grid_neighbor = floor.get_grid(pos_neighbor);
713                 if (is_closed_door(player_ptr, grid_neighbor.feat)) {
714                     m += 3;
715                 }
716
717                 /* Ignore "pre-stamped" entries */
718                 if ((grid_neighbor.dists[i] != 0) && (grid_neighbor.dists[i] <= n) && (grid_neighbor.costs[i] <= m)) {
719                     continue;
720                 }
721
722                 /* Ignore "walls", "holes" and "rubble" */
723                 auto can_move = false;
724                 switch (i) {
725                 case FLOW_CAN_FLY:
726                     can_move = grid_neighbor.cave_has_flag(TerrainCharacteristics::MOVE) || grid_neighbor.cave_has_flag(TerrainCharacteristics::CAN_FLY);
727                     break;
728                 default:
729                     can_move = grid_neighbor.cave_has_flag(TerrainCharacteristics::MOVE);
730                     break;
731                 }
732
733                 if (!can_move && !is_closed_door(player_ptr, grid_neighbor.feat)) {
734                     continue;
735                 }
736
737                 /* Save the flow cost */
738                 if (grid_neighbor.costs[i] == 0 || (grid_neighbor.costs[i] > m)) {
739                     grid_neighbor.costs[i] = m;
740                 }
741                 if (grid_neighbor.dists[i] == 0 || (grid_neighbor.dists[i] > n)) {
742                     grid_neighbor.dists[i] = n;
743                 }
744
745                 // 敵のプレイヤーに対する移動道のりの最大値(この値以上は処理を打ち切る).
746                 constexpr auto monster_flow_depth = 32;
747                 if (n == monster_flow_depth) {
748                     continue;
749                 }
750
751                 que.emplace(pos_neighbor);
752             }
753         }
754     }
755 }
756
757 /*
758  * Take a feature, determine what that feature becomes
759  * through applying the given action.
760  */
761 FEAT_IDX feat_state(const FloorType *floor_ptr, FEAT_IDX feat, TerrainCharacteristics action)
762 {
763     const auto &terrain = TerrainList::get_instance()[feat];
764
765     /* Get the new feature */
766     for (auto i = 0; i < MAX_FEAT_STATES; i++) {
767         if (terrain.state[i].action == action) {
768             return conv_dungeon_feat(floor_ptr, terrain.state[i].result);
769         }
770     }
771
772     if (terrain.flags.has(TerrainCharacteristics::PERMANENT)) {
773         return feat;
774     }
775
776     return (terrain_action_flags[enum2i(action)] & FAF_DESTROY) ? conv_dungeon_feat(floor_ptr, terrain.destroyed) : feat;
777 }
778
779 /*
780  * Takes a location and action and changes the feature at that
781  * location through applying the given action.
782  */
783 void cave_alter_feat(PlayerType *player_ptr, POSITION y, POSITION x, TerrainCharacteristics action)
784 {
785     /* Set old feature */
786     auto *floor_ptr = player_ptr->current_floor_ptr;
787     FEAT_IDX oldfeat = floor_ptr->grid_array[y][x].feat;
788
789     /* Get the new feat */
790     FEAT_IDX newfeat = feat_state(player_ptr->current_floor_ptr, oldfeat, action);
791
792     /* No change */
793     if (newfeat == oldfeat) {
794         return;
795     }
796
797     /* Set the new feature */
798     cave_set_feat(player_ptr, y, x, newfeat);
799     const auto &terrains = TerrainList::get_instance();
800     if (!(terrain_action_flags[enum2i(action)] & FAF_NO_DROP)) {
801         const auto &old_terrain = terrains[oldfeat];
802         const auto &new_terrain = terrains[newfeat];
803         bool found = false;
804
805         /* Handle gold */
806         if (old_terrain.flags.has(TerrainCharacteristics::HAS_GOLD) && new_terrain.flags.has_not(TerrainCharacteristics::HAS_GOLD)) {
807             /* Place some gold */
808             place_gold(player_ptr, y, x);
809             found = true;
810         }
811
812         /* Handle item */
813         if (old_terrain.flags.has(TerrainCharacteristics::HAS_ITEM) && new_terrain.flags.has_not(TerrainCharacteristics::HAS_ITEM) && (randint0(100) < (15 - floor_ptr->dun_level / 2))) {
814             /* Place object */
815             place_object(player_ptr, y, x, 0L);
816             found = true;
817         }
818
819         if (found && w_ptr->character_dungeon && player_can_see_bold(player_ptr, y, x)) {
820             msg_print(_("何かを発見した!", "You have found something!"));
821         }
822     }
823
824     if (terrain_action_flags[enum2i(action)] & FAF_CRASH_GLASS) {
825         const auto &old_terrain = terrains[oldfeat];
826         if (old_terrain.flags.has(TerrainCharacteristics::GLASS) && w_ptr->character_dungeon) {
827             project(player_ptr, PROJECT_WHO_GLASS_SHARDS, 1, y, x, std::min(floor_ptr->dun_level, 100) / 4, AttributeType::SHARDS,
828                 (PROJECT_GRID | PROJECT_ITEM | PROJECT_KILL | PROJECT_HIDE | PROJECT_JUMP | PROJECT_NO_HANGEKI));
829         }
830     }
831 }
832
833 /*!
834  * @brief 指定されたマスがモンスターのテレポート可能先かどうかを判定する。
835  * @param player_ptr プレイヤーへの参照ポインタ
836  * @param m_idx モンスターID
837  * @param y 移動先Y座標
838  * @param x 移動先X座標
839  * @param mode オプション
840  * @return テレポート先として妥当ならばtrue
841  */
842 bool cave_monster_teleportable_bold(PlayerType *player_ptr, MONSTER_IDX m_idx, POSITION y, POSITION x, teleport_flags mode)
843 {
844     const Pos2D pos(y, x);
845     const auto &floor = *player_ptr->current_floor_ptr;
846     const auto &grid = floor.get_grid(pos);
847     const auto &terrain = grid.get_terrain();
848
849     /* Require "teleportable" space */
850     if (terrain.flags.has_not(TerrainCharacteristics::TELEPORTABLE)) {
851         return false;
852     }
853
854     if (grid.m_idx && (grid.m_idx != m_idx)) {
855         return false;
856     }
857     if (player_ptr->is_located_at(pos)) {
858         return false;
859     }
860
861     /* Hack -- no teleport onto rune of protection */
862     if (grid.is_rune_protection()) {
863         return false;
864     }
865     if (grid.is_rune_explosion()) {
866         return false;
867     }
868
869     if (any_bits(mode, TELEPORT_PASSIVE)) {
870         return true;
871     }
872
873     const auto &monster = floor.m_list[m_idx];
874     return monster_can_cross_terrain(player_ptr, grid.feat, &monster.get_monrace(), 0);
875 }
876
877 /*!
878  * @brief 指定されたマスにプレイヤーがテレポート可能かどうかを判定する。
879  * @param player_ptr プレイヤーへの参照ポインタ
880  * @param y 移動先Y座標
881  * @param x 移動先X座標
882  * @param mode オプション
883  * @return テレポート先として妥当ならばtrue
884  */
885 bool cave_player_teleportable_bold(PlayerType *player_ptr, POSITION y, POSITION x, teleport_flags mode)
886 {
887     const Pos2D pos(y, x);
888     const auto &grid = player_ptr->current_floor_ptr->get_grid(pos);
889     const auto &terrain = grid.get_terrain();
890
891     /* Require "teleportable" space */
892     if (terrain.flags.has_not(TerrainCharacteristics::TELEPORTABLE)) {
893         return false;
894     }
895
896     /* No magical teleporting into vaults and such */
897     if (!(mode & TELEPORT_NONMAGICAL) && grid.is_icky()) {
898         return false;
899     }
900
901     if (grid.m_idx && (grid.m_idx != player_ptr->riding)) {
902         return false;
903     }
904
905     /* don't teleport on a trap. */
906     if (terrain.flags.has(TerrainCharacteristics::HIT_TRAP)) {
907         return false;
908     }
909
910     if (any_bits(mode, TELEPORT_PASSIVE)) {
911         return true;
912     }
913
914     if (!player_can_enter(player_ptr, grid.feat, 0)) {
915         return false;
916     }
917
918     if (terrain.flags.has_all_of({ TerrainCharacteristics::WATER, TerrainCharacteristics::DEEP })) {
919         if (!player_ptr->levitation && !player_ptr->can_swim) {
920             return false;
921         }
922     }
923
924     if (terrain.flags.has_not(TerrainCharacteristics::LAVA) || has_immune_fire(player_ptr) || is_invuln(player_ptr)) {
925         return true;
926     }
927
928     /* Always forbid deep lava */
929     if (terrain.flags.has(TerrainCharacteristics::DEEP)) {
930         return false;
931     }
932
933     /* Forbid shallow lava when the player don't have levitation */
934     return player_ptr->levitation != 0;
935 }
936
937 /*!
938  * @brief 地形は開くものであって、かつ開かれているかを返す /
939  * Attempt to open the given chest at the given location
940  * @param feat 地形ID
941  * @return 開いた地形である場合TRUEを返す /  Return TRUE if the given feature is an open door
942  */
943 bool is_open(PlayerType *player_ptr, FEAT_IDX feat)
944 {
945     const auto &terrain = TerrainList::get_instance()[feat];
946     return terrain.flags.has(TerrainCharacteristics::CLOSE) && (feat != feat_state(player_ptr->current_floor_ptr, feat, TerrainCharacteristics::CLOSE));
947 }
948
949 /*!
950  * @brief プレイヤーが地形踏破可能かを返す
951  * @param feature 判定したい地形ID
952  * @param mode 移動に関するオプションフラグ
953  * @return 移動可能ならばTRUEを返す
954  */
955 bool player_can_enter(PlayerType *player_ptr, FEAT_IDX feature, BIT_FLAGS16 mode)
956 {
957     const auto &terrain = TerrainList::get_instance()[feature];
958     if (player_ptr->riding) {
959         return monster_can_cross_terrain(
960             player_ptr, feature, &monraces_info[player_ptr->current_floor_ptr->m_list[player_ptr->riding].r_idx], mode | CEM_RIDING);
961     }
962
963     if (terrain.flags.has(TerrainCharacteristics::PATTERN)) {
964         if (!(mode & CEM_P_CAN_ENTER_PATTERN)) {
965             return false;
966         }
967     }
968
969     if (terrain.flags.has(TerrainCharacteristics::CAN_FLY) && player_ptr->levitation) {
970         return true;
971     }
972     if (terrain.flags.has(TerrainCharacteristics::CAN_SWIM) && player_ptr->can_swim) {
973         return true;
974     }
975     if (terrain.flags.has(TerrainCharacteristics::CAN_PASS) && has_pass_wall(player_ptr)) {
976         return true;
977     }
978
979     if (terrain.flags.has_not(TerrainCharacteristics::MOVE)) {
980         return false;
981     }
982
983     return true;
984 }
985
986 void place_grid(PlayerType *player_ptr, Grid *g_ptr, grid_bold_type gb_type)
987 {
988     switch (gb_type) {
989     case GB_FLOOR: {
990         g_ptr->feat = rand_choice(feat_ground_type);
991         g_ptr->info &= ~(CAVE_MASK);
992         g_ptr->info |= CAVE_FLOOR;
993         break;
994     }
995     case GB_EXTRA: {
996         g_ptr->feat = rand_choice(feat_wall_type);
997         g_ptr->info &= ~(CAVE_MASK);
998         g_ptr->info |= CAVE_EXTRA;
999         break;
1000     }
1001     case GB_EXTRA_PERM: {
1002         g_ptr->feat = feat_permanent;
1003         g_ptr->info &= ~(CAVE_MASK);
1004         g_ptr->info |= CAVE_EXTRA;
1005         break;
1006     }
1007     case GB_INNER: {
1008         g_ptr->feat = feat_wall_inner;
1009         g_ptr->info &= ~(CAVE_MASK);
1010         g_ptr->info |= CAVE_INNER;
1011         break;
1012     }
1013     case GB_INNER_PERM: {
1014         g_ptr->feat = feat_permanent;
1015         g_ptr->info &= ~(CAVE_MASK);
1016         g_ptr->info |= CAVE_INNER;
1017         break;
1018     }
1019     case GB_OUTER: {
1020         g_ptr->feat = feat_wall_outer;
1021         g_ptr->info &= ~(CAVE_MASK);
1022         g_ptr->info |= CAVE_OUTER;
1023         break;
1024     }
1025     case GB_OUTER_NOPERM: {
1026         const auto &terrain = TerrainList::get_instance()[feat_wall_outer];
1027         if (terrain.is_permanent_wall()) {
1028             g_ptr->feat = (int16_t)feat_state(player_ptr->current_floor_ptr, feat_wall_outer, TerrainCharacteristics::UNPERM);
1029         } else {
1030             g_ptr->feat = feat_wall_outer;
1031         }
1032
1033         g_ptr->info &= ~(CAVE_MASK);
1034         g_ptr->info |= (CAVE_OUTER | CAVE_VAULT);
1035         break;
1036     }
1037     case GB_SOLID: {
1038         g_ptr->feat = feat_wall_solid;
1039         g_ptr->info &= ~(CAVE_MASK);
1040         g_ptr->info |= CAVE_SOLID;
1041         break;
1042     }
1043     case GB_SOLID_PERM: {
1044         g_ptr->feat = feat_permanent;
1045         g_ptr->info &= ~(CAVE_MASK);
1046         g_ptr->info |= CAVE_SOLID;
1047         break;
1048     }
1049     case GB_SOLID_NOPERM: {
1050         const auto &terrain = TerrainList::get_instance()[feat_wall_solid];
1051         if ((g_ptr->info & CAVE_VAULT) && terrain.is_permanent_wall()) {
1052             g_ptr->feat = (int16_t)feat_state(player_ptr->current_floor_ptr, feat_wall_solid, TerrainCharacteristics::UNPERM);
1053         } else {
1054             g_ptr->feat = feat_wall_solid;
1055         }
1056         g_ptr->info &= ~(CAVE_MASK);
1057         g_ptr->info |= CAVE_SOLID;
1058         break;
1059     }
1060     default:
1061         // 未知の値が渡されたら何もしない。
1062         return;
1063     }
1064
1065     if (g_ptr->m_idx > 0) {
1066         delete_monster_idx(player_ptr, g_ptr->m_idx);
1067     }
1068 }
1069
1070 /*!
1071  * モンスターにより照明が消されている地形か否かを判定する。 / Is this grid "darkened" by monster?
1072  * @param player_ptr プレイヤーへの参照ポインタ
1073  * @param grid グリッドへの参照ポインタ
1074  * @return 照明が消されている地形ならばTRUE
1075  */
1076 bool darkened_grid(PlayerType *player_ptr, Grid *g_ptr)
1077 {
1078     return ((g_ptr->info & (CAVE_VIEW | CAVE_LITE | CAVE_MNLT | CAVE_MNDK)) == (CAVE_VIEW | CAVE_MNDK)) && !player_ptr->see_nocto;
1079 }
1080
1081 void place_bold(PlayerType *player_ptr, POSITION y, POSITION x, grid_bold_type gb_type)
1082 {
1083     Grid *const g_ptr = &player_ptr->current_floor_ptr->grid_array[y][x];
1084     place_grid(player_ptr, g_ptr, gb_type);
1085 }
1086
1087 void set_cave_feat(FloorType *floor_ptr, POSITION y, POSITION x, FEAT_IDX feature_idx)
1088 {
1089     floor_ptr->grid_array[y][x].feat = feature_idx;
1090 }
1091
1092 /*!
1093  * @brief プレイヤーの周辺9マスに該当する地形がいくつあるかを返す
1094  * @param player_ptr プレイヤーへの参照ポインタ
1095  * @param test 地形条件を判定するための関数ポインタ
1096  * @param under TRUEならばプレイヤーの直下の座標も走査対象にする
1097  * @return 該当する地形の数と、該当する地形の中から1つの座標
1098  */
1099 std::pair<int, Pos2D> count_dt(PlayerType *player_ptr, bool (*test)(PlayerType *, short), bool under)
1100 {
1101     auto count = 0;
1102     Pos2D pos(0, 0);
1103     for (auto d = 0; d < 9; d++) {
1104         if ((d == 8) && !under) {
1105             continue;
1106         }
1107
1108         Pos2D pos_neighbor(player_ptr->y + ddy_ddd[d], player_ptr->x + ddx_ddd[d]);
1109         const auto &grid = player_ptr->current_floor_ptr->get_grid(pos_neighbor);
1110         if (!grid.is_mark()) {
1111             continue;
1112         }
1113
1114         const auto feat = grid.get_feat_mimic();
1115         if (!((*test)(player_ptr, feat))) {
1116             continue;
1117         }
1118
1119         ++count;
1120         pos = pos_neighbor;
1121     }
1122
1123     return { count, pos };
1124 }
1125
1126 /*!
1127  * @brief マス構造体のspecial要素を利用する地形かどうかを判定する.
1128  */
1129 bool feat_uses_special(FEAT_IDX f_idx)
1130 {
1131     return TerrainList::get_instance()[(f_idx)].flags.has(TerrainCharacteristics::SPECIAL);
1132 }
1133
1134 /*
1135  * This function allows us to efficiently add a grid to the "lite" array,
1136  * note that we are never called for illegal grids, or for grids which
1137  * have already been placed into the "lite" array, and we are never
1138  * called when the "lite" array is full.
1139  */
1140 void cave_lite_hack(FloorType *floor_ptr, POSITION y, POSITION x)
1141 {
1142     auto *g_ptr = &floor_ptr->grid_array[y][x];
1143     if (g_ptr->is_lite()) {
1144         return;
1145     }
1146
1147     g_ptr->info |= CAVE_LITE;
1148     floor_ptr->lite_y[floor_ptr->lite_n] = y;
1149     floor_ptr->lite_x[floor_ptr->lite_n++] = x;
1150 }
1151
1152 /*
1153  * For delayed visual update
1154  */
1155 void cave_redraw_later(FloorType *floor_ptr, POSITION y, POSITION x)
1156 {
1157     auto *g_ptr = &floor_ptr->grid_array[y][x];
1158     if (g_ptr->is_redraw()) {
1159         return;
1160     }
1161
1162     g_ptr->info |= CAVE_REDRAW;
1163     floor_ptr->redraw_y[floor_ptr->redraw_n] = y;
1164     floor_ptr->redraw_x[floor_ptr->redraw_n++] = x;
1165 }
1166
1167 /*
1168  * For delayed visual update
1169  */
1170 void cave_note_and_redraw_later(FloorType *floor_ptr, POSITION y, POSITION x)
1171 {
1172     floor_ptr->grid_array[y][x].info |= CAVE_NOTE;
1173     cave_redraw_later(floor_ptr, y, x);
1174 }
1175
1176 void cave_view_hack(FloorType *floor_ptr, POSITION y, POSITION x)
1177 {
1178     auto *g_ptr = &floor_ptr->grid_array[y][x];
1179     if (g_ptr->is_view()) {
1180         return;
1181     }
1182
1183     g_ptr->info |= CAVE_VIEW;
1184     floor_ptr->view_y[floor_ptr->view_n] = y;
1185     floor_ptr->view_x[floor_ptr->view_n] = x;
1186     floor_ptr->view_n++;
1187 }