Object Scripts Object Scripts Object scripts control the complex behaviour of an object. For details on scripting see the C4Script documentation. Creation For every object, the engine calls the function Initialize in the object script when it is created and completed. func Initialize() { CreateContents(Rock); } An object with this script will be given a rock right after it has been created. The Initialize function is called only when the object has reached full size (a building only when its construction has been completed and a living being only when it is fully grown). ActMap An active object can also define activity script calls in its ActMap. The defined StartCall is made whenever an action begins (or repeats), an EndCall is made at the end of each activity. PhaseCall is called at each animation phase step and should only be used for very short animations. The call frequency of PhaseCalls is determined by the speed of the animation. #include An object script can also include the functionality of another script. #include Clonk At this position the complete script of the specified object definition (that of the clonk, in this case) is inserted, including all scripts that that script includes or got via #appendto. The only exception is that every script is included only once, so including both the Clonk script and a script that is included by the Clonk script doesn't include that script twice. Other Obviously, the included definition must be valid and loaded. Declared functions can be overloaded by functions of the same name that occur later in the script. Also see inherited(). Interaction from other scripts Other scripts can call functions of an object obj with the -> and ->~ operators. var obj = CreateObject(Flint); obj->Hit(); Object calls made by the engine The engine calls the following functions is objects at the given time. FunctionParameterDescription Initialize When the object is completed (Con >= 100). Construction object by_objectWhen the object is created. The parameter is a pointer to the object the script of which has created this object. Also see Construction Destruction When the object is removed. Hit When the object collides with the landscape or is collected at high velocity (>=15). Hit2 Like Hit, with speeds >= 20 (see OCF_HitSpeed2). Hit3 Like Hit, with speeds >= 60 (see OCF_HitSpeed3). Grab object target, bool grabWhen the object grabs or lets go of another object. Grabbed object by_object, bool grabWhen the object is grabbed or let go by another object. Get object targetWhen the object takes another object from a container. Put When the object puts another object into a container. DigOutObject object objWhen the object dug out another object that was stuck in solid material or when a new object is created from material during digging. DugOut object object_byWhen the object was spawned from dug out material. The object might get removed afterwards if the material has Dig2ObjectCollect=2. Damage int change, int cause, int by_playerWhen the object is damaged. See Fx*Damagefor cause values. DeepBreath When a living being surfaces after having used up more than half of its breath. Incineration int by_playerWhen the object is incinerated. Notice: with objects changing their definition via BurnTo, this call is made to the burned version! IncinerationEx int by_playerWhen the object is incinerated in and immediately extinguished by a surrounding liquid. Otherwise as Incineration. Death When a living being dies. Activate object by_objectActivation by double dig. Only applies to collected items or directly controlled crew objects. Called after internal handling of the double dig command has been completed (e.g. chopping of trees etc.) Contact_ When the object collides with the landscape. See CNAT - Contact Attachment. Control_ object by_objectWhen the object is controlled from the outside. See Control Functions. Contained_ object by_objectWhen the object is controlled from the inside. See Control Functions. ControlCommand string command, object target, int x, int y, object target2, int data, object command_objectWhen the object has received a command to be independently executed. See Control functions. ControlCommandFinished string command, object target, int x, int y, object target2, any DataWhen the object has completed a command or execution of a command has failed. ControlTransfer object obj, int x, int yWhen an object (obj) using the internal pathfinding algorithm is trying to pass the transfer zone of this object on its way to point x/y. The transfer function can then help the object along by giving special script commands and returning true. Also see SetTransferZone(). OnSynchronized When an object is loaded from a savegame or network synchronization is performed. Objects with a transfer zone should reset the zone in this call. Also see SetTransferZone(). IsFulfilled Only in game goal objects. A return value true indicates that this goal is fulfilled. ControlContents id targetWhen a new inventory object is selected. See Control Functions. Selection object containerWhen the object is selected in an inventory change. If you are processing this event, the function should play its own selection sound. CatchBlow int level, object byWhen the object is hit or punched by another object. QueryCatchBlow object byCalled before the object is hit or punched by another object. By returning true, QueryCatchBlow can reject physical blows. LineBreak int causeWhen a line object is broken. cause: 0 by movement, 1 because of a missing or incomplete target object. BuildNeedsMaterial id material_definition, int amountWhen the object is building another object and building material is required. The parameters are the type and amount of the first needed material. If this function returns true, no material message is displayed above the object. AttachTargetLost When the object is in an ATTACH action and has lost its action target. At this time, the object's action has already been reset. CrewSelection bool deselect, bool cursor_onlyWhen crew selection is changed. cursor_only specifies whether only that crew member has been selected which is also the cursor. GetObject2Drop object for_collection_of_objectCalled to determine the least needed inventory object when a clonk tries to collect a new object and his inventory is full. The function should return the object to be dropped to gain space, or nil if none. CalcValue object in_base, int for_playerCalculates the value of an object. Also see GetValue(). CalcDefValue object in_base, int for_playerCalculates the value of an object type available to buy. Also see GetValue(). CalcBuyValue id item, int valueReturns the buying price of the object type. CalcSellValue object obj, int object_valueReturns the selling price of the object type. LiftTop When an object with LIFT action lifts its action target to the height specified in its DefCore or above. Stuck When the action target of the object's PUSH or LIFT action is stuck. GrabLost When the action target of the object's PUSH or PULL action is lost. Collection object obj, bool putWhen the object has collected another object (obj) (by ingame collection or grabbing and getting). Collection2 object objWhen the object has collected another object (obj) (in all cases, even in script controlled collection or entering). ContentsDestruction object destroyedWhen an object contained in the object has been destroyed/removed. The object still exists when the callback is called, but will be destroyed afterwards. Departure object containerWhen this object has left another object (container). Ejection object objWhen another object (obj) has left the contents of this object (also see script command Exit). Entrance object containerWhen the object has entered another object (container). ActivateEntrance object by_objectWhen another object is trying to enter this object through the entrance. RejectCollect id def, object objCalled before Collection. If RejectCollect returns true, the collection of the other object is prevented. RejectEntrance object into_objectCalled before Entrance. If RejectEntrance returns true, then entrance of the other object is prevented. InitializePlayer int playerCalled in game goals, rules, or environment objects after the joining of a new player and before the corresponding call in the scenario script. SellTo int by_playerWhen the object is sold. Should return nil or the id of the object type which is actually added to the player's homebase material. Sale int by_playerWhen the object is sold. Purchase int by_player, object buy_objectWhen the object is bought. Recruitment int playerWhen the objet is added to the crew of a player. RejectTeamSwitch int player, int new_teamCallback in game goal, rule, and environment objects and in the scenario script. If RejectTeamSwitch returns true, the team switch of a player can be prevented (see SetPlayerTeam). OnTeamSwitch int player, int new_team, int old_teamCallback in game goal, rule, and environment objects and in the scenario script. Called when a player has successfully switch from old_team to new_team (see SetPlayerTeam). EditCursorSelection When object is selected in editor. Use this callback to display extra information for scenario designers. EditCursorDeselection object next_selectionWhen object is deselected in editor. Use this callback to hide any information previously shown in EditCursorSelection. If deselection happens due to another object being selected, that object is passed in next_selection. EditCursorMoved int old_x, int old_yWhen object is moved in editor. Callback is also done when moved in non-network pause mode. old_x, old_y contains object position before movement. SaveScenarioObject proplist propsCalled when scenario is saved from the editor. Object should write creation of itself and properties to the buffer props. Return true if the object should be saved and false if saving of this object should be omitted. See Scenario saving.
Scenario saving When the user chooses the "Save Scenario" option from the editor menu, the engine calls a global function SaveScenarioObjects defined in System.ocg/SaveScenario.c. This function writes all objects to the Objects.c file in their current state. The function stores all objects except the crew of currently joined human players and objects of a type that starts with GUI_. By default, objects are recreated using a call to CreateObject followed by setting a number of default properties like position, rotation, speed, action, if they are not in their default state. For most object, the default saving method should be fine. However, it is possible to override the SaveScenarioObject callback to control how objects are created and which properties are set. For example if a switch wants to save its target which is stored in a local variable called "target", the switch definition can override the callback: local target; func SetTarget(object new_target) { target = new_target; return true; } func SaveScenarioObject(props) { if (!inherited(props, ...)) return false; if (target) props->AddCall("Target", this, "SetTarget", target); return true; } As a result, the generated Objects.c file will include the call to SetTarget if the switch is saved. Dependent objects should always either be passed to the AddCall function or stored as a string from the MakeScenarioSaveName function. If this is done, that object is marked as a dependency. The saving mechanism will ensure that any object this object depends on will be created before. In case of circular dependencies, the object property setting script is detached from object creation script. If an object should not be saved in scenarios - for example, because it is just the helper of another object - the SaveScenarioObject callback should be overloaded to return false. The object creation procedure can also be adjusted. For example, the waterfall object (defined in Objects.ocd/Environment.ocd/Waterfall.ocd) is created using the global functions CreateWaterfall and CreateLiquidDrain, which create a Waterfall object and attach an effect to it. To generate the creation functions from the effects, the waterfall overrides SaveScenarioObject: func SaveScenarioObject(props) { if (!inherited(props, ...)) return false; var fx_waterfall = GetEffect("IntWaterfall", this); if (fx_waterfall) { props->RemoveCreation(); props->Add(SAVEOBJ_Creation, "CreateWaterfall(%d,%d,%d,%v)",fx_waterfall.X, fx_waterfall.Y, fx_waterfall.Strength, fx_waterfall.Material); } return true; } The call to RemoveCreation removes the existing object creation using CreateObject. If you need access to one of the objects created in the editor, you can set its "StaticSaveVar" property to the name of a static variable. The InitializeObjects() function will then save the object in that variable. The following table lists standard properties that are saved if their value is different from the default and if it is not removed using a props->Remove call. Property nameDefault valueDescription Alive trueCategory C4D_Living only: If object is not alive, a call to SetKill is stored. See GetAlive and Kill. Action this.DefaultActionAction as retrieved using GetAction and set using SetAction. Includes ActionTargets. Not stored by default but only if SaveScenarioObjectAction is called. Phase 0Action phase (see GetPhase and SetPhase). Not stored by default but only if SaveScenarioObjectAction is called. Dir DIR_LeftAnimation direction (see GetDir and SetDir) ComDir COMD_StopCommanded movement direction (see GetComDir and SetComDir) Con 100Construction percentage, i.e. object size (see GetCon and SetCon) Category GetID()->GetCategory()Object category (see GetCategory and SetCategory) R 0Rotation (see GetR and SetR) XDir 0Horizontal speed (see GetXDir and SetXDir) YDir 0Vertical speed (see GetYDir and SetYDir). Vertical speed is not saved it is very small and the object touches the ground to avoid saving of speed on idle objects. RDir 0Rotation speed (see GetRDir and SetRDir) Color 0, 0xffffffffObject color of ColorByOwner-surfaces (see GetColo and SetColor) ClrModulation 0, 0xffffffffObject color modulation of all surfaces (see GetClrModulation and SetClrModulation) BlitMode 0Object drawing mode (see GetObjectBlitMode and SetObjectBlitMode) MeshMaterial GetID()->GetMeshMaterial()Custom assignments of mesh materials (see GetMeshMaterial and SetMeshMaterial) Name GetID()->GetName()Object name (see GetName and SetName) MaxEnergy GetID().MaxEnergyMaximum energy (see Properties) Energy GetID().MaxEnergy/1000Current energy level (see GetEnergy and DoEnergy) Visibility VIS_AllObject visibility (see Properties) Plane GetID().PlaneObject plane, i.e. z-order (see Properties) Position Object position. This is only set if the object has a rotation and could not be created directly at the correct offset (see SetPosition) Command NoneStores only the topmost command of the chain (see GetCommand and SetCommand) Fire Fire effect.
By default, effects are not saved in scenarios. To force saving of an effect, define the Fx*SaveScen callback. For example, the fire effect saves itself like this: global func FxFireSaveScen(object obj, proplist fx, proplist props) { // this is burning. Save incineration to scenario. props->AddCall("Fire", obj, "Incinerate", fx.strength, fx.caused_by, fx.blasted, fx.incinerating_object); return true; } obj and fx refer to the object and effect proplist as for any effect call. save_name is the variable name of the effected object and is unset for global effects. Scenario saving reference The following functions are available to call on the "props" parameter passed to SaveScenarioObject callbacks: AddCall bool AddCall(string id, object target, string function, any par1, any par2, ...); Adds a new call of format target->Function(par1, par2, ...) to the stored object script. Object parameters may be passed as is; strings must be quoted explicitely. The id parameter is an identifier which can be used by derived objects to remove the property again. Add bool AddCall(string id, string script, any par1, any par2, ...); Adds a custom script snippet of any format. script may contain format characters and parameters are formatted into the string using Format(). Remove int Remove(string id); Remove all strings added previously using AddCall or Add with the given ID. Can also be used to remove default properties. Returns number of script lines removed. RemoveCreation bool RemoveCreation(); Remove all strings added previously using with IDs SAVEOBJ_Creation or SAVEOBJ_ContentsCreation. Clear bool Clear(); Remove all creation and property setting strings.
sulai2003-11 matthes2004-07 Clonkonaut2008-04 Sven22013-12