OpenClonk
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros
C4Object.cpp
Go to the documentation of this file.
1 /*
2  * OpenClonk, http://www.openclonk.org
3  *
4  * Copyright (c) 1998-2000, Matthes Bender
5  * Copyright (c) 2001-2009, RedWolf Design GmbH, http://www.clonk.de/
6  * Copyright (c) 2009-2016, The OpenClonk Team and contributors
7  *
8  * Distributed under the terms of the ISC license; see accompanying file
9  * "COPYING" for details.
10  *
11  * "Clonk" is a registered trademark of Matthes Bender, used with permission.
12  * See accompanying file "TRADEMARK" for details.
13  *
14  * To redistribute this file separately, substitute the full license texts
15  * for the above references.
16  */
17 
18 /* That which fills the world with life */
19 
20 #include "C4Include.h"
22 #include "object/C4Object.h"
23 
24 #include "script/C4AulExec.h"
25 #include "object/C4Def.h"
26 #include "object/C4DefList.h"
27 #include "script/C4Effect.h"
28 #include "object/C4ObjectInfo.h"
29 #include "game/C4Physics.h"
30 #include "landscape/C4PXS.h"
31 #include "object/C4ObjectCom.h"
32 #include "object/C4Command.h"
33 #include "game/C4Viewport.h"
35 #include "control/C4Record.h"
36 #include "landscape/C4SolidMask.h"
37 #include "platform/C4SoundSystem.h"
38 #include "lib/C4Random.h"
39 #include "lib/C4Log.h"
40 #include "player/C4Player.h"
41 #include "object/C4ObjectMenu.h"
42 #include "player/C4RankSystem.h"
43 #include "gui/C4GameMessage.h"
45 #include "graphics/C4Draw.h"
46 #include "game/C4GraphicsSystem.h"
47 #include "game/C4Game.h"
48 #include "game/C4Application.h"
49 #include "player/C4PlayerList.h"
50 #include "object/C4GameObjects.h"
51 #include "control/C4Record.h"
52 #include "object/C4MeshAnimation.h"
54 #include "landscape/fow/C4FoW.h"
55 #include "landscape/C4Particles.h"
56 
57 static void DrawVertex(C4Facet &cgo, float tx, float ty, int32_t col, int32_t contact)
58 {
59  if (Inside<int32_t>(tx,cgo.X,cgo.X+cgo.Wdt) && Inside<int32_t>(ty,cgo.Y,cgo.Y+cgo.Hgt))
60  {
61  pDraw->DrawLineDw(cgo.Surface, tx - 1, ty, tx + 1, ty, col, 0.5f);
62  pDraw->DrawLineDw(cgo.Surface, tx, ty - 1, tx, ty + 1, col, 0.5f);
63  if (contact) pDraw->DrawFrameDw(cgo.Surface,tx-1.5,ty-1.5,tx+1.5,ty+1.5,C4RGB(0xff, 0xff, 0xff));
64  }
65 }
66 
67 void C4Action::SetBridgeData(int32_t iBridgeTime, bool fMoveClonk, bool fWall, int32_t iBridgeMaterial)
68 {
69  // validity
70  iBridgeMaterial = std::min(iBridgeMaterial, ::MaterialMap.Num-1);
71  if (iBridgeMaterial < 0) iBridgeMaterial = 0xff;
72  iBridgeTime = Clamp<int32_t>(iBridgeTime, 0, 0xffff);
73  // mask in this->Data
74  Data = (uint32_t(iBridgeTime) << 16) + (uint32_t(fMoveClonk) << 8) + (uint32_t(fWall) << 9) + iBridgeMaterial;
75 }
76 
77 void C4Action::GetBridgeData(int32_t &riBridgeTime, bool &rfMoveClonk, bool &rfWall, int32_t &riBridgeMaterial)
78 {
79  // mask from this->Data
80  uint32_t uiData = Data;
81  riBridgeTime = (uint32_t(uiData) >> 16);
82  rfMoveClonk = !!(uiData & 0x100);
83  rfWall = !!(uiData & 0x200);
84  riBridgeMaterial = (uiData & 0xff);
85  if (riBridgeMaterial == 0xff) riBridgeMaterial = -1;
86 }
87 
89 {
91  Default();
92 }
93 
95 {
96  id=C4ID::None;
97  nInfo.Clear();
98  RemovalDelay=0;
102  Category=0;
103  Con=0;
104  Mass=OwnMass=0;
105  Damage=0;
106  Energy=0;
107  Alive=0;
108  Breath=0;
109  InMat=MNone;
110  Color=0;
111  lightRange=0;
113  lightColor=0xffffffff;
114  fix_x=fix_y=fix_r=0;
115  xdir=ydir=rdir=0;
116  Mobile=0;
117  Unsorted=false;
118  Initializing=false;
119  OnFire=0;
120  InLiquid=0;
121  EntranceStatus=0;
124  t_contact=0;
125  OCF=0;
126  Action.Default();
127  Shape.Default();
128  fOwnVertices=0;
129  Contents.Default();
130  SolidMask.Default();
132  Def=nullptr;
133  Info=nullptr;
134  Command=nullptr;
135  Contained=nullptr;
136  TopFace.Default();
137  Menu=nullptr;
138  MaterialContents=nullptr;
139  Marker=0;
140  ColorMod=0xffffffff;
141  BlitMode=0;
142  CrewDisabled=false;
143  Layer=nullptr;
144  pSolidMaskData=nullptr;
145  pGraphics=nullptr;
146  pMeshInstance=nullptr;
147  pDrawTransform=nullptr;
148  pEffects=nullptr;
149  pGfxOverlay=nullptr;
151 
153 }
154 
155 bool C4Object::Init(C4PropList *pDef, C4Object *pCreator,
156  int32_t iOwner, C4ObjectInfo *pInfo,
157  int32_t nx, int32_t ny, int32_t nr,
158  C4Real nxdir, C4Real nydir, C4Real nrdir, int32_t iController)
159 {
161  // currently initializing
162  Initializing=true;
163 
164  // Def & basics
165  Owner=iOwner;
166  if (iController > NO_OWNER) Controller = iController; else Controller=iOwner;
168  Info=pInfo;
169  Def=pDef->GetDef(); assert(Def);
171  id=Def->id;
172  if (Info) SetName(pInfo->Name);
174  Plane = Def->GetPlane(); assert(Plane);
175  Def->Count++;
176  if (pCreator) Layer=pCreator->Layer;
177 
178  // graphics
179  pGraphics = &Def->Graphics;
181  {
182  pMeshInstance = new StdMeshInstance(*pGraphics->Mesh, Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
184  }
185  else
186  {
187  pMeshInstance = nullptr;
188  }
189  BlitMode = Def->BlitMode;
190 
191  // Position
192  if (!Def->Rotateable) { nr=0; nrdir=0; }
193  fix_x=itofix(nx);
194  fix_y=itofix(ny);
195  fix_r=itofix(nr);
196  xdir=nxdir; ydir=nydir; rdir=nrdir;
197 
198  // Initial mobility
199  if (!!xdir || !!ydir || !!rdir)
200  Mobile=1;
201 
202  // Mass
203  Mass=std::max<int32_t>(Def->Mass*Con/FullCon,1);
204 
205  // Life, energy, breath
206  if (Category & C4D_Living) Alive=1;
209 
210  // Color
211  if (Def->ColorByOwner)
212  {
213  if (ValidPlr(Owner))
215  else
216  Color=0xff; // no-owner color: blue
217  }
218 
219  // Shape & face
220  Shape=Def->Shape;
223  UpdateGraphics(false);
224  UpdateFace(true);
225 
226  // Initial audibility
228 
229  // Initial OCF
230  SetOCF();
231 
232  // finished initializing
233  Initializing=false;
234 
235  return true;
236 }
237 
239 {
240  Clear();
241 
242 #if defined(_DEBUG)
243  // debug: mustn't be listed in any list now
245 #endif
246 }
247 
249 {
250  if (FrontParticles != 0)
252  if (BackParticles != 0)
255 }
256 
257 void C4Object::AssignRemoval(bool fExitContents)
258 {
259  // check status
260  if (!Status) return;
261  if (Config.General.DebugRec)
262  {
263  C4RCCreateObj rc;
264  memset(&rc, '\0', sizeof(rc));
265  rc.oei=Number;
266  if (Def && Def->GetName()) strncpy(rc.id, Def->GetName(), 32+1);
267  rc.x=GetX(); rc.y=GetY(); rc.ownr=Owner;
268  AddDbgRec(RCT_DsObj, &rc, sizeof(rc));
269  }
270  // Destruction call in container
271  if (Contained)
272  {
273  C4AulParSet pars(this);
275  if (!Status) return;
276  }
277  // Destruction call
279  // Destruction-callback might have deleted the object already
280  if (!Status) return;
281  // remove all effects (extinguishes as well)
282  if (pEffects)
283  {
285  // Effect-callback might actually have deleted the object already
286  if (!Status) return;
287  }
288  // remove particles
290  // Action idle
291  SetAction(0);
292  // Object system operation
293  if (Status == C4OS_INACTIVE)
294  {
295  // object was inactive: activate first, then delete
298  ::Objects.Add(this);
299  }
300  Status=0;
301  // count decrease
302  Def->Count--;
303 
304  // get container for next actions
305  C4Object *pCont = Contained;
306  // remove or exit contents
307  for (C4Object *cobj : Contents)
308  {
309  if (fExitContents)
310  {
311  // move objects to parent container or exit them completely
312  if (!pCont || !cobj->Enter(pCont, false))
313  cobj->Exit(GetX(), GetY());
314  }
315  else
316  {
317  Contents.Remove(cobj);
318  cobj->Contained = nullptr;
319  cobj->AssignRemoval();
320  }
321  }
322  // remove this object from container *after* its contents have been removed!
323  if (pCont)
324  {
325  pCont->Contents.Remove(this);
326  pCont->UpdateMass();
327  pCont->SetOCF();
328  Contained=nullptr;
329  }
330  // Object info
331  if (Info) Info->Retire();
332  Info = nullptr;
333  // Object system operation
334  ClearRefs();
335  Game.ClearPointers(this);
336  ClearCommands();
337  if (pSolidMaskData)
338  {
339  delete pSolidMaskData;
340  pSolidMaskData = nullptr;
341  }
342  SolidMask.Wdt = 0;
343  RemovalDelay=2;
344 }
345 
346 void C4Object::UpdateShape(bool bUpdateVertices)
347 {
348 
349  // Line shape independent
350  if (Def->Line) return;
351 
352  // Copy shape from def
353  Shape.CopyFrom(Def->Shape, bUpdateVertices, !!fOwnVertices);
354 
355  // Construction zoom
356  if (Con!=FullCon)
357  {
358  if (Def->GrowthType)
359  Shape.Stretch(Con, bUpdateVertices);
360  else
361  Shape.Jolt(Con, bUpdateVertices);
362  }
363 
364  // Rotation
365  if (Def->Rotateable)
366  if (fix_r != Fix0)
367  Shape.Rotate(fix_r, bUpdateVertices);
368 
369  // covered area changed? to be on the save side, update pos
370  UpdatePos();
371 }
372 
374 {
375  // get new area covered
376  // do *NOT* do this while initializing, because object cannot be sorted by main list
377  if (!Initializing && Status == C4OS_NORMAL)
378  ::Objects.UpdatePos(this);
379 }
380 
381 void C4Object::UpdateFace(bool bUpdateShape, bool fTemp)
382 {
383 
384  // Update shape - NOT for temp call, because temnp calls are done in drawing routine
385  // must not change sync relevant data here (although the shape and pos *should* be updated at that time anyway,
386  // because a runtime join would desync otherwise)
387  if (!fTemp) { if (bUpdateShape) UpdateShape(); else UpdatePos(); }
388 
389  // SolidMask
390  if (!fTemp) UpdateSolidMask(false);
391 
392  // Null defaults
393  TopFace.Default();
394 
395  // newgfx: TopFace only
396  if (Con>=FullCon || Def->GrowthType)
397  if (!Def->Rotateable || (fix_r == Fix0))
398  if (Def->TopFace.Wdt>0) // Fullcon & no rotation
399  TopFace.Set(GetGraphics()->GetBitmap(Color),
400  Def->TopFace.x,Def->TopFace.y,
402 
403  // Active face
405 }
406 
407 void C4Object::UpdateGraphics(bool fGraphicsChanged, bool fTemp)
408 {
409  // check color
410  if (!fTemp) if (!pGraphics->IsColorByOwner()) Color=0;
411  // new grafics: update face
412  if (fGraphicsChanged)
413  {
414  // Keep mesh instance if it uses the same underlying mesh
416  &pMeshInstance->GetMesh() != pGraphics->Mesh)
417  {
418  // If this mesh is attached somewhere, detach it before deletion
419  if(pMeshInstance && pMeshInstance->GetAttachParent() != nullptr)
420  {
421  // TODO: If the new mesh has a bone with the same name, we could try updating...
423  attach_parent->Parent->DetachMesh(attach_parent->Number);
424  }
425 
426  delete pMeshInstance;
427 
429  {
430  pMeshInstance = new StdMeshInstance(*pGraphics->Mesh, Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
432  }
433  else
434  {
435  pMeshInstance = nullptr;
436  }
437  }
438 
439  // update face - this also puts any SolidMask
440  UpdateFace(false);
441  }
442 }
443 
445 {
446  int32_t iFlipDir;
447  // We're active
448  C4PropList* pActionDef = GetAction();
449  if (pActionDef)
450  // Get flipdir value from action
451  if ((iFlipDir = pActionDef->GetPropertyInt(P_FlipDir)))
452  // Action dir is in flipdir range
453  if (Action.Dir >= iFlipDir)
454  {
455  // Calculate flipped drawing dir (from the flipdir direction going backwards)
456  Action.DrawDir = (iFlipDir - 1 - (Action.Dir - iFlipDir));
457  // Set draw transform, creating one if necessary
458  if (pDrawTransform)
460  else
462  // Done setting flipdir
463  return;
464  }
465  // No flipdir necessary
467  // Draw transform present?
468  if (pDrawTransform)
469  {
470  // reset flip dir
472  // if it's identity now, remove the matrix
473  if (pDrawTransform->IsIdentity())
474  {
475  delete pDrawTransform;
476  pDrawTransform=nullptr;
477  }
478  }
479 }
480 
481 void C4Object::DrawFaceImpl(C4TargetFacet &cgo, bool action, float fx, float fy, float fwdt, float fhgt, float tx, float ty, float twdt, float thgt, C4DrawTransform* transform) const
482 {
483  C4Surface* sfc;
484  switch (GetGraphics()->Type)
485  {
487  // no graphics.
488  break;
490  sfc = action ? Action.Facet.Surface : GetGraphics()->GetBitmap(Color);
491 
492  pDraw->Blit(sfc,
493  fx, fy, fwdt, fhgt,
494  cgo.Surface, tx, ty, twdt, thgt,
495  true, transform);
496  break;
498  C4Value value;
500  StdMeshMatrix matrix;
501  if (!C4ValueToMatrix(value, &matrix))
502  matrix = StdMeshMatrix::Identity();
503 
504  if (fix_r != Fix0)
505  {
506  // Rotation should happen around the mesh center after application of any mesh transformation
507  // So translate back by the transformed mesh center before rotation
508  auto mesh_center = pMeshInstance->GetMesh().GetBoundingBox().GetCenter();
509  mesh_center = matrix * mesh_center;
510  matrix = StdMeshMatrix::Translate(-mesh_center.x, -mesh_center.y, -mesh_center.z) * matrix;
511  matrix = StdMeshMatrix::Rotate(fixtof(fix_r) * (M_PI / 180.0f), 0.0f, 0.0f, 1.0f) * matrix;
512  matrix = StdMeshMatrix::Translate(mesh_center.x, mesh_center.y, mesh_center.z) * matrix;
513  }
514 
515  if(twdt != fwdt || thgt != fhgt)
516  {
517  // Also scale Z so that the mesh is not totally distorted and
518  // so that normals halfway keep pointing into sensible directions.
519  // We don't have a better guess so use the geometric mean for Z scale.
520  matrix = StdMeshMatrix::Scale(twdt/fwdt,thgt/fhgt,std::sqrt(twdt*thgt/(fwdt*fhgt))) * matrix;
521  }
522 
523  pDraw->SetMeshTransform(&matrix);
524 
525  pDraw->RenderMesh(*pMeshInstance, cgo.Surface, tx, ty, twdt, thgt, Color, transform);
526  pDraw->SetMeshTransform(nullptr);
527  break;
528  }
529 }
530 
531 void C4Object::DrawFace(C4TargetFacet &cgo, float offX, float offY, int32_t iPhaseX, int32_t iPhaseY) const
532 {
533  const float swdt = float(Def->Shape.Wdt);
534  const float shgt = float(Def->Shape.Hgt);
535  // Grow Type Display
536  float fx = float(swdt * iPhaseX);
537  float fy = float(shgt * iPhaseY);
538  float fwdt = float(swdt);
539  float fhgt = float(shgt);
540 
541  float stretch_factor = static_cast<float>(Con) / FullCon;
542  float tx = offX + Def->Shape.GetX() * stretch_factor;
543  float ty = offY + Def->Shape.GetY() * stretch_factor;
544  float twdt = swdt * stretch_factor;
545  float thgt = shgt * stretch_factor;
546 
547  // Construction Type Display
548  if (!Def->GrowthType)
549  {
550  tx = offX + Def->Shape.GetX();
551  twdt = swdt;
552 
553  fy += fhgt - thgt;
554  fhgt = thgt;
555  }
556 
557  C4DrawTransform transform;
558  bool transform_active = false;
559  if (pDrawTransform)
560  {
561  transform.SetTransformAt(*pDrawTransform, offX, offY);
562  transform_active = true;
563  }
564 
565  // Meshes aren't rotated via DrawTransform to ensure lighting is applied correctly.
566  if (GetGraphics()->Type != C4DefGraphics::TYPE_Mesh && Def->Rotateable && fix_r != Fix0)
567  {
568  if (pDrawTransform)
569  transform.Rotate(fixtof(fix_r), offX, offY);
570  else
571  transform.SetRotate(fixtof(fix_r), offX, offY);
572  transform_active = true;
573  }
574 
575  DrawFaceImpl(cgo, false, fx, fy, fwdt, fhgt, tx, ty, twdt, thgt, transform_active ? &transform : nullptr);
576 }
577 
578 void C4Object::DrawActionFace(C4TargetFacet &cgo, float offX, float offY) const
579 {
580  // This should not be called for meshes since Facet has no meaning
581  // for them. Only use DrawFace() with meshes!
582  assert(GetGraphics()->Type == C4DefGraphics::TYPE_Bitmap);
583  C4PropList* pActionDef = GetAction();
584 
585  // Regular action facet
586  const float swdt = float(Action.Facet.Wdt);
587  const float shgt = float(Action.Facet.Hgt);
588  int32_t iPhase = Action.Phase;
589  if (pActionDef->GetPropertyInt(P_Reverse)) iPhase = pActionDef->GetPropertyInt(P_Length) - 1 - Action.Phase;
590 
591  // Grow Type Display
592  float fx = float(Action.Facet.X + swdt * iPhase);
593  float fy = float(Action.Facet.Y + shgt * Action.DrawDir);
594  float fwdt = float(swdt);
595  float fhgt = float(shgt);
596 
597  // draw stretched towards shape center with transform
598  float stretch_factor = static_cast<float>(Con) / FullCon;
599  float tx = (Def->Shape.GetX() + Action.FacetX) * stretch_factor + offX;
600  float ty = (Def->Shape.GetY() + Action.FacetY) * stretch_factor + offY;
601  float twdt = swdt * stretch_factor;
602  float thgt = shgt * stretch_factor;
603 
604  // Construction Type Display
605  if (!Def->GrowthType)
606  {
607  // FIXME
608  if (Con != FullCon)
609  {
610  // incomplete constructions do not show actions
611  DrawFace(cgo, offX, offY);
612  return;
613  }
614  tx = Def->Shape.GetX() + Action.FacetX + offX;
615  twdt = swdt;
616  float offset_from_top = shgt * std::max(FullCon - Con, 0) / FullCon;
617  fy += offset_from_top;
618  fhgt -= offset_from_top;
619  }
620 
621  C4DrawTransform transform;
622  bool transform_active = false;
623  if (pDrawTransform)
624  {
625  transform.SetTransformAt(*pDrawTransform, offX, offY);
626  transform_active = true;
627  }
628 
629  // Meshes aren't rotated via DrawTransform to ensure lighting is applied correctly.
630  if (GetGraphics()->Type != C4DefGraphics::TYPE_Mesh && Def->Rotateable && fix_r != Fix0)
631  {
632  if (pDrawTransform)
633  transform.Rotate(fixtof(fix_r), offX, offY);
634  else
635  transform.SetRotate(fixtof(fix_r), offX, offY);
636  transform_active = true;
637  }
638 
639  DrawFaceImpl(cgo, true, fx, fy, fwdt, fhgt, tx, ty, twdt, thgt, transform_active ? &transform : nullptr);
640 }
641 
643 {
644  Mass=std::max<int32_t>((Def->Mass+OwnMass)*Con/FullCon,1);
646  if (Contained)
647  {
650  }
651 }
652 
653 void C4Object::UpdateInMat()
654 {
655  // get new mat
656  int32_t newmat;
657  if (Contained)
659  else
660  newmat = GBackMat(GetX(), GetY());
661 
662  // mat changed?
663  if (newmat != InMat)
664  {
666  InMat = newmat;
667  }
668 }
669 
671 {
672  C4PropList* pActionDef = GetAction();
673  uint32_t dwOCFOld = OCF;
674  // Update the object character flag according to the object's current situation
675  C4Real cspeed=GetSpeed();
676 #ifdef _DEBUG
678  { LogF("Warning: contained in wild object %p!", static_cast<void*>(Contained)); }
679  else if (Contained && !Contained->Status)
680  { LogF("Warning: contained in deleted object (#%d) (%s)!", Contained->Number, Contained->GetName()); }
681 #endif
682  // OCF_Normal: The OCF is never zero
683  OCF=OCF_Normal;
684  // OCF_Construct: Can be built outside
685  if (Def->Constructable && (Con<FullCon)
686  && (fix_r==Fix0) && !OnFire)
688  // OCF_Grab: Can be pushed
690  OCF|=OCF_Grab;
691  // OCF_Carryable: Can be picked up
694  // OCF_OnFire: Is burning
695  if (OnFire)
696  OCF|=OCF_OnFire;
697  // OCF_Inflammable: Is not burning and is inflammable
700  // OCF_FullCon: Is fully completed/grown
701  if (Con>=FullCon)
702  OCF|=OCF_FullCon;
703  // OCF_Rotate: Can be rotated
704  if (Def->Rotateable)
705  // Don't rotate minimum (invisible) construction sites
706  if (Con>100)
707  OCF|=OCF_Rotate;
708  // OCF_Exclusive: No action through this, no construction in front of this
709  if (Def->Exclusive)
711  // OCF_Entrance: Can currently be entered/activated
712  if ((Def->Entrance.Wdt>0) && (Def->Entrance.Hgt>0))
713  if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (GetR() <= Def->RotatedEntrance)))
714  OCF|=OCF_Entrance;
715  // HitSpeeds
716  if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1;
717  if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2;
718  if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3;
719  if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4;
720  // OCF_Collection
721  if ((OCF & OCF_FullCon) || Def->IncompleteActivity)
722  if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0))
723  if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled)))
725  // OCF_Alive
726  if (Alive) OCF|=OCF_Alive;
727  // OCF_CrewMember
728  if (Def->CrewMember)
729  if (Alive)
731  // OCF_AttractLightning
732  if (Def->AttractLightning)
733  if (OCF & OCF_FullCon)
735  // OCF_NotContained
736  if (!Contained)
738  // OCF_InLiquid
739  if (InLiquid)
740  if (!Contained)
741  OCF|=OCF_InLiquid;
742  // OCF_InSolid
743  if (!Contained)
744  if (GBackSolid(GetX(), GetY()))
745  OCF|=OCF_InSolid;
746  // OCF_InFree
747  if (!Contained)
748  if (!GBackSemiSolid(GetX(), GetY()-1))
749  OCF|=OCF_InFree;
750  // OCF_Available
752  if (!GBackSemiSolid(GetX(), GetY()-1) || (!GBackSolid(GetX(), GetY()-1) && !GBackSemiSolid(GetX(), GetY()-8)))
754  // OCF_Container
758  {
759  C4RCOCF rc = { dwOCFOld, OCF, false };
760  AddDbgRec(RCT_OCF, &rc, sizeof(rc));
761  }
762 }
763 
764 
766 {
767  C4PropList* pActionDef = GetAction();
768  uint32_t dwOCFOld = OCF;
769  // Update the object character flag according to the object's current situation
770  C4Real cspeed=GetSpeed();
771 #ifdef _DEBUG
773  { LogF("Warning: contained in wild object %p!", static_cast<void*>(Contained)); }
774  else if (Contained && !Contained->Status)
775  { LogF("Warning: contained in deleted object %p (%s)!", static_cast<void*>(Contained), Contained->GetName()); }
776 #endif
777  // Keep the bits that only have to be updated with SetOCF (def, category, con, alive, onfire)
780  // OCF_inflammable: can catch fire and is not currently burning.
782  OCF |= OCF_Inflammable;
783  // OCF_Carryable: Can be picked up
786  // OCF_Grab: Can be grabbed.
788  OCF |= OCF_Grab;
789  // OCF_Construct: Can be built outside
790  if (Def->Constructable && (Con<FullCon)
791  && (fix_r == Fix0) && !OnFire)
793  // OCF_Entrance: Can currently be entered/activated
794  if ((Def->Entrance.Wdt>0) && (Def->Entrance.Hgt>0))
795  if ((OCF & OCF_FullCon) && ((Def->RotatedEntrance == 1) || (GetR() <= Def->RotatedEntrance)))
796  OCF|=OCF_Entrance;
797  // HitSpeeds
798  if (cspeed>=HitSpeed1) OCF|=OCF_HitSpeed1;
799  if (cspeed>=HitSpeed2) OCF|=OCF_HitSpeed2;
800  if (cspeed>=HitSpeed3) OCF|=OCF_HitSpeed3;
801  if (cspeed>=HitSpeed4) OCF|=OCF_HitSpeed4;
802  // OCF_Collection
803  if ((OCF & OCF_FullCon) || Def->IncompleteActivity)
804  if ((Def->Collection.Wdt>0) && (Def->Collection.Hgt>0))
805  if (!pActionDef || (!pActionDef->GetPropertyInt(P_ObjectDisabled)))
807  // OCF_NotContained
808  if (!Contained)
810  // OCF_InLiquid
811  if (InLiquid)
812  if (!Contained)
813  OCF|=OCF_InLiquid;
814  // OCF_InSolid
815  if (!Contained)
816  if (GBackSolid(GetX(), GetY()))
817  OCF|=OCF_InSolid;
818  // OCF_InFree
819  if (!Contained)
820  if (!GBackSemiSolid(GetX(), GetY()-1))
821  OCF|=OCF_InFree;
822  // OCF_Available
824  if (!GBackSemiSolid(GetX(), GetY()-1) || (!GBackSolid(GetX(), GetY()-1) && !GBackSemiSolid(GetX(), GetY()-8)))
826  // OCF_Container
830  {
831  C4RCOCF rc = { dwOCFOld, OCF, true };
832  AddDbgRec(RCT_OCF, &rc, sizeof(rc));
833  }
834 #ifdef _DEBUG
836  uint32_t updateOCF = OCF;
837  SetOCF();
838  assert (updateOCF == OCF);
840 #endif
841 }
842 
843 
845 {
846  // Breathing
847  if (!::Game.iTick5)
848  if (Alive && !Def->NoBreath)
849  {
850  // Supply check
851  bool Breathe=false;
852  // Forcefields are breathable.
853  if (GBackMat(GetX(), GetY()+Shape.GetY()/2)==MVehic)
854  { Breathe=true; }
855  else if (GetPropertyInt(P_BreatheWater))
856  { if (GBackMat(GetX(), GetY())==MWater) Breathe=true; }
857  else
858  { if (!GBackSemiSolid(GetX(), GetY()+Shape.GetY()/2)) Breathe=true; }
859  if (Contained) Breathe=true;
860  // No supply
861  if (!Breathe)
862  {
863  // Reduce breath, then energy, bubble
864  if (Breath > 0) DoBreath(-5);
866  }
867  // Supply
868  else
869  {
870  // Take breath
871  int32_t takebreath = GetPropertyInt(P_MaxBreath) - Breath;
872  if (takebreath > 0) DoBreath(takebreath);
873  }
874  }
875 
876  // Corrosion energy loss
877  if (!::Game.iTick10)
878  if (Alive)
879  if (InMat!=MNone)
883 
884  // InMat incineration
885  if (!::Game.iTick10)
886  if (InMat!=MNone)
889  {
891  }
892 
893  // birthday
894  if (!::Game.iTick255)
895  if (Alive)
896  if (Info)
897  {
898  int32_t iPlayingTime = Info->TotalPlayingTime + (Game.Time - Info->InActionTime);
899 
900  int32_t iNewAge = iPlayingTime / 3600 / 5;
901 
902  if (Info->Age != iNewAge && Info->Age)
903  {
904  // message
905  GameMsgObject(FormatString(LoadResStr("IDS_OBJ_BIRTHDAY"),GetName (), Info->TotalPlayingTime / 3600 / 5).getData(),this);
906  StartSoundEffect("UI::Trumpet",false,100,this);
907  }
908 
909  Info->Age = iNewAge;
910 
911 
912  }
913 
914  return true;
915 }
916 
918 {
919  if (Config.General.DebugRec)
920  {
921  // record debug
922  C4RCExecObj rc;
923  rc.Number=Number;
924  rc.fx=fix_x;
925  rc.fy=fix_y;
926  rc.fr=fix_r;
927  AddDbgRec(RCT_ExecObj, &rc, sizeof(rc));
928  }
929  // OCF
930  UpdateOCF();
931  // Command
932  ExecuteCommand();
933  // Action
934  // need not check status, because dead objects have lost their action
935  ExecAction();
936  // commands and actions are likely to have removed the object, and movement
937  // *must not* be executed for dead objects (SolidMask-errors)
938  if (!Status) return;
939  // Movement
940  ExecMovement();
941  if (!Status) return;
942  // effects
943  if (pEffects)
944  {
946  if (!Status) return;
947  }
948  // Life
949  ExecLife();
950  // Animation. If the mesh is attached, then don't execute animation here but let the parent object do it to make sure it is only executed once a frame.
952  pMeshInstance->ExecuteAnimation(1.0f/37.0f /* play smoothly at 37 FPS */);
953  // Menu
954  if (Menu) Menu->Execute();
955 }
956 
957 bool C4Object::At(int32_t ctx, int32_t cty) const
958 {
959  if (Status) if (!Contained) if (Def)
960  if (Inside<int32_t>(cty - (GetY() + Shape.GetY() - addtop()), 0, Shape.Hgt - 1 + addtop()))
961  if (Inside<int32_t>(ctx - (GetX() + Shape.GetX()), 0, Shape.Wdt - 1))
962  return true;
963  return false;
964 }
965 
966 bool C4Object::At(int32_t ctx, int32_t cty, DWORD &ocf) const
967 {
968  if (Status) if (!Contained) if (Def)
969  if (OCF & ocf)
970  if (Inside<int32_t>(cty - (GetY() + Shape.GetY() - addtop()), 0, Shape.Hgt - 1 + addtop()))
971  if (Inside<int32_t>(ctx - (GetX() + Shape.GetX()), 0, Shape.Wdt - 1))
972  {
973  // Set ocf return value
974  GetOCFForPos(ctx, cty, ocf);
975  return true;
976  }
977  return false;
978 }
979 
980 void C4Object::GetOCFForPos(int32_t ctx, int32_t cty, DWORD &ocf) const
981 {
982  DWORD rocf=OCF;
983  // Verify entrance area OCF return
984  if (rocf & OCF_Entrance)
985  if (!Inside<int32_t>(cty - (GetY() + Def->Entrance.y), 0, Def->Entrance.Hgt - 1)
986  || !Inside<int32_t>(ctx - (GetX() + Def->Entrance.x), 0, Def->Entrance.Wdt - 1))
987  rocf &= (~OCF_Entrance);
988  // Verify collection area OCF return
989  if (rocf & OCF_Collection)
990  if (!Inside<int32_t>(cty - (GetY() + Def->Collection.y), 0, Def->Collection.Hgt - 1)
991  || !Inside<int32_t>(ctx - (GetX() + Def->Collection.x), 0, Def->Collection.Wdt - 1))
992  rocf &= (~OCF_Collection);
993  ocf=rocf;
994 }
995 
996 void C4Object::AssignDeath(bool fForced)
997 {
998  C4Object *thing;
999  // Alive objects only
1000  if (!Alive) return;
1001  // clear all effects
1002  // do not delete effects afterwards, because they might have denied removal
1003  // set alive-flag before, so objects know what's up
1004  // and prevent recursive death-calls this way
1005  // get death causing player before doing effect calls, because those might meddle around with the flags
1006  int32_t iDeathCausingPlayer = LastEnergyLossCausePlayer;
1007  Alive=0;
1009  // if the object is alive again, abort here if the kill is not forced
1010  if (Alive && !fForced) return;
1011  // Action
1012  SetActionByName("Dead");
1013  // Values
1014  Alive=0;
1015  ClearCommands();
1016  C4ObjectInfo * pInfo = Info;
1017  if (Info)
1018  {
1019  Info->HasDied=true;
1020  ++Info->DeathCount;
1021  Info->Retire();
1022  }
1023  // Remove from crew/cursor/view
1024  C4Player *pPlr = ::Players.Get(Owner);
1025  if (pPlr) pPlr->ClearPointers(this, true);
1026  // Remove from light sources
1027  SetLightRange(0,0);
1028  // Engine script call
1029  C4AulParSet pars(iDeathCausingPlayer);
1030  Call(PSF_Death, &pars);
1031  // Lose contents
1032  while ((thing=Contents.GetObject())) thing->Exit(thing->GetX(),thing->GetY());
1033  // Update OCF. Done here because previously it would have been done in the next frame
1034  // Whats worse: Having the OCF change because of some unrelated script-call like
1035  // SetCategory, or slightly breaking compatibility?
1036  SetOCF();
1037  // Engine broadcast: relaunch player (in CR, this was called from clonk script.
1038  // Now, it is done for every crew member)
1039  if(pPlr)
1040  if(!pPlr->Crew.ObjectCount())
1042  &C4AulParSet(Owner, iDeathCausingPlayer, Status ? this : nullptr));
1043  if (pInfo)
1044  pInfo->HasDied = false;
1045 }
1046 
1048 {
1049  // Get new definition
1050  C4Def *pDef=C4Id2Def(idNew);
1051  if (!pDef) return false;
1052  // Containment storage
1053  C4Object *pContainer=Contained;
1054  // Exit container (no Ejection/Departure)
1055  if (Contained) Exit(0,0,0,Fix0,Fix0,Fix0,false);
1056  // Pre change resets
1057  SetAction(0);
1058  ResetProperty(&Strings.P[P_Action]); // Enforce ActIdle because SetAction may have failed due to NoOtherAction
1059  SetDir(0); // will drop any outdated flipdir
1060  if (pSolidMaskData) { delete pSolidMaskData; pSolidMaskData=nullptr; }
1061  Def->Count--;
1062  // Def change
1063  Def=pDef;
1065  id=pDef->id;
1066  Def->Count++;
1067  // new def: Needs to be resorted
1068  Unsorted=true;
1069  // graphics change
1070  pGraphics = &pDef->Graphics;
1071  // blit mode adjustment
1073  // an object may have newly become an ColorByOwner-object
1074  // if it had been ColorByOwner, but is not now, this will be caught in UpdateGraphics()
1075  if (!Color && ValidPlr(Owner))
1077  if (!Def->Rotateable) { fix_r=rdir=Fix0; }
1078  // Reset solid mask
1080  // Post change updates
1081  UpdateGraphics(true);
1082  UpdateMass();
1083  UpdateFace(true);
1084  SetOCF();
1085  // Any effect callbacks to this object might need to reinitialize their target functions
1086  // This is ugly, because every effect there is must be updated...
1091  for (C4Object *obj : Objects)
1092  if (obj->pEffects) obj->pEffects->OnObjectChangedDef(this);
1093  // Containment (no Entrance)
1094  if (pContainer) Enter(pContainer,false);
1095  // Done
1096  return true;
1097 }
1098 
1099 void C4Object::DoDamage(int32_t iChange, int32_t iCausedBy, int32_t iCause)
1100 {
1101  // non-living: ask effects first
1102  if (pEffects && !Alive)
1103  {
1104  pEffects->DoDamage(iChange, iCause, iCausedBy);
1105  if (!iChange) return;
1106  }
1107  // Change value
1108  Damage = std::max<int32_t>( Damage+iChange, 0 );
1109  // Engine script call
1110  Call(PSF_Damage,&C4AulParSet(iChange, iCause, iCausedBy));
1111 }
1112 
1113 void C4Object::DoEnergy(int32_t iChange, bool fExact, int32_t iCause, int32_t iCausedByPlr)
1114 {
1115  if (!fExact)
1116  {
1117  // Clamp range of change to prevent integer overflow errors
1118  // Do not clamp directly to (0...MaxEnergy)-current_energy, because
1119  // the change value calculated here may be reduced by effect callbacks
1120  int32_t scale = C4MaxPhysical / 100; // iChange 100% = Physical 100000
1121  iChange = Clamp<int32_t>(iChange, std::numeric_limits<int32_t>::min()/scale, std::numeric_limits<int32_t>::max()/scale)*scale;
1122  }
1123  // Was zero?
1124  bool fWasZero=(Energy==0);
1125  // Mark last damage causing player to trace kills
1126  if (iChange < 0) UpdatLastEnergyLossCause(iCausedByPlr);
1127  // Living things: ask effects for change first
1128  if (pEffects && Alive)
1129  pEffects->DoDamage(iChange, iCause, iCausedByPlr);
1130  // Do change
1131  iChange = Clamp<int32_t>(iChange, -Energy, GetPropertyInt(P_MaxEnergy) - Energy);
1132  Energy += iChange;
1133  // call to object
1134  Call(PSF_EnergyChange,&C4AulParSet(iChange, iCause, iCausedByPlr));
1135  // Alive and energy reduced to zero: death
1136  if (Alive) if (Energy==0) if (!fWasZero) AssignDeath(false);
1137 }
1138 
1139 void C4Object::UpdatLastEnergyLossCause(int32_t iNewCausePlr)
1140 {
1141  // Mark last damage causing player to trace kills
1142  // do not regard self-administered damage if there was a previous damage causing player, because that would steal kills
1143  // if people tumble themselves via stop-stop-(left/right)-throw while falling into teh abyss
1144  if (iNewCausePlr != Controller || LastEnergyLossCausePlayer < 0)
1145  {
1146  LastEnergyLossCausePlayer = iNewCausePlr;
1147  }
1148 }
1149 
1150 void C4Object::DoBreath(int32_t iChange)
1151 {
1152  // Do change
1153  iChange = Clamp<int32_t>(iChange, -Breath, GetPropertyInt(P_MaxBreath) - Breath);
1154  Breath += iChange;
1155  // call to object
1156  Call(PSF_BreathChange,&C4AulParSet(iChange));
1157 }
1158 
1159 void C4Object::DoCon(int32_t iChange, bool grow_from_center)
1160 {
1161  C4Real strgt_con_b = fix_y + Shape.GetBottom();
1162  bool fWasFull = (Con>=FullCon);
1163  int32_t old_con = Con;
1164 
1165  // Change con
1166  if (Def->Oversize)
1167  Con=std::max<int32_t>(Con+iChange,0);
1168  else
1169  Con=Clamp<int32_t>(Con+iChange,0,FullCon);
1170 
1171  // Update OCF
1172  SetOCF();
1173 
1174  // Mass
1175  UpdateMass();
1176 
1177  // shape and position
1178  UpdateShape();
1179  // make the bottom-most vertex stay in place
1180  if (!grow_from_center)
1181  {
1182  fix_y = strgt_con_b - Shape.GetBottom();
1183  }
1184  // Face (except for the shape)
1185  UpdateFace(false);
1186 
1187  // Do a callback on completion change.
1188  if (iChange != 0)
1189  Call(PSF_OnCompletionChange, &C4AulParSet(old_con, Con));
1190 
1191  // Unfullcon
1192  if (fWasFull && (Con<FullCon))
1193  {
1194  // Lose contents
1195  if (!Def->IncompleteActivity)
1196  {
1197  C4Object *cobj;
1198  while ((cobj=Contents.GetObject()))
1199  if (Contained) cobj->Enter(Contained);
1200  else cobj->Exit(cobj->GetX(),cobj->GetY());
1201  SetAction(0);
1202  }
1203  }
1204 
1205  // Completion
1206  if (!fWasFull && (Con>=FullCon))
1208 
1209  // Con Zero Removal
1210  if (Con<=0)
1211  AssignRemoval();
1212  // Mesh Graphics Update
1213  else if(pMeshInstance)
1214  pMeshInstance->SetCompletion(Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
1215 }
1216 
1217 void C4Object::DoExperience(int32_t change)
1218 {
1219  const int32_t MaxExperience = 100000000;
1220 
1221  if (!Info) return;
1222 
1223  Info->Experience=Clamp<int32_t>(Info->Experience+change,0,MaxExperience);
1224 
1225  // Promotion check
1226  if (Info->Experience<MaxExperience)
1228  Promote(Info->Rank+1, false, false);
1229 }
1230 
1231 bool C4Object::Exit(int32_t iX, int32_t iY, int32_t iR, C4Real iXDir, C4Real iYDir, C4Real iRDir, bool fCalls)
1232 {
1233  // 1. Exit the current container.
1234  // 2. Update Contents of container object and set Contained to nullptr.
1235  // 3. Set offset position/motion if desired.
1236  // 4. Call Ejection for container and Departure for object.
1237 
1238  // Not contained
1239  C4Object *pContainer=Contained;
1240  if (!pContainer) return false;
1241  // Remove object from container
1242  pContainer->Contents.Remove(this);
1243  pContainer->UpdateMass();
1244  pContainer->SetOCF();
1245  // No container
1246  Contained=nullptr;
1247  // Position/motion
1248  fix_x=itofix(iX); fix_y=itofix(iY);
1249  fix_r=itofix(iR);
1251  xdir=iXDir; ydir=iYDir; rdir=iRDir;
1252  // Misc updates
1253  Mobile=1;
1254  InLiquid=0;
1255  CloseMenu(true);
1256  UpdateFace(true);
1257  SetOCF();
1258  // Object list callback (before script callbacks, because script callbacks may enter again)
1259  ObjectListChangeListener.OnObjectContainerChanged(this, pContainer, nullptr);
1260  // Engine calls
1261  if (fCalls) pContainer->Call(PSF_Ejection,&C4AulParSet(this));
1262  if (fCalls) Call(PSF_Departure,&C4AulParSet(pContainer));
1263  // Success (if the obj wasn't "re-entered" by script)
1264  return !Contained;
1265 }
1266 
1267 bool C4Object::Enter(C4Object *pTarget, bool fCalls, bool fCopyMotion, bool *pfRejectCollect)
1268 {
1269  // 0. Query entrance and collection
1270  // 1. Exit if contained.
1271  // 2. Set new container.
1272  // 3. Update Contents and mass of the new container.
1273  // 4. Call collection for container
1274  // 5. Call entrance for object.
1275 
1276  // No valid target or target is self
1277  if (!pTarget || (pTarget==this)) return false;
1278  // check if entrance is allowed
1279  if (!! Call(PSF_RejectEntrance, &C4AulParSet(pTarget))) return false;
1280  // check if we end up in an endless container-recursion
1281  for (C4Object *pCnt=pTarget->Contained; pCnt; pCnt=pCnt->Contained)
1282  if (pCnt==this) return false;
1283  // Check RejectCollect, if desired
1284  if (pfRejectCollect)
1285  {
1286  if (!!pTarget->Call(PSF_RejectCollection,&C4AulParSet(Def, this)))
1287  {
1288  *pfRejectCollect = true;
1289  return false;
1290  }
1291  *pfRejectCollect = false;
1292  }
1293  // Exit if contained
1294  if (Contained) if (!Exit(GetX(),GetY())) return false;
1295  if (Contained || !Status || !pTarget->Status) return false;
1296  // Failsafe updates
1297  if (Menu)
1298  {
1299  CloseMenu(true);
1300  // CloseMenu might do bad stuff
1301  if (Contained || !Status || !pTarget->Status) return false;
1302  }
1303  SetOCF();
1304  // Set container
1305  Contained=pTarget;
1306  // Enter
1308  {
1309  Contained=nullptr;
1310  return false;
1311  }
1312  // Assume that the new container controls this object, if it cannot control itself (i.e.: Alive)
1313  // So it can be traced back who caused the damage, if a projectile hits its target
1314  if (!Alive)
1315  Controller = pTarget->Controller;
1316  // Misc updates
1317  // motion must be copied immediately, so the position will be correct when OCF is set, and
1318  // OCF_Available will be set for newly bought items, even if 50/50 is solid in the landscape
1319  // however, the motion must be preserved sometimes to keep flags like OCF_HitSpeed upon collection
1320  if (fCopyMotion)
1321  {
1322  // remove any solidmask before copying the motion...
1323  UpdateSolidMask(false);
1325  }
1326  SetOCF();
1327  UpdateFace(true);
1328  // Update container
1329  Contained->UpdateMass();
1330  Contained->SetOCF();
1331  // Object list callback (before script callbacks, because script callbacks may exit again)
1333  // Collection call
1334  if (fCalls) pTarget->Call(PSF_Collection2,&C4AulParSet(this));
1335  if (!Contained || !Contained->Status || !pTarget->Status) return true;
1336  // Entrance call
1337  if (fCalls) Call(PSF_Entrance,&C4AulParSet(Contained));
1338  if (!Contained || !Contained->Status || !pTarget->Status) return true;
1339  // Success
1340  return true;
1341 }
1342 
1343 void C4Object::Fling(C4Real txdir, C4Real tydir, bool fAddSpeed)
1344 {
1345  if (fAddSpeed) { txdir+=xdir/2; tydir+=ydir/2; }
1346  if (!ObjectActionTumble(this,(txdir<0),txdir,tydir))
1347  if (!ObjectActionJump(this,txdir,tydir,false))
1348  {
1349  xdir=txdir; ydir=tydir;
1350  Mobile=1;
1352  }
1353 }
1354 
1355 bool C4Object::ActivateEntrance(int32_t by_plr, C4Object *by_obj)
1356 {
1357 
1358  // Try entrance activation
1359  if (OCF & OCF_Entrance)
1360  if (!! Call(PSF_ActivateEntrance,&C4AulParSet(by_obj)))
1361  return true;
1362  // Failure
1363  return false;
1364 }
1365 
1366 bool C4Object::Push(C4Real txdir, C4Real dforce, bool fStraighten)
1367 {
1368  // Valid check
1369  if (!Status || !Def || Contained || !(OCF & OCF_Grab)) return false;
1370  // Grabbing okay, no pushing
1371  if (GetPropertyInt(P_Touchable)==2) return true;
1372  // Mobilization check (pre-mobilization zero)
1373  if (!Mobile)
1374  { xdir=ydir=Fix0; }
1375  // General pushing force vs. object mass
1376  dforce=dforce*100/Mass;
1377  // Set dir
1378  if (xdir<0) SetDir(DIR_Left);
1379  if (xdir>0) SetDir(DIR_Right);
1380  // Work towards txdir
1381  if (Abs(xdir-txdir)<=dforce) // Close-enough-set
1382  { xdir=txdir; }
1383  else // Work towards
1384  {
1385  if (xdir<txdir) xdir+=dforce;
1386  if (xdir>txdir) xdir-=dforce;
1387  }
1388  // Straighten
1389  if (fStraighten)
1390  {
1391  if (Inside<int32_t>(GetR(),-StableRange,+StableRange))
1392  {
1393  rdir=0; // cheap way out
1394  }
1395  else
1396  {
1397  if (fix_r > Fix0) { if (rdir>-RotateAccel) rdir-=dforce; }
1398  else { if (rdir<+RotateAccel) rdir+=dforce; }
1399  }
1400  }
1401 
1402  // Mobilization check
1403  if (!!xdir || !!ydir || !!rdir) Mobile=1;
1404 
1405  // Stuck check
1406  if (!::Game.iTick35) if (txdir) if (!Def->NoHorizontalMove)
1407  if (ContactCheck(GetX(), GetY())) // Resets t_contact
1408  {
1409  GameMsgObjectError(FormatString(LoadResStr("IDS_OBJ_STUCK"),GetName()).getData(),this);
1410  Call(PSF_Stuck);
1411  }
1412 
1413  return true;
1414 }
1415 
1416 bool C4Object::Lift(C4Real tydir, C4Real dforce)
1417 {
1418  // Valid check
1419  if (!Status || !Def || Contained) return false;
1420  // Mobilization check
1421  if (!Mobile)
1422  { xdir=ydir=Fix0; Mobile=1; }
1423  // General pushing force vs. object mass
1424  dforce=dforce*100/Mass;
1425  // If close enough, set tydir
1426  if (Abs(tydir-ydir)<=Abs(dforce))
1427  ydir=tydir;
1428  else // Work towards tydir
1429  {
1430  if (ydir<tydir) ydir+=dforce;
1431  if (ydir>tydir) ydir-=dforce;
1432  }
1433  // Stuck check
1434  if (tydir != -GravAccel)
1435  if (ContactCheck(GetX(), GetY())) // Resets t_contact
1436  {
1437  GameMsgObjectError(FormatString(LoadResStr("IDS_OBJ_STUCK"),GetName()).getData(),this);
1438  Call(PSF_Stuck);
1439  }
1440  return true;
1441 }
1442 
1444 {
1445  C4Object *nobj;
1446  if (!(nobj=Game.CreateObject(PropList,this,Owner))) return nullptr;
1447  if (!nobj->Enter(this)) { nobj->AssignRemoval(); return nullptr; }
1448  return nobj;
1449 }
1450 
1452 {
1453  int32_t cnt,cnt2;
1454  for (cnt=0; idlist.GetID(cnt); cnt++)
1455  for (cnt2=0; cnt2<idlist.GetCount(cnt); cnt2++)
1456  if (!CreateContents(C4Id2Def(idlist.GetID(cnt))))
1457  return false;
1458  return true;
1459 }
1460 
1461 static void DrawMenuSymbol(int32_t iMenu, C4Facet &cgo, int32_t iOwner)
1462 {
1463  C4Facet ccgo;
1464 
1465  DWORD dwColor=0;
1466  if (ValidPlr(iOwner)) dwColor=::Players.Get(iOwner)->ColorDw;
1467 
1468  switch (iMenu)
1469  {
1470  case C4MN_Buy:
1471  ::GraphicsResource.fctFlagClr.DrawClr(ccgo = cgo.GetFraction(75, 75), true, dwColor);
1473  ::GraphicsResource.fctArrow.Draw(ccgo = cgo.GetFraction(70, 70, C4FCT_Right, C4FCT_Center), false, 0);
1474  break;
1475  case C4MN_Sell:
1476  ::GraphicsResource.fctFlagClr.DrawClr(ccgo = cgo.GetFraction(75, 75), true, dwColor);
1478  ::GraphicsResource.fctArrow.Draw(ccgo = cgo.GetFraction(70, 70, C4FCT_Right, C4FCT_Center), false, 1);
1479  break;
1480  }
1481 }
1482 
1483 bool C4Object::ActivateMenu(int32_t iMenu, int32_t iMenuSelect,
1484  int32_t iMenuData, int32_t iMenuPosition,
1485  C4Object *pTarget)
1486 {
1487  // Variables
1488  C4FacetSurface fctSymbol;
1489  C4IDList ListItems;
1490  // Close any other menu
1491  if (Menu && Menu->IsActive()) if (!Menu->TryClose(true, false)) return false;
1492  // Create menu
1493  if (!Menu) Menu = new C4ObjectMenu; else Menu->ClearItems();
1494  // Open menu
1495  switch (iMenu)
1496  {
1497  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1498  case C4MN_Activate:
1499  // No target specified: use own container as target
1500  if (!pTarget) if (!(pTarget=Contained)) break;
1501  // Opening contents menu blocked by RejectContents
1502  if (!!pTarget->Call(PSF_RejectContents)) return false;
1503  // Create symbol
1504  fctSymbol.Create(C4SymbolSize,C4SymbolSize);
1505  pTarget->Def->Draw(fctSymbol,false,pTarget->Color,pTarget);
1506  // Init
1507  Menu->Init(fctSymbol,FormatString(LoadResStr("IDS_OBJ_EMPTY"),pTarget->GetName()).getData(),this,C4MN_Extra_None,0,iMenu);
1508  Menu->SetPermanent(true);
1509  Menu->SetRefillObject(pTarget);
1510  // Success
1511  return true;
1512  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1513  case C4MN_Buy:
1514  // No target specified: container is base
1515  if (!pTarget) if (!(pTarget=Contained)) break;
1516  // Create symbol
1517  fctSymbol.Create(C4SymbolSize,C4SymbolSize);
1518  DrawMenuSymbol(C4MN_Buy, fctSymbol, pTarget->Owner);
1519  // Init menu
1520  Menu->Init(fctSymbol,LoadResStr("IDS_PLR_NOBUY"),this,C4MN_Extra_Value,0,iMenu);
1521  Menu->SetPermanent(true);
1522  Menu->SetRefillObject(pTarget);
1523  // Success
1524  return true;
1525  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1526  case C4MN_Sell:
1527  // No target specified: container is base
1528  if (!pTarget) if (!(pTarget=Contained)) break;
1529  // Create symbol & init
1530  fctSymbol.Create(C4SymbolSize,C4SymbolSize);
1531  DrawMenuSymbol(C4MN_Sell, fctSymbol, pTarget->Owner);
1532  Menu->Init(fctSymbol,FormatString(LoadResStr("IDS_OBJ_EMPTY"),pTarget->GetName()).getData(),this,C4MN_Extra_Value,0,iMenu);
1533  Menu->SetPermanent(true);
1534  Menu->SetRefillObject(pTarget);
1535  // Success
1536  return true;
1537  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1538  case C4MN_Get:
1539  case C4MN_Contents:
1540  // No target specified
1541  if (!pTarget) break;
1542  // Opening contents menu blocked by RejectContents
1543  if (!!pTarget->Call(PSF_RejectContents)) return false;
1544  // Create symbol & init
1545  fctSymbol.Create(C4SymbolSize,C4SymbolSize);
1546  pTarget->Def->Draw(fctSymbol,false,pTarget->Color,pTarget);
1547  Menu->Init(fctSymbol,FormatString(LoadResStr("IDS_OBJ_EMPTY"),pTarget->GetName()).getData(),this,C4MN_Extra_None,0,iMenu);
1548  Menu->SetPermanent(true);
1549  Menu->SetRefillObject(pTarget);
1550  // Success
1551  return true;
1552  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1553  case C4MN_Info:
1554  // Target by parameter
1555  if (!pTarget) break;
1556  // Create symbol & init menu
1557  fctSymbol.Create(C4SymbolSize, C4SymbolSize); GfxR->fctOKCancel.Draw(fctSymbol,true,0,1);
1558  Menu->Init(fctSymbol, pTarget->GetName(), this, C4MN_Extra_None, 0, iMenu, C4MN_Style_Info);
1559  Menu->SetPermanent(true);
1561  C4Viewport *pViewport = ::Viewports.GetViewport(Controller); // Hackhackhack!!!
1562  if (pViewport) Menu->SetLocation((pTarget->GetX() + pTarget->Shape.GetX() + pTarget->Shape.Wdt + 10 - pViewport->GetViewX()) * pViewport->GetZoom(),
1563  (pTarget->GetY() + pTarget->Shape.GetY() - pViewport->GetViewY()) * pViewport->GetZoom());
1564  // Add info item
1565  fctSymbol.Create(C4PictureSize, C4PictureSize); pTarget->Def->Draw(fctSymbol, false, pTarget->Color, pTarget);
1566  Menu->Add(pTarget->GetName(), fctSymbol, "", C4MN_Item_NoCount, nullptr, pTarget->GetInfoString().getData());
1567  fctSymbol.Default();
1568  // Success
1569  return true;
1570  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1571  }
1572  // Invalid menu identification
1573  CloseMenu(true);
1574  return false;
1575 }
1576 
1577 bool C4Object::CloseMenu(bool fForce)
1578 {
1579  if (Menu)
1580  {
1581  if (Menu->IsActive()) if (!Menu->TryClose(fForce, false)) return false;
1582  if (!Menu->IsCloseQuerying()) { delete Menu; Menu=nullptr; } // protect menu deletion from recursive menu operation calls
1583  }
1584  return true;
1585 }
1586 
1587 BYTE C4Object::GetArea(int32_t &aX, int32_t &aY, int32_t &aWdt, int32_t &aHgt) const
1588 {
1589  if (!Status || !Def) return 0;
1590  aX = GetX() + Shape.GetX(); aY = GetY() + Shape.GetY();
1591  aWdt=Shape.Wdt; aHgt=Shape.Hgt;
1592  return 1;
1593 }
1594 
1595 BYTE C4Object::GetEntranceArea(int32_t &aX, int32_t &aY, int32_t &aWdt, int32_t &aHgt) const
1596 {
1597  if (!Status || !Def) return 0;
1598  // Return actual entrance
1599  if (OCF & OCF_Entrance)
1600  {
1601  aX=GetX() + Def->Entrance.x;
1602  aY=GetY() + Def->Entrance.y;
1603  aWdt=Def->Entrance.Wdt;
1604  aHgt=Def->Entrance.Hgt;
1605  }
1606  // Return object center
1607  else
1608  {
1609  aX=GetX(); aY=GetY();
1610  aWdt=0; aHgt=0;
1611  }
1612  // Done
1613  return 1;
1614 }
1615 
1617 {
1618  rxdir=rydir=0;
1619  if (!Status || !Def) return 0;
1620  rxdir=xdir; rydir=ydir;
1621  return 1;
1622 }
1623 
1625 {
1626  C4Real cobjspd=Fix0;
1627  if (xdir<0) cobjspd-=xdir; else cobjspd+=xdir;
1628  if (ydir<0) cobjspd-=ydir; else cobjspd+=ydir;
1629  return cobjspd;
1630 }
1631 
1633 {
1634  StdStrBuf Output;
1635  // Type
1636  Output.AppendFormat(LoadResStr("IDS_CNS_TYPE"),GetName(),Def->id.ToString());
1637  // Owner
1638  if (ValidPlr(Owner))
1639  {
1640  Output.Append(LineFeed);
1641  Output.AppendFormat(LoadResStr("IDS_CNS_OWNER"),::Players.Get(Owner)->GetName());
1642  }
1643  // Contents
1644  if (Contents.ObjectCount())
1645  {
1646  Output.Append(LineFeed);
1647  Output.Append(LoadResStr("IDS_CNS_CONTENTS"));
1649  }
1650  // Action
1651  if (GetAction())
1652  {
1653  Output.Append(LineFeed);
1654  Output.Append(LoadResStr("IDS_CNS_ACTION"));
1655  Output.Append(GetAction()->GetName());
1656  }
1657  // Properties
1658  Output.Append(LineFeed);
1659  Output.Append(LoadResStr("IDS_CNS_PROPERTIES"));
1660  Output.Append(LineFeed " ");
1661  AppendDataString(&Output, LineFeed " ");
1662  // Effects
1663  if (pEffects)
1664  {
1665  Output.Append(LineFeed);
1666  Output.Append(LoadResStr("IDS_CNS_EFFECTS"));
1667  Output.Append(": ");
1668  }
1669  for (C4Effect *pEffect = pEffects; pEffect; pEffect = pEffect->pNext)
1670  {
1671  Output.Append(LineFeed);
1672  // Effect name
1673  Output.AppendFormat(" %s: Priority %d, Interval %d", pEffect->GetName(), pEffect->iPriority, pEffect->iInterval);
1674  }
1675 
1676  StdStrBuf Output2;
1677  C4ValueNumbers numbers;
1678  DecompileToBuf_Log<StdCompilerINIWrite>(mkNamingAdapt(mkInsertAdapt(mkParAdapt(*this, &numbers),
1679  mkNamingAdapt(numbers, "Values"), false),
1680  "Object"), &Output2, "C4Object::GetDataString");
1681  Output.Append(LineFeed);
1682  Output.Append(Output2);
1683  return Output;
1684 }
1685 
1686 void C4Object::SetName(const char * NewName)
1687 {
1688  if (!NewName && Info)
1690  else
1691  C4PropList::SetName(NewName);
1692 }
1693 
1694 int32_t C4Object::GetValue(C4Object *pInBase, int32_t iForPlayer)
1695 {
1696  C4Value r = Call(PSF_CalcValue, &C4AulParSet(pInBase, iForPlayer));
1697  int32_t iValue;
1698  if (r != C4VNull)
1699  iValue = r.getInt();
1700  else
1701  {
1702  // get value of def
1703  // Caution: Do not pass pInBase here, because the def base value is to be queried
1704  // - and not the value if you had to buy the object in this particular base
1705  iValue = Def->GetValue(nullptr, iForPlayer);
1706  }
1707  // Con percentage
1708  iValue = iValue * Con / FullCon;
1709  // do any adjustments based on where the item is bought
1710  if (pInBase)
1711  {
1712  r = pInBase->Call(PSF_CalcSellValue, &C4AulParSet(this, iValue));
1713  if (r != C4VNull)
1714  iValue = r.getInt();
1715  }
1716  return iValue;
1717 }
1718 
1719 bool C4Object::Promote(int32_t torank, bool exception, bool fForceRankName)
1720 {
1721  if (!Info) return false;
1722  // get rank system
1723  C4Def *pUseDef = C4Id2Def(Info->id);
1724  C4RankSystem *pRankSys;
1725  if (pUseDef && pUseDef->pRankNames)
1726  pRankSys = pUseDef->pRankNames;
1727  else
1728  pRankSys = &::DefaultRanks;
1729  // always promote info
1730  Info->Promote(torank,*pRankSys, fForceRankName);
1731  // silent update?
1732  if (!pRankSys->GetRankName(torank,false)) return false;
1733  GameMsgObject(FormatString(LoadResStr("IDS_OBJ_PROMOTION"),GetName (),Info->sRankName.getData()).getData(),this);
1734 
1735  // call to object
1737 
1738  StartSoundEffect("UI::Trumpet",0,100,this);
1739  return true;
1740 }
1741 
1743 {
1744  // mesh attachments and animation nodes
1746  // effects
1747  if (pEffects) pEffects->ClearPointers(pObj);
1748  // contents/contained: although normally not necessery because it's done in AssignRemoval and StatusDeactivate,
1749  // it is also required during game destruction (because ClearPointers might do script callbacks)
1750  // Perform silent exit to avoid additional callbacks
1751  if (Contained == pObj)
1752  {
1753  Contained->Contents.Remove(this);
1754  Contained = nullptr;
1755  }
1756  Contents.Remove(pObj);
1757  // Action targets
1758  if (Action.Target==pObj) Action.Target=nullptr;
1759  if (Action.Target2==pObj) Action.Target2=nullptr;
1760  // Commands
1761  C4Command *cCom;
1762  for (cCom=Command; cCom; cCom=cCom->Next)
1763  cCom->ClearPointers(pObj);
1764  // Menu
1765  if (Menu) Menu->ClearPointers(pObj);
1766  // Layer
1767  if (Layer==pObj) Layer=nullptr;
1768  // gfx overlays
1769  if (pGfxOverlay)
1770  {
1771  C4GraphicsOverlay *pNextGfxOvrl = pGfxOverlay, *pGfxOvrl;
1772  while ((pGfxOvrl = pNextGfxOvrl))
1773  {
1774  pNextGfxOvrl = pGfxOvrl->GetNext();
1775  if (pGfxOvrl->GetOverlayObject() == pObj)
1776  // overlay relying on deleted object: Delete!
1777  RemoveGraphicsOverlay(pGfxOvrl->GetID());
1778  }
1779  }
1780 }
1781 
1782 bool C4Object::SetPhase(int32_t iPhase)
1783 {
1784  C4PropList* pActionDef = GetAction();
1785  if (!pActionDef) return false;
1786  const int32_t length = pActionDef->GetPropertyInt(P_Length);
1787  Action.Phase=Clamp<int32_t>(iPhase,0,length);
1788  Action.PhaseDelay = 0;
1789  return true;
1790 }
1791 
1792 void C4Object::Draw(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode, float offX, float offY)
1793 {
1794 #ifndef USE_CONSOLE
1795  C4Facet ccgo;
1796 
1797  // Status
1798  if (!Status || !Def) return;
1799 
1800  // visible?
1801  if (!IsVisible(iByPlayer, !!eDrawMode)) return;
1802 
1803  // Set up custom uniforms.
1804  auto uniform_popper = pDraw->scriptUniform.Push(this);
1805 
1806  // Line
1807  if (Def->Line) { DrawLine(cgo, iByPlayer); return; }
1808 
1809  // background particles (bounds not checked)
1810  if (BackParticles) BackParticles->Draw(cgo, this);
1811 
1812  // Object output position
1813  float newzoom = cgo.Zoom;
1814  if (eDrawMode!=ODM_Overlay)
1815  {
1816  if (!GetDrawPosition(cgo, offX, offY, newzoom)) return;
1817  }
1818  ZoomDataStackItem zdsi(newzoom);
1819 
1820  bool fYStretchObject=false;
1821  C4PropList* pActionDef = GetAction();
1822  if (pActionDef)
1823  if (pActionDef->GetPropertyInt(P_FacetTargetStretch))
1824  fYStretchObject=true;
1825 
1826  // Set audibility
1827  if (!eDrawMode) SetAudibilityAt(cgo, GetX(), GetY(), iByPlayer);
1828 
1829  // Output boundary
1830  if (!fYStretchObject && !eDrawMode && !(Category & C4D_Parallax))
1831  {
1832  // For actions with a custom facet set, check against that action facet. Otherwise (or with oversize objects), just check against shape.
1833  if (pActionDef && fix_r == Fix0 && !pActionDef->GetPropertyInt(P_FacetBase) && Con <= FullCon && Action.Facet.Wdt)
1834  {
1835  // active
1836  if ( !Inside<float>(offX+Shape.GetX()+Action.FacetX,cgo.X-Action.Facet.Wdt,cgo.X+cgo.Wdt)
1837  || (!Inside<float>(offY+Shape.GetY()+Action.FacetY,cgo.Y-Action.Facet.Hgt,cgo.Y+cgo.Hgt)) )
1838  {
1839  if (FrontParticles && !Contained) FrontParticles->Draw(cgo, this);
1840  return;
1841  }
1842  }
1843  else
1844  // idle
1845  if ( !Inside<float>(offX+Shape.GetX(),cgo.X-Shape.Wdt,cgo.X+cgo.Wdt)
1846  || (!Inside<float>(offY+Shape.GetY(),cgo.Y-Shape.Hgt,cgo.Y+cgo.Hgt)) )
1847  {
1848  if (FrontParticles && !Contained) FrontParticles->Draw(cgo, this);
1849  return;
1850  }
1851  }
1852 
1853  // ensure correct color is set
1854  if (GetGraphics()->Type == C4DefGraphics::TYPE_Bitmap)
1855  if (GetGraphics()->Bmp.BitmapClr) GetGraphics()->Bmp.BitmapClr->SetClr(Color);
1856 
1857  // Debug Display //////////////////////////////////////////////////////////////////////
1858  if (::GraphicsSystem.ShowCommand && !eDrawMode)
1859  {
1860  C4Command *pCom;
1861  int32_t ccx=GetX(),ccy=GetY();
1862  float offX1, offY1, offX2, offY2, newzoom;
1863  char szCommand[200];
1864  StdStrBuf Cmds;
1865  int32_t iMoveTos=0;
1866  for (pCom=Command; pCom; pCom=pCom->Next)
1867  {
1868  switch (pCom->Command)
1869  {
1870  case C4CMD_MoveTo:
1871  // Angle
1872  int32_t iAngle; iAngle=Angle(ccx,ccy,pCom->Tx._getInt(),pCom->Ty); while (iAngle>180) iAngle-=360;
1873  // Path
1874  if(GetDrawPosition(cgo, ccx, ccy, cgo.Zoom, offX1, offY1, newzoom) &&
1875  GetDrawPosition(cgo, pCom->Tx._getInt(), pCom->Ty, cgo.Zoom, offX2, offY2, newzoom))
1876  {
1877  ZoomDataStackItem zdsi(newzoom);
1878  pDraw->DrawLineDw(cgo.Surface,offX1,offY1,offX2,offY2,C4RGB(0xca,0,0));
1879  pDraw->DrawFrameDw(cgo.Surface,offX2-1,offY2-1,offX2+1,offY2+1,C4RGB(0xca,0,0));
1880  }
1881 
1882  ccx=pCom->Tx._getInt(); ccy=pCom->Ty;
1883  // Message
1884  iMoveTos++; szCommand[0]=0;
1885  break;
1886  case C4CMD_Put:
1887  sprintf(szCommand,"%s %s to %s",CommandName(pCom->Command),pCom->Target2 ? pCom->Target2->GetName() : pCom->Data ? pCom->Data.GetDataString().getData() : "Content",pCom->Target ? pCom->Target->GetName() : "");
1888  break;
1889  case C4CMD_Buy: case C4CMD_Sell:
1890  sprintf(szCommand,"%s %s at %s",CommandName(pCom->Command),pCom->Data.GetDataString().getData(),pCom->Target ? pCom->Target->GetName() : "closest base");
1891  break;
1892  case C4CMD_Acquire:
1893  sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Data.GetDataString().getData());
1894  break;
1895  case C4CMD_Call:
1896  sprintf(szCommand,"%s %s in %s",CommandName(pCom->Command),pCom->Text->GetCStr(),pCom->Target ? pCom->Target->GetName() : "(null)");
1897  break;
1898  case C4CMD_None:
1899  szCommand[0]=0;
1900  break;
1901  case C4CMD_Transfer:
1902  // Path
1903  if(GetDrawPosition(cgo, ccx, ccy, cgo.Zoom, offX1, offY1, newzoom) &&
1904  GetDrawPosition(cgo, pCom->Tx._getInt(), pCom->Ty, cgo.Zoom, offX2, offY2, newzoom))
1905  {
1906  ZoomDataStackItem zdsi(newzoom);
1907  pDraw->DrawLineDw(cgo.Surface,offX1,offY1,offX2,offY2,C4RGB(0,0xca,0));
1908  pDraw->DrawFrameDw(cgo.Surface,offX2-1,offY2-1,offX2+1,offY2+1,C4RGB(0,0xca,0));
1909  }
1910 
1911  ccx=pCom->Tx._getInt(); ccy=pCom->Ty;
1912  // Message
1913  sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Target ? pCom->Target->GetName() : "");
1914  break;
1915  default:
1916  sprintf(szCommand,"%s %s",CommandName(pCom->Command),pCom->Target ? pCom->Target->GetName() : "");
1917  break;
1918  }
1919  // Compose command stack message
1920  if (szCommand[0])
1921  {
1922  // End MoveTo stack first
1923  if (iMoveTos) { Cmds.AppendChar('|'); Cmds.AppendFormat("%dx MoveTo",iMoveTos); iMoveTos=0; }
1924  // Current message
1925  Cmds.AppendChar('|');
1926  if (pCom->Finished) Cmds.Append("<i>");
1927  Cmds.Append(szCommand);
1928  if (pCom->Finished) Cmds.Append("</i>");
1929  }
1930  }
1931  // Open MoveTo stack
1932  if (iMoveTos) { Cmds.AppendChar('|'); Cmds.AppendFormat("%dx MoveTo",iMoveTos); iMoveTos=0; }
1933  // Draw message
1934  int32_t cmwdt,cmhgt; ::GraphicsResource.FontRegular.GetTextExtent(Cmds.getData(),cmwdt,cmhgt,true);
1936  }
1937  // Debug Display ///////////////////////////////////////////////////////////////////////////////
1938 
1939  // Don't draw (show solidmask)
1940  if (::GraphicsSystem.Show8BitSurface != 0)
1941  if (SolidMask.Wdt)
1942  {
1943  // DrawSolidMask(cgo); - no need to draw it, because the 8bit-surface will be shown
1944  return;
1945  }
1946 
1947  // Contained check
1948  if (Contained && !eDrawMode) return;
1949 
1950  // Visibility inside FoW
1951  const C4FoWRegion* pOldFoW = pDraw->GetFoW();
1952  if(pOldFoW && (Category & C4D_IgnoreFoW))
1953  pDraw->SetFoW(nullptr);
1954 
1955  // color modulation (including construction sign...)
1956  if (ColorMod != 0xffffffff || BlitMode) if (!eDrawMode) PrepareDrawing();
1957 
1958  // Not active or rotated: BaseFace only
1959  if (!pActionDef)
1960  {
1961  DrawFace(cgo, offX, offY);
1962  }
1963 
1964  // Active
1965  else
1966  {
1967  // FacetBase
1969  DrawFace(cgo, offX, offY, 0, Action.DrawDir);
1970 
1971  // Special: stretched action facet
1973  {
1974  if (Action.Target)
1976  float(Action.Facet.X),float(Action.Facet.Y),float(Action.Facet.Wdt),float(Action.Facet.Hgt),
1977  cgo.Surface,
1978  offX + Shape.GetX() + Action.FacetX, offY + Shape.GetY() + Action.FacetY,Action.Facet.Wdt,
1980  true);
1981  }
1982  else if (Action.Facet.Surface)
1983  DrawActionFace(cgo, offX, offY);
1984  }
1985 
1986  // end of color modulation
1987  if (ColorMod != 0xffffffff || BlitMode) if (!eDrawMode) FinishedDrawing();
1988 
1989  // draw overlays - after blit mode changes, because overlay gfx set their own
1990  if (pGfxOverlay) if (eDrawMode!=ODM_BaseOnly)
1991  for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
1992  if (!pGfxOvrl->IsPicture())
1993  pGfxOvrl->Draw(cgo, this, iByPlayer);
1994 
1995  // local particles in front of the object
1996  if (eDrawMode!=ODM_BaseOnly)
1997  {
1998  if (FrontParticles)
1999  FrontParticles->Draw(cgo, this);
2000  }
2001 
2002  // Debug Display ////////////////////////////////////////////////////////////////////////
2003  if (::GraphicsSystem.ShowVertices) if (eDrawMode!=ODM_BaseOnly)
2004  {
2005  int32_t cnt;
2006  if (Shape.VtxNum>1)
2007  for (cnt=0; cnt<Shape.VtxNum; cnt++)
2008  {
2009  DrawVertex(cgo,
2010  offX+Shape.VtxX[cnt],
2011  offY+Shape.VtxY[cnt],
2012  (Shape.VtxCNAT[cnt] & CNAT_NoCollision) ? C4RGB(0, 0, 0xff) : (Mobile ? C4RGB(0xff, 0, 0) : C4RGB(0xef, 0xef, 0)),
2013  Shape.VtxContactCNAT[cnt]);
2014  }
2015  }
2016 
2017  if (::GraphicsSystem.ShowEntrance) if (eDrawMode!=ODM_BaseOnly)
2018  {
2019  if (OCF & OCF_Entrance)
2020  pDraw->DrawFrameDw(cgo.Surface,offX+Def->Entrance.x,
2021  offY+Def->Entrance.y,
2022  offX+Def->Entrance.x+Def->Entrance.Wdt-1,
2023  offY+Def->Entrance.y+Def->Entrance.Hgt-1,
2024  C4RGB(0, 0, 0xff));
2025  if (OCF & OCF_Collection)
2026  pDraw->DrawFrameDw(cgo.Surface,offX+Def->Collection.x,
2027  offY+Def->Collection.y,
2028  offX+Def->Collection.x+Def->Collection.Wdt-1,
2029  offY+Def->Collection.y+Def->Collection.Hgt-1,
2030  C4RGB(0xca, 0, 0));
2031  }
2032 
2033  if (::GraphicsSystem.ShowAction) if (eDrawMode!=ODM_BaseOnly)
2034  {
2035  if (pActionDef)
2036  {
2037  StdStrBuf str;
2038  str.Format("%s (%d)",pActionDef->GetName(),Action.Phase);
2039  int32_t cmwdt,cmhgt; ::GraphicsResource.FontRegular.GetTextExtent(str.getData(),cmwdt,cmhgt,true);
2041  1.0, cgo.Surface, offX, offY + Shape.GetY() - cmhgt,
2043  }
2044  }
2045  // Debug Display ///////////////////////////////////////////////////////////////////////
2046 
2047  // Restore visibility inside FoW
2048  if (pOldFoW) pDraw->SetFoW(pOldFoW);
2049 #endif
2050 }
2051 
2052 void C4Object::DrawTopFace(C4TargetFacet &cgo, int32_t iByPlayer, DrawMode eDrawMode, float offX, float offY)
2053 {
2054 #ifndef USE_CONSOLE
2055  // Status
2056  if (!Status || !Def) return;
2057  // visible?
2058  if (!IsVisible(iByPlayer, eDrawMode==ODM_Overlay)) return;
2059  // target pos (parallax)
2060  float newzoom = cgo.Zoom;
2061  if (eDrawMode!=ODM_Overlay) GetDrawPosition(cgo, offX, offY, newzoom);
2062  ZoomDataStackItem zdsi(newzoom);
2063  // TopFace
2064  if (!(TopFace.Surface || (OCF & OCF_Construct))) return;
2065  // Output bounds check
2066  if (!Inside<float>(offX, cgo.X - Shape.Wdt, cgo.X + cgo.Wdt)
2067  || !Inside<float>(offY, cgo.Y - Shape.Hgt, cgo.Y + cgo.Hgt))
2068  return;
2069  // Don't draw (show solidmask)
2070  if (::GraphicsSystem.Show8BitSurface != 0 && SolidMask.Wdt) return;
2071  // Contained
2072  if (Contained) if (eDrawMode!=ODM_Overlay) return;
2073  // Construction sign
2074  if (OCF & OCF_Construct && fix_r == Fix0)
2075  if (eDrawMode!=ODM_BaseOnly)
2076  {
2078  pDraw->Blit(fctConSign.Surface,
2079  fctConSign.X, fctConSign.Y,
2080  fctConSign.Wdt, fctConSign.Hgt,
2081  cgo.Surface,
2082  offX + Shape.GetX(), offY + Shape.GetY() + Shape.Hgt - fctConSign.Hgt,
2083  fctConSign.Wdt, fctConSign.Hgt, true);
2084  }
2085  if(TopFace.Surface)
2086  {
2087  // FacetTopFace: Override TopFace.GetX()/GetY()
2088  C4PropList* pActionDef = GetAction();
2089  if (pActionDef && pActionDef->GetPropertyInt(P_FacetTopFace))
2090  {
2091  int32_t iPhase = Action.Phase;
2092  if (pActionDef->GetPropertyInt(P_Reverse)) iPhase = pActionDef->GetPropertyInt(P_Length) - 1 - Action.Phase;
2093  TopFace.X = pActionDef->GetPropertyInt(P_X) + Def->TopFace.x + pActionDef->GetPropertyInt(P_Wdt) * iPhase;
2094  TopFace.Y = pActionDef->GetPropertyInt(P_Y) + Def->TopFace.y + pActionDef->GetPropertyInt(P_Hgt) * Action.DrawDir;
2095  }
2096  // ensure correct color is set
2097  if (GetGraphics()->Bmp.BitmapClr) GetGraphics()->Bmp.BitmapClr->SetClr(Color);
2098  // color modulation
2099  if (!eDrawMode) PrepareDrawing();
2100  // Draw top face bitmap
2101  if (Con!=FullCon && Def->GrowthType)
2102  // stretched
2105  cgo.Surface,
2106  offX + Shape.GetX() + float(Def->TopFace.tx * Con) / FullCon, offY + Shape.GetY() + float(Def->TopFace.ty * Con) / FullCon,
2107  float(TopFace.Wdt * Con) / FullCon, float(TopFace.Hgt * Con) / FullCon,
2108  true, pDrawTransform ? &C4DrawTransform(*pDrawTransform, offX, offY) : nullptr);
2109  else
2110  // normal
2112  TopFace.X,TopFace.Y,
2114  cgo.Surface,
2115  offX + Shape.GetX() + Def->TopFace.tx, offY + Shape.GetY() + Def->TopFace.ty,
2117  true, pDrawTransform ? &C4DrawTransform(*pDrawTransform, offX, offY) : nullptr);
2118  }
2119  // end of color modulation
2120  if (!eDrawMode) FinishedDrawing();
2121 #endif
2122 }
2123 
2124 void C4Object::DrawLine(C4TargetFacet &cgo, int32_t at_player)
2125 {
2126  // Nothing to draw if the object has less than two vertices
2127  if (Shape.VtxNum < 2)
2128  return;
2129 #ifndef USE_CONSOLE
2130  // Audibility
2131  SetAudibilityAt(cgo, Shape.VtxX[0], Shape.VtxY[0], at_player);
2132  SetAudibilityAt(cgo, Shape.VtxX[Shape.VtxNum - 1], Shape.VtxY[Shape.VtxNum - 1], at_player);
2133  // additive mode?
2134  PrepareDrawing();
2135  // Draw line segments
2136  C4Value colorsV; GetProperty(P_LineColors, &colorsV);
2137  C4ValueArray *colors = colorsV.getArray();
2138  // TODO: Edge color (color1) is currently ignored.
2139  int32_t color0 = 0xFFFF00FF;// , color1 = 0xFFFF00FF; // use bright colors so author notices
2140  if (colors)
2141  {
2142  color0 = colors->GetItem(0).getInt();
2143  }
2144 
2145  std::vector<C4BltVertex> vertices;
2146  vertices.resize( (Shape.VtxNum - 1) * 2);
2147  for (int32_t vtx=0; vtx+1<Shape.VtxNum; vtx++)
2148  {
2149  DwTo4UB(color0, vertices[2*vtx].color);
2150  DwTo4UB(color0, vertices[2*vtx+1].color);
2151 
2152  vertices[2*vtx].ftx = Shape.VtxX[vtx] + cgo.X - cgo.TargetX;
2153  vertices[2*vtx].fty = Shape.VtxY[vtx] + cgo.Y - cgo.TargetY;
2154  vertices[2*vtx+1].ftx = Shape.VtxX[vtx+1] + cgo.X - cgo.TargetX;
2155  vertices[2*vtx+1].fty = Shape.VtxY[vtx+1] + cgo.Y - cgo.TargetY;
2156  }
2157 
2158  pDraw->PerformMultiLines(cgo.Surface, &vertices[0], vertices.size(), 1.0f, nullptr);
2159 
2160  // reset blit mode
2161  FinishedDrawing();
2162 #endif
2163 }
2164 
2166 {
2167  bool deserializing = pComp->isDeserializer();
2168  if (deserializing)
2169  Clear();
2170 
2171  // Compile ID, search definition
2172  pComp->Value(mkNamingAdapt(id, "id", C4ID::None ));
2173  if (deserializing)
2174  {
2175  Def = ::Definitions.ID2Def(id);
2176  if (!Def)
2177  { pComp->excNotFound(LoadResStr("IDS_PRC_UNDEFINEDOBJECT"),id.ToString()); return; }
2178  }
2179 
2180  pComp->Value(mkNamingAdapt( mkParAdapt(static_cast<C4PropListNumbered&>(*this), numbers), "Properties"));
2181  pComp->Value(mkNamingAdapt( Status, "Status", 1 ));
2182  if (Info) nInfo = Info->Name; else nInfo.Clear();
2183  pComp->Value(mkNamingAdapt( toC4CStrBuf(nInfo), "Info", "" ));
2184  pComp->Value(mkNamingAdapt( Owner, "Owner", NO_OWNER ));
2185  pComp->Value(mkNamingAdapt( Controller, "Controller", NO_OWNER ));
2186  pComp->Value(mkNamingAdapt( LastEnergyLossCausePlayer, "LastEngLossPlr", NO_OWNER ));
2187  pComp->Value(mkNamingAdapt( Category, "Category", 0 ));
2188  pComp->Value(mkNamingAdapt( Plane, "Plane", 0 ));
2189 
2190  pComp->Value(mkNamingAdapt( iLastAttachMovementFrame, "LastSolidAtchFrame", -1 ));
2191  pComp->Value(mkNamingAdapt( Con, "Size", 0 ));
2192  pComp->Value(mkNamingAdapt( OwnMass, "OwnMass", 0 ));
2193  pComp->Value(mkNamingAdapt( Mass, "Mass", 0 ));
2194  pComp->Value(mkNamingAdapt( Damage, "Damage", 0 ));
2195  pComp->Value(mkNamingAdapt( Energy, "Energy", 0 ));
2196  pComp->Value(mkNamingAdapt( Alive, "Alive", false ));
2197  pComp->Value(mkNamingAdapt( Breath, "Breath", 0 ));
2198  pComp->Value(mkNamingAdapt( Color, "Color", 0u ));
2199  pComp->Value(mkNamingAdapt( fix_x, "X", Fix0 ));
2200  pComp->Value(mkNamingAdapt( fix_y, "Y", Fix0 ));
2201  pComp->Value(mkNamingAdapt( fix_r, "R", Fix0 ));
2202  pComp->Value(mkNamingAdapt( xdir, "XDir", 0 ));
2203  pComp->Value(mkNamingAdapt( ydir, "YDir", 0 ));
2204  pComp->Value(mkNamingAdapt( rdir, "RDir", 0 ));
2205  pComp->Value(mkParAdapt(Shape, &Def->Shape));
2206  pComp->Value(mkNamingAdapt( fOwnVertices, "OwnVertices", false ));
2207  pComp->Value(mkNamingAdapt( SolidMask, "SolidMask", Def->SolidMask ));
2208  pComp->Value(mkNamingAdapt( PictureRect, "Picture" ));
2209  pComp->Value(mkNamingAdapt( Mobile, "Mobile", false ));
2210  pComp->Value(mkNamingAdapt( OnFire, "OnFire", false ));
2211  pComp->Value(mkNamingAdapt( InLiquid, "InLiquid", false ));
2212  pComp->Value(mkNamingAdapt( EntranceStatus, "EntranceStatus", false ));
2213  pComp->Value(mkNamingAdapt( OCF, "OCF", 0u ));
2214  pComp->Value(Action);
2215  pComp->Value(mkNamingAdapt( Contained, "Contained", C4ObjectPtr::Null ));
2216  pComp->Value(mkNamingAdapt( Action.Target, "ActionTarget1", C4ObjectPtr::Null ));
2217  pComp->Value(mkNamingAdapt( Action.Target2, "ActionTarget2", C4ObjectPtr::Null ));
2218  pComp->Value(mkNamingAdapt( mkParAdapt(Contents, numbers), "Contents" ));
2219  pComp->Value(mkNamingAdapt( lightRange, "LightRange", 0 ));
2220  pComp->Value(mkNamingAdapt( lightFadeoutRange, "LightFadeoutRange", 0 ));
2221  pComp->Value(mkNamingAdapt( lightColor, "lightColor", 0xffffffffu ));
2222  pComp->Value(mkNamingAdapt( ColorMod, "ColorMod", 0xffffffffu ));
2223  pComp->Value(mkNamingAdapt( BlitMode, "BlitMode", 0u ));
2224  pComp->Value(mkNamingAdapt( CrewDisabled, "CrewDisabled", false ));
2225  pComp->Value(mkNamingAdapt( Layer, "Layer", C4ObjectPtr::Null ));
2226  pComp->Value(mkNamingAdapt( C4DefGraphicsAdapt(pGraphics), "Graphics", &Def->Graphics ));
2227  pComp->Value(mkNamingPtrAdapt( pDrawTransform, "DrawTransform" ));
2228  pComp->Value(mkParAdapt(mkNamingPtrAdapt( pEffects, "Effects" ), this, numbers));
2229  pComp->Value(mkNamingAdapt( C4GraphicsOverlayListAdapt(pGfxOverlay),"GfxOverlay", (C4GraphicsOverlay *)nullptr));
2230 
2231  // Serialize mesh instance if we have a mesh graphics
2233  {
2234  if(pComp->isDeserializer())
2235  {
2236  assert(!pMeshInstance);
2237  pMeshInstance = new StdMeshInstance(*pGraphics->Mesh, Def->GrowthType ? 1.0f : static_cast<float>(Con)/static_cast<float>(FullCon));
2238  }
2239 
2241 
2242  // Does not work because unanimated meshes without attached meshes
2243  // do not even write a [Mesh] header so this does not create a mesh instance in that case
2244 /* pComp->Value(mkNamingContextPtrAdapt( pMeshInstance, *pGraphics->Mesh, "Mesh"));
2245  if(!pMeshInstance)
2246  pComp->excCorrupt("Mesh graphics without mesh instance");*/
2247  }
2248 
2249  // TODO: Animations / attached meshes
2250 
2251  // Commands
2252  if (pComp->FollowName("Commands"))
2253  {
2254  if (deserializing)
2255  {
2256  C4Command *pCmd = nullptr;
2257  for (int i = 1; ; i++)
2258  {
2259  // Every command has its own naming environment
2260  StdStrBuf Naming = FormatString("Command%d", i);
2261  pComp->Value(mkParAdapt(mkNamingPtrAdapt(pCmd ? pCmd->Next : Command, Naming.getData()), numbers));
2262  // Last command?
2263  pCmd = (pCmd ? pCmd->Next : Command);
2264  if (!pCmd)
2265  break;
2266  pCmd->cObj = this;
2267  }
2268  }
2269  else
2270  {
2271  C4Command *pCmd = Command;
2272  for (int i = 1; pCmd; i++, pCmd = pCmd->Next)
2273  {
2274  StdStrBuf Naming = FormatString("Command%d", i);
2275  pComp->Value(mkNamingAdapt(mkParAdapt(*pCmd, numbers), Naming.getData()));
2276  }
2277  }
2278  }
2279 
2280  // Compiling? Do initialization.
2281  if (deserializing)
2282  {
2283  // add to def count
2284  Def->Count++;
2285 
2286 
2287  // Set action (override running data)
2288  /* FIXME
2289  int32_t iTime=Action.Time;
2290  int32_t iPhase=Action.Phase;
2291  int32_t iPhaseDelay=Action.PhaseDelay;
2292  if (SetActionByName(Action.pActionDef->GetName(),0,0,false))
2293  {
2294  Action.Time=iTime;
2295  Action.Phase=iPhase; // No checking for valid phase
2296  Action.PhaseDelay=iPhaseDelay;
2297  }*/
2298 
2299  if (pMeshInstance)
2300  {
2301  // Set Action animation by slot 0
2304  }
2305 
2306  // blit mode not assigned? use definition default then
2307  if (!BlitMode) BlitMode = Def->BlitMode;
2308 
2309  // object needs to be resorted? May happen if there's unsorted objects in savegame
2310  if (Unsorted) Game.fResortAnyObject = true;
2311  }
2312 
2313 }
2314 
2316 {
2317  C4PropList::Denumerate(numbers);
2318  // Standard enumerated pointers
2323 
2324  // Post-compile object list
2326 
2327  // Commands
2328  for (C4Command *pCom=Command; pCom; pCom=pCom->Next)
2329  pCom->Denumerate(numbers);
2330 
2331  // effects
2332  if (pEffects) pEffects->Denumerate(numbers);
2333 
2334  // gfx overlays
2335  if (pGfxOverlay)
2336  for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
2337  pGfxOvrl->DenumeratePointers();
2338 
2339  // mesh instance
2341 }
2342 
2343 void C4Object::DrawPicture(C4Facet &cgo, bool fSelected, C4DrawTransform* transform)
2344 {
2345  // Draw def picture with object color
2346  Def->Draw(cgo,fSelected,Color,this,0,0,transform);
2347 }
2348 
2350 {
2351  // set picture rect to facet
2352  C4Rect fctPicRect = PictureRect;
2353  if (!fctPicRect.Wdt) fctPicRect = Def->PictureRect;
2354  C4Facet fctPicture;
2355  fctPicture.Set(GetGraphics()->GetBitmap(Color),fctPicRect.x,fctPicRect.y,fctPicRect.Wdt,fctPicRect.Hgt);
2356 
2357  // use direct facet w/o own data if possible
2358  if (ColorMod == 0xffffffff && BlitMode == C4GFXBLIT_NORMAL && !pGfxOverlay)
2359  {
2360  cgo.Set(fctPicture);
2361  return;
2362  }
2363 
2364  // otherwise, draw to picture facet
2365  if (!cgo.Create(cgo.Wdt, cgo.Hgt)) return;
2366 
2367  // specific object color?
2368  PrepareDrawing();
2369 
2370  // draw picture itself
2371  fctPicture.Draw(cgo,true);
2372 
2373  // draw overlays
2374  if (pGfxOverlay)
2375  for (C4GraphicsOverlay *pGfxOvrl = pGfxOverlay; pGfxOvrl; pGfxOvrl = pGfxOvrl->GetNext())
2376  if (pGfxOvrl->IsPicture())
2377  pGfxOvrl->DrawPicture(cgo, this, nullptr);
2378 
2379  // done; reset drawing states
2380  FinishedDrawing();
2381 }
2382 
2384 {
2385  // Check owner and controller
2386  if (!ValidPlr(Owner)) Owner=NO_OWNER;
2388  // Color is not reset any more, because many scripts change colors to non-owner-colors these days
2389  // Additionally, player colors are now guarantueed to remain the same in savegame resumes
2390  return true;
2391 }
2392 
2394 {
2395  if (Info || !ValidPlr(Owner)) return false;
2396  // In crew list?
2397  C4Player *pPlr = ::Players.Get(Owner);
2398  if (pPlr->Crew.GetLink(this))
2399  {
2400  // Register with player
2401  if (!::Players.Get(Owner)->MakeCrewMember(this, true, false))
2402  pPlr->Crew.Remove(this);
2403  return true;
2404  }
2405  // Info set, but not in crew list, so
2406  // a) The savegame is old-style (without crew list)
2407  // or b) The clonk is dead
2408  // or c) The clonk belongs to a script player that's restored without Game.txt
2409  else if (nInfo.getLength())
2410  {
2411  if (!::Players.Get(Owner)->MakeCrewMember(this, true, false))
2412  return false;
2413  // Dead and gone (info flags, remove from crew/cursor)
2414  if (!Alive)
2415  {
2416  if (ValidPlr(Owner)) ::Players.Get(Owner)->ClearPointers(this, true);
2417  }
2418  return true;
2419  }
2420  return false;
2421 }
2422 
2424 {
2425  if (!lightRange && !lightFadeoutRange) return true;
2426 
2427  UpdateLight();
2428  return true;
2429 }
2430 
2432 {
2433  if (Info==pInfo)
2434  {
2435  Info=nullptr;
2436  }
2437 }
2438 
2440 {
2442 
2443  if (pEffects) { delete pEffects; pEffects=nullptr; }
2444  if (pSolidMaskData) { delete pSolidMaskData; pSolidMaskData=nullptr; }
2445  if (Menu) delete Menu; Menu=nullptr;
2446  if (MaterialContents) delete MaterialContents; MaterialContents=nullptr;
2447  // clear commands!
2448  C4Command *pCom, *pNext;
2449  for (pCom=Command; pCom; pCom=pNext)
2450  {
2451  pNext=pCom->Next; delete pCom; pCom=pNext;
2452  }
2453  if (pDrawTransform) { delete pDrawTransform; pDrawTransform=nullptr; }
2454  if (pGfxOverlay) { delete pGfxOverlay; pGfxOverlay=nullptr; }
2455  if (pMeshInstance) { delete pMeshInstance; pMeshInstance = nullptr; }
2456 }
2457 
2458 bool C4Object::MenuCommand(const char *szCommand)
2459 {
2460  // Native script execution
2461  if (!Def || !Status) return false;
2462  return !! ::AulExec.DirectExec(this, szCommand, "MenuCommand");
2463 }
2464 
2465 void C4Object::SetSolidMask(int32_t iX, int32_t iY, int32_t iWdt, int32_t iHgt, int32_t iTX, int32_t iTY)
2466 {
2467  // remove old
2468  if (pSolidMaskData) { delete pSolidMaskData; pSolidMaskData=nullptr; }
2469  // set new data
2470  SolidMask.Set(iX,iY,iWdt,iHgt,iTX,iTY);
2471  // re-put if valid
2472  if (CheckSolidMaskRect()) UpdateSolidMask(false);
2473 }
2474 
2476 {
2477  if (!pSolidMaskData) return;
2479 }
2480 
2482 {
2483  // Ensure SolidMask rect lies within bounds of SolidMask bitmap in definition
2484  CSurface8 *sfcGraphics = Def->pSolidMask;
2485  if (!sfcGraphics)
2486  {
2487  // no graphics to set solid in
2488  SolidMask.Set(0,0,0,0,0,0);
2489  return false;
2490  }
2491  SolidMask.Set(std::max<int32_t>(SolidMask.x,0), std::max<int32_t>(SolidMask.y,0),
2492  std::min<int32_t>(SolidMask.Wdt,sfcGraphics->Wdt-SolidMask.x), std::min<int32_t>(SolidMask.Hgt, sfcGraphics->Hgt-SolidMask.y),
2494  if (SolidMask.Hgt<=0) SolidMask.Wdt=0;
2495  return SolidMask.Wdt>0;
2496 }
2497 
2499 {
2500  // Misc. no-save safeties
2502  InMat = MNone;
2503  t_contact = 0;
2504  // Update OCF
2505  SetOCF();
2506  // Menu
2507  CloseMenu(true);
2508  // Material contents
2509  if (MaterialContents) delete MaterialContents; MaterialContents=nullptr;
2510  // reset speed of staticback-objects
2511  if (Category & C4D_StaticBack)
2512  {
2513  xdir = ydir = 0;
2514  }
2515 }
2516 
2518 {
2519  // Status
2520  if (!Status) return;
2521  // No select marks in film playback
2522  if (Game.C4S.Head.Film && Game.C4S.Head.Replay) return;
2523  // target pos (parallax)
2524  float offX, offY, newzoom;
2525  GetDrawPosition(cgo, offX, offY, newzoom);
2526  // Output boundary
2527  if (!Inside<float>(offX, cgo.X, cgo.X + cgo.Wdt)
2528  || !Inside<float>(offY, cgo.Y, cgo.Y + cgo.Hgt)) return;
2529  // Draw select marks
2530  float cox = offX + Shape.GetX() - cgo.X + cgo.X - 2;
2531  float coy = offY + Shape.GetY() - cgo.Y + cgo.Y - 2;
2532  GfxR->fctSelectMark.Draw(cgo.Surface,cox,coy,0);
2533  GfxR->fctSelectMark.Draw(cgo.Surface,cox+Shape.Wdt,coy,1);
2534  GfxR->fctSelectMark.Draw(cgo.Surface,cox,coy+Shape.Hgt,2);
2535  GfxR->fctSelectMark.Draw(cgo.Surface,cox+Shape.Wdt,coy+Shape.Hgt,3);
2536 }
2537 
2539 {
2540  C4Command *pNext;
2541  while (Command)
2542  {
2543  pNext=Command->Next;
2544  if (!Command->iExec)
2545  delete Command;
2546  else
2547  Command->iExec = 2;
2548  Command=pNext;
2549  }
2550 }
2551 
2553 {
2554  C4Command *pCom,*pNext;
2555  for (pCom=Command; pCom; pCom=pNext)
2556  {
2557  // Last one to clear
2558  if (pCom==pUntil) pNext=nullptr;
2559  // Next one to clear after this
2560  else pNext=pCom->Next;
2561  Command=pCom->Next;
2562  if (!pCom->iExec)
2563  delete pCom;
2564  else
2565  pCom->iExec = 2;
2566  }
2567 }
2568 
2569 bool C4Object::AddCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy,
2570  int32_t iUpdateInterval, C4Object *pTarget2,
2571  bool fInitEvaluation, C4Value iData, bool fAppend,
2572  int32_t iRetries, C4String *szText, int32_t iBaseMode)
2573 {
2574  // Command stack size safety
2575  const int32_t MaxCommandStack = 35;
2576  C4Command *pCom,*pLast; int32_t iCommands;
2577  for (pCom=Command,iCommands=0; pCom; pCom=pCom->Next,iCommands++) {}
2578  if (iCommands>=MaxCommandStack) return false;
2579  // Valid command safety
2580  if (!Inside(iCommand,C4CMD_First,C4CMD_Last)) return false;
2581  // Allocate and set new command
2582  if (!(pCom=new C4Command)) return false;
2583  pCom->Set(iCommand,this,pTarget,iTx,iTy,pTarget2,iData,
2584  iUpdateInterval,!fInitEvaluation,iRetries,szText,iBaseMode);
2585  // Append to bottom of stack
2586  if (fAppend)
2587  {
2588  for (pLast=Command; pLast && pLast->Next; pLast=pLast->Next) {}
2589  if (pLast) pLast->Next=pCom;
2590  else Command=pCom;
2591  }
2592  // Add to top of command stack
2593  else
2594  {
2595  pCom->Next=Command;
2596  Command=pCom;
2597  }
2598  // Success
2599  return true;
2600 }
2601 
2602 void C4Object::SetCommand(int32_t iCommand, C4Object *pTarget, C4Value iTx, int32_t iTy,
2603  C4Object *pTarget2, bool fControl, C4Value iData,
2604  int32_t iRetries, C4String *szText)
2605 {
2606  // Clear stack
2607  ClearCommands();
2608  // Close menu
2609  if (fControl)
2610  if (!CloseMenu(false)) return;
2611  // Script overload
2612  if (fControl)
2614  pTarget,
2615  iTx,
2616  iTy,
2617  pTarget2,
2618  iData)))
2619  return;
2620  // Inside vehicle control overload
2621  if (Contained)
2623  {
2626  pTarget,
2627  iTx,
2628  iTy,
2629  pTarget2,
2630  iData,
2631  this)))
2632  return;
2633  }
2634  // Outside vehicle control overload
2635  if (GetProcedure()==DFA_PUSH)
2637  {
2640  pTarget,
2641  iTx,
2642  iTy,
2643  pTarget2,
2644  iData)))
2645  return;
2646  }
2647  // Add new command
2648  AddCommand(iCommand,pTarget,iTx,iTy,0,pTarget2,true,iData,false,iRetries,szText,C4CMD_Mode_Base);
2649 }
2650 
2651 C4Command *C4Object::FindCommand(int32_t iCommandType) const
2652 {
2653  // seek all commands
2654  for (C4Command *pCom = Command; pCom; pCom=pCom->Next)
2655  if (pCom->Command == iCommandType) return pCom;
2656  // nothing found
2657  return nullptr;
2658 }
2659 
2661 {
2662  // Execute first command
2663  if (Command) Command->Execute();
2664  // Command finished: engine call
2665  if (Command && Command->Finished)
2667  // Clear finished commands
2669  // Done
2670  return true;
2671 }
2672 
2674 {
2675  // Flag resort
2676  Unsorted=true;
2677  Game.fResortAnyObject = true;
2678  // Must not immediately resort - link change/removal would crash Game::ExecObjects
2679 }
2680 
2682 {
2683  C4Value value;
2684  GetProperty(P_Action, &value);
2685  return value.getPropList();
2686 }
2687 
2688 bool C4Object::SetAction(C4PropList * Act, C4Object *pTarget, C4Object *pTarget2, int32_t iCalls, bool fForce)
2689 {
2690  C4Value vLastAction;
2691  GetProperty(P_Action, &vLastAction);
2692  C4PropList * LastAction = vLastAction.getPropList();
2693  int32_t iLastPhase=Action.Phase;
2694  C4Object *pLastTarget = Action.Target;
2695  C4Object *pLastTarget2 = Action.Target2;
2696  // No other action
2697  if (LastAction)
2698  if (LastAction->GetPropertyInt(P_NoOtherAction) && !fForce)
2699  if (Act != LastAction)
2700  return false;
2701  // Set animation on instance. Abort if the mesh does not have
2702  // such an animation.
2703  if (pMeshInstance)
2704  {
2706  Action.Animation = nullptr;
2707 
2708  C4String* Animation = Act ? Act->GetPropertyStr(P_Animation) : nullptr;
2709  if (Animation)
2710  {
2711  // note that weight is ignored
2712  Action.Animation = pMeshInstance->PlayAnimation(Animation->GetData(), 0, nullptr, new C4ValueProviderAction(this), new C4ValueProviderConst(itofix(1)), true);
2713  }
2714  }
2715  // Stop previous act sound
2716  if (LastAction)
2717  if (Act != LastAction)
2718  if (LastAction->GetPropertyStr(P_Sound))
2719  StopSoundEffect(LastAction->GetPropertyStr(P_Sound)->GetCStr(),this);
2720  // Unfullcon objects no action
2721  if (Con<FullCon)
2722  if (!Def->IncompleteActivity)
2723  Act = 0;
2724  // Reset action time on change
2725  if (Act!=LastAction)
2726  {
2727  Action.Time=0;
2728  // reset action data and targets if procedure is changed
2729  if ((Act ? Act->GetPropertyP(P_Procedure) : -1)
2730  != (LastAction ? LastAction->GetPropertyP(P_Procedure) : -1))
2731  {
2732  Action.Data = 0;
2733  Action.Target = nullptr;
2734  Action.Target2 = nullptr;
2735  }
2736  }
2737  // Set new action
2740  // Set target if specified
2741  if (pTarget) Action.Target=pTarget;
2742  if (pTarget2) Action.Target2=pTarget2;
2743  // Set Action Facet
2744  UpdateActionFace();
2745  // update flipdir
2746  if ((LastAction ? LastAction->GetPropertyInt(P_FlipDir) : 0)
2747  != (Act ? Act->GetPropertyInt(P_FlipDir) : 0)) UpdateFlipDir();
2748  // Start act sound
2749  if (Act)
2750  if (Act != LastAction)
2751  if (Act->GetPropertyStr(P_Sound))
2752  StartSoundEffect(Act->GetPropertyStr(P_Sound)->GetCStr(),+1,100,this);
2753  // Reset OCF
2754  SetOCF();
2755  // issue calls
2756  // Execute EndCall for last action
2757  if (iCalls & SAC_EndCall && !fForce)
2758  if (LastAction)
2759  {
2760  if (LastAction->GetPropertyStr(P_EndCall))
2761  {
2762  C4Def *pOldDef = Def;
2763  Call(LastAction->GetPropertyStr(P_EndCall)->GetCStr());
2764  // abort exeution if def changed
2765  if (Def != pOldDef || !Status) return true;
2766  }
2767  }
2768  // Execute AbortCall for last action
2769  if (iCalls & SAC_AbortCall && !fForce)
2770  if (LastAction)
2771  {
2772  if (LastAction->GetPropertyStr(P_AbortCall))
2773  {
2774  C4Def *pOldDef = Def;
2775  if (pLastTarget && !pLastTarget->Status) pLastTarget = nullptr;
2776  if (pLastTarget2 && !pLastTarget2->Status) pLastTarget2 = nullptr;
2777  Call(LastAction->GetPropertyStr(P_AbortCall)->GetCStr(), &C4AulParSet(iLastPhase, pLastTarget, pLastTarget2));
2778  // abort exeution if def changed
2779  if (Def != pOldDef || !Status) return true;
2780  }
2781  }
2782  // Execute StartCall for new action
2783  if (iCalls & SAC_StartCall)
2784  if (Act)
2785  {
2786  if (Act->GetPropertyStr(P_StartCall))
2787  {
2788  C4Def *pOldDef = Def;
2790  // abort exeution if def changed
2791  if (Def != pOldDef || !Status) return true;
2792  }
2793  }
2794 
2795  C4Def *pOldDef = Def;
2796  Call(PSF_OnActionChanged, &C4AulParSet(LastAction ? LastAction->GetName() : "Idle"));
2797  if (Def != pOldDef || !Status) return true;
2798 
2799  return true;
2800 }
2801 
2803 {
2804  // Default: no action face
2805  Action.Facet.Default();
2806  // Active: get action facet from action definition
2807  C4PropList* pActionDef = GetAction();
2808  if (pActionDef)
2809  {
2810  if (pActionDef->GetPropertyInt(P_Wdt)>0)
2811  {
2812  Action.Facet.Set(GetGraphics()->GetBitmap(Color),
2813  pActionDef->GetPropertyInt(P_X),pActionDef->GetPropertyInt(P_Y),
2814  pActionDef->GetPropertyInt(P_Wdt),pActionDef->GetPropertyInt(P_Hgt));
2815  Action.FacetX=pActionDef->GetPropertyInt(P_OffX);
2816  Action.FacetY=pActionDef->GetPropertyInt(P_OffY);
2817  }
2818  }
2819 }
2820 
2822  C4Object *pTarget, C4Object *pTarget2,
2823  int32_t iCalls, bool fForce)
2824 {
2825  assert(ActName);
2826  // If we get the null string or ActIdle by name, set ActIdle
2827  if (!ActName || ActName == &Strings.P[P_Idle])
2828  return SetAction(0,0,0,iCalls,fForce);
2829  C4Value ActMap; GetProperty(P_ActMap, &ActMap);
2830  if (!ActMap.getPropList()) return false;
2831  C4Value Action; ActMap.getPropList()->GetPropertyByS(ActName, &Action);
2832  if (!Action.getPropList()) return false;
2833  return SetAction(Action.getPropList(),pTarget,pTarget2,iCalls,fForce);
2834 }
2835 
2836 bool C4Object::SetActionByName(const char * szActName,
2837  C4Object *pTarget, C4Object *pTarget2,
2838  int32_t iCalls, bool fForce)
2839 {
2840  C4String * ActName = Strings.RegString(szActName);
2841  ActName->IncRef();
2842  bool r = SetActionByName(ActName, pTarget, pTarget2, iCalls, fForce);
2843  ActName->DecRef();
2844  return r;
2845 }
2846 
2847 void C4Object::SetDir(int32_t iDir)
2848 {
2849  // Not active
2850  C4PropList* pActionDef = GetAction();
2851  if (!pActionDef) return;
2852  // Invalid direction
2853  if (!Inside<int32_t>(iDir,0,pActionDef->GetPropertyInt(P_Directions)-1)) return;
2854  // Execute turn action
2855  if (iDir != Action.Dir)
2856  if (pActionDef->GetPropertyStr(P_TurnAction))
2857  { SetActionByName(pActionDef->GetPropertyStr(P_TurnAction)); }
2858  // Set dir
2859  Action.Dir=iDir;
2860  // update by flipdir?
2861  if (pActionDef->GetPropertyInt(P_FlipDir))
2862  UpdateFlipDir();
2863  else
2864  Action.DrawDir=iDir;
2865 }
2866 
2867 int32_t C4Object::GetProcedure() const
2868 {
2869  C4PropList* pActionDef = GetAction();
2870  if (!pActionDef) return -1;
2871  return pActionDef->GetPropertyP(P_Procedure);
2872 }
2873 
2874 void GrabLost(C4Object *cObj, C4Object *prev_target)
2875 {
2876  // Grab lost script call on target (quite hacky stuff...)
2877  if (prev_target && prev_target->Status) prev_target->Call(PSF_GrabLost);
2878  // Clear commands down to first PushTo (if any) in command stack
2879  for (C4Command *pCom=cObj->Command; pCom; pCom=pCom->Next)
2880  if (pCom->Next && pCom->Next->Command==C4CMD_PushTo)
2881  {
2882  cObj->ClearCommand(pCom);
2883  break;
2884  }
2885 }
2886 
2887 static void DoGravity(C4Object *cobj);
2888 
2890 {
2891  // Active objects
2892  if (GetAction())
2893  {
2894  int32_t iProcedure = GetProcedure();
2895  C4Object *prev_target = Action.Target;
2896  // Scaling upwards: corner scale
2897  if (iProcedure == DFA_SCALE && Action.ComDir != COMD_Stop && ComDirLike(Action.ComDir, COMD_Up))
2898  if (ObjectActionCornerScale(this)) return;
2899  if (iProcedure == DFA_SCALE && Action.ComDir == COMD_Left && Action.Dir == DIR_Left)
2900  if (ObjectActionCornerScale(this)) return;
2901  if (iProcedure == DFA_SCALE && Action.ComDir == COMD_Right && Action.Dir == DIR_Right)
2902  if (ObjectActionCornerScale(this)) return;
2903  // Scaling and stopped: fall off to side (avoid zuppel)
2904  if ((iProcedure == DFA_SCALE) && (Action.ComDir == COMD_Stop))
2905  {
2906  if (Action.Dir == DIR_Left)
2907  { if (ObjectActionJump(this,itofix(1),Fix0,false)) return; }
2908  else
2909  { if (ObjectActionJump(this,itofix(-1),Fix0,false)) return; }
2910  }
2911  // Pushing: grab loss
2912  if (iProcedure==DFA_PUSH) GrabLost(this, prev_target);
2913  // Else jump
2914  ObjectActionJump(this,xdir,ydir,false);
2915  }
2916  // Inactive objects, simple mobile natural gravity
2917  else
2918  {
2919  DoGravity(this);
2920  Mobile=1;
2921  }
2922 }
2923 
2925 {
2926  // Take certain action on contact. Evaluate t_contact-CNAT and Procedure.
2927 
2928  // Determine Procedure
2929  C4PropList* pActionDef = GetAction();
2930  if (!pActionDef) return;
2931  int32_t iProcedure=pActionDef->GetPropertyP(P_Procedure);
2932  int32_t fDisabled=pActionDef->GetPropertyInt(P_ObjectDisabled);
2933 
2934  //------------------------------- Hit Bottom ---------------------------------------------
2935  if (t_contact & CNAT_Bottom)
2936  switch (iProcedure)
2937  {
2938  case DFA_FLIGHT:
2939  if (ydir < 0) return;
2940  // Jump: FlatHit / HardHit / Walk
2941  if ((OCF & OCF_HitSpeed4) || fDisabled)
2942  if (ObjectActionFlat(this,Action.Dir)) return;
2943  if (OCF & OCF_HitSpeed3)
2944  if (ObjectActionKneel(this)) return;
2945  ObjectActionWalk(this);
2946  ydir = 0;
2947  return;
2948  case DFA_SCALE:
2949  // Scale down: stand
2951  {
2952  ObjectActionStand(this);
2953  return;
2954  }
2955  break;
2956  case DFA_DIG:
2957  // no special action
2958  break;
2959  case DFA_SWIM:
2960  // Try corner scale out
2961  if (!GBackSemiSolid(GetX(),GetY()-1+Def->Float*Con/FullCon-1))
2962  if (ObjectActionCornerScale(this)) return;
2963  break;
2964  }
2965 
2966  //------------------------------- Hit Ceiling -----------------------------------------
2967  if (t_contact & CNAT_Top)
2968  switch (iProcedure)
2969  {
2970  case DFA_WALK:
2971  // Walk: Stop
2972  ObjectActionStand(this); return;
2973  case DFA_SCALE:
2974  // Scale: Try hangle, else stop if going upward
2976  {
2977  if (ObjectActionHangle(this))
2978  {
2980  return;
2981  }
2983  }
2984  break;
2985  case DFA_FLIGHT:
2986  // Jump: Try hangle, else bounce off
2987  // High Speed Flight: Tumble
2988  if ((OCF & OCF_HitSpeed3) || fDisabled)
2989  { ObjectActionTumble(this, Action.Dir, xdir, ydir); break; }
2990  if (ObjectActionHangle(this)) return;
2991  break;
2992  case DFA_DIG:
2993  // No action
2994  break;
2995  case DFA_HANGLE:
2997  break;
2998  }
2999 
3000  //---------------------------- Hit Left Wall ----------------------------------------
3001  if (t_contact & CNAT_Left)
3002  {
3003  switch (iProcedure)
3004  {
3005  case DFA_FLIGHT:
3006  // High Speed Flight: Tumble
3007  if ((OCF & OCF_HitSpeed3) || fDisabled)
3008  { ObjectActionTumble(this, DIR_Left, xdir, ydir); break; }
3009  // Else
3010  else if (!ComDirLike(Action.ComDir, COMD_Right) && ObjectActionScale(this,DIR_Left)) return;
3011  break;
3012  case DFA_WALK:
3013  // Walk: Try scale
3015  {
3016  if (ObjectActionScale(this,DIR_Left))
3017  {
3018  ydir = C4REAL100(-1);
3019  return;
3020  }
3021  }
3022  // Heading away from solid
3024  {
3025  // Slide off
3026  ObjectActionJump(this,xdir/2,ydir,false);
3027  }
3028  return;
3029  case DFA_SWIM:
3030  // Only scale if swimming at the surface
3031  if (!GBackSemiSolid(GetX(),GetY()-1+Def->Float*Con/FullCon-1))
3032  {
3033  // Try scale, only if swimming at the surface.
3035  if (ObjectActionScale(this,DIR_Left)) return;
3036  // Try corner scale out
3037  if (ObjectActionCornerScale(this)) return;
3038  }
3039  return;
3040  case DFA_HANGLE:
3041  // Hangle: Try scale
3042  if (ObjectActionScale(this,DIR_Left))
3043  {
3044  ydir = C4REAL100(1);
3045  return;
3046  }
3047  return;
3048  case DFA_DIG:
3049  // Dig: no action
3050  break;
3051  }
3052  }
3053 
3054  //------------------------------ Hit Right Wall --------------------------------------
3055  if (t_contact & CNAT_Right)
3056  {
3057  switch (iProcedure)
3058  {
3059  case DFA_FLIGHT:
3060  // High Speed Flight: Tumble
3061  if ((OCF & OCF_HitSpeed3) || fDisabled)
3062  { ObjectActionTumble(this, DIR_Right, xdir, ydir); break; }
3063  // Else Scale
3064  else if (!ComDirLike(Action.ComDir, COMD_Left) && ObjectActionScale(this,DIR_Right)) return;
3065  break;
3066  case DFA_WALK:
3067  // Walk: Try scale
3069  {
3070  if (ObjectActionScale(this,DIR_Right))
3071  {
3072  ydir = C4REAL100(-1);
3073  return;
3074  }
3075  }
3076  // Heading away from solid
3078  {
3079  // Slide off
3080  ObjectActionJump(this,xdir/2,ydir,false);
3081  }
3082  return;
3083  case DFA_SWIM:
3084  // Only scale if swimming at the surface
3085  if (!GBackSemiSolid(GetX(),GetY()-1+Def->Float*Con/FullCon-1))
3086  {
3087  // Try scale
3089  if (ObjectActionScale(this,DIR_Right)) return;
3090  // Try corner scale out
3091  if (ObjectActionCornerScale(this)) return;
3092  }
3093  return;
3094  case DFA_HANGLE:
3095  // Hangle: Try scale
3096  if (ObjectActionScale(this,DIR_Right))
3097  {
3098  ydir = C4REAL100(1);
3099  return;
3100  }
3101  return;
3102  case DFA_DIG:
3103  // Dig: no action
3104  break;
3105  }
3106  }
3107 
3108  //---------------------------- Unresolved Cases ---------------------------------------
3109 
3110  // Flight stuck
3111  if (iProcedure==DFA_FLIGHT)
3112  {
3113  // Enforce slide free (might slide through tiny holes this way)
3114  if (!ydir)
3115  {
3116  int fAllowDown = !(t_contact & CNAT_Bottom);
3117  if (t_contact & CNAT_Right)
3118  {
3119  ForcePosition(fix_x - 1, fix_y + fAllowDown);
3120  xdir=ydir=0;
3121  }
3122  if (t_contact & CNAT_Left)
3123  {
3124  ForcePosition(fix_x + 1, fix_y + fAllowDown);
3125  xdir=ydir=0;
3126  }
3127  }
3128  if (!xdir)
3129  {
3130  if (t_contact & CNAT_Top)
3131  {
3132  ForcePosition(fix_x, fix_y + 1);
3133  xdir=ydir=0;
3134  }
3135  }
3136  }
3137 }
3138 
3139 void Towards(C4Real &val, C4Real target, C4Real step)
3140 {
3141  if (val==target) return;
3142  if (Abs(val-target)<=step) { val=target; return; }
3143  if (val<target) val+=step; else val-=step;
3144 }
3145 
3146 bool DoBridge(C4Object *clk)
3147 {
3148  int32_t iBridgeTime; bool fMoveClonk, fWall; int32_t iBridgeMaterial;
3149  clk->Action.GetBridgeData(iBridgeTime, fMoveClonk, fWall, iBridgeMaterial);
3150  if (!iBridgeTime) iBridgeTime = 100; // default bridge time
3151  if (clk->Action.Time>=iBridgeTime) { ObjectActionStand(clk); return false; }
3152  // get bridge advancement
3153  int32_t dtp;
3154  if (fWall) switch (clk->Action.ComDir)
3155  {
3156  case COMD_Left: case COMD_Right: dtp = 4; fMoveClonk = false; break; // vertical wall: default 25 pixels
3157  case COMD_UpLeft: case COMD_UpRight: dtp = 5; fMoveClonk = false; break; // diagonal roof over Clonk: default 20 pixels up and 20 pixels side (28 pixels - optimized to close tunnels completely)
3158  case COMD_Up: dtp = 5; break; // horizontal roof over Clonk
3159  default: return true; // bridge procedure just for show
3160  }
3161  else switch (clk->Action.ComDir)
3162  {
3163  case COMD_Left: case COMD_Right: dtp = 5; break; // horizontal bridges: default 20 pixels
3164  case COMD_Up: dtp = 4; break; // vertical bridges: default 25 pixels (same as
3165  case COMD_UpLeft: case COMD_UpRight: dtp = 6; break; // diagonal bridges: default 16 pixels up and 16 pixels side (23 pixels)
3166  default: return true; // bridge procedure just for show
3167  }
3168  if (clk->Action.Time % dtp) return true; // no advancement in this frame
3169  // get target pos for Clonk and bridge
3170  int32_t cx=clk->GetX(), cy=clk->GetY(), cw=clk->Shape.Wdt, ch=clk->Shape.Hgt;
3171  int32_t tx=cx,ty=cy+ch/2;
3172  int32_t dt;
3173  if (fMoveClonk) dt = 0; else dt = clk->Action.Time / dtp;
3174  if (fWall) switch (clk->Action.ComDir)
3175  {
3176  case COMD_Left: tx-=cw/2; ty+=-dt; break;
3177  case COMD_Right: tx+=cw/2; ty+=-dt; break;
3178  case COMD_Up:
3179  {
3180  int32_t x0;
3181  if (fMoveClonk) x0=-3; else x0=(iBridgeTime/dtp)/-2;
3182  tx+=(x0+dt)*((clk->Action.Dir==DIR_Right)*2-1); cx+=((clk->Action.Dir==DIR_Right)*2-1); ty-=ch+3; break;
3183  }
3184  case COMD_UpLeft: tx-=-4+dt; ty+=-ch-7+dt; break;
3185  case COMD_UpRight: tx+=-4+dt; ty+=-ch-7+dt; break;
3186  }
3187  else switch (clk->Action.ComDir)
3188  {
3189  case COMD_Left: tx+=-3-dt; --cx; break;
3190  case COMD_Right: tx+=+2+dt; ++cx; break;
3191  case COMD_Up: tx+=(-cw/2+(cw-1)*(clk->Action.Dir==DIR_Right))*(!fMoveClonk); ty+=-dt-fMoveClonk; --cy; break;
3192  case COMD_UpLeft: tx+=-5-dt+fMoveClonk*3; ty+=2-dt-fMoveClonk*3; --cx; --cy; break;
3193  case COMD_UpRight: tx+=+5+dt-fMoveClonk*2; ty+=2-dt-fMoveClonk*3; ++cx; --cy; break;
3194  }
3195  // check if Clonk movement is posible
3196  if (fMoveClonk)
3197  {
3198  int32_t cx2=cx, cy2=cy;
3199  if ( clk->Shape.CheckContact(cx2, cy2-1))
3200  {
3201  // Clonk would collide here: Change to nonmoving Clonk mode and redo bridging
3202  iBridgeTime -= clk->Action.Time;
3203  clk->Action.Time = 0;
3204  if (fWall && clk->Action.ComDir==COMD_Up)
3205  {
3206  // special for roof above Clonk: The nonmoving roof is started at bridgelength before the Clonk
3207  // so, when interrupted, an action time halfway through the action must be set
3208  clk->Action.Time = iBridgeTime;
3209  iBridgeTime += iBridgeTime;
3210  }
3211  clk->Action.SetBridgeData(iBridgeTime, false, fWall, iBridgeMaterial);
3212  return DoBridge(clk);
3213  }
3214  }
3215  // draw bridge into landscape
3216  ::Landscape.DrawMaterialRect(iBridgeMaterial,tx-2,ty,4,3);
3217  // Move Clonk
3218  if (fMoveClonk) clk->MovePosition(cx-clk->GetX(), cy-clk->GetY());
3219  return true;
3220 }
3221 
3222 static void DoGravity(C4Object *cobj)
3223 {
3224  // Floatation in liquids
3225  if (cobj->InLiquid && cobj->Def->Float)
3226  {
3227  cobj->ydir-=GravAccel * C4REAL100(80);
3228  if (cobj->ydir<C4REAL100(-160)) cobj->ydir=C4REAL100(-160);
3229  if (cobj->xdir<-FloatFriction) cobj->xdir+=FloatFriction;
3230  if (cobj->xdir>+FloatFriction) cobj->xdir-=FloatFriction;
3231  if (cobj->rdir<-FloatFriction) cobj->rdir+=FloatFriction;
3232  if (cobj->rdir>+FloatFriction) cobj->rdir-=FloatFriction;
3233  // Reduce upwards speed when about to leave liquid to prevent eternal moving up and down.
3234  // Check both for no liquid one and two pixels above the surface, because the object could
3235  // skip one pixel as its speed can be more than 100.
3236  int32_t y_float = cobj->GetY() - 1 + cobj->Def->Float * cobj->GetCon() / FullCon;
3237  if (!GBackLiquid(cobj->GetX(), y_float - 1) || !GBackLiquid(cobj->GetX(), y_float - 2))
3238  if (cobj->ydir < 0)
3239  {
3240  // Reduce the upwards speed and set to zero for small values to prevent fluctuations.
3241  cobj->ydir /= 2;
3242  if (Abs(cobj->ydir) < C4REAL100(10))
3243  cobj->ydir = 0;
3244  }
3245  }
3246  // Free fall gravity
3247  else if (~cobj->Category & C4D_StaticBack)
3248  cobj->ydir+=GravAccel;
3249 }
3250 
3252 {
3253  ObjectComStop(cobj);
3254  cobj->AddCommand(C4CMD_Wait,nullptr,0,0,50);
3255 }
3256 
3257 bool ReduceLineSegments(C4Shape &rShape, bool fAlternate)
3258 {
3259  // try if line could go by a path directly when skipping on evertex. If fAlternate is true, try by skipping two vertices
3260  for (int32_t cnt=0; cnt+2+fAlternate<rShape.VtxNum; cnt++)
3261  if (PathFree(rShape.VtxX[cnt],rShape.VtxY[cnt],
3262  rShape.VtxX[cnt+2+fAlternate],rShape.VtxY[cnt+2+fAlternate]))
3263  {
3264  if (fAlternate) rShape.RemoveVertex(cnt+2);
3265  rShape.RemoveVertex(cnt+1);
3266  return true;
3267  }
3268  return false;
3269 }
3270 
3272 {
3273  C4Real iTXDir;
3274  C4Real lftspeed,tydir;
3275  int32_t iTargetX;
3276  int32_t iPushRange,iPushDistance;
3277 
3278  // Standard phase advance
3279  int32_t iPhaseAdvance=1;
3280 
3281  // Upright attachment check
3282  if (!Mobile)
3283  if (Def->UprightAttach)
3284  if (Inside<int32_t>(GetR(),-StableRange,+StableRange))
3285  {
3287  Mobile=1;
3288  }
3289 
3290  C4PropList* pActionDef = GetAction();
3291  // No IncompleteActivity? Reset action if there was one
3292  if (!(OCF & OCF_FullCon) && !Def->IncompleteActivity && pActionDef)
3293  {
3294  SetAction(0);
3295  pActionDef = 0;
3296  }
3297 
3298  // InLiquidAction check
3299  if (InLiquid)
3300  if (pActionDef && pActionDef->GetPropertyStr(P_InLiquidAction))
3301  {
3303  pActionDef = GetAction();
3304  }
3305 
3306  // Idle objects do natural gravity only
3307  if (!pActionDef)
3308  {
3310  if (Mobile) DoGravity(this);
3311  return;
3312  }
3313 
3314  C4Real fWalk,fMove;
3315 
3316  // Action time advance
3317  Action.Time++;
3318 
3319  C4Value Attach;
3320  pActionDef->GetProperty(P_Attach, &Attach);
3321  if (Attach.GetType() != C4V_Nil)
3322  {
3323  Action.t_attach = Attach.getInt();
3324  }
3325  else switch (pActionDef->GetPropertyP(P_Procedure))
3326  {
3327  case DFA_SCALE:
3330  break;
3331  case DFA_HANGLE:
3333  break;
3334  case DFA_WALK:
3335  case DFA_KNEEL:
3336  case DFA_THROW:
3337  case DFA_BRIDGE:
3338  case DFA_PUSH:
3339  case DFA_PULL:
3340  case DFA_DIG:
3342  break;
3343  default:
3345  }
3346 
3347  // if an object is in controllable state, so it can be assumed that if it dies later because of NO_OWNER's cause,
3348  // it has been its own fault and not the fault of the last one who threw a flint on it
3349  // do not reset for burning objects to make sure the killer is set correctly if they fall out of the map while burning
3350  if (!pActionDef->GetPropertyInt(P_ObjectDisabled) && pActionDef->GetPropertyP(P_Procedure) != DFA_FLIGHT && !OnFire)
3352 
3353  // Handle Default Action Procedure: evaluates Procedure and Action.ComDir
3354  // Update xdir,ydir,Action.Dir,attachment,iPhaseAdvance
3355  int32_t dir = Action.Dir;
3356  C4Real accel = C4REAL100(pActionDef->GetPropertyInt(P_Accel));
3357  C4Real decel = accel;
3358  {
3359  C4Value decel_val;
3360  pActionDef->GetProperty(P_Decel, &decel_val);
3361  if (decel_val.GetType() != C4V_Nil)
3362  decel = C4REAL100(decel_val.getInt());
3363  }
3364  C4Real limit = C4REAL100(pActionDef->GetPropertyInt(P_Speed));
3365 
3366  switch (pActionDef->GetPropertyP(P_Procedure))
3367  {
3368  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3369  case DFA_WALK:
3370  switch (Action.ComDir)
3371  {
3372  case COMD_Left: case COMD_UpLeft: case COMD_DownLeft:
3373  // breaaak!!!
3374  if (dir == DIR_Right)
3375  xdir-=decel;
3376  else
3377  xdir-=accel;
3378  if (xdir<-limit) xdir=-limit;
3379  break;
3380  case COMD_Right: case COMD_UpRight: case COMD_DownRight:
3381  if (dir == DIR_Left)
3382  xdir+=decel;
3383  else
3384  xdir+=accel;
3385  if (xdir>+limit) xdir=+limit;
3386  break;
3387  case COMD_Stop: case COMD_Up: case COMD_Down:
3388  if (xdir<0) xdir+=decel;
3389  if (xdir>0) xdir-=decel;
3390  if ((xdir>-decel) && (xdir<+decel)) xdir=0;
3391  break;
3392  }
3393  iPhaseAdvance=0;
3394  if (xdir<0)
3395  {
3396  if (dir != DIR_Left) { SetDir(DIR_Left); xdir = -1; }
3397  iPhaseAdvance=-fixtoi(xdir*10);
3398  }
3399  if (xdir>0)
3400  {
3401  if (dir != DIR_Right) { SetDir(DIR_Right); xdir = 1; }
3402  iPhaseAdvance=+fixtoi(xdir*10);
3403  }
3404 
3405  Mobile=1;
3406  // object is rotateable? adjust to ground, if in horizontal movement or not attached to the center vertex
3407  if (Def->Rotateable && Shape.AttachMat != MNone && (!!xdir || Def->Shape.VtxX[Shape.iAttachVtx]))
3408  AdjustWalkRotation(20, 20, 100);
3409  else
3410  rdir=0;
3411  break;
3412  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3413  case DFA_KNEEL:
3414  ydir=0;
3415  Mobile=1;
3416  break;
3417  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3418  case DFA_SCALE:
3419  {
3420  int ComDir = Action.ComDir;
3421  if (Shape.CheckScaleToWalk(GetX(), GetY()))
3422  {
3423  ObjectActionWalk(this);
3424  return;
3425  }
3426  if ((Action.Dir == DIR_Left && ComDir == COMD_Left) || (Action.Dir == DIR_Right && ComDir == COMD_Right))
3427  {
3428  ComDir = COMD_Up;
3429  }
3430  switch (ComDir)
3431  {
3432  case COMD_Up: case COMD_UpRight: case COMD_UpLeft:
3433  if (ydir > 0) ydir -= decel;
3434  else ydir -= accel;
3435  if (ydir < -limit) ydir = -limit; break;
3436  case COMD_Down: case COMD_DownRight: case COMD_DownLeft:
3437  if (ydir < 0) ydir += decel;
3438  else ydir += accel;
3439  if (ydir > +limit) ydir = +limit; break;
3440  case COMD_Left: case COMD_Right: case COMD_Stop:
3441  if (ydir < 0) ydir += decel;
3442  if (ydir > 0) ydir -= decel;
3443  if ((ydir > -decel) && (ydir < +decel)) ydir = 0;
3444  break;
3445  }
3446  iPhaseAdvance=0;
3447  if (ydir<0) iPhaseAdvance=-fixtoi(ydir*14);
3448  if (ydir>0) iPhaseAdvance=+fixtoi(ydir*14);
3449  xdir=0;
3450  Mobile=1;
3451  break;
3452  }
3453  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3454  case DFA_HANGLE:
3455  switch (Action.ComDir)
3456  {
3457  case COMD_Left: case COMD_UpLeft: case COMD_DownLeft:
3458  if (xdir > 0) xdir -= decel;
3459  else xdir -= accel;
3460  if (xdir < -limit) xdir = -limit;
3461  break;
3462  case COMD_Right: case COMD_UpRight: case COMD_DownRight:
3463  if (xdir < 0) xdir += decel;
3464  else xdir += accel;
3465  if (xdir > +limit) xdir = +limit;
3466  break;
3467  case COMD_Up:
3468  if (Action.Dir == DIR_Left)
3469  if (xdir > 0) xdir -= decel;
3470  else xdir -= accel;
3471  else
3472  if (xdir < 0) xdir += decel;
3473  else xdir += accel;
3474  if (xdir < -limit) xdir = -limit;
3475  if (xdir > +limit) xdir = +limit;
3476  break;
3477  case COMD_Stop: case COMD_Down:
3478  if (xdir < 0) xdir += decel;
3479  if (xdir > 0) xdir -= decel;
3480  if ((xdir > -decel) && (xdir < +decel)) xdir = 0;
3481  break;
3482  }
3483  iPhaseAdvance=0;
3484  if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); }
3485  if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); }
3486  ydir=0;
3487  Mobile=1;
3488  break;
3489  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3490  case DFA_FLIGHT:
3491  // Contained: fall out (one try only)
3492  if (!::Game.iTick10)
3493  if (Contained)
3494  {
3495  StopActionDelayCommand(this);
3497  }
3498 
3499  switch (Action.ComDir)
3500  {
3501  case COMD_Left: case COMD_UpLeft: case COMD_DownLeft:
3502  xdir -= std::max(std::min(limit + xdir, xdir > 0 ? decel : accel), itofix(0));
3503  break;
3504  case COMD_Right: case COMD_UpRight: case COMD_DownRight:
3505  xdir += std::max(std::min(limit - xdir, xdir < 0 ? decel : accel), itofix(0));
3506  break;
3507  }
3508 
3509  // Gravity/mobile
3510  DoGravity(this);
3511  Mobile=1;
3512  break;
3513  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3514  case DFA_DIG:
3515  {
3516  int32_t smpx = GetX(), smpy = GetY();
3517  bool fAttachOK = false;
3518  if (Action.t_attach & CNAT_Bottom && Shape.Attach(smpx,smpy,CNAT_Bottom)) fAttachOK = true;
3519  else if (Action.t_attach & CNAT_Left && Shape.Attach(smpx,smpy,CNAT_Left)) { fAttachOK = true; }
3520  else if (Action.t_attach & CNAT_Right && Shape.Attach(smpx,smpy,CNAT_Right)) { fAttachOK = true; }
3521  else if (Action.t_attach & CNAT_Top && Shape.Attach(smpx,smpy,CNAT_Top)) fAttachOK = true;
3522  if (!fAttachOK)
3523  { ObjectComStopDig(this); return; }
3524  iPhaseAdvance=fixtoi(itofix(40)*limit);
3525 
3526  if (xdir < 0) SetDir(DIR_Left); else if (xdir > 0) SetDir(DIR_Right);
3528  Mobile=1;
3529  break;
3530  }
3531  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3532  case DFA_SWIM:
3533  // ComDir changes xdir/ydir
3534  switch (Action.ComDir)
3535  {
3536  case COMD_Up: ydir-=accel; break;
3537  case COMD_UpRight: ydir-=accel; xdir+=accel; break;
3538  case COMD_Right: xdir+=accel; break;
3539  case COMD_DownRight:ydir+=accel; xdir+=accel; break;
3540  case COMD_Down: ydir+=accel; break;
3541  case COMD_DownLeft: ydir+=accel; xdir-=accel; break;
3542  case COMD_Left: xdir-=accel; break;
3543  case COMD_UpLeft: ydir-=accel; xdir-=accel; break;
3544  case COMD_Stop:
3545  if (xdir<0) xdir+=decel;
3546  if (xdir>0) xdir-=decel;
3547  if ((xdir>-decel) && (xdir<+decel)) xdir=0;
3548  if (ydir<0) ydir+=decel;
3549  if (ydir>0) ydir-=decel;
3550  if ((ydir>-decel) && (ydir<+decel)) ydir=0;
3551  break;
3552  }
3553 
3554  // Out of liquid check
3555  if (!InLiquid)
3556  {
3557  // Just above liquid: move down
3558  if (GBackLiquid(GetX(),GetY()+1+Def->Float*Con/FullCon-1)) ydir=+accel;
3559  // Free fall: walk
3560  else { ObjectActionWalk(this); return; }
3561  }
3562 
3563  // xdir/ydir bounds, don't apply if COMD_None
3564  if (Action.ComDir != COMD_None)
3565  {
3566  if (ydir<-limit) ydir=-limit; if (ydir>+limit) ydir=+limit;
3567  if (xdir>+limit) xdir=+limit; if (xdir<-limit) xdir=-limit;
3568  }
3569  // Surface dir bound
3570  if (!GBackLiquid(GetX(),GetY()-1+Def->Float*Con/FullCon-1)) if (ydir<0) ydir=0;
3571  // Dir, Phase, Attach
3572  if (xdir<0) SetDir(DIR_Left);
3573  if (xdir>0) SetDir(DIR_Right);
3574  iPhaseAdvance=fixtoi(limit*10);
3575  Mobile=1;
3576 
3577  break;
3578  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3579  case DFA_THROW:
3580  Mobile=1;
3581  break;
3582  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3583  case DFA_BRIDGE:
3584  {
3585  if (!DoBridge(this)) return;
3586  switch (Action.ComDir)
3587  {
3588  case COMD_Left: case COMD_UpLeft: SetDir(DIR_Left); break;
3589  case COMD_Right: case COMD_UpRight: SetDir(DIR_Right); break;
3590  }
3591  ydir=0; xdir=0;
3592  Mobile=1;
3593  }
3594  break;
3595  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3596  case DFA_PUSH:
3597  // No target
3598  if (!Action.Target) { StopActionDelayCommand(this); return; }
3599  // Inside target
3600  if (Contained==Action.Target) { StopActionDelayCommand(this); return; }
3601  // Target pushing force
3602  bool fStraighten;
3603  iTXDir=0; fStraighten=false;
3604  switch (Action.ComDir)
3605  {
3606  case COMD_Left: case COMD_DownLeft: iTXDir=-limit; break;
3607  case COMD_UpLeft: fStraighten=1; iTXDir=-limit; break;
3608  case COMD_Right: case COMD_DownRight: iTXDir=+limit; break;
3609  case COMD_UpRight: fStraighten=1; iTXDir=+limit; break;
3610  case COMD_Up: fStraighten=1; break;
3611  case COMD_Stop: case COMD_Down: iTXDir=0; break;
3612  }
3613  // Push object
3614  if (!Action.Target->Push(iTXDir,accel,fStraighten))
3615  { StopActionDelayCommand(this); return; }
3616  // Set target controller
3618  // ObjectAction got hold check
3619  iPushDistance = std::max(Shape.Wdt/2-8,0);
3620  iPushRange = iPushDistance + 10;
3621  int32_t sax,say,sawdt,sahgt;
3622  Action.Target->GetArea(sax,say,sawdt,sahgt);
3623  // Object lost
3624  if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange)
3625  || !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange))
3626  {
3627  C4Object *prev_target = Action.Target;
3628  // Wait command (why, anyway?)
3629  StopActionDelayCommand(this);
3630  // Grab lost action
3631  GrabLost(this, prev_target);
3632  // Done
3633  return;
3634  }
3635  // Follow object (full xdir reset)
3636  // Vertical follow: If object moves out at top, assume it's being pushed upwards and the Clonk must run after it
3637  if (GetY()-iPushDistance > say+sahgt && iTXDir) { if (iTXDir>0) sax+=sawdt/2; sawdt/=2; }
3638  // Horizontal follow
3639  iTargetX=Clamp(GetX(),sax-iPushDistance,sax+sawdt-1+iPushDistance);
3640  if (GetX()==iTargetX) xdir=0;
3641  else { if (GetX()<iTargetX) xdir=+limit; if (GetX()>iTargetX) xdir=-limit; }
3642  // Phase by XDir
3643  if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); }
3644  if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); }
3645  // No YDir
3646  ydir=0;
3647  Mobile=1;
3648  break;
3649  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3650  case DFA_PULL:
3651  // No target
3652  if (!Action.Target) { StopActionDelayCommand(this); return; }
3653  // Inside target
3654  if (Contained==Action.Target) { StopActionDelayCommand(this); return; }
3655  // Target contained
3656  if (Action.Target->Contained) { StopActionDelayCommand(this); return; }
3657 
3658  int32_t iPullDistance;
3659  int32_t iPullX;
3660 
3661  iPullDistance = Action.Target->Shape.Wdt/2 + Shape.Wdt/2;
3662 
3663  iTargetX=GetX();
3664  if (Action.ComDir==COMD_Right) iTargetX = Action.Target->GetX()+iPullDistance;
3665  if (Action.ComDir==COMD_Left) iTargetX = Action.Target->GetX()-iPullDistance;
3666 
3667  iPullX=Action.Target->GetX();
3668  if (Action.ComDir==COMD_Right) iPullX = GetX()-iPullDistance;
3669  if (Action.ComDir==COMD_Left) iPullX = GetX()+iPullDistance;
3670 
3671  fWalk = limit;
3672 
3673  fMove = 0;
3674  if (Action.ComDir==COMD_Right) fMove = +fWalk;
3675  if (Action.ComDir==COMD_Left) fMove = -fWalk;
3676 
3677  iTXDir = fMove + fWalk * Clamp<int32_t>(iPullX-Action.Target->GetX(),-10,+10) / 10;
3678 
3679  // Push object
3680  if (!Action.Target->Push(iTXDir,accel,false))
3681  { StopActionDelayCommand(this); return; }
3682  // Set target controller
3684 
3685  // Train pulling: com dir transfer
3686  if ( (Action.Target->GetProcedure()==DFA_WALK)
3687  || (Action.Target->GetProcedure()==DFA_PULL) )
3688  {
3690  if (iTXDir<0) Action.Target->Action.ComDir=COMD_Left;
3691  if (iTXDir>0) Action.Target->Action.ComDir=COMD_Right;
3692  }
3693 
3694  // Pulling range
3695  iPushDistance = std::max(Shape.Wdt/2-8,0);
3696  iPushRange = iPushDistance + 20;
3697  Action.Target->GetArea(sax,say,sawdt,sahgt);
3698  // Object lost
3699  if (!Inside(GetX()-sax,-iPushRange,sawdt-1+iPushRange)
3700  || !Inside(GetY()-say,-iPushRange,sahgt-1+iPushRange))
3701  {
3702  // Remember target. Will be lost on changing action.
3703  C4Object *prev_target = Action.Target;
3704  // Wait command (why, anyway?)
3705  StopActionDelayCommand(this);
3706  // Grab lost action
3707  GrabLost(this, prev_target);
3708  // Lose target
3709  Action.Target=nullptr;
3710  // Done
3711  return;
3712  }
3713 
3714  // Move to pulling position
3715  xdir = fMove + fWalk * Clamp<int32_t>(iTargetX-GetX(),-10,+10) / 10;
3716 
3717  // Phase by XDir
3718  iPhaseAdvance=0;
3719  if (xdir<0) { iPhaseAdvance=-fixtoi(xdir*10); SetDir(DIR_Left); }
3720  if (xdir>0) { iPhaseAdvance=+fixtoi(xdir*10); SetDir(DIR_Right); }
3721  // No YDir
3722  ydir=0;
3723  Mobile=1;
3724 
3725  break;
3726  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3727  case DFA_LIFT:
3728  // Valid check
3729  if (!Action.Target) { SetAction(0); return; }
3730  // Target lifting force
3731  lftspeed=itofix(2); tydir=0;
3732  switch (Action.ComDir)
3733  {
3734  case COMD_Up: tydir=-lftspeed; break;
3735  case COMD_Stop: tydir=-GravAccel; break;
3736  case COMD_Down: tydir=+lftspeed; break;
3737  }
3738  // Lift object
3739  if (!Action.Target->Lift(tydir,C4REAL100(50)))
3740  { SetAction(0); return; }
3741  // Check LiftTop
3742  if (Def->LiftTop)
3743  if (Action.Target->GetY()<=(GetY()+Def->LiftTop))
3744  if (Action.ComDir==COMD_Up)
3745  Call(PSF_LiftTop);
3746  // General
3747  DoGravity(this);
3748  break;
3749  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3750  case DFA_FLOAT:
3751  // ComDir changes xdir/ydir
3752  switch (Action.ComDir)
3753  {
3754  case COMD_Up:
3755  ydir-=accel;
3756  if (xdir<0) xdir+=decel;
3757  if (xdir>0) xdir-=decel;
3758  if ((xdir>-decel) && (xdir<+decel)) xdir=0;
3759  break;
3760  case COMD_UpRight:
3761  ydir-=accel; xdir+=accel; break;
3762  case COMD_Right:
3763  xdir+=accel;
3764  if (ydir<0) ydir+=decel;
3765  if (ydir>0) ydir-=decel;
3766  if ((ydir>-decel) && (ydir<+decel)) ydir=0;
3767  break;
3768  case COMD_DownRight:
3769  ydir+=accel; xdir+=accel; break;
3770  case COMD_Down:
3771  ydir+=accel;
3772  if (xdir<0) xdir+=decel;
3773  if (xdir>0) xdir-=decel;
3774  if ((xdir>-decel) && (xdir<+decel)) xdir=0;
3775  break;
3776  case COMD_DownLeft:
3777  ydir+=accel; xdir-=accel; break;
3778  case COMD_Left:
3779  xdir-=accel;
3780  if (ydir<0) ydir+=decel;
3781  if (ydir>0) ydir-=decel;
3782  if ((ydir>-decel) && (ydir<+decel)) ydir=0;
3783  break;
3784  case COMD_UpLeft:
3785  ydir-=accel; xdir-=accel; break;
3786  case COMD_Stop:
3787  if (xdir<0) xdir+=decel;
3788  if (xdir>0) xdir-=decel;
3789  if ((xdir>-decel) && (xdir<+decel)) xdir=0;
3790  if (ydir<0) ydir+=decel;
3791  if (ydir>0) ydir-=decel;
3792  if ((ydir>-decel) && (ydir<+decel)) ydir=0;
3793  break;
3794  }
3795  // xdir/ydir bounds, don't apply if COMD_None
3796  if (Action.ComDir != COMD_None)
3797  {
3798  if (ydir<-limit) ydir=-limit; if (ydir>+limit) ydir=+limit;
3799  if (xdir>+limit) xdir=+limit; if (xdir<-limit) xdir=-limit;
3800  }
3801 
3802  Mobile=1;
3803  break;
3804  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3805  // ATTACH: Force position to target object
3806  // own vertex index is determined by high-order byte of action data
3807  // target vertex index is determined by low-order byte of action data
3808  case DFA_ATTACH:
3809 
3810  // No target
3811  if (!Action.Target)
3812  {
3813  if (Status)
3814  {
3815  SetAction(0);
3817  }
3818  return;
3819  }
3820 
3821  // Target incomplete and no incomplete activity
3822  if (!(Action.Target->OCF & OCF_FullCon))
3824  { SetAction(0); return; }
3825 
3826  // Force containment
3828  {
3829  if (Action.Target->Contained)
3831  else
3832  Exit(GetX(),GetY(),GetR());
3833  }
3834 
3835  // Object might have detached in Enter/Exit call
3836  if (!Action.Target) break;
3837 
3838  // Move position (so objects on solidmask move)
3840  -Shape.VtxX[Action.Data>>8] - fix_x,
3842  -Shape.VtxY[Action.Data>>8] - fix_y);
3843  // must zero motion...
3844  xdir=ydir=0;
3845 
3846  break;
3847  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3848  case DFA_CONNECT:
3849  {
3850  bool fBroke=false;
3851  bool fLineChange = false;
3852 
3853  // Line destruction check: Target missing or incomplete
3854  if (!Action.Target || (Action.Target->Con<FullCon)) fBroke=true;
3855  if (!Action.Target2 || (Action.Target2->Con<FullCon)) fBroke=true;
3856  if (fBroke)
3857  {
3859  AssignRemoval();
3860  return;
3861  }
3862 
3863  // Movement by Target
3864  // Connect to attach vertex
3865  C4Value lineAttachV; C4ValueArray *lineAttach;
3866  Action.Target->GetProperty(P_LineAttach, &lineAttachV);
3867  lineAttach = lineAttachV.getArray();
3868  int32_t iConnectX1, iConnectY1;
3869  iConnectX1 = Action.Target->GetX();
3870  iConnectY1 = Action.Target->GetY();
3871  if (lineAttach)
3872  {
3873  iConnectX1 += lineAttach->GetItem(0).getInt();
3874  iConnectY1 += lineAttach->GetItem(1).getInt();
3875  }
3876  if ((iConnectX1!=Shape.VtxX[0]) || (iConnectY1!=Shape.VtxY[0]))
3877  {
3878  // Regular wrapping line
3879  if (Def->LineIntersect == 0)
3880  if (!Shape.LineConnect(iConnectX1,iConnectY1,0,+1,
3881  Shape.VtxX[0],Shape.VtxY[0])) fBroke=true;
3882  // No-intersection line
3883  if (Def->LineIntersect == 1)
3884  { Shape.VtxX[0]=iConnectX1; Shape.VtxY[0]=iConnectY1; }
3885 
3886  fLineChange = true;
3887  }
3888 
3889  // Movement by Target2
3890  // Connect to attach vertex
3891  Action.Target2->GetProperty(P_LineAttach, &lineAttachV);
3892  lineAttach = lineAttachV.getArray();
3893  int32_t iConnectX2, iConnectY2;
3894  iConnectX2 = Action.Target2->GetX();
3895  iConnectY2 = Action.Target2->GetY();
3896  if (lineAttach)
3897  {
3898  iConnectX2 += lineAttach->GetItem(0).getInt();
3899  iConnectY2 += lineAttach->GetItem(1).getInt();
3900  }
3901  if ((iConnectX2!=Shape.VtxX[Shape.VtxNum-1]) || (iConnectY2!=Shape.VtxY[Shape.VtxNum-1]))
3902  {
3903  // Regular wrapping line
3904  if (Def->LineIntersect == 0)
3905  if (!Shape.LineConnect(iConnectX2,iConnectY2,Shape.VtxNum-1,-1,
3906  Shape.VtxX[Shape.VtxNum-1],Shape.VtxY[Shape.VtxNum-1])) fBroke=true;
3907  // No-intersection line
3908  if (Def->LineIntersect == 1)
3909  { Shape.VtxX[Shape.VtxNum-1]=iConnectX2; Shape.VtxY[Shape.VtxNum-1]=iConnectY2; }
3910 
3911  fLineChange = true;
3912  }
3913 
3914  // Line fBroke
3915  if (fBroke)
3916  {
3917  Call(PSF_OnLineBreak,0);
3918  AssignRemoval();
3919  return;
3920  }
3921 
3922  // Reduce line segments
3923  if (!::Game.iTick35)
3925  fLineChange = true;
3926 
3927  // Line change callback
3928  if (fLineChange)
3930  }
3931  break;
3932  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3933  default:
3934  // Attach
3935  if (Action.t_attach)
3936  {
3937  xdir = ydir = 0;
3938  Mobile = 1;
3939  }
3940  // Free gravity
3941  else
3942  DoGravity(this);
3943  break;
3944  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3945  }
3946 
3947  // Phase Advance (zero delay means no phase advance)
3948  if (pActionDef->GetPropertyInt(P_Delay))
3949  {
3950  Action.PhaseDelay+=iPhaseAdvance;
3951  if (Action.PhaseDelay >= pActionDef->GetPropertyInt(P_Delay))
3952  {
3953  // Advance Phase
3954  Action.PhaseDelay=0;
3955  Action.Phase += pActionDef->GetPropertyInt(P_Step);
3956  // Phase call
3957  if (pActionDef->GetPropertyStr(P_PhaseCall))
3958  {
3959  Call(pActionDef->GetPropertyStr(P_PhaseCall)->GetCStr());
3960  }
3961  // Phase end
3962  if (Action.Phase>=pActionDef->GetPropertyInt(P_Length))
3963  {
3964  C4String *next_action = pActionDef->GetPropertyStr(P_NextAction);
3965  // Keep current action if there is no NextAction
3966  if (!next_action)
3967  Action.Phase = 0;
3968  // set new action if it's not Hold
3969  else if (next_action == &Strings.P[P_Hold])
3970  {
3971  Action.Phase = pActionDef->GetPropertyInt(P_Length)-1;
3972  Action.PhaseDelay = pActionDef->GetPropertyInt(P_Delay)-1;
3973  }
3974  else
3975  {
3976  // Set new action
3977  SetActionByName(next_action, nullptr, nullptr, SAC_StartCall | SAC_EndCall);
3978  }
3979  }
3980  }
3981  }
3982 
3983  return;
3984 }
3985 
3986 
3987 bool C4Object::SetOwner(int32_t iOwner)
3988 {
3989  // Check valid owner
3990  if (!(ValidPlr(iOwner) || iOwner == NO_OWNER)) return false;
3991  // always set color, even if no owner-change is done
3992  if (iOwner != NO_OWNER)
3993  if (GetGraphics()->IsColorByOwner())
3994  {
3995  Color=::Players.Get(iOwner)->ColorDw;
3996  UpdateFace(false);
3997  }
3998  // no change?
3999  if (Owner == iOwner) return true;
4000  // set new owner
4001  int32_t iOldOwner=Owner;
4002  Owner=iOwner;
4003  // this automatically updates controller
4004  Controller = Owner;
4005  // script callback
4006  Call(PSF_OnOwnerChanged, &C4AulParSet(Owner, iOldOwner));
4007  // done
4008  return true;
4009 }
4010 
4011 
4012 bool C4Object::SetLightRange(int32_t iToRange, int32_t iToFadeoutRange)
4013 {
4014  // set new range
4015  lightRange = iToRange;
4016  lightFadeoutRange = iToFadeoutRange;
4017  // resort into player's FoW-repeller-list
4018  UpdateLight();
4019  // success
4020  return true;
4021 }
4022 
4023 
4024 bool C4Object::SetLightColor(uint32_t iValue)
4025 {
4026  // set new color value
4027  lightColor = iValue;
4028  // resort into player's FoW-repeller-list
4029  UpdateLight();
4030  // success
4031  return true;
4032 }
4033 
4034 
4036 {
4037  if (Landscape.HasFoW()) Landscape.GetFoW()->Add(this);
4038 }
4039 
4040 void C4Object::SetAudibilityAt(C4TargetFacet &cgo, int32_t iX, int32_t iY, int32_t player)
4041 {
4042  // target pos (parallax)
4043  float offX, offY, newzoom;
4044  GetDrawPosition(cgo, iX, iY, cgo.Zoom, offX, offY, newzoom);
4045  int32_t audible_at_pos = Clamp(100 - 100 * Distance(cgo.X + cgo.Wdt / 2, cgo.Y + cgo.Hgt / 2, offX, offY) / 700, 0, 100);
4046  if (audible_at_pos > Audible)
4047  {
4048  Audible = audible_at_pos;
4049  AudiblePan = Clamp<int>(200 * (offX - cgo.X - (cgo.Wdt / 2)) / cgo.Wdt, -100, 100);
4051  }
4052 }
4053 
4054 bool C4Object::IsVisible(int32_t iForPlr, bool fAsOverlay) const
4055 {
4056  bool fDraw;
4057  C4Value vis;
4058  if (!GetProperty(P_Visibility, &vis))
4059  return true;
4060 
4061  int32_t Visibility;
4062  C4ValueArray *parameters = vis.getArray();
4063  if (parameters && parameters->GetSize())
4064  {
4065  Visibility = parameters->GetItem(0).getInt();
4066  }
4067  else
4068  {
4069  Visibility = vis.getInt();
4070  }
4071  // check layer
4072  if (Layer && Layer != this && !fAsOverlay)
4073  {
4074  fDraw = Layer->IsVisible(iForPlr, false);
4075  if (Layer->GetPropertyInt(P_Visibility) & VIS_LayerToggle) fDraw = !fDraw;
4076  if (!fDraw) return false;
4077  }
4078  // no flags set?
4079  if (!Visibility) return true;
4080  // check overlay
4081  if (Visibility & VIS_OverlayOnly)
4082  {
4083  if (!fAsOverlay) return false;
4084  if (Visibility == VIS_OverlayOnly) return true;
4085  }
4086  // editor visibility
4087  if (::Application.isEditor)
4088  {
4089  if (Visibility & VIS_Editor) return true;
4090  }
4091  // check visibility
4092  fDraw=false;
4093  if (Visibility & VIS_Owner) fDraw = fDraw || (iForPlr==Owner);
4094  if (iForPlr!=NO_OWNER)
4095  {
4096  // check all
4097  if (Visibility & VIS_Allies) fDraw = fDraw || (iForPlr!=Owner && !Hostile(iForPlr, Owner));
4098  if (Visibility & VIS_Enemies) fDraw = fDraw || (iForPlr!=Owner && Hostile(iForPlr, Owner));
4099  if (parameters)
4100  {
4101  if (Visibility & VIS_Select) fDraw = fDraw || parameters->GetItem(1+iForPlr).getBool();
4102  }
4103  }
4104  else fDraw = fDraw || (Visibility & VIS_God);
4105  return fDraw;
4106 }
4107 
4109 {
4110  return GBackLiquid(GetX(),GetY()+Def->Float*Con/FullCon-1);
4111 }
4112 
4113 void C4Object::SetRotation(int32_t nr)
4114 {
4115  while (nr<0) nr+=360; nr%=360;
4116  // remove solid mask
4117  if (pSolidMaskData) pSolidMaskData->Remove(false);
4118  // set rotation
4119  fix_r=itofix(nr);
4120  // Update face
4121  UpdateFace(true);
4122 }
4123 
4125 {
4126  // color modulation
4128  // other blit modes
4130 }
4131 
4133 {
4134  // color modulation
4136  // extra blitting flags
4137  pDraw->ResetBlitMode();
4138 }
4139 
4141 {
4142  // mask must exist
4143  if (!pSolidMaskData) return;
4144  // draw it
4145  pSolidMaskData->Draw(cgo);
4146 }
4147 
4148 void C4Object::UpdateSolidMask(bool fRestoreAttachedObjects)
4149 {
4150  // solidmask doesn't make sense with non-existant objects
4151  // (the solidmask has already been destroyed in AssignRemoval -
4152  // do not reset it!)
4153  if (!Status) return;
4154  // Determine necessity, update cSolidMask, put or remove mask
4155  // Mask if enabled, fullcon, not contained
4156  if (SolidMask.Wdt > 0 && Con >= FullCon && !Contained)
4157  {
4158  // Recheck and put mask
4159  if (!pSolidMaskData)
4160  {
4161  pSolidMaskData = new C4SolidMask(this);
4162  }
4163  else
4164  pSolidMaskData->Remove(false);
4165  pSolidMaskData->Put(true, nullptr, fRestoreAttachedObjects);
4166  }
4167  // Otherwise, remove and destroy mask
4168  else if (pSolidMaskData)
4169  {
4170  delete pSolidMaskData; pSolidMaskData = nullptr;
4171  }
4172 }
4173 
4175 {
4176  // Object enter container
4177  bool fRejectCollect;
4178  if (!pObj->Enter(this, true, false, &fRejectCollect))
4179  return false;
4180  // Cancel attach (hacky)
4181  ObjectComCancelAttach(pObj);
4182  // Container Collection call
4184  // Object Hit call
4185  if (pObj->Status && pObj->OCF & OCF_HitSpeed1) pObj->Call(PSF_Hit);
4186  if (pObj->Status && pObj->OCF & OCF_HitSpeed2) pObj->Call(PSF_Hit2);
4187  if (pObj->Status && pObj->OCF & OCF_HitSpeed3) pObj->Call(PSF_Hit3);
4188  // post-copy the motion of the new container
4189  if (pObj->Contained == this) pObj->CopyMotion(this);
4190  // done, success
4191  return true;
4192 }
4193 
4195 {
4196  // safety
4197  if (!pFrom) return false; if (!Status || !pFrom->Status) return false;
4198  // even more safety (own info: success)
4199  if (pFrom == this) return true;
4200  // only if other object has info
4201  if (!pFrom->Info) return false;
4202  // clear own info object
4203  if (Info)
4204  {
4205  Info->Retire();
4206  ClearInfo (Info);
4207  }
4208  // remove objects from any owning crews
4209  ::Players.ClearPointers(pFrom);
4210  ::Players.ClearPointers(this);
4211  // set info
4212  Info = pFrom->Info; pFrom->ClearInfo (pFrom->Info);
4213  // set name
4214  SetName(Info->Name);
4215  // retire from old crew
4216  Info->Retire();
4217  // if alive, recruit to new crew
4218  if (Alive) Info->Recruit();
4219  // make new crew member
4220  C4Player *pPlr = ::Players.Get(Owner);
4221  if (pPlr) pPlr->MakeCrewMember(this);
4222  // done, success
4223  return true;
4224 }
4225 
4226 bool C4Object::ShiftContents(bool fShiftBack, bool fDoCalls)
4227 {
4228  // get current object
4229  C4Object *c_obj = Contents.GetObject();
4230  if (!c_obj) return false;
4231  // get next/previous
4232  auto it = fShiftBack ? Contents.reverse().begin() : ++Contents.begin();
4233  while (!it.atEnd())
4234  {
4235  auto pObj = (*it);
4236  // check object
4237  if (pObj->Status)
4238  if (!c_obj->CanConcatPictureWith(pObj))
4239  {
4240  // object different: shift to this
4241  DirectComContents(pObj, !!fDoCalls);
4242  return true;
4243  }
4244  // next/prev item
4245  it++;
4246  }
4247  return false;
4248 }
4249 
4250 void C4Object::DirectComContents(C4Object *pTarget, bool fDoCalls)
4251 {
4252  // safety
4253  if (!pTarget || !pTarget->Status || pTarget->Contained != this) return;
4254  // Desired object already at front?
4255  if (Contents.GetObject() == pTarget) return;
4256  // select object via script?
4257  if (fDoCalls)
4258  if (Call("~ControlContents", &C4AulParSet(pTarget)))
4259  return;
4260  // default action
4261  if (!(Contents.ShiftContents(pTarget))) return;
4262  // Selection sound
4263  if (fDoCalls) if (!Contents.GetObject()->Call("~Selection", &C4AulParSet(this))) StartSoundEffect("Clonk::Action::Grab",false,100,this);
4264  // update menu with the new item in "put" entry
4265  if (Menu && Menu->IsActive() && Menu->IsContextMenu())
4266  {
4267  Menu->Refill();
4268  }
4269  // Done
4270  return;
4271 }
4272 
4273 void C4Object::GetParallaxity(int32_t *parX, int32_t *parY) const
4274 {
4275  assert(parX); assert(parY);
4276  *parX = 100; *parY = 100;
4277  if (Category & C4D_Foreground)
4278  {
4279  *parX = 0; *parY = 0;
4280  return;
4281  }
4282  if (!(Category & C4D_Parallax)) return;
4283  C4Value parV; GetProperty(P_Parallaxity, &parV);
4284  C4ValueArray *par = parV.getArray();
4285  if (!par) return;
4286  *parX = par->GetItem(0).getInt();
4287  *parY = par->GetItem(1).getInt();
4288 }
4289 
4290 bool C4Object::GetDragImage(C4Object **drag_object, C4Def **drag_def) const
4291 {
4292  // drag is possible if MouseDragImage is assigned
4293  C4Value parV; GetProperty(P_MouseDragImage, &parV);
4294  if (!parV) return false;
4295  // determine drag object/id
4296  C4Object *obj = parV.getObj();
4297  C4Def * def = nullptr;
4298  if (!obj) def = parV.getDef();
4299  if (drag_object) *drag_object = obj;
4300  if (drag_def) *drag_def = def;
4301  // drag possible, even w./o image
4302  return true;
4303 }
4304 
4305 int32_t C4Object::AddObjectAndContentsToArray(C4ValueArray *target_array, int32_t index)
4306 {
4307  // add self, contents and child contents count recursively to value array. Return index after last added item.
4308  target_array->SetItem(index++, C4VObj(this));
4309  for (C4Object *cobj : Contents)
4310  {
4311  index = cobj->AddObjectAndContentsToArray(target_array, index);