1 /**
2  * \file obj-pile.c
3  * \brief Deal with piles of objects
4  *
5  * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
6  *
7  * This work is free software; you can redistribute it and/or modify it
8  * under the terms of either:
9  *
10  * a) the GNU General Public License as published by the Free Software
11  *    Foundation, version 2, or
12  *
13  * b) the "Angband licence":
14  *    This software may be copied and distributed for educational, research,
15  *    and not for profit purposes provided that this copyright and statement
16  *    are included in all such copies.  Other copyrights may also apply.
17  */
18 
19 #include "angband.h"
20 #include "cave.h"
21 #include "effects.h"
22 #include "cmd-core.h"
23 #include "game-input.h"
24 #include "generate.h"
25 #include "grafmode.h"
26 #include "init.h"
27 #include "mon-make.h"
28 #include "mon-util.h"
29 #include "monster.h"
30 #include "obj-curse.h"
31 #include "obj-desc.h"
32 #include "obj-gear.h"
33 #include "obj-ignore.h"
34 #include "obj-info.h"
35 #include "obj-knowledge.h"
36 #include "obj-make.h"
37 #include "obj-pile.h"
38 #include "obj-slays.h"
39 #include "obj-tval.h"
40 #include "obj-util.h"
41 #include "player-calcs.h"
42 #include "player-history.h"
43 #include "player-spell.h"
44 #include "player-util.h"
45 #include "randname.h"
46 #include "trap.h"
47 #include "z-queue.h"
48 
49 /* #define LIST_DEBUG */
50 
51 static struct object *fail_pile;
52 static struct object *fail_object;
53 static bool fail_prev;
54 static bool fail_next;
55 static char *fail_file;
56 static int fail_line;
57 
write_pile(ang_file * fff)58 void write_pile(ang_file *fff)
59 {
60 	file_putf(fff, "Pile integrity failure at %s:%d\n\n", fail_file, fail_line);
61 	file_putf(fff, "Guilty object\n=============\n");
62 	if (fail_object && fail_object->kind) {
63 		file_putf(fff, "Name: %s\n", fail_object->kind->name);
64 		if (fail_prev) {
65 			file_putf(fff, "Previous: ");
66 			if (fail_object->prev && fail_object->prev->kind) {
67 				file_putf(fff, "%s\n", fail_object->prev->kind->name);
68 			} else {
69 				file_putf(fff, "bad object\n");
70 			}
71 		}
72 		if (fail_next) {
73 			file_putf(fff, "Next: ");
74 			if (fail_object->next && fail_object->next->kind) {
75 				file_putf(fff, "%s\n", fail_object->next->kind->name);
76 			} else {
77 				file_putf(fff, "bad object\n");
78 			}
79 		}
80 		file_putf(fff, "\n");
81 	}
82 	if (fail_pile) {
83 		file_putf(fff, "Guilty pile\n=============\n");
84 		while (fail_pile) {
85 			if (fail_pile->kind) {
86 				file_putf(fff, "Name: %s\n", fail_pile->kind->name);
87 			} else {
88 				file_putf(fff, "bad object\n");
89 			}
90 			fail_pile = fail_pile->next;
91 		}
92 	}
93 }
94 
95 /**
96  * Quit on getting an object pile error, writing a diagnosis file
97  */
pile_integrity_fail(struct object * pile,struct object * obj,char * file,int line)98 void pile_integrity_fail(struct object *pile, struct object *obj, char *file,
99 						 int line)
100 {
101 	char path[1024];
102 
103 	/* Set the pile info to write out */
104 	fail_pile = pile;
105 	fail_object = obj;
106 	fail_prev = (obj->prev != NULL);
107 	fail_next = (obj->next != NULL);
108 	fail_file = file;
109 	fail_line = line;
110 
111 	/* Write to the user directory */
112 	path_build(path, sizeof(path), ANGBAND_DIR_USER, "pile_error.txt");
113 
114 	if (text_lines_to_file(path, write_pile)) {
115 		quit_fmt("Failed to create file %s.new", path);
116 	}
117 	quit_fmt("Pile integrity failure, details written to %s", path);
118 }
119 
120 /**
121  * Check the integrity of a linked - make sure it's not circular and that each
122  * entry in the chain has consistent next and prev pointers.
123  */
pile_check_integrity(const char * op,struct object * pile,struct object * hilight)124 void pile_check_integrity(const char *op, struct object *pile, struct object *hilight)
125 {
126 	struct object *obj = pile;
127 	struct object *prev = NULL;
128 
129 #ifdef LIST_DEBUG
130 	int i = 0;
131 	fprintf(stderr, "\n%s  pile %08x\n", op, (int)pile);
132 #endif
133 
134 	/* Check prev<->next chain */
135 	while (obj) {
136 #ifdef LIST_DEBUG
137 		fprintf(stderr, "[%2d] this = %08x  prev = %08x  next = %08x  %s\n",
138 			i, (int)obj, (int)obj->prev, (int)obj->next,
139 			(obj == hilight) ? "*" : "");
140 		i++;
141 #endif
142 
143 		if (obj->prev != prev) {
144 			pile_integrity_fail(pile, obj, __FILE__, __LINE__);
145 		}
146 		prev = obj;
147 		obj = obj->next;
148 	};
149 
150 	/* Check for circularity */
151 	for (obj = pile; obj; obj = obj->next) {
152 		struct object *check;
153 		for (check = obj->next; check; check = check->next) {
154 			if (check->next == obj) {
155 				pile_integrity_fail(pile, check, __FILE__, __LINE__);
156 			}
157 		}
158 	}
159 }
160 
161 /**
162  * Insert 'obj' into the pile 'pile'.
163  *
164  * 'obj' must not already be in any other lists.
165  */
pile_insert(struct object ** pile,struct object * obj)166 void pile_insert(struct object **pile, struct object *obj)
167 {
168 	if (obj->prev || obj->next) {
169 		pile_integrity_fail(NULL, obj, __FILE__, __LINE__);
170 	}
171 
172 	if (*pile) {
173 		obj->next = *pile;
174 		(*pile)->prev = obj;
175 	}
176 
177 	*pile = obj;
178 
179 	pile_check_integrity("insert", *pile, obj);
180 }
181 
182 /**
183  * Insert 'obj' at the end of pile 'pile'.
184  *
185  * Unlike pile_insert(), obj can be the beginning of a new list of objects.
186  */
pile_insert_end(struct object ** pile,struct object * obj)187 void pile_insert_end(struct object **pile, struct object *obj)
188 {
189 	if (obj->prev) {
190 		pile_integrity_fail(NULL, obj, __FILE__, __LINE__);
191 	}
192 
193 	if (*pile) {
194 		struct object *end = pile_last_item(*pile);
195 
196 		end->next = obj;
197 		obj->prev = end;
198 	} else {
199 		*pile = obj;
200 	}
201 
202 	pile_check_integrity("insert_end", *pile, obj);
203 }
204 
205 /**
206  * Remove object 'obj' from pile 'pile'.
207  */
pile_excise(struct object ** pile,struct object * obj)208 void pile_excise(struct object **pile, struct object *obj)
209 {
210 	struct object *prev = obj->prev;
211 	struct object *next = obj->next;
212 
213 	if (!pile_contains(*pile, obj)) {
214 		pile_integrity_fail(*pile, obj, __FILE__, __LINE__);
215 	}
216 	pile_check_integrity("excise [pre]", *pile, obj);
217 
218 	/* Special case: unlink top object */
219 	if (*pile == obj) {
220 		if (prev) {
221 			pile_integrity_fail(*pile, obj, __FILE__, __LINE__);
222 		}
223 
224 		*pile = next;
225 	} else {
226 		if (obj->prev == NULL) {
227 			pile_integrity_fail(*pile, obj, __FILE__, __LINE__);
228 		}
229 
230 		/* Otherwise unlink from the previous */
231 		prev->next = next;
232 		obj->prev = NULL;
233 	}
234 
235 	/* And then unlink from the next */
236 	if (next) {
237 		next->prev = prev;
238 		obj->next = NULL;
239 	}
240 
241 	pile_check_integrity("excise [post]", *pile, NULL);
242 }
243 
244 /**
245  * Return the last item in pile 'pile'.
246  */
pile_last_item(struct object * const pile)247 struct object *pile_last_item(struct object *const pile)
248 {
249 	struct object *obj = pile;
250 
251 	pile_check_integrity("last_item", pile, NULL);
252 
253 	/* No pile at all */
254 	if (!pile)
255 		return NULL;
256 
257 	/* Run along the list, stopping just before the end */
258 	while (obj->next)
259 		obj = obj->next;
260 
261 	return obj;
262 }
263 
264 /**
265  * Check if pile 'pile' contains object 'obj'.
266  */
pile_contains(const struct object * top,const struct object * obj)267 bool pile_contains(const struct object *top, const struct object *obj)
268 {
269 	const struct object *pile_obj = top;
270 
271 	while (pile_obj) {
272 		if (obj == pile_obj)
273 			return true;
274 		pile_obj = pile_obj->next;
275 	}
276 
277 	return false;
278 }
279 
280 /**
281  * Create a new object and return it
282  */
object_new(void)283 struct object *object_new(void)
284 {
285 	return mem_zalloc(sizeof(struct object));
286 }
287 
288 /**
289  * Free up an object
290  *
291  * This doesn't affect any game state outside of the object itself
292  */
object_free(struct object * obj)293 void object_free(struct object *obj)
294 {
295 	mem_free(obj->slays);
296 	mem_free(obj->brands);
297 	mem_free(obj->curses);
298 	mem_free(obj);
299 }
300 
301 /**
302  * Delete an object and free its memory, and set its pointer to NULL
303  */
object_delete(struct object ** obj_address)304 void object_delete(struct object **obj_address)
305 {
306 	struct object *obj = *obj_address;
307 	struct object *prev = obj->prev;
308 	struct object *next = obj->next;
309 
310 	/* Check any next and previous objects */
311 	if (next) {
312 		if (prev) {
313 			prev->next = next;
314 			next->prev = prev;
315 		} else {
316 			next->prev = NULL;
317 		}
318 	} else if (prev) {
319 		prev->next = NULL;
320 	}
321 
322 	/* If we're tracking the object, stop */
323 	if (player && player->upkeep && obj == player->upkeep->object)
324 		player->upkeep->object = NULL;
325 
326 	/* Orphan rather than actually delete if we still have a known object */
327 	if (cave && player && player->cave && obj->oidx &&
328 		(obj == cave->objects[obj->oidx]) &&
329 		player->cave->objects[obj->oidx]) {
330 		obj->grid = loc(0, 0);
331 		obj->held_m_idx = 0;
332 		obj->mimicking_m_idx = 0;
333 
334 		/* Object is now purely imaginary to the player */
335 		obj->known->notice |= OBJ_NOTICE_IMAGINED;
336 
337 		return;
338 	}
339 
340 	/* Remove from any lists */
341 	if (player && player->cave && player->cave->objects && obj->oidx
342 		&& (obj == player->cave->objects[obj->oidx]))
343 		player->cave->objects[obj->oidx] = NULL;
344 
345 	if (cave && cave->objects && obj->oidx
346 		&& (obj == cave->objects[obj->oidx]))
347 		cave->objects[obj->oidx] = NULL;
348 
349 	object_free(obj);
350 	*obj_address = NULL;
351 }
352 
353 /**
354  * Free an entire object pile
355  */
object_pile_free(struct object * obj)356 void object_pile_free(struct object *obj)
357 {
358 	struct object *current = obj, *next;
359 
360 	while (current) {
361 		next = current->next;
362 		object_delete(&current);
363 		current = next;
364 	}
365 }
366 
367 
368 /**
369  * Determine if an item can "absorb" a second item
370  *
371  * See "object_absorb()" for the actual "absorption" code.
372  *
373  * If permitted, we allow weapons/armor to stack, if "known".
374  *
375  * Missiles will combine if both stacks have the same "known" status.
376  * This is done to make unidentified stacks of missiles useful.
377  *
378  * Food, potions, scrolls, and "easy know" items always stack.
379  *
380  * Chests, and activatable items, except rods, never stack (for various
381  * reasons).
382  */
object_stackable(const struct object * obj1,const struct object * obj2,object_stack_t mode)383 bool object_stackable(const struct object *obj1, const struct object *obj2,
384 					  object_stack_t mode)
385 {
386 	int i;
387 
388 	/* Equipment items don't stack */
389 	if (object_is_equipped(player->body, obj1))
390 		return false;
391 	if (object_is_equipped(player->body, obj2))
392 		return false;
393 
394 	/* If either item is unknown, do not stack */
395 	if (mode & OSTACK_LIST && obj1->kind != obj1->known->kind) return false;
396 	if (mode & OSTACK_LIST && obj2->kind != obj2->known->kind) return false;
397 
398 	/* Hack -- identical items cannot be stacked */
399 	if (obj1 == obj2) return false;
400 
401 	/* Require identical object kinds */
402 	if (obj1->kind != obj2->kind) return false;
403 
404 	/* Different flags don't stack */
405 	if (!of_is_equal(obj1->flags, obj2->flags)) return false;
406 
407 	/* Different elements don't stack */
408 	for (i = 0; i < ELEM_MAX; i++) {
409 		if (obj1->el_info[i].res_level != obj2->el_info[i].res_level)
410 			return false;
411 		if ((obj1->el_info[i].flags & (EL_INFO_HATES | EL_INFO_IGNORE)) !=
412 			(obj2->el_info[i].flags & (EL_INFO_HATES | EL_INFO_IGNORE)))
413 			return false;
414 	}
415 
416 	/* Artifacts never stack */
417 	if (obj1->artifact || obj2->artifact) return false;
418 
419 	/* Analyze the items */
420 	if (tval_is_chest(obj1)) {
421 		/* Chests never stack */
422 		return false;
423 	}
424 	else if (tval_is_edible(obj1) || tval_is_potion(obj1) ||
425 		tval_is_scroll(obj1) || tval_is_rod(obj1)) {
426 		/* Food, potions, scrolls and rods all stack nicely,
427 		   since the kinds are identical, either both will be
428 		   aware or both will be unaware */
429 	} else if (tval_can_have_charges(obj1) || tval_is_money(obj1)) {
430 		/* Gold, staves and wands stack most of the time */
431 		/* Too much gold or too many charges */
432 		if (obj1->pval + obj2->pval > MAX_PVAL)
433 			return false;
434 
435 		/* ... otherwise ok */
436 	} else if (tval_is_weapon(obj1) || tval_is_armor(obj1) ||
437 		tval_is_jewelry(obj1) || tval_is_light(obj1)) {
438 		bool obj1_is_known = object_fully_known((struct object *)obj1);
439 		bool obj2_is_known = object_fully_known((struct object *)obj2);
440 
441 		/* Require identical values */
442 		if (obj1->ac != obj2->ac) return false;
443 		if (obj1->dd != obj2->dd) return false;
444 		if (obj1->ds != obj2->ds) return false;
445 
446 		/* Require identical bonuses */
447 		if (obj1->to_h != obj2->to_h) return false;
448 		if (obj1->to_d != obj2->to_d) return false;
449 		if (obj1->to_a != obj2->to_a) return false;
450 
451 		/* Require all identical modifiers */
452 		for (i = 0; i < OBJ_MOD_MAX; i++)
453 			if (obj1->modifiers[i] != obj2->modifiers[i])
454 				return (false);
455 
456 		/* Require identical ego-item types */
457 		if (obj1->ego != obj2->ego) return false;
458 
459 		/* Require identical curses */
460 		if (!curses_are_equal(obj1, obj2)) return false;
461 
462 		/* Hack - Never stack recharging wearables ... */
463 		if ((obj1->timeout || obj2->timeout) &&
464 			!tval_is_light(obj1)) return false;
465 
466 		/* ... and lights must have same amount of fuel */
467 		else if ((obj1->timeout != obj2->timeout) &&
468 				 tval_is_light(obj1)) return false;
469 
470 		/* Prevent unIDd items stacking with IDd items in the object list */
471 		if (mode & OSTACK_LIST && (obj1_is_known != obj2_is_known))
472 			return false;
473 	} else {
474 		/* Anything else probably okay */
475 	}
476 
477 	/* Require compatible inscriptions */
478 	if (obj1->note && obj2->note && (obj1->note != obj2->note))
479 		return false;
480 
481 	/* They must be similar enough */
482 	return true;
483 }
484 
485 /**
486  * Return whether each stack of objects can be merged into one stack.
487  */
object_similar(const struct object * obj1,const struct object * obj2,object_stack_t mode)488 bool object_similar(const struct object *obj1, const struct object *obj2,
489 					object_stack_t mode)
490 {
491 	int total = obj1->number + obj2->number;
492 
493 	/* Check against stacking limit - except in stores which absorb anyway */
494 	if (!(mode & OSTACK_STORE) && (total > obj1->kind->base->max_stack))
495 		return false;
496 
497 	return object_stackable(obj1, obj2, mode);
498 }
499 
500 /**
501  * Combine the origins of two objects
502  */
object_origin_combine(struct object * obj1,const struct object * obj2)503 void object_origin_combine(struct object *obj1, const struct object *obj2)
504 {
505 	int act = 2;
506 
507 	if (obj1->origin_race && obj2->origin_race) {
508 		bool uniq1 = false;
509 		bool uniq2 = false;
510 
511 		if (obj1->origin_race) {
512 			uniq1 = rf_has(obj1->origin_race->flags, RF_UNIQUE) ? true : false;
513 		}
514 		if (obj2->origin_race) {
515 			uniq2 = rf_has(obj2->origin_race->flags, RF_UNIQUE) ? true : false;
516 		}
517 
518 		if (uniq1 && !uniq2) act = 0;
519 		else if (uniq2 && !uniq1) act = 1;
520 		else act = 2;
521 	}
522 
523 	switch (act)
524 	{
525 		/* Overwrite with obj2 */
526 		case 1:
527 		{
528 			obj1->origin = obj2->origin;
529 			obj1->origin_depth = obj2->origin_depth;
530 			obj1->origin_race = obj2->origin_race;
531 			break;
532 		}
533 
534 		/* Set as "mixed" */
535 		case 2:
536 		{
537 			obj1->origin = ORIGIN_MIXED;
538 			break;
539 		}
540 		default: break;
541 	}
542 }
543 
544 /**
545  * Allow one item to "absorb" another, assuming they are similar.
546  *
547  * The blending of the "note" field assumes that either (1) one has an
548  * inscription and the other does not, or (2) neither has an inscription.
549  * In both these cases, we can simply use the existing note, unless the
550  * blending object has a note, in which case we use that note.
551  *
552 * These assumptions are enforced by the "object_similar()" code.
553  */
object_absorb_merge(struct object * obj1,const struct object * obj2)554 static void object_absorb_merge(struct object *obj1, const struct object *obj2)
555 {
556 	int total;
557 
558 	/* First object gains any extra knowledge from second */
559 	if (obj1->known && obj2->known) {
560 		if (obj2->known->effect)
561 			obj1->known->effect = obj1->effect;
562 		player_know_object(player, obj1);
563 	}
564 
565 	/* Merge inscriptions */
566 	if (obj2->note)
567 		obj1->note = obj2->note;
568 
569 	/* Combine timeouts for rod stacking */
570 	if (tval_can_have_timeout(obj1))
571 		obj1->timeout += obj2->timeout;
572 
573 	/* Combine pvals for wands and staves */
574 	if (tval_can_have_charges(obj1) || tval_is_money(obj1)) {
575 		total = obj1->pval + obj2->pval;
576 		obj1->pval = total >= MAX_PVAL ? MAX_PVAL : total;
577 	}
578 
579 	/* Combine origin data as best we can */
580 	object_origin_combine(obj1, obj2);
581 }
582 
583 /**
584  * Merge a smaller stack into a larger stack, leaving two uneven stacks.
585  */
object_absorb_partial(struct object * obj1,struct object * obj2)586 void object_absorb_partial(struct object *obj1, struct object *obj2)
587 {
588 	int smallest = MIN(obj1->number, obj2->number);
589 	int largest = MAX(obj1->number, obj2->number);
590 	int difference = obj1->kind->base->max_stack - largest;
591 	obj1->number = largest + difference;
592 	obj2->number = smallest - difference;
593 
594 	object_absorb_merge(obj1, obj2);
595 }
596 
597 /**
598  * Merge two stacks into one stack.
599  */
object_absorb(struct object * obj1,struct object * obj2)600 void object_absorb(struct object *obj1, struct object *obj2)
601 {
602 	struct object *known = obj2->known;
603 	int total = obj1->number + obj2->number;
604 
605 	/* Add together the item counts */
606 	obj1->number = MIN(total, obj1->kind->base->max_stack);
607 
608 	object_absorb_merge(obj1, obj2);
609 	if (known) {
610 		if (!loc_is_zero(known->grid)) {
611 			square_excise_object(player->cave, known->grid, known);
612 		}
613 		delist_object(player->cave, known);
614 		object_delete(&known);
615 	}
616 	object_delete(&obj2);
617 }
618 
619 /**
620  * Wipe an object clean.
621  */
object_wipe(struct object * obj)622 void object_wipe(struct object *obj)
623 {
624 	/* Free slays and brands */
625 	mem_free(obj->slays);
626 	mem_free(obj->brands);
627 	mem_free(obj->curses);
628 
629 	/* Wipe the structure */
630 	memset(obj, 0, sizeof(*obj));
631 }
632 
633 
634 /**
635  * Prepare an object based on an existing object
636  */
object_copy(struct object * dest,const struct object * src)637 void object_copy(struct object *dest, const struct object *src)
638 {
639 	/* Copy the structure */
640 	memcpy(dest, src, sizeof(struct object));
641 
642 	if (src->slays) {
643 		dest->slays = mem_zalloc(z_info->slay_max * sizeof(bool));
644 		memcpy(dest->slays, src->slays, z_info->slay_max * sizeof(bool));
645 	}
646 	if (src->brands) {
647 		dest->brands = mem_zalloc(z_info->brand_max * sizeof(bool));
648 		memcpy(dest->brands, src->brands, z_info->brand_max * sizeof(bool));
649 	}
650 	if (src->curses) {
651 		size_t array_size = z_info->curse_max * sizeof(struct curse_data);
652 		dest->curses = mem_zalloc(array_size);
653 		memcpy(dest->curses, src->curses, array_size);
654 	}
655 
656 	/* Detach from any pile */
657 	dest->prev = NULL;
658 	dest->next = NULL;
659 }
660 
661 /**
662  * Prepare an object `dst` representing `amt` objects,  based on an existing
663  * object `src` representing at least `amt` objects.
664  *
665  * Takes care of the charge redistribution concerns of stacked items.
666  */
object_copy_amt(struct object * dest,struct object * src,int amt)667 void object_copy_amt(struct object *dest, struct object *src, int amt)
668 {
669 	int charge_time = randcalc(src->time, 0, AVERAGE), max_time;
670 
671 	/* Get a copy of the object */
672 	object_copy(dest, src);
673 
674 	/* Modify quantity */
675 	dest->number = amt;
676 	dest->note = src->note;
677 
678 	/*
679 	 * If the item has charges/timeouts, set them to the correct level
680 	 * too. We split off the same amount as distribute_charges.
681 	 */
682 	if (tval_can_have_charges(src))
683 		dest->pval = src->pval * amt / src->number;
684 
685 	if (tval_can_have_timeout(src)) {
686 		max_time = charge_time * amt;
687 
688 		if (src->timeout > max_time)
689 			dest->timeout = max_time;
690 		else
691 			dest->timeout = src->timeout;
692 	}
693 }
694 
695 /**
696  * Split off 'amt' items from 'src' and return.
697  *
698  * Where object_copy_amt() makes `amt` new objects, this function leaves the
699  * total number unchanged; otherwise the two functions are similar.
700  *
701  * This function should only be used when amt < src->number
702  */
object_split(struct object * src,int amt)703 struct object *object_split(struct object *src, int amt)
704 {
705 	struct object *dest = object_new(), *dest_known;
706 
707 	/* Get a copy of the object */
708 	object_copy(dest, src);
709 
710 	/* Do we need a new known object? */
711 	if (src->known) {
712 		/* Ensure numbers are aligned (should not be necessary, but safer) */
713 		src->known->number = src->number;
714 
715 		/* Make the new object */
716 		dest_known = object_new();
717 		object_copy(dest_known, src->known);
718 		dest->known = dest_known;
719 	}
720 
721 	/* Check legality */
722 	assert(src->number > amt);
723 
724 	/* Distribute charges of wands, staves, or rods */
725 	distribute_charges(src, dest, amt);
726 	if (src->known)
727 		distribute_charges(src->known, dest->known, amt);
728 
729 	/* Modify quantity */
730 	dest->number = amt;
731 	src->number -= amt;
732 	if (src->note)
733 		dest->note = src->note;
734 	if (src->known) {
735 		dest->known->number = dest->number;
736 		src->known->number = src->number;
737 		dest->known->note = src->known->note;
738 	}
739 
740 	/* Remove any index */
741 	if (dest->known)
742 		dest->known->oidx = 0;
743 	dest->oidx = 0;
744 
745 	return dest;
746 }
747 
748 /**
749  * Remove an amount of an object from the floor, returning a detached object
750  * which can be used - it is assumed that the object is on the player grid.
751  *
752  * Optionally describe what remains.
753  */
floor_object_for_use(struct object * obj,int num,bool message,bool * none_left)754 struct object *floor_object_for_use(struct object *obj, int num, bool message,
755 									bool *none_left)
756 {
757 	struct object *usable;
758 	char name[80];
759 
760 	/* Bounds check */
761 	num = MIN(num, obj->number);
762 
763 	/* Split off a usable object if necessary */
764 	if (obj->number > num) {
765 		usable = object_split(obj, num);
766 	} else {
767 		usable = obj;
768 		square_excise_object(player->cave, usable->grid, usable->known);
769 		delist_object(player->cave, usable->known);
770 		square_excise_object(cave, usable->grid, usable);
771 		delist_object(cave, usable);
772 		*none_left = true;
773 
774 		/* Stop tracking item */
775 		if (tracked_object_is(player->upkeep, obj))
776 			track_object(player->upkeep, NULL);
777 
778 		/* Inventory has changed, so disable repeat command */
779 		cmd_disable_repeat();
780 	}
781 
782 	/* Object no longer has a location */
783 	usable->known->grid = loc(0, 0);
784 	usable->grid = loc(0, 0);
785 
786 	/* Housekeeping */
787 	player->upkeep->update |= (PU_BONUS | PU_INVEN);
788 	player->upkeep->notice |= (PN_COMBINE);
789 	player->upkeep->redraw |= (PR_INVEN | PR_EQUIP);
790 
791 	/* Print a message if requested and there is anything left */
792 	if (message) {
793 		if (usable == obj)
794 			obj->number = 0;
795 
796 		/* Get a description */
797 		object_desc(name, sizeof(name), obj, ODESC_PREFIX | ODESC_FULL);
798 
799 		if (usable == obj)
800 			obj->number = num;
801 
802 		/* Print a message */
803 		msg("You see %s.", name);
804 	}
805 
806 	return usable;
807 }
808 
809 
810 /**
811  * Find and return the oldest object on the given grid marked as "ignore".
812  */
floor_get_oldest_ignored(struct chunk * c,struct loc grid)813 static struct object *floor_get_oldest_ignored(struct chunk *c, struct loc grid)
814 {
815 	struct object *obj, *ignore = NULL;
816 
817 	for (obj = square_object(c, grid); obj; obj = obj->next)
818 		if (ignore_item_ok(obj))
819 			ignore = obj;
820 
821 	return ignore;
822 }
823 
824 
825 /**
826  * Let the floor carry an object, deleting old ignored items if necessary.
827  * The calling function must deal with the dropped object on failure.
828  *
829  * Optionally put the object at the top or bottom of the pile
830  */
floor_carry(struct chunk * c,struct loc grid,struct object * drop,bool * note)831 bool floor_carry(struct chunk *c, struct loc grid, struct object *drop,
832 				 bool *note)
833 {
834 	int n = 0;
835 	struct object *obj, *ignore = floor_get_oldest_ignored(c, grid);
836 
837 	/* Fail if the square can't hold objects */
838 	if (!square_isobjectholding(c, grid))
839 		return false;
840 
841 	/* Scan objects in that grid for combination */
842 	for (obj = square_object(c, grid); obj; obj = obj->next) {
843 		/* Check for combination */
844 		if (object_similar(obj, drop, OSTACK_FLOOR)) {
845 			/* Combine the items */
846 			object_absorb(obj, drop);
847 
848 			/* Note the pile */
849 			if (square_isview(c, grid)) {
850 				square_note_spot(c, grid);
851 			}
852 
853 			/* Don't mention if ignored */
854 			if (ignore_item_ok(obj)) {
855 				*note = false;
856 			}
857 
858 			/* Result */
859 			return true;
860 		}
861 
862 		/* Count objects */
863 		n++;
864 	}
865 
866 	/* The stack is already too large */
867 	if (n >= z_info->floor_size || (!OPT(player, birth_stacking) && n)) {
868 		/* Delete the oldest ignored object */
869 		if (ignore) {
870 			square_excise_object(c, grid, ignore);
871 			delist_object(c, ignore);
872 			object_delete(&ignore);
873 		} else {
874 			return false;
875 		}
876 	}
877 
878 	/* Location */
879 	drop->grid = grid;
880 
881 	/* Forget monster */
882 	drop->held_m_idx = 0;
883 
884 	/* Link to the first object in the pile */
885 	pile_insert(&c->squares[grid.y][grid.x].obj, drop);
886 
887 	/* Record in the level list */
888 	list_object(c, drop);
889 
890 	/* If there's a known version, put it in the player's view of the
891 	 * cave but at an unknown location.  square_note_spot() will move
892 	 * it to the correct place if seen. */
893 	if (drop->known) {
894 		drop->known->oidx = drop->oidx;
895 		drop->known->held_m_idx = 0;
896 		drop->known->grid = loc(0, 0);
897 		player->cave->objects[drop->oidx] = drop->known;
898 	}
899 
900 	/* Redraw */
901 	square_note_spot(c, grid);
902 	square_light_spot(c, grid);
903 
904 	/* Don't mention if ignored */
905 	if (ignore_item_ok(drop)) {
906 		*note = false;
907 	}
908 
909 	/* Result */
910 	return true;
911 }
912 
913 /**
914  * Delete an object when the floor fails to carry it, and attempt to remove
915  * it from the object list
916  */
floor_carry_fail(struct object * drop,bool broke)917 static void floor_carry_fail(struct object *drop, bool broke)
918 {
919 	struct object *known = drop->known;
920 
921 	/* Delete completely */
922 	if (known) {
923 		char o_name[80];
924 		char *verb = broke ? VERB_AGREEMENT(drop->number, "breaks", "break")
925 			: VERB_AGREEMENT(drop->number, "disappears", "disappear");
926 		object_desc(o_name, sizeof(o_name), drop, ODESC_BASE);
927 		msg("The %s %s.", o_name, verb);
928 		if (!loc_is_zero(known->grid))
929 			square_excise_object(player->cave, known->grid, known);
930 		delist_object(player->cave, known);
931 		object_delete(&known);
932 	}
933 	delist_object(cave, drop);
934 	object_delete(&drop);
935 }
936 
937 /**
938  * Find a grid near the given one for an object to fall on
939  *
940  * We check several locations to see if we can find a location at which
941  * the object can combine, stack, or be placed.  Artifacts will try very
942  * hard to be placed, including "teleporting" to a useful grid if needed.
943  *
944  * If prefer_pile is true, does not apply a penalty for putting different types
945  * items in the same grid.
946  *
947  * If no appropriate grid is found, the given grid is unchanged
948  */
drop_find_grid(struct object * drop,bool prefer_pile,struct loc * grid)949 static void drop_find_grid(struct object *drop, bool prefer_pile, struct loc *grid)
950 {
951 	int best_score = -1;
952 	struct loc start = *grid;
953 	struct loc best = start;
954 	int i, dy, dx;
955 	struct object *obj;
956 
957 	/* Scan local grids */
958 	for (dy = -3; dy <= 3; dy++) {
959 		for (dx = -3; dx <= 3; dx++) {
960 			bool combine = false;
961 			int dist = (dy * dy) + (dx * dx);
962 			struct loc try = loc_sum(start, loc(dx, dy));
963 			int num_shown = 0;
964 			int num_ignored = 0;
965 			int score;
966 
967 			/* Lots of reasons to say no */
968 			if ((dist > 10) ||
969 				!square_in_bounds_fully(cave, try) ||
970 				!los(cave, start, try) ||
971 				!square_isfloor(cave, try) ||
972 				square_istrap(cave, try))
973 				continue;
974 
975 			/* Analyse the grid for carrying the new object */
976 			for (obj = square_object(cave, try); obj; obj = obj->next){
977 				/* Check for possible combination */
978 				if (object_similar(obj, drop, OSTACK_FLOOR))
979 					combine = true;
980 
981 				/* Count objects */
982 				if (!ignore_item_ok(obj))
983 					num_shown++;
984 				else
985 					num_ignored++;
986 			}
987 			if (!combine)
988 				num_shown++;
989 
990 			/* Disallow if the stack size is too big */
991 			if ((!OPT(player, birth_stacking) && (num_shown > 1)) ||
992 				((num_shown + num_ignored) > z_info->floor_size &&
993 				 !floor_get_oldest_ignored(cave, try)))
994 				continue;
995 
996 			/* Score the location based on how close and how full the grid is */
997 			score = 1000 -
998 				(dist + (prefer_pile ? 0 : num_shown * 5));
999 
1000 			if ((score < best_score) || ((score == best_score) && one_in_(2)))
1001 				continue;
1002 
1003 			best_score = score;
1004 			best = try;
1005 		}
1006 	}
1007 
1008 	/* Return if we have a score, otherwise fail or try harder for artifacts */
1009 	if (best_score >= 0) {
1010 		*grid = best;
1011 		return;
1012 	} else if (!drop->artifact) {
1013 		return;
1014 	}
1015 	for (i = 0; i < 2000; i++) {
1016 		/* Start bouncing from grid to grid, stopping if we find an empty one */
1017 		if (i < 1000) {
1018 			best = rand_loc(best, 1, 1);
1019 		} else {
1020 			/* Now go to purely random locations */
1021 			best = loc(randint0(cave->width), randint0(cave->height));
1022 		}
1023 		if (square_canputitem(cave, best)) {
1024 			*grid = best;
1025 			return;
1026 		}
1027 	}
1028 }
1029 
1030 /**
1031  * Let an object fall to the ground at or near a location.
1032  *
1033  * The initial location is assumed to be "square_in_bounds_fully(cave, )".
1034  *
1035  * This function takes a parameter "chance".  This is the percentage
1036  * chance that the item will "disappear" instead of drop.  If the object
1037  * has been thrown, then this is the chance of disappearance on contact.
1038  *
1039  * This function will produce a description of a drop event under the player
1040  * when "verbose" is true.
1041  *
1042  * If "prefer_pile" is true, the penalty for putting different types of items
1043  * in the same square is not applied.
1044  *
1045  * The calling function needs to deal with the consequences of the dropped
1046  * object being destroyed or absorbed into an existing pile.
1047  */
drop_near(struct chunk * c,struct object ** dropped,int chance,struct loc grid,bool verbose,bool prefer_pile)1048 void drop_near(struct chunk *c, struct object **dropped, int chance,
1049 			   struct loc grid, bool verbose, bool prefer_pile)
1050 {
1051 	char o_name[80];
1052 	struct loc best = grid;
1053 	bool dont_ignore = verbose && !ignore_item_ok(*dropped);
1054 
1055 	/* Only called in the current level */
1056 	assert(c == cave);
1057 
1058 	/* Describe object */
1059 	object_desc(o_name, sizeof(o_name), *dropped, ODESC_BASE);
1060 
1061 	/* Handle normal breakage */
1062 	if (!((*dropped)->artifact) && (randint0(100) < chance)) {
1063 		floor_carry_fail(*dropped, true);
1064 		return;
1065 	}
1066 
1067 	/* Find the best grid and drop the item, destroying if there's no space */
1068 	drop_find_grid(*dropped, prefer_pile, &best);
1069 	if (floor_carry(c, best, *dropped, &dont_ignore)) {
1070 		sound(MSG_DROP);
1071 		if (dont_ignore && (square(c, best)->mon < 0)) {
1072 			msg("You feel something roll beneath your feet.");
1073 		}
1074 	} else {
1075 		floor_carry_fail(*dropped, false);
1076 	}
1077 }
1078 
1079 /**
1080  * This will push objects off a square.
1081  *
1082  * The methodology is to load all objects on the square into a queue. Replace
1083  * the previous square with a type that does not allow for objects. Drop the
1084  * objects. Last, put the square back to its original type.
1085  */
push_object(struct loc grid)1086 void push_object(struct loc grid)
1087 {
1088 	/* Save the original terrain feature */
1089 	struct feature *feat_old = square_feat(cave, grid);
1090 	struct object *obj = square_object(cave, grid);
1091 	struct queue *queue = q_new(z_info->floor_size);
1092 	struct trap *trap = square_trap(cave, grid);
1093 
1094 	/* Push all objects on the square, stripped of pile info, into the queue */
1095 	while (obj) {
1096 		struct object *next = obj->next;
1097 		/* In case the object is known, make a copy to work with
1098 		 * and try to delete the original which will orphan it to
1099 		 * serve as a placeholder for the known version. */
1100 		struct object *newobj = object_new();
1101 
1102 		object_copy(newobj, obj);
1103 		newobj->oidx = 0;
1104 		newobj->grid = loc(0, 0);
1105 		if (newobj->known) {
1106 			newobj->known = object_new();
1107 			object_copy(newobj->known, obj->known);
1108 			newobj->known->oidx = 0;
1109 			newobj->known->grid = loc(0, 0);
1110 		}
1111 		q_push_ptr(queue, newobj);
1112 
1113 		delist_object(cave, obj);
1114 		object_delete(&obj);
1115 
1116 		/* Next object */
1117 		obj = next;
1118 	}
1119 
1120 	/* Disassociate the objects from the square */
1121 	square_set_obj(cave, grid, NULL);
1122 
1123 	/* Set feature to an open door */
1124 	square_force_floor(cave, grid);
1125 	square_add_door(cave, grid, false);
1126 
1127 	/* Drop objects back onto the floor */
1128 	while (q_len(queue) > 0) {
1129 		/* Take object from the queue */
1130 		obj = q_pop_ptr(queue);
1131 
1132 		/* Unrevealed mimics require special handling, as always. */
1133 		if (obj->mimicking_m_idx) {
1134 			/*
1135 			 * Try to find a location; there's 49 positions in
1136 			 * the 7 x 7 square so make at most a small multiple
1137 			 * of that number in attempts to find an appropriate
1138 			 * one that doesn't already have a monster or the
1139 			 * player.  If scatter accepted a predicate argument,
1140 			 * could avoid the multiple attempts.
1141 			 */
1142 			struct monster *mimic =
1143 				cave_monster(cave, obj->mimicking_m_idx);
1144 			int ntry = 0;
1145 
1146 			assert(mimic);
1147 			/*
1148 			 * Reset since the current value is a dangling
1149 			 * reference to a deleted object.
1150 			 */
1151 			mimic->mimicked_obj = NULL;
1152 
1153 			while (1) {
1154 				struct loc newgrid;
1155 
1156 				if (ntry > 150) {
1157 					/*
1158 					 * Give up.  Destroy both the mimic
1159 					 * and the object.
1160 					 */
1161 					delete_monster_idx(obj->mimicking_m_idx);
1162 					if (obj->known) {
1163 						object_delete(&obj->known);
1164 					}
1165 					object_delete(&obj);
1166 					break;
1167 				}
1168 				scatter(cave, &newgrid, grid, 3, true);
1169 				if (square(cave, newgrid)->mon == 0) {
1170 					bool dummy = true;
1171 
1172 					if (floor_carry(cave, newgrid, obj, &dummy)) {
1173 						/*
1174 						 * Move the monster and give it
1175 						 * the object.
1176 						 */
1177 						monster_swap(grid, newgrid);
1178 						mimic->mimicked_obj = obj;
1179 						break;
1180 					}
1181 				}
1182 				++ntry;
1183 			}
1184 		} else {
1185 			/* Drop the object */
1186 			drop_near(cave, &obj, 0, grid, false, false);
1187 		}
1188 	}
1189 
1190 	/* Reset cave feature, remove trap if needed */
1191 	square_set_feat(cave, grid, feat_old->fidx);
1192 	if (trap && !square_istrappable(cave, grid)) {
1193 		square_destroy_trap(cave, grid);
1194 	}
1195 
1196 	q_free(queue);
1197 }
1198 
1199 /**
1200  * Describe the charges on an item on the floor.
1201  */
floor_item_charges(struct object * obj)1202 void floor_item_charges(struct object *obj)
1203 {
1204 	/* Require staff/wand */
1205 	if (!tval_can_have_charges(obj)) return;
1206 
1207 	/* Require known item */
1208 	if (!object_flavor_is_aware(obj)) return;
1209 
1210 	/* Print a message */
1211 	msg("There %s %d charge%s remaining.", (obj->pval != 1) ? "are" : "is",
1212 	     obj->pval, (obj->pval != 1) ? "s" : "");
1213 }
1214 
1215 
1216 
1217 /**
1218  * Get a list of the objects at the player's location.
1219  *
1220  * Return the number of objects acquired.
1221  */
scan_floor(struct object ** items,int max_size,object_floor_t mode,item_tester tester)1222 int scan_floor(struct object **items, int max_size, object_floor_t mode,
1223 			   item_tester tester)
1224 {
1225 	struct object *obj;
1226 	int num = 0;
1227 
1228 	/* Sanity */
1229 	if (!square_in_bounds(cave, player->grid)) return 0;
1230 
1231 	/* Scan all objects in the grid */
1232 	for (obj = square_object(cave, player->grid); obj; obj = obj->next) {
1233 		/* Enforce limit */
1234 		if (num >= max_size) break;
1235 
1236 		/* Item tester */
1237 		if ((mode & OFLOOR_TEST) && !object_test(tester, obj)) continue;
1238 
1239 		/* Sensed or known */
1240 		if ((mode & OFLOOR_SENSE) && (!obj->known)) continue;
1241 
1242 		/* Visible */
1243 		if ((mode & OFLOOR_VISIBLE) && !is_unknown(obj) && ignore_item_ok(obj))
1244 			continue;
1245 
1246 		/* Accept this item */
1247 		items[num++] = obj;
1248 
1249 		/* Only one */
1250 		if (mode & OFLOOR_TOP) break;
1251 	}
1252 
1253 	return num;
1254 }
1255 
1256 /**
1257  * Get a list of the known objects at the given location.
1258  *
1259  * Return the number of objects acquired.
1260  */
scan_distant_floor(struct object ** items,int max_size,struct loc grid)1261 int scan_distant_floor(struct object **items, int max_size, struct loc grid)
1262 {
1263 	struct object *obj;
1264 	int num = 0;
1265 
1266 	/* Sanity */
1267 	if (!square_in_bounds(player->cave, grid)) return 0;
1268 
1269 	/* Scan all objects in the grid */
1270 	for (obj = square_object(player->cave, grid); obj; obj = obj->next) {
1271 		/* Enforce limit */
1272 		if (num >= max_size) break;
1273 
1274 		/* Known */
1275 		if (obj->kind == unknown_item_kind) continue;
1276 
1277 		/* Visible */
1278 		if (ignore_known_item_ok(obj)) continue;
1279 
1280 		/* Accept this item's base object */
1281 		items[num++] = cave->objects[obj->oidx];
1282 	}
1283 
1284 	return num;
1285 }
1286 
1287 /**
1288  * Get a list of "valid" objects.
1289  *
1290  * Fills item_list[] with items that are "okay" as defined by the
1291  * provided tester function, etc.  mode determines what combination of
1292  * inventory, equipment, quiver and player's floor location should be used
1293  * when drawing up the list.
1294  *
1295  * Returns the number of items placed into the list.
1296  *
1297  * Maximum space that can be used is
1298  * z_info->pack_size + z_info->quiver_size + player->body.count +
1299  * z_info->floor_size,
1300  * though practically speaking much smaller numbers are likely.
1301  */
scan_items(struct object ** item_list,size_t item_max,int mode,item_tester tester)1302 int scan_items(struct object **item_list, size_t item_max, int mode,
1303 			   item_tester tester)
1304 {
1305 	bool use_inven = ((mode & USE_INVEN) ? true : false);
1306 	bool use_equip = ((mode & USE_EQUIP) ? true : false);
1307 	bool use_quiver = ((mode & USE_QUIVER) ? true : false);
1308 	bool use_floor = ((mode & USE_FLOOR) ? true : false);
1309 
1310 	int floor_max = z_info->floor_size;
1311 	struct object **floor_list = mem_zalloc(floor_max * sizeof(struct object *));
1312 	int floor_num;
1313 
1314 	int i;
1315 	size_t item_num = 0;
1316 
1317 	if (use_inven)
1318 		for (i = 0; i < z_info->pack_size && item_num < item_max; i++) {
1319 			if (object_test(tester, player->upkeep->inven[i]))
1320 				item_list[item_num++] = player->upkeep->inven[i];
1321 		}
1322 
1323 	if (use_equip)
1324 		for (i = 0; i < player->body.count && item_num < item_max; i++) {
1325 			if (object_test(tester, slot_object(player, i)))
1326 				item_list[item_num++] = slot_object(player, i);
1327 		}
1328 
1329 	if (use_quiver)
1330 		for (i = 0; i < z_info->quiver_size && item_num < item_max; i++) {
1331 			if (object_test(tester, player->upkeep->quiver[i]))
1332 				item_list[item_num++] = player->upkeep->quiver[i];
1333 		}
1334 
1335 	/* Scan all non-gold objects in the grid */
1336 	if (use_floor) {
1337 		floor_num = scan_floor(floor_list, floor_max,
1338 							   OFLOOR_TEST | OFLOOR_SENSE | OFLOOR_VISIBLE,
1339 							   tester);
1340 
1341 		for (i = 0; i < floor_num && item_num < item_max; i++)
1342 			item_list[item_num++] = floor_list[i];
1343 	}
1344 
1345 	mem_free(floor_list);
1346 	return item_num;
1347 }
1348 
1349 
1350 /**
1351  * Check if the given item is available for the player to use.
1352  */
item_is_available(struct object * obj)1353 bool item_is_available(struct object *obj)
1354 {
1355 	if (object_is_carried(player, obj)) return true;
1356 	if (cave && square_holds_object(cave, player->grid, obj))
1357 		return true;
1358 	return false;
1359 }
1360