Debian Codegraph @

src/cdogs/bullet_class.c

raw symbols SCIP
1 /*
2 C-Dogs SDL
3 A port of the legendary (and fun) action/arcade cdogs.
4 Copyright (C) 1995 Ronny Wester
5 Copyright (C) 2003 Jeremy Chin
6 Copyright (C) 2003-2007 Lucas Martin-King
7
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21
22 This file incorporates work covered by the following copyright and
23 permission notice:
24
25 Copyright (c) 2013-2019, 2021, 2023 Cong Xu
26 All rights reserved.
27
28 Redistribution and use in source and binary forms, with or without
29 modification, are permitted provided that the following conditions are met:
30
31 Redistributions of source code must retain the above copyright notice, this
32 list of conditions and the following disclaimer.
33 Redistributions in binary form must reproduce the above copyright notice,
34 this list of conditions and the following disclaimer in the documentation
35 and/or other materials provided with the distribution.
36
37 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
38 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
41 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
42 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
43 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
44 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
45 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
47 POSSIBILITY OF SUCH DAMAGE.
48 */
49 #include "bullet_class.h"
50
51 #include <float.h>
52 #include <math.h>
53
54 #include "ai_utils.h"
55 #include "collision/collision.h"
56 #include "draw/drawtools.h"
57 #include "game_events.h"
58 #include "json_utils.h"
59 #include "log.h"
60 #include "net_util.h"
61 #include "objs.h"
62 #include "screen_shake.h"
63
64 BulletClasses gBulletClasses;
65
66 #define WALL_MARK_Z 5
67 // Special damage durations
68 #define FLAMED_COUNT 10
69 #define POISONED_COUNT 8
70 #define MAX_POISONED_COUNT 140
71 #define PETRIFIED_COUNT 95
72 #define CONFUSED_COUNT 700
73
74 int BulletClassesCount(const BulletClasses *classes)
75 {
76 return (int)(classes->Classes.size + classes->CustomClasses.size);
77 }
78
79 // TODO: use map structure?
80 BulletClass *StrBulletClass(const char *s)
81 {
82 if (s == NULL || strlen(s) == 0)
83 {
84 return NULL;
85 }
86 CA_FOREACH(BulletClass, b, gBulletClasses.CustomClasses)
87 if (strcmp(s, b->Name) == 0)
88 {
89 return b;
90 }
91 CA_FOREACH_END()
92 CA_FOREACH(BulletClass, b, gBulletClasses.Classes)
93 if (strcmp(s, b->Name) == 0)
94 {
95 return b;
96 }
97 CA_FOREACH_END()
98 CASSERT(false, "cannot parse bullet name");
99 return NULL;
100 }
101 BulletClass *IdBulletClass(const int i)
102 {
103 CASSERT(
104 i >= 0 && i < (int)gBulletClasses.Classes.size +
105 (int)gBulletClasses.CustomClasses.size,
106 "Bullet index out of bounds");
107 if (i < (int)gBulletClasses.Classes.size)
108 {
109 return CArrayGet(&gBulletClasses.Classes, i);
110 }
111 return CArrayGet(
112 &gBulletClasses.CustomClasses, i - gBulletClasses.Classes.size);
113 }
114
115 // Draw functions
116
117 static void BulletDraw(GraphicsDevice *g, const int id, const struct vec2i pos)
118 {
119 const TMobileObject *obj = CArrayGet(&gMobObjs, id);
120 CASSERT(obj->isInUse, "Cannot draw non-existent mobobj");
121 struct vec2i drawPos =
122 svec2i_subtract(pos, svec2i(0, (int)(obj->z / Z_FACTOR)));
123
124 CPicDrawContext c = CPicDrawContextNew();
125 // Calculate direction based on velocity
126 c.Dir = RadiansToDirection(svec2_angle(obj->thing.Vel) + MPI_2);
127 const Pic *pic = CPicGetPic(&obj->thing.CPic, c.Dir);
128 if (pic != NULL)
129 {
130 c.Offset = svec2i_scale_divide(pic->size, -2);
131 }
132 CPicDraw(g, &obj->thing.CPic, drawPos, &c);
133 }
134
135 static struct vec2 SeekTowards(
136 const struct vec2 pos, const struct vec2 vel, const float speedMin,
137 const struct vec2 targetPos, const int seekFactor)
138 {
139 // Compensate for bullet's velocity
140 const struct vec2 targetVel =
141 svec2_subtract(svec2_subtract(targetPos, pos), vel);
142 // Don't seek if the coordinates are too big
143 if (fabsf(targetVel.x) > 40 || fabsf(targetVel.y) > 40 ||
144 svec2_is_zero(targetVel))
145 {
146 return vel;
147 }
148 const float targetMag = svec2_length(targetVel);
149 const float magnitude = MAX(speedMin, svec2_length(vel));
150 const float combinedX =
151 vel.x / magnitude * seekFactor + targetVel.x / targetMag;
152 const float combinedY =
153 vel.y / magnitude * seekFactor + targetVel.y / targetMag;
154 return svec2(
155 combinedX * magnitude / (seekFactor + 1),
156 combinedY * magnitude / (seekFactor + 1));
157 }
158
159 static void FireGuns(const TMobileObject *obj, const CArray *guns);
160 static void AddTrail(
161 TMobileObject *obj, const struct vec2 from, const struct vec2 to,
162 const int ticks);
163 typedef struct
164 {
165 HitType Type;
166 struct vec2 Pos;
167 struct vec2 Normal;
168 } HitResult;
169 static HitResult HitItem(
170 TMobileObject *obj, const struct vec2 pos, const struct vec2 vel,
171 const bool multipleHits);
172 bool BulletUpdate(struct MobileObject *obj, const int ticks)
173 {
174 ThingUpdate(&obj->thing, ticks);
175 obj->count += ticks;
176 if (obj->count < obj->bulletClass->Delay)
177 {
178 return true;
179 }
180
181 if (obj->range >= 0 && obj->count > obj->range)
182 {
183 if (!gCampaign.IsClient)
184 {
185 FireGuns(obj, &obj->bulletClass->OutOfRangeGuns);
186 }
187 if (obj->bulletClass->OutOfRangeSpark != NULL)
188 {
189 GameEvent s = GameEventNew(GAME_EVENT_ADD_PARTICLE);
190 s.u.AddParticle.Class = obj->bulletClass->OutOfRangeSpark;
191 s.u.AddParticle.Pos = obj->thing.Pos;
192 s.u.AddParticle.Z = obj->z;
193 GameEventsEnqueue(&gGameEvents, s);
194 }
195 return false;
196 }
197
198 if (obj->bulletClass->SeekFactor > 0)
199 {
200 // Find the closest target to this bullet and steer towards it
201 const TActor *owner = ActorGetByUID(obj->ActorUID);
202 if (owner == NULL)
203 {
204 return false;
205 }
206 const TActor *target =
207 AIGetClosestEnemy(obj->thing.Pos, owner, obj->flags);
208 if (target && !target->dead)
209 {
210 for (int i = 0; i < ticks; i++)
211 {
212 obj->thing.Vel = SeekTowards(
213 obj->thing.Pos, obj->thing.Vel, obj->bulletClass->SpeedLow,
214 target->Pos, obj->bulletClass->SeekFactor);
215 }
216 }
217 }
218
219 // Bullet travel, including bouncing, and trails
220 struct vec2 pos =
221 svec2_add(obj->thing.Pos, svec2_scale(obj->thing.Vel, (float)ticks));
222 // Loop over multiple bounces
223 struct vec2 posStart = obj->thing.Pos;
224 struct vec2 vel = svec2_subtract(pos, obj->thing.Pos);
225 bool alive = true;
226 bool bounced = false;
227 bool hasHit = false;
228 do
229 {
230 const HitResult hit =
231 HitItem(obj, posStart, vel, obj->bulletClass->Persists);
232 if (hit.Type == HIT_NONE)
233 {
234 break;
235 }
236 hasHit = true;
237 bounced = hit.Type == HIT_WALL && !svec2_is_zero(obj->thing.Vel) &&
238 alive &&
239 !svec2_is_nearly_equal(posStart, hit.Pos, EPSILON_POS);
240 const struct vec2 hitPos = hit.Type != HIT_NONE ? hit.Pos : pos;
241 if (bounced)
242 {
243 // Bouncing
244 GetWallBouncePosVel(
245 posStart, obj->thing.Vel, hit.Pos, hit.Normal, &pos,
246 &obj->thing.Vel);
247 }
248
249 if (!gCampaign.IsClient)
250 {
251 GameEvent b = GameEventNew(GAME_EVENT_BULLET_BOUNCE);
252 b.u.BulletBounce.UID = obj->UID;
253 b.u.BulletBounce.HitType = (int)hit.Type;
254 if ((hit.Type == HIT_WALL && !obj->bulletClass->WallBounces) ||
255 (hit.Type == HIT_OBJECT && obj->bulletClass->Hit.Object.Hit) ||
256 (hit.Type == HIT_FLESH && obj->bulletClass->Hit.Flesh.Hit))
257 {
258 b.u.BulletBounce.Spark = true;
259 CASSERT(
260 !gCampaign.IsClient, "Cannot process bounces as client");
261 FireGuns(obj, &obj->bulletClass->HitGuns);
262 if (hit.Type == HIT_WALL || !obj->bulletClass->Persists)
263 {
264 alive = false;
265 }
266 // Leave a wall mark if hitting a south-facing wall
267 if (hit.Type == HIT_WALL && vel.y < 0 &&
268 !TileIsOpaque(MapGetTile(
269 &gMap, Vec2ToTile(svec2(hit.Pos.x, hit.Pos.y + 1)))))
270 {
271 b.u.BulletBounce.WallMark = true;
272 }
273 }
274 b.u.BulletBounce.Pos = b.u.BulletBounce.BouncePos =
275 Vec2ToNet(hitPos);
276 b.u.BulletBounce.Vel = Vec2ToNet(obj->thing.Vel);
277 if (bounced)
278 {
279 b.u.BulletBounce.Pos = Vec2ToNet(pos);
280 }
281 b.u.BulletBounce.HitSound = obj->thing.SoundLock == 0;
282 if (obj->thing.SoundLock <= 0)
283 {
284 obj->thing.SoundLock += SOUND_LOCK_THING;
285 }
286 GameEventsEnqueue(&gGameEvents, b);
287 }
288
289 AddTrail(obj, posStart, (bounced || !alive) ? hit.Pos : pos, ticks);
290 if (bounced)
291 {
292 // Get the remaining length of travel after the bounce
293 const float preBounceLen =
294 svec2_length(svec2_subtract(hit.Pos, posStart));
295 const float fullLen = svec2_length(vel);
296 const struct vec2 velNorm = svec2_normalize(obj->thing.Vel);
297 // Move bullet slightly in direction of bounce so that it doesn't
298 // bounce against the same wall
299 posStart = svec2_add(hit.Pos, velNorm);
300 vel = svec2_scale(velNorm, fullLen - preBounceLen - 1);
301 }
302 // Don't allow slow moving bullets to bounce forever
303 } while (alive && bounced && svec2_length_squared(vel) > 2);
304 if (!alive)
305 {
306 return false;
307 }
308 AddTrail(obj, posStart, svec2_add(posStart, vel), ticks);
309 if (hasHit && obj->thing.SoundLock == 0)
310 {
311 obj->thing.SoundLock += SOUND_LOCK_THING;
312 }
313
314 // Falling (grenades)
315 if (obj->bulletClass->Falling.GravityFactor != 0)
316 {
317 bool hasDropped = obj->z <= 0;
318 for (int i = 0; i < ticks; i++)
319 {
320 obj->z += obj->dz;
321 if (obj->z <= 0)
322 {
323 obj->z = 0;
324 if (obj->bulletClass->Falling.Bounces)
325 {
326 obj->dz = -obj->dz / 2;
327 }
328 else
329 {
330 obj->dz = 0;
331 }
332 if (!hasDropped)
333 {
334 if (!gCampaign.IsClient)
335 {
336 FireGuns(obj, &obj->bulletClass->Falling.DropGuns);
337 }
338 }
339 hasDropped = true;
340 if (obj->bulletClass->Falling.DestroyOnDrop)
341 {
342 return false;
343 }
344 GameEvent es = GameEventNew(GAME_EVENT_SOUND_AT);
345 strcpy(es.u.SoundAt.Sound, obj->bulletClass->Hit.Wall.Sound);
346 es.u.SoundAt.Pos = Vec2ToNet(pos);
347 GameEventsEnqueue(&gGameEvents, es);
348 }
349 else
350 {
351 obj->dz -= obj->bulletClass->Falling.GravityFactor;
352 }
353 if (!obj->bulletClass->Falling.FallsDown)
354 {
355 obj->dz = MAX(0, obj->dz);
356 }
357 }
358 }
359
360 // Friction
361 const bool isDiagonal = fabsf(obj->thing.Vel.x) < FLT_EPSILON &&
362 fabsf(obj->thing.Vel.y) < FLT_EPSILON;
363 const float frictionComponent = isDiagonal
364 ? obj->bulletClass->Friction / sqrtf(2)
365 : obj->bulletClass->Friction;
366 for (int i = 0; i < ticks; i++)
367 {
368 if (obj->thing.Vel.x > FLT_EPSILON)
369 {
370 obj->thing.Vel.x -= frictionComponent;
371 }
372 else if (obj->thing.Vel.x < -FLT_EPSILON)
373 {
374 obj->thing.Vel.x += frictionComponent;
375 }
376
377 if (obj->thing.Vel.y > FLT_EPSILON)
378 {
379 obj->thing.Vel.y -= frictionComponent;
380 }
381 else if (obj->thing.Vel.y < -FLT_EPSILON)
382 {
383 obj->thing.Vel.y += frictionComponent;
384 }
385 }
386 if (!MapTryMoveThing(&gMap, &obj->thing, pos))
387 {
388 obj->count = obj->range;
389 return false;
390 }
391
392 if (obj->bulletClass->Erratic)
393 {
394 for (int i = 0; i < ticks; i++)
395 {
396 obj->thing.Vel = svec2_add(
397 obj->thing.Vel,
398 svec2_scale(
399 svec2((float)(rand() % 3) - 1, (float)(rand() % 3) - 1),
400 0.5f));
401 }
402 }
403
404 // Proximity function, destroy
405 // Only check proximity every now and then
406 if (obj->bulletClass->ProximityGuns.size > 0 && !(obj->count & 3))
407 {
408 if (!gCampaign.IsClient)
409 {
410 // Detonate the mine if there are characters in the tiles around it
411 const struct vec2i tv = Vec2ToTile(pos);
412 struct vec2i dv;
413 for (dv.y = -1; dv.y <= 1; dv.y++)
414 {
415 for (dv.x = -1; dv.x <= 1; dv.x++)
416 {
417 const struct vec2i dtv = svec2i_add(tv, dv);
418 if (!MapIsTileIn(&gMap, dtv))
419 {
420 continue;
421 }
422 if (TileHasCharacter(MapGetTile(&gMap, dtv)))
423 {
424 FireGuns(obj, &obj->bulletClass->ProximityGuns);
425 return false;
426 }
427 }
428 }
429 }
430 }
431
432 return true;
433 }
434 static void FireGuns(const TMobileObject *obj, const CArray *guns)
435 {
436 const float angle = svec2_angle(obj->thing.Vel) + MPI_2;
437 for (int i = 0; i < (int)guns->size; i++)
438 {
439 const WeaponClass **wc = CArrayGet(guns, i);
440 CASSERT((*wc)->Type != GUNTYPE_MULTI, "unexpected gun type");
441 WeaponClassFire(
442 *wc, obj->thing.Pos, obj->z, angle, obj->flags, obj->ActorUID,
443 true, false);
444 }
445 }
446 static void AddTrail(
447 TMobileObject *obj, const struct vec2 from, const struct vec2 to,
448 const int ticks)
449 {
450 if (obj->bulletClass->Trail.P == NULL)
451 {
452 return;
453 }
454 const struct vec2 vel = svec2_subtract(to, from);
455 AddParticle ap;
456 memset(&ap, 0, sizeof ap);
457 ap.Pos = svec2_scale(svec2_add(to, from), 0.5f);
458 ap.Z = obj->z / Z_FACTOR;
459 ap.Angle = svec2_angle(vel) + MPI_2;
460 ap.Mask = colorTransparent;
461 if (obj->bulletClass->Trail.P->Type == PARTICLE_PIC)
462 {
463 const CPic *cpic = &obj->bulletClass->Trail.P->u.Pic;
464 const Pic *pic = CPicGetPic(cpic, 0);
465 if (obj->bulletClass->Trail.Width > 0)
466 {
467 const struct vec2 trailSize =
468 svec2(obj->bulletClass->Trail.Width, svec2_length(vel));
469 ap.DrawScale =
470 svec2_divide(trailSize, svec2_assign_vec2i(pic->size));
471 }
472 ap.Mask = cpic->Mask;
473 }
474 if (obj->trail.ticksPerEmit > 0 && ticks > 0)
475 {
476 EmitterUpdate(&obj->trail, &ap, ticks);
477 }
478 else
479 {
480 EmitterStart(&obj->trail, &ap);
481 }
482 }
483 typedef struct
484 {
485 HitType HitType;
486 bool MultipleHits;
487 TMobileObject *Obj;
488 union {
489 Thing *Target;
490 struct vec2i TilePos;
491 } u;
492 struct vec2 ColPos;
493 struct vec2 ColNormal;
494 float ColPosDist2;
495 } HitItemData;
496 static bool HitItemFunc(
497 Thing *ti, void *data, const struct vec2 colA, const struct vec2 colB,
498 const struct vec2 normal);
499 static bool CheckWall(const struct vec2i tilePos);
500 static bool HitWallFunc(
501 const struct vec2i tilePos, void *data, const struct vec2 col,
502 const struct vec2 normal);
503 static void OnHit(HitItemData *data, Thing *target);
504 static HitResult HitItem(
505 TMobileObject *obj, const struct vec2 pos, const struct vec2 vel,
506 const bool multipleHits)
507 {
508 // Get all items that collide
509 HitItemData data;
510 data.HitType = HIT_NONE;
511 data.MultipleHits = multipleHits;
512 data.Obj = obj;
513 data.ColPos = pos;
514 data.ColNormal = svec2_zero();
515 data.ColPosDist2 = -1;
516 const CollisionParams params = {
517 THING_CAN_BE_SHOT, COLLISIONTEAM_NONE, IsPVP(gCampaign.Entry.Mode),
518 false};
519 OverlapThings(
520 &obj->thing, pos, vel, obj->thing.size, params, HitItemFunc, &data,
521 CheckWall, HitWallFunc, &data);
522 if (!multipleHits && data.ColPosDist2 >= 0)
523 {
524 if (data.HitType == HIT_OBJECT || data.HitType == HIT_FLESH)
525 {
526 OnHit(&data, data.u.Target);
527 }
528 }
529 HitResult hit = {data.HitType, data.ColPos, data.ColNormal};
530 return hit;
531 }
532 static HitType GetHitType(
533 const Thing *ti, const TMobileObject *bullet, int *targetUID);
534 static void SetClosestCollision(
535 HitItemData *data, const struct vec2 col, const struct vec2 normal,
536 const HitType ht, Thing *target, const struct vec2i tilePos);
537 static bool HitItemFunc(
538 Thing *ti, void *data, const struct vec2 colA, const struct vec2 colB,
539 const struct vec2 normal)
540 {
541 UNUSED(colB);
542 HitItemData *hData = data;
543
544 // Check bullet-to-other collisions
545 if (!CanHit(
546 hData->Obj->bulletClass, hData->Obj->flags, hData->Obj->ActorUID,
547 ti))
548 {
549 goto bail;
550 }
551
552 // If we can hit multiple targets, just process those hits immediately
553 // Otherwise, find the closest target and only process the hit for that one
554 // at the end.
555 if (hData->MultipleHits)
556 {
557 OnHit(hData, ti);
558 }
559 else
560 {
561 SetClosestCollision(
562 hData, colA, normal, GetHitType(ti, hData->Obj, NULL), ti,
563 svec2i_zero());
564 }
565
566 bail:
567 return true;
568 }
569 static HitType GetHitType(
570 const Thing *ti, const TMobileObject *bullet, int *targetUID)
571 {
572 int tUID = -1;
573 HitType ht = HIT_NONE;
574 switch (ti->kind)
575 {
576 case KIND_CHARACTER:
577 ht = HIT_FLESH;
578 tUID = ((const TActor *)CArrayGet(&gActors, ti->id))->uid;
579 break;
580 case KIND_OBJECT:
581 ht = HIT_OBJECT;
582 tUID = ((const TObject *)CArrayGet(&gObjs, ti->id))->uid;
583 break;
584 default:
585 CASSERT(false, "cannot damage target kind");
586 break;
587 }
588 if (bullet->thing.SoundLock > 0 ||
589 !HasHitSound(
590 ti->kind, tUID, bullet->bulletClass->Special.Effect, true))
591 {
592 ht = HIT_NONE;
593 }
594 if (targetUID != NULL)
595 {
596 *targetUID = tUID;
597 }
598 return ht;
599 }
600 static bool CheckWall(const struct vec2i tilePos)
601 {
602 const Tile *t = MapGetTile(&gMap, tilePos);
603 return t == NULL || TileIsShootable(t);
604 }
605 static bool HitWallFunc(
606 const struct vec2i tilePos, void *data, const struct vec2 col,
607 const struct vec2 normal)
608 {
609 HitItemData *hData = data;
610
611 SetClosestCollision(hData, col, normal, HIT_WALL, NULL, tilePos);
612
613 return true;
614 }
615 static void SetClosestCollision(
616 HitItemData *data, const struct vec2 col, const struct vec2 normal,
617 const HitType ht, Thing *target, const struct vec2i tilePos)
618 {
619 // Choose the best collision point (i.e. closest to origin)
620 const float d2 = svec2_distance_squared(col, data->Obj->thing.Pos);
621 if (data->ColPosDist2 < 0 || d2 < data->ColPosDist2)
622 {
623 data->ColPos = col;
624 data->ColPosDist2 = d2;
625 data->ColNormal = normal;
626 data->HitType = ht;
627 if (ht == HIT_WALL)
628 {
629 data->u.TilePos = tilePos;
630 }
631 else
632 {
633 data->u.Target = target;
634 }
635 }
636 }
637 static void OnHit(HitItemData *data, Thing *target)
638 {
639 if (gCampaign.IsClient)
640 {
641 return;
642 }
643 int targetUID = -1;
644 data->HitType = GetHitType(target, data->Obj, &targetUID);
645 const TActor *source = ActorGetByUID(data->Obj->ActorUID);
646 Damage(
647 data->Obj->thing.Vel, data->Obj->bulletClass, data->Obj->weapon,
648 data->Obj->flags, source, target->kind, targetUID);
649 if (target->SoundLock <= 0)
650 {
651 target->SoundLock += SOUND_LOCK_THING;
652 }
653 }
654
655 #define VERSION 5
656 static void LoadBullet(
657 BulletClass *b, json_t *node, const BulletClass *defaultBullet,
658 const int version);
659 void BulletInitialize(BulletClasses *bullets)
660 {
661 memset(bullets, 0, sizeof *bullets);
662 CArrayInit(&bullets->Classes, sizeof(BulletClass));
663 CArrayInit(&bullets->CustomClasses, sizeof(BulletClass));
664 }
665 static void BulletClassFree(BulletClass *b);
666 void BulletLoadJSON(
667 BulletClasses *bullets, CArray *classes, json_t *bulletNode)
668 {
669 LOG(LM_MAP, LL_DEBUG, "loading bullets");
670 int version;
671 LoadInt(&version, bulletNode, "Version");
672 if (version > VERSION || version <= 0)
673 {
674 CASSERT(false, "cannot read bullets file version");
675 return;
676 }
677
678 // Defaults
679 json_t *defaultNode = json_find_first_label(bulletNode, "DefaultBullet");
680 if (defaultNode != NULL)
681 {
682 BulletClassFree(&bullets->Default);
683 LoadBullet(&bullets->Default, defaultNode->child, NULL, version);
684 }
685
686 json_t *bulletsNode = json_find_first_label(bulletNode, "Bullets")->child;
687 for (json_t *child = bulletsNode->child; child; child = child->next)
688 {
689 BulletClass b;
690 LoadBullet(&b, child, &bullets->Default, version);
691 CArrayPushBack(classes, &b);
692 }
693
694 bullets->root = bulletNode;
695 }
696 static void LoadParticle(
697 const ParticleClass **p, json_t *node, const char *name);
698 static void LoadHitsound(
699 char **hitsound, json_t *node, const char *name, const int version);
700 static void LoadBullet(
701 BulletClass *b, json_t *node, const BulletClass *defaultBullet,
702 const int version)
703 {
704 memset(b, 0, sizeof *b);
705 if (defaultBullet != NULL)
706 {
707 memcpy(b, defaultBullet, sizeof *b);
708 if (defaultBullet->Name != NULL)
709 {
710 CSTRDUP(b->Name, defaultBullet->Name);
711 }
712 if (defaultBullet->Hit.Object.Sound != NULL)
713 {
714 CSTRDUP(b->Hit.Object.Sound, defaultBullet->Hit.Object.Sound);
715 }
716 if (defaultBullet->Hit.Flesh.Sound != NULL)
717 {
718 CSTRDUP(b->Hit.Flesh.Sound, defaultBullet->Hit.Flesh.Sound);
719 }
720 if (defaultBullet->Hit.Wall.Sound != NULL)
721 {
722 CSTRDUP(b->Hit.Wall.Sound, defaultBullet->Hit.Wall.Sound);
723 }
724 // TODO: enable default bullet guns?
725 memset(&b->Falling.DropGuns, 0, sizeof b->Falling.DropGuns);
726 memset(&b->OutOfRangeGuns, 0, sizeof b->OutOfRangeGuns);
727 memset(&b->HitGuns, 0, sizeof b->HitGuns);
728 memset(&b->ProximityGuns, 0, sizeof b->ProximityGuns);
729 }
730
731 char *tmp;
732
733 tmp = NULL;
734 LoadStr(&tmp, node, "Name");
735 if (tmp != NULL)
736 {
737 CFREE(b->Name);
738 b->Name = tmp;
739 }
740 if (json_find_first_label(node, "Pic"))
741 {
742 CPicLoadJSON(&b->CPic, json_find_first_label(node, "Pic")->child);
743 }
744 if (json_find_first_label(node, "Trail"))
745 {
746 json_t *trail = json_find_first_label(node, "Trail")->child;
747 tmp = NULL;
748 LoadStr(&tmp, trail, "Particle");
749 if (tmp != NULL)
750 {
751 b->Trail.P = StrParticleClass(&gParticleClasses, tmp);
752 CFREE(tmp);
753 }
754 b->Trail.Width = 1.0f;
755 LoadFloat(&b->Trail.Width, trail, "Width");
756 LoadInt(&b->Trail.TicksPerEmit, trail, "TicksPerEmit");
757 }
758 LoadVec2i(&b->ShadowSize, node, "ShadowSize");
759 LoadInt(&b->Delay, node, "Delay");
760 if (json_find_first_label(node, "Speed"))
761 {
762 LoadFullInt(&b->SpeedLow, node, "Speed");
763 b->SpeedHigh = b->SpeedLow;
764 }
765 LoadFullInt(&b->SpeedLow, node, "SpeedLow");
766 LoadFullInt(&b->SpeedHigh, node, "SpeedHigh");
767 b->SpeedLow = MIN(b->SpeedLow, b->SpeedHigh);
768 b->SpeedHigh = MAX(b->SpeedLow, b->SpeedHigh);
769 LoadBool(&b->SpeedScale, node, "SpeedScale");
770 LoadFullInt(&b->Friction, node, "Friction");
771 if (json_find_first_label(node, "Range"))
772 {
773 LoadInt(&b->RangeLow, node, "Range");
774 b->RangeHigh = b->RangeLow;
775 }
776 LoadInt(&b->RangeLow, node, "RangeLow");
777 LoadInt(&b->RangeHigh, node, "RangeHigh");
778 b->RangeLow = MIN(b->RangeLow, b->RangeHigh);
779 b->RangeHigh = MAX(b->RangeLow, b->RangeHigh);
780 LoadInt(&b->Power, node, "Power");
781
782 if (version < 2)
783 {
784 // Old version default mass = power
785 b->Mass = (float)b->Power;
786 }
787 else
788 {
789 LoadFloat(&b->Mass, node, "Mass");
790 }
791
792 LoadVec2i(&b->Size, node, "Size");
793
794 tmp = NULL;
795 if (version < 4)
796 {
797 LoadStr(&tmp, node, "Special");
798 if (tmp != NULL)
799 {
800 b->Special.Effect = StrSpecialDamage(tmp);
801 CFREE(tmp);
802 }
803 }
804 else
805 {
806 if (json_find_first_label(node, "Special"))
807 {
808 json_t *special = json_find_first_label(node, "Special")->child;
809 LoadStr(&tmp, special, "Effect");
810 if (tmp != NULL)
811 {
812 b->Special.Effect = StrSpecialDamage(tmp);
813 CFREE(tmp);
814 }
815 LoadInt(&b->Special.Ticks, special, "Ticks");
816 }
817 }
818 if (b->Special.Effect != SPECIAL_NONE && b->Special.Ticks == 0)
819 {
820 // Default special damage ticks
821 switch (b->Special.Effect)
822 {
823 case SPECIAL_FLAME:
824 b->Special.Ticks = FLAMED_COUNT;
825 break;
826 case SPECIAL_POISON:
827 b->Special.Ticks = POISONED_COUNT;
828 break;
829 case SPECIAL_PETRIFY:
830 b->Special.Ticks = PETRIFIED_COUNT;
831 break;
832 case SPECIAL_CONFUSE:
833 b->Special.Ticks = CONFUSED_COUNT;
834 break;
835 default:
836 CASSERT(false, "unknown special damage");
837 break;
838 }
839 }
840
841 LoadBool(&b->HurtAlways, node, "HurtAlways");
842 LoadBool(&b->Persists, node, "Persists");
843 LoadParticle(&b->Spark, node, "Spark");
844 LoadParticle(&b->OutOfRangeSpark, node, "OutOfRangeSpark");
845 LoadParticle(&b->WallMark, node, "WallMark");
846 if (version < 5)
847 {
848 if (json_find_first_label(node, "HitSounds"))
849 {
850 json_t *hitSounds =
851 json_find_first_label(node, "HitSounds")->child;
852 LoadHitsound(&b->Hit.Object.Sound, hitSounds, "Object", version);
853 LoadHitsound(&b->Hit.Flesh.Sound, hitSounds, "Flesh", version);
854 LoadHitsound(&b->Hit.Wall.Sound, hitSounds, "Wall", version);
855 }
856 // Version < 5 HitsObjects represents both object and flesh hits
857 bool hitsObjectsAndFlesh = true;
858 LoadBool(&hitsObjectsAndFlesh, node, "HitsObjects");
859 b->Hit.Object.Hit = b->Hit.Flesh.Hit = hitsObjectsAndFlesh;
860 }
861 else if (json_find_first_label(node, "Hit"))
862 {
863 const json_t *hits = json_find_first_label(node, "Hit")->child;
864 const char *hitNodes[] = {"Object", "Flesh", "Wall"};
865 HitProps *hps[] = {&b->Hit.Object, &b->Hit.Flesh, &b->Hit.Wall};
866 for (int i = 0; i < 3; i++)
867 {
868 HitProps *hp = hps[i];
869 hp->Hit = false;
870 if (json_find_first_label(hits, hitNodes[i]))
871 {
872 json_t *hit = json_find_first_label(hits, hitNodes[i])->child;
873 hp->Hit = true;
874 if (json_find_first_label(hit, "Sound"))
875 {
876 CFREE(hp->Sound);
877 hp->Sound = GetString(hit, "Sound");
878 }
879 }
880 }
881 }
882 LoadBool(&b->WallBounces, node, "WallBounces");
883 if (json_find_first_label(node, "Falling"))
884 {
885 json_t *falling = json_find_first_label(node, "Falling")->child;
886 LoadFloat(&b->Falling.GravityFactor, falling, "GravityFactor");
887 b->Falling.FallsDown = true;
888 LoadBool(&b->Falling.FallsDown, falling, "FallsDown");
889 LoadBool(&b->Falling.DestroyOnDrop, falling, "DestroyOnDrop");
890 LoadBool(&b->Falling.Bounces, falling, "Bounces");
891 }
892 LoadInt(&b->SeekFactor, node, "SeekFactor");
893 LoadBool(&b->Erratic, node, "Erratic");
894
895 b->node = node;
896
897 LOG(LM_MAP, LL_DEBUG,
898 "loaded bullet name(%s) shadowSize(%d, %d) delay(%d) speed(%f-%f)...",
899 b->Name != NULL ? b->Name : "", b->ShadowSize.x, b->ShadowSize.y,
900 b->Delay, b->SpeedLow, b->SpeedHigh);
901 LOG(LM_MAP, LL_DEBUG,
902 "...speedScale(%s) friction(%f) range(%d-%d) power(%d)...",
903 b->SpeedScale ? "true" : "false", b->Friction, b->RangeLow,
904 b->RangeHigh, b->Power);
905 LOG(LM_MAP, LL_DEBUG,
906 "...size(%d, %d) hurtAlways(%s) persists(%s) spark(%s, %s)...",
907 b->Size.x, b->Size.y, b->HurtAlways ? "true" : "false",
908 b->Persists ? "true" : "false", b->Spark != NULL ? b->Spark->Name : "",
909 b->OutOfRangeSpark != NULL ? b->OutOfRangeSpark->Name : "");
910 LOG(LM_MAP, LL_DEBUG, "...wallMark(%s)...",
911 b->WallMark != NULL ? b->WallMark->Name : "");
912 LOG(LM_MAP, LL_DEBUG,
913 "...hit(object(%s, %s), flesh(%s, %s), wall(%s, %s)) "
914 "wallBounces(%s)...",
915 b->Hit.Object.Hit ? "true" : "false",
916 b->Hit.Object.Sound != NULL ? b->Hit.Object.Sound : "",
917 b->Hit.Flesh.Hit ? "true" : "false",
918 b->Hit.Flesh.Sound != NULL ? b->Hit.Flesh.Sound : "",
919 b->Hit.Wall.Hit ? "true" : "false",
920 b->Hit.Wall.Sound != NULL ? b->Hit.Wall.Sound : "",
921 b->WallBounces ? "true" : "false");
922 LOG(LM_MAP, LL_DEBUG, "...gravity(%f) fallsDown(%s) destroyOnDrop(%s)...",
923 b->Falling.GravityFactor, b->Falling.FallsDown ? "true" : "false",
924 b->Falling.DestroyOnDrop ? "true" : "false");
925 LOG(LM_MAP, LL_DEBUG,
926 "...dropGuns(%d) seekFactor(%d) erratic(%s) trail(%s@%f per %d)...",
927 (int)b->Falling.DropGuns.size, b->SeekFactor,
928 b->Erratic ? "true" : "false",
929 b->Trail.P != NULL ? b->Trail.P->Name : "", b->Trail.Width,
930 b->Trail.TicksPerEmit);
931 LOG(LM_MAP, LL_DEBUG,
932 "...outOfRangeGuns(%d) hitGuns(%d) proximityGuns(%d)",
933 (int)b->OutOfRangeGuns.size, (int)b->HitGuns.size,
934 (int)b->ProximityGuns.size);
935 }
936 static void LoadHitsound(
937 char **hitsound, json_t *node, const char *name, const int version)
938 {
939 CFREE(*hitsound);
940 *hitsound = NULL;
941 LoadStr(hitsound, node, name);
942 if (version < 3)
943 {
944 // Moved hit_XXX sounds to hits folder
945 if (*hitsound != NULL)
946 {
947 char buf[CDOGS_FILENAME_MAX];
948 strcpy(buf, "hits/");
949 if (strncmp(*hitsound, "hit_", strlen("hit_")) == 0)
950 {
951 strcat(buf, *hitsound + strlen("hit_"));
952 CFREE(*hitsound);
953 CSTRDUP(*hitsound, buf);
954 }
955 else if (strncmp(*hitsound, "knife_", strlen("knife_")) == 0)
956 {
957 strcpy(buf, "hits/knife_");
958 strcat(buf, *hitsound + strlen("knife_"));
959 CFREE(*hitsound);
960 CSTRDUP(*hitsound, buf);
961 }
962 }
963 }
964 }
965 static void LoadParticle(
966 const ParticleClass **p, json_t *node, const char *name)
967 {
968 char *tmp = NULL;
969 LoadStr(&tmp, node, name);
970 if (tmp != NULL)
971 {
972 *p = StrParticleClass(&gParticleClasses, tmp);
973 }
974 CFREE(tmp);
975 }
976 static void BulletClassesLoadWeapons(CArray *classes);
977 void BulletLoadWeapons(BulletClasses *bullets)
978 {
979 BulletClassesLoadWeapons(&bullets->Classes);
980 BulletClassesLoadWeapons(&bullets->CustomClasses);
981 json_free_value(&bullets->root);
982 }
983 static void BulletClassesLoadWeapons(CArray *classes)
984 {
985 for (int i = 0; i < (int)classes->size; i++)
986 {
987 BulletClass *b = CArrayGet(classes, i);
988 if (b->node == NULL)
989 {
990 continue;
991 }
992
993 if (json_find_first_label(b->node, "Falling"))
994 {
995 LoadBulletGuns(
996 &b->Falling.DropGuns,
997 json_find_first_label(b->node, "Falling")->child, "DropGuns");
998 }
999 LoadBulletGuns(&b->OutOfRangeGuns, b->node, "OutOfRangeGuns");
1000 LoadBulletGuns(&b->HitGuns, b->node, "HitGuns");
1001 LoadBulletGuns(&b->ProximityGuns, b->node, "ProximityGuns");
1002
1003 b->node = NULL;
1004 }
1005 }
1006 void BulletTerminate(BulletClasses *bullets)
1007 {
1008 BulletClassFree(&bullets->Default);
1009 BulletClassesClear(&bullets->Classes);
1010 CArrayTerminate(&bullets->Classes);
1011 BulletClassesClear(&bullets->CustomClasses);
1012 CArrayTerminate(&bullets->CustomClasses);
1013 }
1014 void BulletClassesClear(CArray *classes)
1015 {
1016 for (int i = 0; i < (int)classes->size; i++)
1017 {
1018 BulletClassFree(CArrayGet(classes, i));
1019 }
1020 CArrayClear(classes);
1021 }
1022 static void BulletClassFree(BulletClass *b)
1023 {
1024 CFREE(b->Name);
1025 CFREE(b->Hit.Object.Sound);
1026 CFREE(b->Hit.Flesh.Sound);
1027 CFREE(b->Hit.Wall.Sound);
1028 CArrayTerminate(&b->OutOfRangeGuns);
1029 CArrayTerminate(&b->HitGuns);
1030 CArrayTerminate(&b->Falling.DropGuns);
1031 CArrayTerminate(&b->ProximityGuns);
1032 }
1033
1034 void BulletAdd(const NAddBullet add)
1035 {
1036 const struct vec2 pos = NetToVec2(add.MuzzlePos);
1037
1038 // Find an empty slot in mobobj list
1039 TMobileObject *obj = NULL;
1040 int i;
1041 for (i = 0; i < (int)gMobObjs.size; i++)
1042 {
1043 TMobileObject *m = CArrayGet(&gMobObjs, i);
1044 if (!m->isInUse)
1045 {
1046 obj = m;
1047 break;
1048 }
1049 }
1050 if (obj == NULL)
1051 {
1052 TMobileObject m;
1053 memset(&m, 0, sizeof m);
1054 CArrayPushBack(&gMobObjs, &m);
1055 i = (int)gMobObjs.size - 1;
1056 obj = CArrayGet(&gMobObjs, i);
1057 }
1058 memset(obj, 0, sizeof *obj);
1059 obj->UID = add.UID;
1060 obj->bulletClass = StrBulletClass(add.BulletClass);
1061 ThingInit(&obj->thing, i, KIND_MOBILEOBJECT, obj->bulletClass->Size, 0);
1062 obj->z = (float)add.MuzzleHeight;
1063 obj->dz = (float)add.Elevation;
1064
1065 EmitterInit(
1066 &obj->trail, obj->bulletClass->Trail.P, svec2_zero(), 0, 0, 0, 0, 0, 0,
1067 obj->bulletClass->Trail.TicksPerEmit);
1068
1069 obj->thing.Vel = svec2_scale(
1070 Vec2FromRadians(add.Angle),
1071 RAND_FLOAT(obj->bulletClass->SpeedLow, obj->bulletClass->SpeedHigh));
1072 if (obj->bulletClass->SpeedScale)
1073 {
1074 obj->thing.Vel.y *= (float)TILE_WIDTH / TILE_HEIGHT;
1075 }
1076
1077 obj->ActorUID = add.ActorUID;
1078 obj->range =
1079 RAND_INT(obj->bulletClass->RangeLow, obj->bulletClass->RangeHigh);
1080
1081 obj->flags = add.Flags;
1082 if (obj->bulletClass->HurtAlways)
1083 {
1084 obj->flags |= FLAGS_HURTALWAYS;
1085 }
1086
1087 obj->weapon = StrWeaponClass(add.Gun);
1088
1089 obj->isInUse = true;
1090 obj->thing.drawFunc = NULL;
1091 obj->thing.drawData.MobObjId = i;
1092 obj->thing.CPic = obj->bulletClass->CPic;
1093 obj->thing.CPicFunc = BulletDraw;
1094 obj->thing.ShadowSize = obj->bulletClass->ShadowSize;
1095 MapTryMoveThing(&gMap, &obj->thing, pos);
1096
1097 // Update shots
1098 if (!gCampaign.IsClient)
1099 {
1100 const TActor *source = ActorGetByUID(add.ActorUID);
1101 const int playerUID = source != NULL ? source->PlayerUID : -1;
1102 PlayerData *p = PlayerDataGetByUID(playerUID);
1103 if (p)
1104 {
1105 WeaponUsagesUpdate(p->WeaponUsages, obj->weapon, 1, 0);
1106 }
1107 }
1108 }
1109
1110 void BulletBounce(const NBulletBounce bb)
1111 {
1112 TMobileObject *o = MobObjGetByUID(bb.UID);
1113 if (o == NULL || !o->isInUse)
1114 return;
1115 const struct vec2 bouncePos = NetToVec2(bb.BouncePos);
1116 if (bb.HitSound)
1117 {
1118 PlayHitSound(o->bulletClass, (HitType)bb.HitType, bouncePos);
1119 }
1120 if (bb.Spark && o->bulletClass->Spark != NULL)
1121 {
1122 GameEvent s = GameEventNew(GAME_EVENT_ADD_PARTICLE);
1123 s.u.AddParticle.Class = o->bulletClass->Spark;
1124 s.u.AddParticle.Pos = bouncePos;
1125 s.u.AddParticle.Z = o->z;
1126 GameEventsEnqueue(&gGameEvents, s);
1127 }
1128 if (bb.WallMark && o->bulletClass->WallMark != NULL)
1129 {
1130 GameEvent s = GameEventNew(GAME_EVENT_ADD_PARTICLE);
1131 s.u.AddParticle.Class = o->bulletClass->WallMark;
1132 s.u.AddParticle.Pos = bouncePos;
1133 // Randomise Z on the wall
1134 s.u.AddParticle.Z = o->z + (int)RAND_FLOAT(-WALL_MARK_Z, WALL_MARK_Z);
1135 GameEventsEnqueue(&gGameEvents, s);
1136 }
1137 MapTryMoveThing(&gMap, &o->thing, NetToVec2(bb.Pos));
1138 o->thing.Vel = NetToVec2(bb.Vel);
1139 }
1140
1141 void PlayHitSound(const BulletClass *b, const HitType t, const struct vec2 pos)
1142 {
1143 GameEvent es = GameEventNew(GAME_EVENT_SOUND_AT);
1144 const char *sound = NULL;
1145 switch (t)
1146 {
1147 case HIT_NONE:
1148 // Do nothing
1149 return;
1150 case HIT_WALL:
1151 sound = b->Hit.Wall.Sound;
1152 break;
1153 case HIT_OBJECT:
1154 sound = b->Hit.Object.Sound;
1155 break;
1156 case HIT_FLESH:
1157 sound = b->Hit.Flesh.Sound;
1158 break;
1159 default:
1160 CASSERT(false, "unknown hit type")
1161 return;
1162 }
1163 if (!sound || strlen(sound) == 0)
1164 {
1165 return;
1166 }
1167 strcpy(es.u.SoundAt.Sound, sound);
1168 es.u.SoundAt.Pos = Vec2ToNet(pos);
1169 GameEventsEnqueue(&gGameEvents, es);
1170 }
1171
1172 void BulletDestroy(TMobileObject *obj)
1173 {
1174 CASSERT(obj->isInUse, "Destroying not-in-use bullet");
1175 MapRemoveThing(&gMap, &obj->thing);
1176 obj->isInUse = false;
1177 }