public static object RunActionHandler(ModEntry mod, DllMeta dll, ActionDef act) { try { var lib = ModPhases.LoadDll(mod, dll.Path); if (lib == null) { return(false); } var handler = ActionMods[dll]; foreach (var type in dll.Methods[ACTION_METHOD]) { var result = ModPhases.CallInit(mod, lib, type, ACTION_METHOD, (e) => ParamValue(act, e, mod, handler)); if (result is bool success) { if (success) { return(true); } } else if (result is Exception ex) { return(ex); } else if (result != null) { handler.Log().Info("Unexpected ActionMod result: {0}", result.GetType()); } } return(null); } catch (Exception ex) { mod.Error(ex); return(null); } }
private MenuItem CreateCardMenuItem(BaseActionDef baseAction) { var item = new MenuItem { Header = baseAction.Name }; var actionGroupDef = baseAction as ActionGroupDef; if (actionGroupDef != null) { foreach (MenuItem subItem in actionGroupDef.Children.Select(CreateCardMenuItem)) { item.Items.Add(subItem); } return(item); } var action = baseAction as ActionDef; item.Tag = action; if (action != null) { item.InputGestureText = action.Shortcut; if (action.DefaultAction) { item.FontWeight = FontWeights.Bold; _defaultCardAction = action; } } item.Click += CardActionClicked; return(item); }
internal static bool AbortOnError(Logger log, ActionDef act, Exception err) { act.TryGetValue("onerror", out object onerror); var handle = TrimAndLower(onerror) ?? "log"; if (handle.IndexOf("log") >= 0) { log.Error(err); } else if (handle.IndexOf("err") >= 0) { log.Error(err); } else if (handle.IndexOf("warn") >= 0) { log.Warn(err); } else if (handle.IndexOf("info") >= 0) { log.Info(err); } else if (handle.IndexOf("verbo") >= 0) { log.Verbo(err); } if (handle.IndexOf("stop") >= 0) { log.Info("Aborting because OnError == Stop ({0})", handle); return(true); } return(false); }
protected WorldObject actor; //Object that uses (is capable of) this action //private Texture2D cursorTex = null; //public Texture2D cursor { get { return ResourceManager.loadTexture(ref cursorTex, HoverCursor); } } public Action(string def, WorldObject act) { if (act) { actor = act; } else { Debug.LogError("Action with no parent object!"); } if (def.Length > 0) { this.def = DefStorage.getDef(def) as ActionDef; } else { this.def = DefStorage.getDef(getDefName()) as ActionDef; } if (this.def == null) { this.def = new ActionDef(); } //this.def = ResourceManager. menuImage = new LazyResource <Texture2D>(this.def.MenuIcon); //Init def //InitDef(); }
public void AddAction() { if (actions == null) { actions = new List <ActionDef>(); } int id = 0; if (actions.Count > 0) { id = actions[this.curActionIndex].animNo + 1; } ActionDef a = new ActionDef(id); if (actions.Count > 0) { actions.Insert(this.curActionIndex + 1, a); curActionIndex = this.curActionIndex + 1; } else { actions.Add(a); curActionIndex = 0; } }
[TestMethod()] public void FilterActionTest() { ActionDef[] defs = new ActionDef[] { CreateDef("action", "Default", "all", "Def1"), CreateDef("eval", "Code1"), CreateDef("action", "Default", "more", "Def2"), CreateDef("skip", "splash", "phase", "SplashMod"), CreateDef("eval", "Code2"), }; var splash = ModActions.FilterActions(defs, "splashmod", out int defCount); Assert.AreEqual(1, splash?.Count, "1 splash actions"); splash[0].TryGetValue("skip", out object val); Assert.AreEqual("splash", val, "splash field"); splash[0].TryGetValue("all", out val); Assert.AreEqual("Def1", val, "splash def 1"); splash[0].TryGetValue("more", out val); Assert.AreEqual("Def2", val, "splash def 2"); Assert.AreEqual(2, defCount, "splash defCount"); var main = ModActions.FilterActions(defs, "mainmod", out defCount); Assert.AreEqual(2, main?.Count, "2 main actions"); Assert.AreEqual(2, defCount, "main defCount"); }
/// <summary> /// Loads the action defs. /// </summary> /// <returns><c>true</c>, if action defs was loaded, <c>false</c> otherwise.</returns> private static bool loadActionDefs() { try{ string json = g_JM.loadJSON(GameConfig.root_dir + "/Content/json/actions.v"); JsonObject jo = g_JM.jsonToJsonObject(json); List <Dictionary <string, object> > aDefs = jo ["action_defs"].asList <Dictionary <string, object> > (); foreach (Dictionary <string, object> dict in aDefs) { jo = new JsonObject(dict); ActionDef aDef = default(ActionDef); aDef.Name = jo["name"].asString(); aDef.ActionType = jo["action_type"].asEnum <ActionType>(); aDef.DamageDef = DamageDefs[jo["damage_def"].asString()]; ActionDefs.Add(aDef.Name, aDef); } }catch (Exception e) { Console.Error.WriteLine("ERROR: failed to load actions:" + e.ToString()); return(false); } return(true); }
private static string GetText(this ActionDef act, string key, string fallback = null) { if (act.TryGetValue(key, out object o) && o is string txt) { return(txt); } return(fallback); }
public void Play(ActionDef action) { this.action = action; state = AnimState.Playing; animElem = 0; animElemTime = 0; animTime = 0; }
internal static ActionDef[] Resolve(ModEntry mod, ActionDef[] list) { try { ActionDef defValues = null; return(PreprocessActions(mod, list, ref defValues, 0)); } catch (Exception ex) { mod.Log().Error(ex); return(new ActionDef[0]); } }
private static ActionDef CreateDef(params string[] keyValues) { var result = new ActionDef(); for (int i = 0; i < keyValues.Length; i += 2) { result.Add(keyValues[i]?.ToString(), keyValues[i + 1]); } return(result); }
private static object ParamValue(ActionDef act, ParameterInfo arg, ModEntry actionMod, ModEntry handler) { if (arg.ParameterType == typeof(ActionDef)) { return(act); } if (arg.ParameterType == typeof(string)) { return(actionMod.Metadata.Id); } return(ModPhases.ParamValue(arg, handler)); }
private static void MergeDefAction(ref ActionDef defValues, ActionDef a) { if (defValues == null) { defValues = new ActionDef(); } foreach (var e in a) { if ("action".Equals(e.Key)) { continue; } defValues[e.Key] = e.Value; } }
private static void MergeDefAction(ref ActionDef defValues, ActionDef a) { if (defValues == null) { defValues = new ActionDef(); } foreach (var e in a) { if ("action".Equals(e.Key) && "default".Equals(TrimAndLower(e.Value as string))) { continue; } defValues.Add(e.Key, e.Value); } }
public static Entity createAction(ActionDef aDef, Entity owner, Entity Target) { Entity e = ActionFactory.ECSInstance.create(); VAction action = new VAction(); action.ActionDef = aDef; action.Owner = owner; action.Target = Target; ActionFactory.ECSInstance.add_component(e, action); ActionFactory.ECSInstance.resolve(e); return(e); }
private static ActionDef AddDefAction(ActionDef a, ActionDef defValues) { a = new ActionDef(a); if (defValues == null) { return(a); } foreach (var e in defValues) { if (!a.ContainsKey(e.Key)) { a.Add(e.Key, e.Value); } } return(a); }
private void CreateContextMenus() { _cardHeader = null; _defaultGroupAction = _defaultCardAction = null; GroupDef def = group.Definition; // Create the card actions List <Control> cardItems = CreateCardMenuItems(def); _cardMenu.Collection = cardItems; // Create the group actions List <Control> groupItems = CreateGroupMenuItems(def); _groupMenu.Collection = groupItems; }
private static object RunActionHandler(ModEntry mod, DllMeta dll, ActionDef act) { try { var lib = ModPhases.LoadDll(mod, dll.Path); if (lib == null) { return(false); } var handler = ActionMods[dll]; object GetParamValue(ParameterInfo pi) => ParamValue(act, pi, mod, handler); object result; foreach (var type in dll.Methods["ActionMod"]) { result = ModPhases.CallInit(mod, lib, type, "ActionMod", GetParamValue); if (result is bool success) { if (success) { return(true); } } else if (result is Exception ex) { LogActionError(handler.Log(), act, ex); if (InList(act.GetText("onerror"), "continue")) { continue; } if (InList(act.GetText("onerror"), "skip")) { return(null); } mod.Log().Info("Aborting Actions. Set OnError to \"Log,Continue\" or \"Log,Skip\" to ignore the error."); return(ex); } else if (result != null) { handler.Log().Error("Unexpected ActionMod result: {0}", result.GetType()); } } return(null); } catch (Exception ex) { mod.Error(ex); return(null); } }
public static List <ActionDef> FilterActions(ActionDef[] list, string phase, out int defaultCount) { defaultCount = 0; ActionDef defValues = null; var actions = new List <ActionDef>(); foreach (var a in list) { if ("default".Equals(GetActionField(a, defValues, "action"))) { MergeDefAction(ref defValues, a); defaultCount++; continue; } if (PhaseMatch(GetActionField(a, defValues, "phase"), phase)) { actions.Add(AddDefAction(a, defValues)); } } return(actions.Count > 0 ? actions : null); }
private static void LogActionError(Logger log, ActionDef act, Exception err) { var directives = act.GetText("onerror", "log"); if (InList(directives, "log") || InList(directives, "error")) { log.Error(err); } else if (InList(directives, "warn")) { log.Warn(err); } else if (InList(directives, "info")) { log.Info(err); } else if (InList(directives, "verbo")) { log.Verbo(err); } }
private static ActionDef[] PreprocessActions(ModEntry mod, ActionDef[] list, ref ActionDef defValues, int level) { var actions = new List <ActionDef>(); foreach (var a in list) { if (a.GetText("include") is string file) { actions.AddRange(LoadInclude(mod, file, ref defValues, level + 1)); } else if (string.Equals(a.GetText("action"), "default", StringComparison.InvariantCultureIgnoreCase)) { MergeDefAction(ref defValues, a); } else { actions.Add(AddDefAction(a, defValues)); } } return(actions.Count > 0 ? actions.ToArray() : null); }
private static ActionDef[] LoadInclude(ModEntry mod, string path, ref ActionDef defValues, int level) { if (!IsSafePath(path)) { mod.Log().Error("Invalid or unsafe path: {0}", path); return(new ActionDef[0]); } if (level > 9) { throw new ApplicationException("Action includes too deep: " + path); } // todo: refactor mod path var actions = Json.Parse <ActionDef[]>(ReadText(Path.Combine(Path.GetDirectoryName(mod.Path), path))); ModMeta.NormDictArray(ref actions); try { return(PreprocessActions(mod, actions, ref defValues, level)); } catch (ApplicationException ex) { throw new ApplicationException("Error when including " + path, ex); } }
// -------- API -------- /// <summary> /// Define a new action. All following Options will become child options of this action. /// </summary> /// <param name="name">Name of the action (null = global / no action)</param> /// <param name="callback">Callback executed when the action has been selected</param> public Arguments <T> Action(string name, Action <T, string> callback = null) { if (name == null) { name = ""; } if (actions.ContainsKey(name)) { throw new ArgumentException($"Action '{name}' already defined."); } definedAction = new ActionDef() { name = name, callback = callback }; actions[definedAction.name] = definedAction; definedOption = null; return(this); }
private static ActionDef AddDefAction(ActionDef a, ActionDef defValues) { a = new ActionDef(a); if (defValues == null) { return(a); } foreach (var e in defValues) { if (!a.ContainsKey(e.Key)) { a.Add(e.Key, e.Value); } } if (!a.ContainsKey("phase")) { a.Add("phase", DEFAULT_PHASE_LOWER); } else { a["phase"] = a["phase"].ToString().Trim().ToLowerInvariant(); } return(a); }
private static ActionDef MergeActions(ActionDef a, ActionDef b) { if (a == null) { throw new ArgumentNullException(nameof(a)); } if (b == null) { throw new ArgumentNullException(nameof(b)); } if (a.FullName != b.FullName) { throw new NotSupportedException( $"Merging actions is expected only on actions with the same FullName. In this case trying to merge '{a.FullName}' and '{b.FullName}'."); } if (a.KnownActionType != b.KnownActionType) { throw new NotSupportedException( $"There are two actions named {a.FullName}, but with different known actions: '{a.KnownActionType}' and '{b.KnownActionType}'."); } switch (a.KnownActionType) { case KnownActions.Create: return(new CreateAction(a.FullName, a.Description, a.SupportsBulk || b.SupportsBulk)); case KnownActions.UpdateInsert: return(new UpsertAction(a.FullName, a.Description, a.SupportsBulk || b.SupportsBulk)); case KnownActions.Query: return(new QueryAction()); case KnownActions.Update: return(new UpdateAction( a.FullName, a.Description, a.SupportsBulk || b.SupportsBulk, a.SupportsMultipleRecordOperations || b.SupportsMultipleRecordOperations)); case KnownActions.Delete: return(new DeleteAction( a.FullName, a.Description, a.SupportsBulk || b.SupportsBulk, a.SupportsMultipleRecordOperations || b.SupportsMultipleRecordOperations)); case KnownActions.NativeQuery: return(new NativeQueryAction()); case KnownActions.CreateWith: return(new CreateWithAction(a.FullName, a.Description, a.SupportsBulk || b.SupportsBulk)); case KnownActions.UpdateWith: return(new UpdateWithAction( a.FullName, a.Description, a.SupportsBulk || b.SupportsBulk, a.SupportsMultipleRecordOperations || b.SupportsMultipleRecordOperations)); case KnownActions.None: case KnownActions.InsertUpdate: default: throw new NotSupportedException( $"Metadata reflection does not support {a.KnownActionType}"); } throw new NotSupportedException( $"There are two actions named {a.FullName}, but with different known actions: '{a.KnownActionType}' and '{b.KnownActionType}'."); }
public static bool UserCan(UserDef user, ActionDef action) { switch (action) { case ActionDef.CRUDProfile: { return (user._role == RoleDef.Administrator); } case ActionDef.CRUDDataset: case ActionDef.CRUDSchema: case ActionDef.CRUDDomain: { return (user._role == RoleDef.Administrator || user.ProFlag); } case ActionDef.DefaultProc: { return (user._role == RoleDef.Administrator || user._role == RoleDef.Operator); } } return false; }
protected override void process(Entity entity) { Projectile projectile = (Projectile)p_ProjectileMapper.get(entity); projectile.ElapsedTime += ecs_instance.ElapsedTime; //is it time for the projectile to die? if (projectile.ElapsedTime >= projectile.LifeTime) { ecs_instance.delete_entity(entity); return; } Position position = (Position)p_PositionMapper.get(entity); Velocity velocity = (Velocity)p_VelocityMapper.get(entity); Heading heading = (Heading)p_HeadingMapper.get(entity); SpatialPartition spatial = (SpatialPartition)p_SpatialMapper.get(p_Spatial); Vector2 pos = position.Pos; //List<Entity> locals = spatial.QuadTree.retrieveContentsAtLocation(pos); List <Entity> locals = spatial.QuadTree.findAllWithinRange(pos, 32); //anything retrieved? if (locals != null) { //anyone aruond? if (locals.Count > 0) { //for all the locals see if we should do anything for (int i = 0; i < locals.Count; i++) { //dont interact with whom fired you if (locals[i] == projectile.Originator) { continue; } Life life = (Life)p_LifeMapper.get(locals[i]); //if no life, uh, don't check for it... if (life == null) { continue; } //if target is dead, dont worry if (!life.IsAlive) { continue; } //is there an interaction available? Interactable interaction = (Interactable)p_InteractionMapper.get(locals[i]); if (interaction != null) { //get this local's position Position localPosition = (Position)p_PositionMapper.get(locals[i]); //are we close to it? //23 - minimal radial distance for collision to occur if (Vector2.Distance(pos + position.Offset, localPosition.Pos + localPosition.Offset) < 23) { //can we do anything to it? if (interaction.SupportedInteractions.PROJECTILE_COLLIDABLE && interaction.SupportedInteractions.ATTACKABLE) { Factions lfactions = (Factions)p_FactionMapper.get(locals[i]); Factions pfactions = (Factions)p_FactionMapper.get(projectile.Originator); if (lfactions.OwnerFaction.FactionType == pfactions.OwnerFaction.FactionType) { continue; } //UtilFactory.createAttack(projectile.Originator, locals[i], AttackType.Projectile); ActionDef def = GameConfig.ActionDefs["RANGED_DMG"]; ActionFactory.createAction(def, projectile.Originator, locals[i]); //destory yourself ecs_instance.delete_entity(entity); return; } } } } } } MapCollidable mapCollide = (MapCollidable)p_MapCollidableMapper.get(entity); if (mapCollide != null) { if (mapCollide.Collided) { /* * Vector2 norm = mapCollide.ResponseVector; * norm.Normalize(); * Vector2 reflect = Vector2.Reflect(heading.getHeading(), norm); * reflect.Normalize(); * * //Transform trans = (Transform)p_TransformMapper.get(entity); * * //trans.Rotation = -VectorHelper.getAngle2(new Vector2(1,0), reflect); * * heading.setHeading(reflect); */ UtilFactory.createSound("audio\\effects\\hitwall", true, 0.5f); ecs_instance.delete_entity(entity); } } pos += heading.getHeading() * velocity.Vel; position.Pos = pos; }
private static string GetActionField(ActionDef action, ActionDef def, string key) => action.TryGetValue(key, out object val) || def?.TryGetValue(key, out val) == true ? TrimAndLower(val as string) : null;
private static GameEffectWorldMethod CreateMethod_ShootGems(string itemDefId, int gemCost, int duration) { return(delegate(EffectContext context) { /* ######################################### * Check if there is enough money to shoot #########################################*/ if (!LazySingletonBehavior <NetworkManager> .Instance.IsSimulationServer) { return; } Actor wielder = context.sourceActor; if (wielder.IsRemoteSimulation) { return; } WeaponBody weapon = context.sourceWeapon; ActionDef action = context.sourceAction; int num = 0; if (weapon != null) { string ammoId = weapon.ItemDef.ammoId; num = weapon.GetAmmoUse(action); Inventory inventory = Inventory.Get(wielder.gameObject, true); int playerGems = inventory.GetCurrency("Gem1"); // (For Ammo system) Checks if the weapon uses ammo and the rounds used are 0 or greater if (num >= 0 && !string.IsNullOrEmpty(ammoId)) { //Inventory inventory = Inventory.Get(wielder.gameObject); if (inventory == null || !inventory.HasAmmo(ammoId, num)) { //Debug.Log("Not playing NO AMMO animation."); wielder.thisAnimator.SetTrigger(wielder.Body.thisAnimator.GetControlId("AttackEmpty")); return; } if (num > 0) { inventory.RemoveAmmo(ammoId, num); } inventory.UpdateRangedSlot(); } // (For consuming gems without an ammo system) if cost of gem projectile <= to player's bank account... if (gemCost <= playerGems) { // remove cost of gem projectile //Debug.Log("The Ambassador bribes its enemy to death."); inventory.RemoveCurrency("Gem1", gemCost); // Maybe give the amount returned by RemoveCurrency() to context.targetActor? } else { // Uncomment the line below to trigger a NO AMMO animation if there isn't enough money. // wielder.thisAnimator.SetTrigger(wielder.Body.thisAnimator.GetControlId("AttackEmpty")); //Debug.Log("Ain't got no gems."); return; } } /* ######################################### * Handle the business of shooting #########################################*/ ItemDef itemDef = LazySingletonBehavior <DataManager> .Instance.Items.Get(itemDefId); num = ((num <= 0) ? 1 : num); int count = 0; Vector3 position = weapon.transform.position; Quaternion rotation = weapon.transform.rotation; for (int i = 0; i < num; i++) { PrefabManager.InstantiatePrefab(itemDef.prefabName, false, null, position, rotation, delegate(GameObject go) { Projectile component = go.GetComponent <Projectile>(); if (component == null) { //GameEffectManager.log.Error("Item \"" + itemDefId + "\" doesn't have a valid projectile prefab: " + go.name, go); Debug.LogError("Item \"" + itemDefId + "\" doesn't have a valid projectile prefab: " + go.name, go); go.Despawn(); return; } Vector3 zero = Vector3.zero; float num2 = 1f; if (count++ > 0) { zero = new Vector3((UnityEngine.Random.value - 0.5f) * num2, (UnityEngine.Random.value - 0.5f) * num2, (UnityEngine.Random.value - 0.5f) * num2); } go.SetActive(true); component.Initialize(itemDef, wielder, weapon, action, wielder.TargetObject, duration, zero, Projectile.ProjectileType.Shoot, 0u); }); } }); }
public void ActionToClass(StreamWriter sw, string actionsNamespace, string structNamespace, string contractName, ActionDef action, AbiDef abi) { sw.WriteLine("using Newtonsoft.Json;"); sw.WriteLine("using Ditch.EOS;"); sw.WriteLine($"using {structNamespace};"); sw.WriteLine("using Ditch.EOS.Models;"); sw.WriteLine(); sw.WriteLine($"namespace {actionsNamespace}"); sw.WriteLine("{"); var inden = new string(' ', 4); sw.WriteLine($"{inden}[JsonObject(MemberSerialization.OptIn)]"); sw.WriteLine($"{inden}public class {action.Name.ToTitleCase()}Action : BaseAction"); sw.WriteLine($"{inden}{{"); sw.WriteLine($"{inden}{inden}public const string ContractName = \"{contractName}\";"); sw.WriteLine($"{inden}{inden}public const string ActionName = \"{action.Name}\";"); sw.WriteLine(); sw.WriteLine($"{inden}{inden}public {action.Name.ToTitleCase()}Action() : base(ContractName, ActionName) {{ }}"); sw.WriteLine(); var str = abi.Structs.FirstOrDefault(i => i.Name.Equals(action.Type)); if (str != null && str.Fields.Any()) { sw.WriteLine($"{inden}{inden}public {action.Name.ToTitleCase()}Action(string accountName, Ditch.EOS.Models.PermissionLevel[] permissionLevels, {action.Type.ToTitleCase()} args)"); sw.WriteLine($"{inden}{inden} : base(ContractName, accountName, ActionName, permissionLevels, args) {{ }}"); } else { sw.WriteLine($"{inden}{inden}public {action.Name.ToTitleCase()}Action(string accountName, Ditch.EOS.Models.PermissionLevel[] permissionLevels)"); sw.WriteLine($"{inden}{inden} : base(ContractName, accountName, ActionName, permissionLevels, null) {{ }}"); } sw.WriteLine($"{inden}}}"); sw.WriteLine("}"); }
public void ActionToClass(string outDirPath, string actionsNamespace, string structNamespace, string contractName, ActionDef action, AbiDef abi) { FileStream fs = null; StreamWriter sw = null; try { fs = new FileStream($"{outDirPath}{action.Name.ToTitleCase()}Action.cs", FileMode.OpenOrCreate); sw = new StreamWriter(fs); ActionToClass(sw, actionsNamespace, structNamespace, contractName, action, abi); } finally { sw?.Dispose(); fs?.Dispose(); } }