// IComponent public void Init(DeltinScript deltinScript) { DeltinScript = deltinScript; _waitAsyncQueue = DeltinScript.VarCollection.Assign("waitAsync_queue", true, false); DeltinScript.InitialGlobal.ActionSet.AddAction(_waitAsyncQueue.SetVariable(Element.EmptyArray())); // Rule creator. var rule = new TranslateRule(DeltinScript, "waitAsync", RuleEvent.OngoingGlobal); rule.Conditions.Add(new Condition( Element.Any(_waitAsyncQueue.Get(), ArrayElementTimeSurpassed(Element.ArrayElement())) )); // Get the affected item. var item = DeltinScript.VarCollection.Assign("waitAsync_item", true, false); rule.ActionSet.AddAction(item.SetVariable(Element.FirstOf(Element.Filter( Element.Map(_waitAsyncQueue.Get(), Element.ArrayIndex()), ArrayElementTimeSurpassed(_waitAsyncQueue.Get()[Element.ArrayElement()]) )))); // Activate item lambda. DeltinScript.WorkshopConverter.LambdaBuilder.Call(rule.ActionSet.New(Element.LastOf(_waitAsyncQueue.Get()[item.Get()])), new Functions.Builder.CallInfo(), null); // Remove from queue. rule.ActionSet.AddAction(_waitAsyncQueue.ModifyVariable(Operation.RemoveFromArrayByIndex, item.Get())); // Loop if another item needs to execute on the same tick. rule.ActionSet.AddAction(Element.LoopIfConditionIsTrue()); // Get the rule. DeltinScript.WorkshopRules.Add(rule.GetRule()); }
void GetResolveCurrentRule() { // Create the rule that will get the closest node. TranslateRule getResolveRule = new TranslateRule(DeltinScript, "Pathfinder: Resolve Current", RuleEvent.OngoingPlayer); // The rule will activate when DoGetCurrent is set to true. getResolveRule.Conditions.Add(new Condition((Element)DoGetCurrent.GetVariable(), Operator.Equal, Element.True())); // Set the Current variable to the closest node. getResolveRule.ActionSet.AddAction(Current.SetVariable(ClosestNode(getResolveRule.ActionSet, PlayerPosition()))); // If the OnPathStart hook is null, do the default which is throttling the player to the next node. if (OnPathStart == null) { // Start throttle to the current node. ThrottleEventPlayerToNextNode(getResolveRule.ActionSet); } // Otherwise, use the hook. else { OnPathStart.Invoke(getResolveRule.ActionSet); } // Update IsPathfindStuck data. UpdateStuckDetector(getResolveRule.ActionSet, EventPlayer()); // Reset DoGetCurrent to false. getResolveRule.ActionSet.AddAction(DoGetCurrent.SetVariable(Element.False())); // Add the rule. DeltinScript.WorkshopRules.Add(getResolveRule.GetRule()); }
public SubroutineCatalogItem Initiate() { // Setup the subroutine element. Subroutine subroutine = _deltinScript.SubroutineCollection.NewSubroutine(_context.ElementName); // Create the rule. _subroutineRule = new TranslateRule(_deltinScript, subroutine, _context.RuleName, _context.VariableGlobalDefault); // Setup the return handler. _actionSet = _subroutineRule.ActionSet .ContainVariableAssigner() .SetThisTypeLinker(_context.TypeLinker) .New(_context.Controller.Attributes.IsRecursive); // Create the function builder. var controller = _context.Controller; // Create the parameter handlers. _parameterHandler = controller.CreateParameterHandler(_actionSet, null); // If the subroutine is an object function inside a class, create a variable to store the class object. if (controller.Attributes.IsInstance) { _objectStore = _actionSet.VarCollection.Assign(_context.ObjectStackName, true, !controller.Attributes.IsRecursive); // Set the objectStore as an empty array if the subroutine is recursive. if (controller.Attributes.IsRecursive) { // Initialize as empty array. _actionSet.InitialSet().AddAction(_objectStore.SetVariable(Element.EmptyArray())); // Add to assigner with the last of the objectStore stack being the object instance. _context.ContainingType?.AddObjectVariablesToAssigner(_actionSet.ToWorkshop, Element.LastOf(_objectStore.GetVariable()), _actionSet.IndexAssigner); // Set the actionSet. _actionSet = _actionSet.New(Element.LastOf(_objectStore.Get())).PackThis().New(_objectStore.CreateChild(Element.CountOf(_objectStore.Get()) - 1)); } else { // Add to assigner with the objectStore being the object instance. _context.ContainingType?.AddObjectVariablesToAssigner(_actionSet.ToWorkshop, _objectStore.GetVariable(), _actionSet.IndexAssigner); // Set the actionSet. _actionSet = _actionSet.New(_objectStore.Get()).PackThis().New(_objectStore); } } _functionBuilder = new WorkshopFunctionBuilder(_actionSet, controller); _functionBuilder.ModifySet(a => a.PackThis()); // TODO: is this required? _functionBuilder.SetupReturnHandler(); _parameterHandler.AddParametersToAssigner(_actionSet.IndexAssigner); // Done. return(Result = new SubroutineCatalogItem( subroutine: subroutine, parameterHandler: _parameterHandler, objectStack: _objectStore, returnHandler: _functionBuilder.ReturnHandler)); }
private Rule GetStartRule(DeltinScript deltinScript) { var condition = new Condition( Element.Part <V_CountOf>(Path.GetVariable()), Operators.GreaterThan, 0 ); Element eventPlayer = new V_EventPlayer(); Element eventPlayerPos = Element.Part <V_PositionOf>(eventPlayer); TranslateRule rule = new TranslateRule(deltinScript, Constants.INTERNAL_ELEMENT + "Pathfinder: Move", RuleEvent.OngoingPlayer); IfBuilder isBetween = new IfBuilder(rule.ActionSet, Element.Part <V_And>( Element.Part <V_CountOf>(Path.GetVariable()) >= 2, IsBetween(eventPlayerPos, NextPosition(eventPlayer), PositionAt(eventPlayer, 1)) ) ); isBetween.Setup(); rule.ActionSet.AddAction(Next()); isBetween.Finish(); rule.ActionSet.AddAction(ArrayBuilder <Element> .Build ( LastUpdate.SetVariable(new V_TotalTimeElapsed()), DistanceToNext.SetVariable(Element.Part <V_DistanceBetween>(Element.Part <V_PositionOf>(new V_EventPlayer()), NextPosition(new V_EventPlayer()))), // Element.Part<A_StartFacing>( // new V_EventPlayer(), // Element.Part<V_DirectionTowards>( // new V_EyePosition(), // NextPosition() // ), // new V_Number(700), // EnumData.GetEnumValue(Relative.ToWorld), // EnumData.GetEnumValue(FacingRev.DirectionAndTurnRate) // ), // Move to the next node. Element.Part <A_StartThrottleInDirection>( new V_EventPlayer(), Element.Part <V_DirectionTowards>( new V_EyePosition(), NextPosition(new V_EventPlayer()) // Because of ThrottleRev this will be reevaluated so 'Start Throttle In Direction' only needs to run once. ), new V_Number(1), EnumData.GetEnumValue(Relative.ToWorld), EnumData.GetEnumValue(ThrottleBehavior.ReplaceExistingThrottle), EnumData.GetEnumValue(ThrottleRev.DirectionAndMagnitude) ) )); var result = rule.GetRule(); result.Conditions = new Condition[] { condition }; return(result); }
void TLogTranslateItem_OnAfterRuleLoad(object sender, TranslateEventArgs e) { TranslateRule transrule = (TranslateRule)sender; if (transrule.ID == "L30") { //When we reach the 30 record we reset the discount line number so we can reassign it later if the 30 record has a valid Line (L) item to create DiscountLineNumber = -1; //Reset out counter to keep track of the number of discount line items in the transaction. UniqueDiscountId = 0; } if (transrule.ID == "L60") { XPathNavigator nav = e.CurrentTranslateItem.CreateNavigator(); if (Convert.ToBoolean(nav.Evaluate(GetXpathExpression("string(@type) = '2' and string(@seq_num) = '38'")))) { if (String.IsNullOrEmpty(PolledNetSalesFile)) { PolledNetSalesFile = base.PluginConfig.GetValue("PolledNetSalesFile"); } //NetSales sales = new NetSales(); string netsales = nav.Evaluate(GetXpathExpression("string(@amount)")).ToString(); string storeNum = nav.Evaluate(GetXpathExpression("string(@store_num)")).ToString(); DateTime TransDate = Convert.ToDateTime(nav.Evaluate(GetXpathExpression("string(@trans_date)")).ToString()); WritePolledNetSales(storeNum, netsales, TransDate); } } //This will store the notes for bank deposit and will be added to the output when the translate hits the 52 record if (transrule.ID == "L51") { if (BankNotes == null) { BankNotes = new List <XmlNode>(); } XPathNavigator nav = e.CurrentTranslateItem.CreateNavigator(); int transType = 10; while (transType <= 26) { string strExpr = String.Format("count(following-sibling::L52[@Tender_id_sub1='{0}' and number(@tender_id) = 0]) > 0", transType); if (Convert.ToBoolean(nav.Evaluate(GetXpathExpression(strExpr)))) { string LineNote = String.Format("number(following-sibling::L52[@Tender_id_sub1='{0}' and number(@tender_id) = 0]/@extended_amount)", transType); string NoteType = String.Format("number(100 + number(following-sibling::L52[@Tender_id_sub1='{0}' and number(@tender_id) = 0]/@Tender_id_sub1))", transType); XmlNode BankNote = DestinationDocumentTemplate.SelectSingleNode("//N"); BankNote.Attributes["Line_id"].Value = "0"; BankNote.Attributes["Line_Note"].Value = Convert.ToString(nav.Evaluate(GetXpathExpression(LineNote))); BankNote.Attributes["Line_note_type"].Value = Convert.ToString(nav.Evaluate(GetXpathExpression(NoteType))); BankNotes.Add(BankNote); } transType++; } } }
public CustomMethodBase GetObject(TranslateRule context, ScopeGroup scope, IWorkshopTree[] parameters, Location methodLocation, Location[] parameterLocations) { CustomMethodBase customMethod = GetObject(); customMethod.TranslateContext = context; customMethod.Scope = scope; customMethod.Parameters = parameters; customMethod.ParameterLocations = parameterLocations; customMethod.MethodLocation = methodLocation; return(customMethod); }
void GetNextNodeRule() { // The 'next' rule will set current to the next node index when the current node is reached. TranslateRule next = new TranslateRule(DeltinScript, "Pathfinder: Resolve Next", RuleEvent.OngoingPlayer); next.Conditions.Add(NodeReachedCondition(next.ActionSet)); next.Conditions.Add(new Condition(ParentArray.Get(), Operator.NotEqual, Element.Null())); GetNextNode(next.ActionSet, EventPlayer()); // Loop the next rule if the condition is true. next.ActionSet.AddAction(LoopIfConditionIsTrue()); // Add rule DeltinScript.WorkshopRules.Add(next.GetRule()); }
static float ROUND_RATIO = 150; // the round ratio for dealing with not accurate calculation public static Point applyTranslateRule(Point originalLocation, TranslateRule translateRule) { Point location = new Point(originalLocation.x * 1000, originalLocation.y * 1000, originalLocation.z * 1000); Point vectorToStartingPoint = new Point(location.x - translateRule.startingLocation.x, 0, location.z - translateRule.startingLocation.z); float rotatedx = (float)(vectorToStartingPoint.x * Math.Cos(translateRule.changeInOrientation * Math.PI / 180) + vectorToStartingPoint.y * Math.Sin(translateRule.changeInOrientation * Math.PI / 180)); float rotatedy = (float)(vectorToStartingPoint.y * Math.Cos(translateRule.changeInOrientation * Math.PI / 180) - vectorToStartingPoint.x * Math.Sin(translateRule.changeInOrientation * Math.PI / 180)); Point rotatedPoint = new Point(rotatedx, 0.6f, rotatedy); rotatedPoint.x += translateRule.dX + translateRule.startingLocation.x; rotatedPoint.z += translateRule.dZ + translateRule.startingLocation.z; rotatedPoint.x = (float)Math.Round(rotatedPoint.x * 1000000000) / 1000000000 / 1000; rotatedPoint.z = (float)Math.Round(rotatedPoint.z * 1000000000) / 1000000000 / 1000; return(rotatedPoint); }
public VariableChaseData GetChaseData(IndexedVar var, TranslateRule context) { var existingChaseData = context.ParserData.Chasing.FirstOrDefault(cd => cd.Var == var); if (existingChaseData != null) { return(existingChaseData); } IndexedVar destination = context.VarCollection.AssignVar(null, $"'{var.Name}' chase destination", var.IsGlobal, null); IndexedVar rate = context.VarCollection.AssignVar(null, $"'{var.Name}' chase duration", var.IsGlobal, null); VariableChaseData newChaseData = new VariableChaseData(var, destination, rate); context.ParserData.Chasing.Add(newChaseData); Rule chaseRule = new Rule( Constants.INTERNAL_ELEMENT + "Chase Variable: " + var.Name, var.IsGlobal ? RuleEvent.OngoingGlobal : RuleEvent.OngoingPlayer ); chaseRule.Conditions = new Condition[] { new Condition( rate.GetVariable(), Operators.NotEqual, new V_Number(0) ) }; chaseRule.Actions = ArrayBuilder <Element> .Build( UpdateVariable(var, destination, rate), A_Wait.MinimumWait, new A_LoopIfConditionIsTrue() ); context.ParserData.AdditionalRules.Add(chaseRule); return(newChaseData); }
private void selectTranslatebtn_Click(object sender, RoutedEventArgs e) { if (calibrateRuleStack.Children.Count == 1) { Console.WriteLine(calibrateRuleStack.Children[0].ToString()); string[] translateRuleString = calibrateRuleStack.Children[0].ToString().Split(' '); //Console.WriteLine(translateRuleString[2]); translateRule = new TranslateRule(float.Parse(translateRuleString[4]), float.Parse(translateRuleString[5]), float.Parse(translateRuleString[6]), float.Parse(translateRuleString[7]), float.Parse(translateRuleString[8]), new Point3D(Convert.ToDouble(translateRuleString[9]), Convert.ToDouble(translateRuleString[10]), Convert.ToDouble(translateRuleString[11]))); Console.WriteLine(translateRule.ToString()); updateTranslateRuleLabels(); translateRulePopup.IsOpen = false; string messageBoxText = "Translate Rule is been loaded"; string caption = "Status"; MessageBoxButton button = MessageBoxButton.OK; MessageBoxImage icon = MessageBoxImage.Information; MessageBox.Show(messageBoxText, caption, button, icon); //calibrateRuleStack.Children.RemoveAt(calibrateRuleStack.Children.Count - 1); } }
private void ResetTranslateRule_Click(object sender, RoutedEventArgs e) { MessageBoxResult result = MessageBox.Show("Do you want to reset translate rule?\n", "Confirmation", MessageBoxButton.YesNoCancel); if (result == MessageBoxResult.Yes) { translateRule = new TranslateRule(0, 0, 0, 0, 0, new Point3D(0, 0, 0)); Console.WriteLine("Reset calibration rule:"); Console.WriteLine(JObject.FromObject(translateRule).ToString()); updateTranslateRuleLabels(); // Yes code here } else { // No code here } }
public Point3D applyTranslateRule(Point3D locationInMeters, TranslateRule translateRule) { Point3D location = new Point3D(locationInMeters.X * 1000, locationInMeters.Y * 1000, locationInMeters.Z * 1000); Vector vectorToStartingPoint = new Vector(location.X - translateRule.startingLocation.X, location.Z - translateRule.startingLocation.Z); Point3D rotatedPoint = new Point3D( vectorToStartingPoint.X * Math.Cos(translateRule.changeInOrientation * Math.PI / 180) + vectorToStartingPoint.Y * Math.Sin(translateRule.changeInOrientation * Math.PI / 180),//location.Z * Math.Sin(translateRule.changeInOrientation * Math.PI / 180), 0.6, vectorToStartingPoint.Y * Math.Cos(translateRule.changeInOrientation * Math.PI / 180) - vectorToStartingPoint.X * Math.Sin(translateRule.changeInOrientation * Math.PI / 180));//location.X * Math.Sin(translateRule.changeInOrientation * Math.PI / 180)); rotatedPoint.X += translateRule.dX + translateRule.startingLocation.X; rotatedPoint.Z += translateRule.dZ + translateRule.startingLocation.Z; rotatedPoint.X = Math.Round(rotatedPoint.X * 1000000000) / 1000000000 / 1000; rotatedPoint.Z = Math.Round(rotatedPoint.Z * 1000000000) / 1000000000 / 1000; //Console.WriteLine(locationInMeters.Y); return rotatedPoint; }
public RegisterCapsule(string sensorType, float FOV, int rangeInMM, TranslateRule rule) { this.sensorType = sensorType; this.FOV = FOV; this.rangeInMM = rangeInMM; this.translateRule = rule; if (sensorType == "Kinect1") { this.frameHeight = 480; this.frameWidth = 640; } else if (sensorType == "Kinect2") { this.frameHeight = 424; this.frameWidth = 512; } }
public void SubscribeToRoutes(Client socket) { socket.On("connect", (fn) => { Console.WriteLine("\r\nConnected ...\r\n"); TellServerAboutSensor(); }); socket.On("getFrameFromSensor", (fn) => { Console.WriteLine("GOT A CALIBRATION CALL"); BroadcastCapsule broadcastData; if (kinectSensor != null) { broadcastData = new BroadcastCapsule("setCalibrationFrame", depthRenderer2.frameData); } else { //no Kinect sensor detected? error? broadcastData = new BroadcastCapsule("setCalibrationFrame", ""); } socket.Emit("broadcast", broadcastData); }); socket.On("setTranslateRule", (fn) => { var results = JsonConvert.DeserializeObject<dynamic>(fn.Json.ToJsonString()); Console.WriteLine(results); Console.WriteLine(fn.Json.Args[0].startingLocation); translateRule = new TranslateRule((float)fn.Json.Args[0].degree, (float)fn.Json.Args[0].xDistance, (float)fn.Json.Args[0].zDistance, (float)fn.Json.Args[0].xSpaceTransition, (float)fn.Json.Args[0].zSpaceTransition, JsonConvert.DeserializeObject<Point3D>(fn.Json.Args[0].startingLocation + "")); //update rule display on UI /* lblCalibrationOrientation.Content = "Change in Orientation: " + translateRule.changeInOrientation; lblCalibrationPoint.Content = "dX, dZ: " + translateRule.dX + ", " + translateRule.dZ; lblCalibrationTranslation.Content = "xTran, zTran: " + translateRule.xSpace + ", " + translateRule.zSpace; lblCalibrationStartingLocation.Content = "Starting Location: " + translateRule.startingLocation.X + ", " + translateRule.startingLocation.Y + ", " + translateRule.startingLocation.Z; Console.WriteLine("New calibration rule:"); Console.WriteLine(JObject.FromObject(translateRule).ToString()); */ updateTranslateRuleLabels(); }); socket.On("resetRule", (fn) => { translateRule = new TranslateRule(0, 0, 0, 0, 0, new Point3D(0, 0, 0)); Console.WriteLine("Reset calibration rule:"); Console.WriteLine(JObject.FromObject(translateRule).ToString()); updateTranslateRuleLabels(); }); }
private void GetResolveRoutine() { // Create the rule that will get the closest node. TranslateRule getResolveRule = new TranslateRule(DeltinScript, "Pathfinder: Resolve Current", RuleEvent.OngoingPlayer); // The rule will activate when DoGetCurrent is set to true. getResolveRule.Conditions.Add(new Condition((Element)DoGetCurrent.GetVariable(), Operators.Equal, new V_True())); // Set the Current variable to the closest node. getResolveRule.ActionSet.AddAction(Current.SetVariable(ClosestNode(getResolveRule.ActionSet, PlayerPosition()))); // If the OnPathStart hook is null, do the default which is throttling the player to the next node. if (OnPathStart == null) { // Start throttle to the current node. ThrottleEventPlayerToNextNode(getResolveRule.ActionSet); } // Otherwise, use the hook. else { OnPathStart.Invoke(getResolveRule.ActionSet); } // Update IsPathfindStuck data. UpdateStuckDetector(getResolveRule.ActionSet); // Reset DoGetCurrent to false. getResolveRule.ActionSet.AddAction(DoGetCurrent.SetVariable(new V_False())); // Add the rule. DeltinScript.WorkshopRules.Add(getResolveRule.GetRule()); // Resolve the rule that increments the current node. // The 'next' rule will set current to the next node index when the current node is reached. TranslateRule next = new TranslateRule(DeltinScript, "Pathfinder: Resolve Next", RuleEvent.OngoingPlayer); next.Conditions.Add(NodeReachedCondition(next.ActionSet)); next.Conditions.Add(new Condition(ParentArray.Get(), Operators.NotEqual, new V_Null())); if (OnPathCompleted == null || !OnPathCompleted.EmptyBlock) { next.ActionSet.AddAction(Element.Part <A_If>(new V_Compare(Current.Get(), Operators.NotEqual, new V_Number(-1)))); } // Get last attribute. next.ActionSet.AddAction(CurrentAttribute.SetVariable(NextSegmentAttribute(new V_EventPlayer()))); // Set current as the current's parent. next.ActionSet.AddAction(Current.SetVariable(ParentArray.Get()[Current.Get()] - 1)); // Update stuck UpdateStuckDetector(next.ActionSet); // Invoke OnNodeReached OnNodeReached?.Invoke(next.ActionSet); if (OnPathCompleted == null || !OnPathCompleted.EmptyBlock) { next.ActionSet.AddAction(Element.Part <A_Else>()); } if (OnPathCompleted == null) { next.ActionSet.AddAction(Element.Part <A_StopThrottleInDirection>(new V_EventPlayer())); StopPathfinding(next.ActionSet, new V_EventPlayer()); } else if (!OnPathCompleted.EmptyBlock) { OnPathCompleted.Invoke(next.ActionSet); } if (OnPathCompleted == null || !OnPathCompleted.EmptyBlock) { next.ActionSet.AddAction(Element.Part <A_End>()); } // Add rule DeltinScript.WorkshopRules.Add(next.GetRule()); }