protected void OnEnable() { this.tracker.AddOnNewDetectedDelegate(this.OnNewDetected); if (this._ignoreList.Count == 0) return; // Unless this is a AreaTargetTracker. Stop here. if (this.tracker.area == null) return; // Sync the ignore list with the TargetTracker by removing any ignore targetables. var areaListCopy = new TargetList(this.tracker.area); for (int i = 0; i < areaListCopy.Count; i++) { this.currentTargetable = areaListCopy[i].targetable; if (this.currentTargetable == null) continue; if (this._ignoreList.Contains(this.currentTargetable)) { this.tracker.area.Remove(this.currentTargetable); } } }
//constructors public ARPListener(LivePacketDevice device) : base(device) { base.Filter = "arp"; _targets = new TargetList(); _gateways = new TargetList(); }
private void FilterTrackerTargetList(TargetList targets) { // Quit if the mask is set to nothing == OFF if (this.targetTrackerLayerMask.value == 0) return; Vector3 fromPos = this.tracker.perimeter.transform.position; LayerMask mask = this.targetTrackerLayerMask; this.FilterTargetList(targets, mask, fromPos, Color.red); }
/// <summary> /// Concrete response for target list replies /// </summary> /// <param name="input">The byte representation of the reply</param> public TargetListResponse(byte[] input) { TargetObject = TargetList.CreateBuilder().MergeFrom(input).Build(); data = new List<TargetEntry>(); foreach (targetentry entry in TargetObject.ThistargetList) { data.Add(new TargetEntry(entry.Text.Text, entry.Text.TopLeftY, entry.Text.TopLeftX, entry.Text.Height, entry.Text.Width)); Console.WriteLine(entry.Text.Text); Console.WriteLine(entry.Text.TopLeftX); Console.WriteLine(entry.Text.TopLeftY); Console.WriteLine(entry.Text.Width); Console.WriteLine(entry.Text.Height); } }
protected void FilterTrackerTargetList(TargetTracker source, TargetList targets) { // Quit if the mask is set to nothing == OFF if (this.targetTrackerLayerMask.value == 0) return; Vector3 fromPos; if (this.tracker.area != null) fromPos = this.tracker.area.transform.position; else fromPos = this.tracker.transform.position; LayerMask mask = this.targetTrackerLayerMask; this.FilterTargetList(targets, mask, fromPos, Color.red); }
private void FilterFireTargetList(TargetList targets) { // Quit if the mask is set to nothing == OFF if (this.fireControllerLayerMask.value == 0) return; Vector3 fromPos; if (this.fireCtrl.emitter != null) fromPos = this.fireCtrl.emitter.position; else fromPos = this.fireCtrl.transform.position; LayerMask mask = this.fireControllerLayerMask; this.FilterTargetList(targets, mask, fromPos, Color.yellow); }
private void Target_Edit_Click(object sender, EventArgs e) { try { Int32 selectedCellCount = TargetList.GetCellCount(DataGridViewElementStates.Selected); if (selectedCellCount > 0) { int index = TargetList.SelectedRows[0].Index; string TargetName = Convert.ToString(TargetList.Rows[index].Cells["mTargetName"].Value); if (PS4.Dialogs.EditTarget(TargetName) == DialogResult.OK) { UpdateTargetList(); } } } catch { } }
public void CancelTarget(long entityId) { m_constructionBlock.ParticleManager.CancelTarget(entityId); foreach (var item in m_targetTracker.ToList()) { if (item.Key.EntityId == entityId) { m_targetTracker.Remove(item.Key); } } foreach (IMyEntity item in TargetList.Where(x => ((IMyEntity)x).EntityId == entityId)) { Logging.Instance.WriteLine(string.Format("[Floating] Cancelling Floating Object Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, item.EntityId, item.GetPosition()), 1); } TargetList.RemoveAll(x => ((IMyEntity)x).EntityId == entityId); PotentialTargetList.RemoveAll(x => ((IMyEntity)x).EntityId == entityId); }
public Program() { { targetList = new TargetList(this); controller = (IMyShipController)(GridTerminalSystem.GetBlockWithName(Controller)); designator = (IMyShipController)(GridTerminalSystem.GetBlockWithName(PodDesignator)); GridTerminalSystem.SearchBlocksOfName(Cockpit, Cockpits, x => x is IMyShipController); r_azimuth = (IMyMotorStator)(GridTerminalSystem.GetBlockWithName(Azimuth)); r_elevation = (IMyMotorStator)(GridTerminalSystem.GetBlockWithName(Elevation)); var Gyros = new List <IMyGyro>(); GridTerminalSystem.GetBlocksOfType(Gyros, x => (x.CustomName.Contains(Gyro) && x.CubeGrid == controller.CubeGrid)); Gyroscopes = new GyroscopeSystem(Gyros, controller); GridTerminalSystem.GetBlocksOfType(TForward, (x => (x.CubeGrid == controller.CubeGrid || x.CustomName.Contains("S_Thruster")) && (controller.WorldMatrix.Forward.Dot(x.WorldMatrix.Backward) > 0.65))); GridTerminalSystem.GetBlocksOfType(TBackward, (x => (x.CubeGrid == controller.CubeGrid || x.CustomName.Contains("S_Thruster")) && (controller.WorldMatrix.Backward.Dot(x.WorldMatrix.Backward) > 0.65))); GridTerminalSystem.GetBlocksOfType(TRight, (x => (x.CubeGrid == controller.CubeGrid || x.CustomName.Contains("S_Thruster")) && (controller.WorldMatrix.Right.Dot(x.WorldMatrix.Backward) > 0.65))); GridTerminalSystem.GetBlocksOfType(TLeft, (x => (x.CubeGrid == controller.CubeGrid || x.CustomName.Contains("S_Thruster")) && (controller.WorldMatrix.Left.Dot(x.WorldMatrix.Backward) > 0.65))); GridTerminalSystem.GetBlocksOfType(TUp, (x => (x.CubeGrid == controller.CubeGrid || x.CustomName.Contains("S_Thruster")) && (controller.WorldMatrix.Up.Dot(x.WorldMatrix.Backward) > 0.65))); GridTerminalSystem.GetBlocksOfType(TDown, (x => (x.CubeGrid == controller.CubeGrid || x.CustomName.Contains("S_Thruster")) && (controller.WorldMatrix.Down.Dot(x.WorldMatrix.Backward) > 0.65))); var TurretCores = new List <IMyTerminalBlock>(); GridTerminalSystem.SearchBlocksOfName(CoreName, TurretCores); foreach (IMyTerminalBlock core in TurretCores) { Turret turret = new Turret(core, controller); Turrets.Add(turret); } initcounter = Turrets.Count; GridTerminalSystem.GetBlocksOfType(Designators); initcounter = Turrets.Count; } }
private IContextMenuTarget FindUpTarget(TargetList targets, Rectangle currentRect) { // We compare from the top edge always currentRect.Height = 0; // Best match found so far IContextMenuTarget nextTarget = null; Rectangle nextRect = Rectangle.Empty; // Search all targets, looking for a better match than the current best foreach (IContextMenuTarget target in targets) { Rectangle targetRect = target.ClientRectangle; // Only interested in targets that are above the current one if (targetRect.Bottom <= currentRect.Top) { // It nothing found so far, it automatically becomes the best match if (nextTarget == null) { nextTarget = target; nextRect = targetRect; } else { double currentDistance = CenterDistance(currentRect, new Rectangle(nextRect.X, nextRect.Bottom, nextRect.Width, 0)); double nextDistance = CenterDistance(currentRect, new Rectangle(targetRect.X, targetRect.Bottom, targetRect.Width, 0)); // If next target is nearer than the current best... if (nextDistance < currentDistance) { //...then it becomes the new best match nextTarget = target; nextRect = targetRect; } } } } return(nextTarget); }
public override void Update() { foreach (var item in TargetList.ToList()) { var block = item as IMySlimBlock; if (block != null) { ProcessItem(block); } } foreach (var item in TempPhysicless.ToList()) { if (DateTime.Now - item.Value > TimeSpan.FromSeconds(10)) { if (item.Key.Closed) { TempPhysicless.Remove(item.Key); continue; } if (!item.Key.Closed && item.Key.Physics != null) { item.Key.Physics.LinearVelocity = Vector3.Zero; item.Key.Physics.AngularVelocity = Vector3.Zero; item.Key.Physics.LinearDamping = 0.0f; item.Key.Physics.AngularDamping = 0.0f; /* * MyAPIGateway.Utilities.InvokeOnGameThread(() => * { * item.Key.Physics.LinearVelocity = Vector3.Zero; * item.Key.Physics.AngularVelocity = Vector3.Zero; * }); */ } TempPhysicless.Remove(item.Key); } } }
private void RemoveGridTarget(IMyCubeGrid grid) { foreach (var item in m_validBeaconedGrids) { if (item.MainGrid == grid) { foreach (var block in item.RemoveList) { PotentialTargetList.Remove(block); TargetList.Remove(block); } m_validBeaconedGrids.Remove(item); break; } } if (m_areaTargetBlocks.ContainsKey(grid)) { m_areaTargetBlocks.Remove(grid); } }
public void AttackTargets(bool Maintarg) { //SendConsole("first sort", ConsoleLvl.High); // showTargetlist(); //SendConsole("--sort", ConsoleLvl.High); if (!Maintarg) { TargetList.Sort(); Cible = TargetList[0].Target; } else { Cible = MainTargetList.Peek().Target; } if (Cible != null) { Cible.Target(); deplacement(Cible); if (Cible.StartedCombat == false) { if (waitTimePreCombat != 0) { Thread.Sleep(waitTimePreCombat); } PreCombatRoutine(); Thread.Sleep(this.PreCombatTick); } CombatRoutine(Cible); } else { SendConsole("No Cible Selected Error", ConsoleLvl.High); } Cible = null; CibleI = 9999; }
protected override void CombatRoutine(GUnit Cible) { while (Cible.IsAlive && localPlayer.IsAlive) { if (BreakCurActionB == true) { BreakCurActionB = false; break; } LuaVM.DoString(LuaHelp.AttackingTarget); Repositionnement(Cible); if (!Cible.inCombat || !localPlayer.inCombat) { Cible.Target(); Thread.Sleep(100); } Thread.Sleep(200); TargetList.Sort(); } }
private void Target_Delete_Click(object sender, EventArgs e) { try { Int32 selectedCellCount = TargetList.GetCellCount(DataGridViewElementStates.Selected); if (selectedCellCount > 0) { int index = TargetList.SelectedRows[0].Index; string TargetName = Convert.ToString(TargetList.Rows[index].Cells["mTargetName"].Value); if (DarkMessageBox.ShowInformation("Are you sure you want to delete Target \"" + TargetName + "\"?", "Delete Target?", DarkDialogButton.YesNo) == DialogResult.Yes) { PS4.Target[TargetName].Delete(); UpdateTargetList(); } } } catch { } }
/// <summary> /// Handle right key being pressed. /// </summary> public void KeyRight() { TargetList targets = ConstructKeyboardTargets(Root); // Find the next appropriate target IContextMenuTarget newTarget = null; if (_target == null) { newTarget = FindTopLeftTarget(targets); } else { newTarget = FindRightTarget(targets, _target); } // If we found a new target, then make it the current target if ((newTarget != null) && (newTarget != _target)) { SetTarget(newTarget, false); } }
private void AddTarget(object obj) { if (SelectedTarget.Id == 0) { int periodValue = 0; switch (SelectedTarget.TargetType) { case TargetType.Year: periodValue = CurrentYear.Data; break; case TargetType.Month: periodValue = currentMonth.Data.Key; break; case TargetType.Week: periodValue = CurrentWeek.Data.Key; break; case TargetType.Day: periodValue = CurrentDay.Data.Key; break; } Target newTarget = new Target(SelectedTarget.Name, SelectedTarget.Description, SelectedTarget.TargetType, CurrentYear.Data, periodValue, SelectedTarget.LastDate, SelectedTarget.Important, null); newTarget.Tasks = SelectedTarget.Tasks; TargetList.Add(newTarget); } else { TargetList.Edit(SelectedTarget); } CloseAction(); }
private void FilterFireTargetList(TargetList targets) { // Quit if the mask is set to nothing == OFF if (this.fireControllerLayerMask.value == 0) { return; } Vector3 fromPos; if (this.fireCtrl.emitter != null) { fromPos = this.fireCtrl.emitter.position; } else { fromPos = this.fireCtrl.transform.position; } LayerMask mask = this.fireControllerLayerMask; this.FilterTargetList(targets, mask, fromPos, Color.yellow); }
public void InitPortfolio(IPortfolio portfolio) { TargetPortfolio = portfolio; //TargetList.Clear(); if (portfolio != null) { portfolio.PositionList.ForEach(v => { var pos = TargetList.FirstOrDefault(x => x.TargetTicker == v.Name); if (pos == null) { PosWeightTarget posweight = new PosWeightTarget(); posweight.TargetTicker = v.Name; posweight.Shares = v.Shares; posweight.CurrentPrice = v.CurrentPrice; posweight.CurrentWeight = v.CurrentValue / portfolio.CurrentValue; posweight.DataTime = v.DataTime; posweight.CurrentCurrency = v.CurrentCurrency; posweight.TargetPortfolioName = portfolio.Name; TargetList.Add(posweight); } }); } }
public override void Do() { int insertId = _insertId + 1; if (_isDoed) { foreach (var lyric in _addItems) { TargetList.Insert(insertId++, lyric); } } else { foreach (var lyric in Positions.Values.OrderBy(l => l).ToList()) { var time = _isBig ? lyric.Time - _interpolation : lyric.Time + _interpolation; var addItem = new Lyric(time, lyric.Content); _addItems.Add(addItem); TargetList.Insert(insertId++, addItem); } } _isDoed = true; }
/// <summary> /// Handles all firing events including target aquisition and firing. /// Events are: /// OnStart() : /// Runs once when the firing system first becomes active /// OnUpdate() : /// Runs each frame while the firing system is active /// OnTargetUpdate() : /// Runs each frame while tracking a target (there is at least one target.) /// OnIdleUpdate() : /// Runs each frame while the firing system is idle (no targets) /// OnFire() : /// Runs when it is time to fire. /// /// Counter Behavior Notes: /// * If there are no targets. the counter will keep running up. /// This means the next target to enter will be fired upon /// immediatly. /// /// * The counter is always active so if the last target exits, then a /// new target enters right after that, there may still be a wait. /// </summary> protected IEnumerator FiringSystem() { if (this.targetTracker == null) { this.targetTracker = this.GetComponent<TargetTracker>(); if (this.targetTracker == null) { // Give it a frame to see if this.targetTracker is being set by code. yield return null; if (this.targetTracker == null) throw new MissingComponentException ( "FireControllers must be on the same GameObject as a TargetTracker " + "or have it's targetTracker property set by code or drag-and-drop " + "in the inspector." ); } } // While (true) because of the timer, we want this to run all the time, not // start and stop based on targets in range if (this.initIntervalCountdownAtZero) this.fireIntervalCounter = 0; else this.fireIntervalCounter = this.interval; this.targets.Clear(); this.OnStart(); // EVENT TRIGGER this.keepFiring = true; // Can be turned off elsewhere to kill the firing system while (this.keepFiring) { // if there is no target, counter++, handle idle behavior, and // try next frame. // Will init this.targets for child classes as well. this.targets = new TargetList(this.targetTracker.targets); if (this.targets.Count != 0) { if (this.fireIntervalCounter <= 0) { // Let the delegate filter a copy of the list just for the OnFire // Test. We still want this.targets to remain as is. // Do this in here to still trigger OnTargetUpdate this.targetsCopy.Clear(); this.targetsCopy.AddRange(this.targets); if (targetsCopy.Count != 0 && this.onPreFireDelegates != null) this.onPreFireDelegates(this.targetsCopy); // If all is right, fire // Check targetsCopy incase of pre-fire delegate changes if (targetsCopy.Count != 0) { this.Fire(); this.fireIntervalCounter = this.interval; // Reset } } // Update event while tracking a target this.OnTargetUpdate(this.targets); // EVENT TRIGGER } else { // Update event while NOT tracking a target this.OnIdleUpdate(); // EVENT TRIGGER } this.fireIntervalCounter -= Time.deltaTime; // Update event no matter what this.OnUpdate(); // EVENT TRIGGER // Stager calls to get Target (the whole system actually) yield return null; } // Wipe out the target list when stopped this.targets.Clear(); }
public static void AddTargetEntry(this TargetList targetList, TargetEntry entry) { targetList.Add(entry.Target, (uint)entry.Flags, (uint)entry.Info); }
/// <summary> /// Fire on the targets /// </summary> private void OnFire() { // Log a message to show what is being fired on if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format("Firing on: {0}\nHitEffects{1}", this.targetsString, this.effectsOnTarget.ToString()); Debug.Log(string.Format("{0}: {1}", this, msg)); } // Create a new list of targets which have this target tracker reference. var targetCopies = new TargetList(); Target target; foreach (Target inTarget in this.targets) { // Can't edit a struct in a foreach loop, so need to copy and store target = new Target(inTarget); target.fireController = this; // Add reference. null before t targetCopies.Add(target); switch (this.notifyTargets) { case NOTIFY_TARGET_OPTIONS.Direct: target.targetable.OnHit(this.effectsOnTarget, target); this.SpawnAmmunition(target, false, false); break; case NOTIFY_TARGET_OPTIONS.PassToProjectile: this.SpawnAmmunition(target, true, true); break; case NOTIFY_TARGET_OPTIONS.UseProjectileEffects: this.SpawnAmmunition(target, true, false); break; } if (this.notifyTargets > NOTIFY_TARGET_OPTIONS.Off) { // Just for debug. Show a gizmo line when firing if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(this.emitter.position, target.transform.position, Color.red); } } // Write the result over the old target list. This is for output so targets // which are handled at all by this target tracker are stamped with a // reference. this.targets = targetCopies; // Trigger the delegates if (this.onFireDelegates != null) this.onFireDelegates(this.targets); }
public override void FindTargets(ref Dictionary <string, int> available) { if (!IsEnabled()) { return; } if (TargetList.Count >= GetMaximumTargets()) { if (PotentialTargetList.Count > 0) { m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!"; } return; } using (Lock.AcquireExclusiveUsing()) { for (int r = PotentialTargetList.Count - 1; r >= 0; r--) { if (m_constructionBlock.IsUserDefinedLimitReached()) { m_lastInvalidTargetReason = "User defined maximum nanite limit reached"; return; } var item = (IMyPlayer)PotentialTargetList[r]; if (TargetList.Contains(item)) { continue; } if (item.Controller == null || item.Controller.ControlledEntity == null || item.Controller.ControlledEntity.Entity == null) { PotentialTargetList.RemoveAt(r); continue; } var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); bool found = false; foreach (var block in blockList) { if (block.Targets.First(x => x is NaniteMedicalTargets).TargetList.Contains(item)) { found = true; break; } } if (found) { m_lastInvalidTargetReason = "Another factory has this block as a target"; continue; } if (Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), item.GetPosition()) < m_maxDistance * m_maxDistance && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { TargetList.Add(item); Logging.Instance.WriteLine(string.Format("ADDING Medical Target: conid={0} type={1} playerName={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, item.GetType().Name, item.DisplayName, item.GetPosition())); if (TargetList.Count >= GetMaximumTargets()) { break; } } } } }
private void OnFire() { if (this.debugLevel > DEBUG_LEVELS.Off) { string arg = string.Format("Firing on: {0}\nHitEffects{1}", this.targetsString, this.effectsOnTarget.ToString()); UnityEngine.Debug.Log(string.Format("{0}: {1}", this, arg)); } TargetList targetList = new TargetList(); foreach (Target current in this.targets) { Target target = new Target(current); target.fireController = this; targetList.Add(target); switch (this.notifyTargets) { case FireController.NOTIFY_TARGET_OPTIONS.Direct: target.targetable.OnHit(this.effectsOnTarget, target); this.SpawnAmmunition(target, false, false); break; case FireController.NOTIFY_TARGET_OPTIONS.PassToProjectile: this.SpawnAmmunition(target, true, true); break; case FireController.NOTIFY_TARGET_OPTIONS.UseProjectileEffects: this.SpawnAmmunition(target, true, false); break; } if (this.notifyTargets > FireController.NOTIFY_TARGET_OPTIONS.Off && this.debugLevel > DEBUG_LEVELS.Off) { UnityEngine.Debug.DrawLine(this.emitter.position, target.transform.position, Color.red); } } this.targets = targetList; if (this.onFireDelegates != null) { this.onFireDelegates(this.targets); } }
protected void FilterFireCtrlTargetList(TargetList targets) { if (this.filterType == FILTER_TYPE.WaitToFireEvent) this.FilterTargetList(targets); // Else do nothing. }
/// <summary> /// Destroys the projectile on impact and finds objects in range to /// affect if they share the same tag as target. /// </summary> public void DetonateProjectile() { // Prevent being run more than once in a frame where it has already // been destroyed. if (!this.gameObject.activeInHierarchy) return; // Build a new list of targets depending on the options used var targetList = new TargetList(); if (this.areaHit) { // This is turned back off OnDisable() (base class) this.perimeter.enabled = true; targetList.AddRange(this.targets); // Add all targets in range } else { if (this.target != Target.Null) targetList.Add(this.target); // Add projectile target } if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format("Detonating with targets: {0}", targetList); Debug.Log(string.Format("Projectile ({0}): {1}", this.name, msg)); } // Create a new list of targets which have this target tracker reference. // This is for output so targets which are handled at all by this Projectile // are stamped with a reference. var targetCopies = new TargetList(); Target target; foreach (Target inTarget in targetList) { if (inTarget == Target.Null) continue; // Can't edit a struct in a foreach loop, so need to copy and store target = new Target(inTarget); target.projectile = this; // Add reference. null before t targetCopies.Add(target); switch (this.notifyTargets) { case NOTIFY_TARGET_OPTIONS.Direct: target.targetable.OnHit(this.effectsOnTarget, target, this.collider); break; } // Just for debug. Show a gizmo line when firing if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine ( this.xform.position, target.transform.position, Color.red ); } switch (this.notifyTargets) { case NOTIFY_TARGET_OPTIONS.Direct: this.SpawnDetonatorPrefab(false); break; case NOTIFY_TARGET_OPTIONS.PassToDetonator: this.SpawnDetonatorPrefab(true); break; } // Trigger delegates if (this.OnDetonationDelegates != null) this.OnDetonationDelegates(targetCopies); // Clean-up in case this instance is used in a pooling system like PoolManager this.target = Target.Null; InstanceManager.Despawn(this.transform); }
public void Should_return_valid_target_list() { TargetList.ShouldBeEmpty(); }
public override void FindTargets(ref Dictionary <string, int> available, List <NaniteConstructionBlock> blockList) { MyAPIGateway.Utilities.InvokeOnGameThread(() => { m_lastInvalidTargetReason = ""; ComponentsRequired.Clear(); }); var maxTargets = GetMaximumTargets(); if (TargetList.Count >= maxTargets) { if (PotentialTargetList.Count > 0) { InvalidTargetReason("Maximum targets reached. Add more upgrades!"); } return; } NaniteConstructionInventory inventoryManager = m_constructionBlock.InventoryManager; Vector3D sourcePosition = m_constructionBlock.ConstructionBlock.GetPosition(); Dictionary <string, int> missing = new Dictionary <string, int>(); string LastInvalidTargetReason = ""; int TargetListCount = TargetList.Count; foreach (var item in PotentialTargetList.OrderBy(x => Vector3D.Distance(sourcePosition, EntityHelper.GetBlockPosition((IMySlimBlock)x))).ToList()) { if (item == null || TargetList.Contains(item)) { continue; } missing = inventoryManager.GetProjectionComponents((IMySlimBlock)item); bool haveComponents = inventoryManager.CheckComponentsAvailable(ref missing, ref available); if ((MyAPIGateway.Session.CreativeMode || haveComponents) && m_constructionBlock.HasRequiredPowerForNewTarget(this) && ((IMySlimBlock)item).CubeGrid.GetPosition() != Vector3D.Zero) { bool found = false; foreach (var block in blockList.ToList()) { if (block != null && block.GetTarget <NaniteProjectionTargets>().TargetList.Contains(item)) { found = true; LastInvalidTargetReason = "Another factory has this block as a target"; break; } } if (found) { continue; } AddTarget(item); IMySlimBlock slimBlock = (IMySlimBlock)item; var def = slimBlock.BlockDefinition as MyCubeBlockDefinition; Logging.Instance.WriteLine(string.Format("[Projection] Adding Projection Target: conid={0} subtypeid={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, slimBlock.FatBlock != null ? slimBlock.FatBlock.EntityId : 0, slimBlock.Position), 1); if (++TargetListCount >= maxTargets) { break; } } else if (!haveComponents) { LastInvalidTargetReason = "Missing components to start projected block"; } else if (!m_constructionBlock.HasRequiredPowerForNewTarget(this)) { LastInvalidTargetReason = "Insufficient power for another target."; break; } } if (LastInvalidTargetReason != "") { InvalidTargetReason(LastInvalidTargetReason); } }
private void OnDetonateProjectile(TargetList targets) { }
protected void FilterTrackerTargetList(TargetTracker source, TargetList targets) { if (this.filterType == FILTER_TYPE.IgnoreTargetTracking) this.FilterTargetList(targets); // Else do nothing. }
public static TargetList GetTextTargetList() { TargetList targetlist = new TargetList(); targetlist.AddTextTargets ((int) TransferDataType.Default); return (targetlist); }
protected void FilterTargetList(TargetList targets, LayerMask mask, Vector3 fromPos, Color debugLineColor) { #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif Vector3 toPos; bool isNotLOS; var iterTargets = new List<Target>(targets); Collider targetColl; foreach (Target target in iterTargets) { isNotLOS = false; if (this.testMode == TEST_MODE.BoundingBox) { targetColl = target.targetable.coll; // This solution works with rotation pretty well Matrix4x4 mtx = target.targetable.transform.localToWorldMatrix; Vector3 ext = targetColl.bounds.extents * 0.5f; var bboxPnts = new Vector3[8]; bboxPnts[0] = mtx.MultiplyPoint3x4(ext); bboxPnts[1] = mtx.MultiplyPoint3x4(new Vector3(-ext.x, ext.y, ext.z)); bboxPnts[2] = mtx.MultiplyPoint3x4(new Vector3(ext.x, ext.y, -ext.z)); bboxPnts[3] = mtx.MultiplyPoint3x4(new Vector3(-ext.x, ext.y, -ext.z)); bboxPnts[4] = mtx.MultiplyPoint3x4(new Vector3(ext.x, -ext.y, ext.z)); bboxPnts[5] = mtx.MultiplyPoint3x4(new Vector3(-ext.x, -ext.y, ext.z)); bboxPnts[6] = mtx.MultiplyPoint3x4(new Vector3(ext.x, -ext.y, -ext.z)); bboxPnts[7] = mtx.MultiplyPoint3x4(-ext); for (int i = 0; i < bboxPnts.Length; i++) { isNotLOS = Physics.Linecast(fromPos, bboxPnts[i], mask); // Quit loop at first positive test if (isNotLOS) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(fromPos, bboxPnts[i], debugLineColor, 0.01f); #endif continue; } else break; } } else { toPos = target.targetable.transform.position; isNotLOS = Physics.Linecast(fromPos, toPos, mask); #if UNITY_EDITOR if (isNotLOS && this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(fromPos, toPos, debugLineColor, 0.01f); #endif } if (isNotLOS) { targets.Remove(target); #if UNITY_EDITOR debugRemoveNames.Add(target.targetable.name); #endif } } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) Debug.Log("Holding fire for LOS: " + string.Join(",", debugRemoveNames.ToArray())); #endif }
protected void FilterTargetList(TargetList targets) { #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif this.iterTargets.Clear(); this.iterTargets.AddRange(targets); for (int i = 0; i < iterTargets.Count; i++) { this.currentTarget = iterTargets[i]; if (this.IsInAngle(this.currentTarget)) continue; // This target is good. Don't ignore it. Continue. #if UNITY_EDITOR debugRemoveNames.Add(this.currentTarget.targetable.name); #endif targets.Remove(this.currentTarget); } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) { string msg = string.Format ( "Holding fire due to misalignment: {0}", string.Join(", ", debugRemoveNames.ToArray()) ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif }
public virtual void Remove(object target) { TargetList.Remove(target); PotentialTargetList.Remove(target); }
public List <string> GetTargetIDsFromString(string readString) { TargetList targetList = JsonUtility.FromJson <TargetList>(readString); return(targetList.results); }
public override void FindTargets(ref Dictionary <string, int> available, List <NaniteConstructionBlock> blockList) { InvalidTargetReason(""); var maxTargets = GetMaximumTargets(); if (m_targetList.Count >= maxTargets) { if (PotentialTargetList.Count > 0) { InvalidTargetReason("Maximum targets reached. Add more upgrades!"); } return; } Dictionary <string, int> missing = new Dictionary <string, int>(); string LastInvalidTargetReason = ""; int targetListCount = m_targetList.Count; foreach (IMySlimBlock item in m_potentialTargetList.ToList()) { if (item == null || TargetList.Contains(item)) { continue; } missing.Clear(); item.GetMissingComponents(missing); if (missing == null && !MyAPIGateway.Session.CreativeMode) { continue; } bool foundMissingComponents = true; if (missing.Count > 0) { foundMissingComponents = m_constructionBlock.InventoryManager.CheckComponentsAvailable(ref missing, ref available); } if (foundMissingComponents && m_constructionBlock.HasRequiredPowerForNewTarget(this)) { bool found = false; foreach (var block in blockList.ToList()) { if (block != null && block != m_constructionBlock && !m_constructionBlock.Slaves.Contains(block) && block.Targets.First(y => y is NaniteConstructionTargets).TargetList.Contains(item as IMySlimBlock)) { found = true; LastInvalidTargetReason = "Another factory has this block as a target"; break; } } if (found) { continue; } AddTarget(item); var def = item.BlockDefinition as MyCubeBlockDefinition; Logging.Instance.WriteLine(string.Format("[Construction] Adding Construction/Repair Target: conid={0} subtype={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, item.FatBlock != null ? item.FatBlock.EntityId : 0, item.Position), 1); if (++targetListCount >= maxTargets) { break; } } else if (!foundMissingComponents) { LastInvalidTargetReason = "Missing components"; } else if (!m_constructionBlock.HasRequiredPowerForNewTarget(this)) { LastInvalidTargetReason = "Insufficient power for another target."; break; } } if (LastInvalidTargetReason != "") { InvalidTargetReason(LastInvalidTargetReason); } }
public void DetonateProjectile() { if (!base.gameObject.activeInHierarchy) { return; } TargetList targetList = new TargetList(); if (this.areaHit) { base.perimeter.enabled = true; targetList.AddRange(this.targets); } else if (this.target != Target.Null) { targetList.Add(this.target); } if (this.debugLevel > DEBUG_LEVELS.Off) { string arg = string.Format("Detonating with targets: {0}", targetList); UnityEngine.Debug.Log(string.Format("Projectile ({0}): {1}", base.name, arg)); } TargetList targetList2 = new TargetList(); Projectile.NOTIFY_TARGET_OPTIONS nOTIFY_TARGET_OPTIONS; foreach (Target current in targetList) { if (!(current == Target.Null)) { Target target = new Target(current); target.projectile = this; targetList2.Add(target); nOTIFY_TARGET_OPTIONS = this.notifyTargets; if (nOTIFY_TARGET_OPTIONS == Projectile.NOTIFY_TARGET_OPTIONS.Direct) { target.targetable.OnHit(this.effectsOnTarget, target, base.GetComponent<Collider>()); } if (this.debugLevel > DEBUG_LEVELS.Off) { UnityEngine.Debug.DrawLine(this.xform.position, target.transform.position, Color.red); } } } nOTIFY_TARGET_OPTIONS = this.notifyTargets; if (nOTIFY_TARGET_OPTIONS != Projectile.NOTIFY_TARGET_OPTIONS.Direct) { if (nOTIFY_TARGET_OPTIONS == Projectile.NOTIFY_TARGET_OPTIONS.PassToDetonator) { this.SpawnDetonatorPrefab(true); } } else { this.SpawnDetonatorPrefab(false); } if (this.OnDetonationDelegates != null) { this.OnDetonationDelegates(targetList2); } this.target = Target.Null; InstanceManager.Despawn(base.transform); }
public override void FindTargets(ref Dictionary <string, int> available) { if (!IsEnabled()) { return; } if (TargetList.Count >= GetMaximumTargets()) { if (PotentialTargetList.Count > 0) { m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!"; } return; } DateTime start = DateTime.Now; using (Lock.AcquireExclusiveUsing()) { if (m_constructionBlock.IsUserDefinedLimitReached()) { m_lastInvalidTargetReason = "User defined maximum nanite limit reached"; return; } //foreach (NaniteMiningItem item in PotentialTargetList) for (int r = PotentialTargetList.Count - 1; r >= 0; r--) { var item = (NaniteMiningItem)PotentialTargetList[r]; if (TargetList.Contains(item)) { continue; } if (m_globalPositionList.Contains(item.Position)) { m_lastInvalidTargetReason = "Another factory has this voxel as a target"; continue; } var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); bool found = false; foreach (var block in blockList) { // This can be sped up if necessary by indexing items by position if (block.GetTarget <NaniteMiningTargets>().TargetList.FirstOrDefault(x => ((NaniteMiningItem)x).Position == item.Position) != null) { found = true; break; } } if (found) { m_lastInvalidTargetReason = "Another factory has this voxel as a target"; continue; } if (!NaniteMining.CheckVoxelContent(item.VoxelId, item.Position)) { continue; } if (Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), item.Position) < m_maxDistance * m_maxDistance && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { Logging.Instance.WriteLine(string.Format("ADDING Mining Target: conid={0} pos={1} type={2}", m_constructionBlock.ConstructionBlock.EntityId, item.Position, MyDefinitionManager.Static.GetVoxelMaterialDefinition(item.VoxelMaterial).MinedOre)); //PotentialTargetList.Remove(item); TargetList.Add(item); m_globalPositionList.Add(item.Position); if (TargetList.Count >= GetMaximumTargets()) { break; } } } } //Logging.Instance.WriteLine(string.Format("FindTargets took {0}ms", (DateTime.Now - start).TotalMilliseconds)); }
private IEnumerator Detonate() { if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = "Detonating..."; Debug.Log(string.Format("Detonator ({0}): {1}", this.name, msg)); } // Wait for next frame to begin to be sure targets have been propegated // This also makes this loop easier to manage. yield return new WaitForFixedUpdate(); // Because of physics...matters? // START EVENT if (this.OnDetonatingDelegates != null) this.OnDetonatingDelegates(); // Keep track of targets which have already been processed so they // aren't hit twice var processedTargetList = new TargetList(); this.range = Vector3.zero; float timer = 0; float progress = 0; // Normalized mount processed 0-1 // The timer can exit the loop if used while (true) { // UPDATE EVENT if (this.OnDetonatingUpdateDelegates != null) this.OnDetonatingUpdateDelegates(progress); // Exit? if (timer >= this.durration) break; timer += Time.deltaTime; progress = timer / this.durration; this.range = this.maxRange * progress; // Build a list of targets in range which have NOT been processed yet. var newTargets = new TargetList(); foreach (Target target in this.targets) if (!processedTargetList.Contains(target)) newTargets.Add(target); if (newTargets.Count > 0) { if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format("Detonation hitting targets: {0}", this.targets); Debug.Log(string.Format("Detonator ({0}): {1}", this.name, msg)); } foreach (Target target in newTargets) { target.targetable.OnHit ( this.effectsOnTarget, target, this.perimeter.collider ); processedTargetList.Add(target); } } yield return new WaitForFixedUpdate(); // Because of physics...matters? } // Prevent being run more than once in a frame where it has already // been destroyed. if (!this.gameObject.activeInHierarchy) yield break; // Same as return PathologicalGames.InstanceManager.Despawn(this.transform); }
public override void FindTargets(ref Dictionary <string, int> available, List <NaniteConstructionBlock> blockList) { var maxTargets = GetMaximumTargets(); if (TargetList.Count >= maxTargets) { if (m_potentialMiningTargets.Count > 0) { InvalidTargetReason("Maximum targets reached. Add more upgrades!"); } return; } string LastInvalidTargetReason = ""; int targetListCount = m_targetList.Count; HashSet <Vector3D> usedPositions = new HashSet <Vector3D>(); List <NaniteMiningItem> removeList = new List <NaniteMiningItem>(); foreach (NaniteMiningItem item in m_potentialMiningTargets.ToList()) { if (item == null || TargetList.Contains(item)) { removeList.Add(item); continue; } if (m_globalPositionList.Contains(item.Position) || usedPositions.Contains(item.Position)) { LastInvalidTargetReason = "Mining position was already targeted"; removeList.Add(item); continue; } if (!m_constructionBlock.HasRequiredPowerForNewTarget(this)) { LastInvalidTargetReason = "Insufficient power for another target"; break; } bool found = false; foreach (var block in blockList.ToList()) { if (block != null && block.GetTarget <NaniteMiningTargets>().TargetList.FirstOrDefault(x => ((NaniteMiningItem)x).Position == item.Position) != null) { found = true; LastInvalidTargetReason = "Another factory has this voxel as a target"; break; } } if (found) { removeList.Add(item); continue; } var nearestFactory = GetNearestFactory(TargetName, item.Position); if (IsInRange(nearestFactory, item.Position, m_maxDistance)) { Logging.Instance.WriteLine(string.Format("[Mining] Adding Mining Target: conid={0} pos={1} type={2}", m_constructionBlock.ConstructionBlock.EntityId, item.Position, MyDefinitionManager.Static.GetVoxelMaterialDefinition(item.VoxelMaterial).MinedOre), 1); removeList.Add(item); usedPositions.Add(item.Position); MyAPIGateway.Utilities.InvokeOnGameThread(() => { try { if (m_constructionBlock.IsUserDefinedLimitReached()) { InvalidTargetReason("User defined maximum nanite limit reached"); } else if (item != null) { removeList.Add(item); TargetList.Add(item); } } catch (Exception e) { Logging.Instance.WriteLine("NaniteMiningTargets.FindTargets.Invocation1: " + e.ToString()); } }); if (targetListCount++ >= maxTargets) { break; } } else { removeList.Add(item); } } foreach (var item in removeList) { m_potentialMiningTargets.Remove(item); } if (LastInvalidTargetReason != "") { InvalidTargetReason(LastInvalidTargetReason); } }
/// <summary> /// /// </summary> /// <param name="UseSandbox"></param> /// <param name="Name"></param> /// <param name="Countries"></param> /// <param name="Languages"></param> /// <param name="BudgetPeriod"></param> /// <param name="BudgetAmount"></param> /// <param name="MaxAdGroups"></param> /// <param name="DisplayUrl"></param> /// <param name="destinationUrlPrefix"></param> public void CreateCampaignByKeywordDensityContentMatch(bool UseSandbox, Guid AffiliateSiteRefId, int BudgetPeriod, Moneyv200906 BudgetAmount, AdGroupCriterionMoneyv200906 KeywordMaxCpc, string DisplayUrl, int MaxAdGroups, int AdKeywordType, int MinKeywordDensity, int MaxKeywordDensity, int MinContentMatch, decimal maxApiUsageDollars) { // Create a user (reads headers from App.config file). AdWordsUser user = new AdWordsUser(); if (UseSandbox) user.UseSandbox(); // use sandbox AccountService accountService = (AccountService)user.GetService(ApiServices.v13.AccountService); string[] accounts = accountService.getClientAccounts(); try { #region Create Campaign PpcNetwork ppcNetwork = DataRepository.PpcNetworkProvider.GetByName("AdWords"); TList<PpcCampaign> Campaigns = DataRepository.PpcCampaignProvider.GetByPpcNetworkRefId(ppcNetwork.PpcNetworkRefId); foreach (PpcCampaign campaign in Campaigns) { // Target the campaign at CampaignServicev200906 campaignService = (com.google.api.adwords.v200906.CampaignService.CampaignService) user.GetService(ApiServices.v200906.CampaignService); // Create a new campaign with an ad group. First create a // campaign, so we can get its id. Campaignv200906 newCampaign = new Campaignv200906(); // The campaign name is optional. An error results if a campaign // of the same name already exists. newCampaign.name = campaign.CampaignName + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); // Set the campaign status to paused, we don't want to start // paying for this test. // Required: Set the campaign status. newCampaign.status = CampaignStatusv200906.ACTIVE; newCampaign.statusSpecified = true; // Required: Specify the currency and budget amount. Budget budget = new Budget(); BudgetAmount.microAmountSpecified = true; budget.amount = BudgetAmount; // Required: Specify the bidding strategy. newCampaign.biddingStrategy = new ManualCPC(); // Optional: Specify the budget period and delivery method. budget.periodSpecified = true; budget.period = BudgetBudgetPeriod.DAILY; budget.deliveryMethodSpecified = true; budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD; newCampaign.budget = budget; // Optional: Specify an endDate for the campaign. newCampaign.endDate = DateTime.Now.AddDays(campaign.DurationInDays).ToString("yyyyMMdd"); // Define an Add operation to add the campaign. CampaignOperation campaignOperation = new CampaignOperation(); campaignOperation.operatorSpecified = true; campaignOperation.@operator = CampaignOperatorv200906.ADD; campaignOperation.operand = newCampaign; try { CampaignReturnValue results = campaignService.mutate(new CampaignOperation[] { campaignOperation }); if (results != null && results.value != null && results.value.Length > 0) { newCampaign.id = results.value[0].id; newCampaign.idSpecified = true; Trace.TraceInformation( "New campaign with name = \"{0}\" and id = " + "\"{1}\" was created.", results.value[0].name, results.value[0].id); } } catch (Exception ex) { Trace.TraceError("Error:" + ex.Message); throw new Exception("Failed to create campaign. " + ex.Message); } #endregion #region Targeting CampaignTargetService service = (CampaignTargetService)user.GetService(ApiServices.v200906.CampaignTargetService); // Create a language target - for English language. LanguageTargetv200906 languageTarget = new LanguageTargetv200906(); languageTarget.languageCode = "en"; //TODO: Add as property LanguageTargetList languageTargetList = new LanguageTargetList(); languageTargetList.targets = new LanguageTargetv200906[] { languageTarget }; languageTargetList.campaignId = newCampaign.id; languageTargetList.campaignIdSpecified = true; // Create a country target - include US, exclude metrocode 743. CountryTargetv200906 countryTarget = new CountryTargetv200906(); countryTarget.countryCode = campaign.TargetCountry; countryTarget.excludedSpecified = true; countryTarget.excluded = false; MetroTargetv200906 metroTarget = new MetroTargetv200906(); metroTarget.excludedSpecified = true; metroTarget.excluded = true; metroTarget.metroCode = campaign.ExcludeMetroTarget; GeoTargetList geoTargetList = new GeoTargetList(); geoTargetList.targets = new GeoTargetv200906[] { countryTarget, metroTarget }; geoTargetList.campaignId = newCampaign.id; geoTargetList.campaignIdSpecified = true; // Create a network target - Google Search. NetworkTargetv200906 networkTarget1 = new NetworkTargetv200906(); networkTarget1.networkCoverageTypeSpecified = true; networkTarget1.networkCoverageType = NetworkCoverageTypev200906.GOOGLE_SEARCH; NetworkTargetv200906 networkTarget2 = new NetworkTargetv200906(); networkTarget2.networkCoverageTypeSpecified = true; networkTarget2.networkCoverageType = NetworkCoverageTypev200906.SEARCH_NETWORK; NetworkTargetList networkTargetList = new NetworkTargetList(); networkTargetList.targets = new NetworkTargetv200906[] { networkTarget1, networkTarget2 }; networkTargetList.campaignId = newCampaign.id; networkTargetList.campaignIdSpecified = true; TargetList[] targets = new TargetList[] { languageTargetList, geoTargetList, networkTargetList }; ArrayList campaignTargetOperations = new ArrayList(); foreach (TargetList target in targets) { CampaignTargetOperation ops = new CampaignTargetOperation(); ops.operatorSpecified = true; ops.@operator = CampaignTargetOperatorv200906.SET; ops.operand = target; campaignTargetOperations.Add(ops); } try { service.mutate((CampaignTargetOperation[]) campaignTargetOperations.ToArray(typeof(CampaignTargetOperation))); Trace.TraceInformation("Geo, language, and network targeting were " + "successfully added to campaign id = \"{0}\".", newCampaign.id); } catch (Exception ex) { Trace.TraceError("Failed to create campaign targeting. " + "Exception says \"{0}\"", ex.Message); } #endregion #region Create your Services //create your services List<SeedKeyword> keywords = new List<SeedKeyword>(); AdGroupAdServicev200906 adService = (AdGroupAdServicev200906)user.GetService(ApiServices.v200906.AdGroupAdService); KeywordToolService keywordToolService = (KeywordToolService)user.GetService(ApiServices.v13.KeywordToolService); AdGroupServicev200906 adgroupService = (AdGroupServicev200906)user.GetService(ApiServices.v200906.AdGroupService); TrafficEstimatorService trafficEstimatorService = (TrafficEstimatorService)user.GetService(ApiServices.v13.TrafficEstimatorService); #endregion #region Enumerate thru all the keywords by category AdGroupv200906 newAdGroup = null; foreach ( SiteCategory siteCategory in DataRepository.SiteCategoryProvider.GetByAffiliateSiteRefId(AffiliateSiteRefId)) { int adGroupCnt = 1; //enumerate thru all the keywords foreach ( KeywordUrLsDistinct keywordUrLsDistinct in DataRepository.KeywordUrLsDistinctProvider.GetBySiteCategoryRefId( siteCategory.SiteCategoryRefId)) { VList<KeywordDensity> keywordDensityList = DataRepository.KeywordDensityProvider.GetURLKeywordDensity(keywordUrLsDistinct.Url, MinKeywordDensity, MaxKeywordDensity). FindAllDistinct("SiteContent"); int GroupAdCount = 0; //check the avg keyword density if (keywordDensityList.Count >= MinContentMatch) { if (adGroupCnt == 1) { #region Ad AdGroup if (GroupAdCount >= MaxAdGroups) break; //Create an ad group by site category newAdGroup = new AdGroupv200906(); newAdGroup.name = siteCategory.Name; newAdGroup.campaignId = newCampaign.id; newAdGroup.campaignIdSpecified = true; //newAdGroup.campaignName = newCampaign.name; // Optional: set the status of adgroup. newAdGroup.statusSpecified = true; newAdGroup.status = AdGroupStatus.ENABLED; // Optional: Create a Manual CPC Bid. ManualCPCAdGroupBids bids = new ManualCPCAdGroupBids(); // Set the keyword content max cpc. bids.keywordContentMaxCpc = new Bid(); Money kwdContentMaxCpc = new Money(); kwdContentMaxCpc.microAmountSpecified = true; kwdContentMaxCpc.microAmount = KeywordMaxCpc.microAmount; bids.keywordContentMaxCpc.amount = kwdContentMaxCpc; // Set the keyword max cpc. bids.keywordMaxCpc = new Bid(); Money kwdMaxCpc = new Money(); kwdMaxCpc.microAmountSpecified = true; kwdMaxCpc.microAmount = KeywordMaxCpc.microAmount; bids.keywordMaxCpc.amount = kwdMaxCpc; // Set the manual bid to the adgroup. newAdGroup.bids = bids; AdGroupOperation adGroupOperation = new AdGroupOperation(); adGroupOperation.operatorSpecified = true; adGroupOperation.@operator = AddGroupOperatorv200906.ADD; adGroupOperation.operand = newAdGroup; try { AdGroupReturnValue results = adgroupService.mutate(new AdGroupOperation[] { adGroupOperation }); if (results != null && results.value != null && results.value.Length > 0) { newAdGroup.id = results.value[0].id; newAdGroup.idSpecified = true; Trace.TraceInformation( "New ad group with name = \"{0}\" and id = \"{1}\" was created.", results.value[0].name, results.value[0].id); } } catch (Exception ex) { Trace.TraceError("Failed to create ad group. Exception says \"{0}\"", ex.Message); } adGroupCnt++; #endregion } Trace.TraceInformation(keywordUrLsDistinct.Url); //Create an add for each product // // IMPORTANT: create an ad before adding keywords! Else the // minCpc will have a higher value. TList<PpcAdTemplate> ppcAdTemplateList = DataRepository.PpcAdTemplateProvider.GetByPpcCampaignRefId(campaign.PpcCampaignRefId); foreach (var ppcAdTemplate in ppcAdTemplateList) { TextAdv200906 newTextAd = new TextAdv200906(); Product prod = DataRepository.ProductProvider.GetByProductRefId( (Guid)keywordUrLsDistinct.ProductRefId); newTextAd.headline = StringUtils.ScrubProdName(prod.Name); while (newTextAd.headline.Length > 25) { // if one word longer than 25 chars if (newTextAd.headline.LastIndexOf(" ") < 0) continue; newTextAd.headline = newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")). Substring( 0, newTextAd.headline.Substring(0, newTextAd.headline.LastIndexOf(" ")) . LastIndexOf(" ")); } newTextAd.description1 = ppcAdTemplate.AdLine1.Replace(KeywordToken, keywordDensityList[0].Keywords).Replace(ProductNameToken, newTextAd.headline); newTextAd.description2 = ppcAdTemplate.AdLine2; //} newTextAd.displayUrl = DisplayUrl; newTextAd.url = keywordUrLsDistinct.Url; //don't add it yet, there is a check below to see if it meets criteria //SeedKeyword[] keywordsArray = new SeedKeyword[] { new SeedKeyword() }; //keywordsArray = keywords.ToArray(); // Associate this ad group with the newly created campaign. Send // the request to add the new ad group. try { //we found a keyword that meets criteria so ad the new Ad. AdGroupAd adGroupAd = new AdGroupAd(); adGroupAd.adGroupId = newAdGroup.id; adGroupAd.adGroupIdSpecified = true; adGroupAd.ad = newTextAd; AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation(); adGroupAdOperation.operatorSpecified = true; adGroupAdOperation.@operator = AddGroupAdOperatorv200906.ADD; adGroupAdOperation.operand = adGroupAd; AdGroupAdReturnValue result = null; try { result = adService.mutate(new AdGroupAdOperation[] { adGroupAdOperation }); if (result.value != null && result.value.Length > 0) { foreach (AdGroupAd tempAdGroupAd in result.value) { Trace.TraceInformation( String.Format( "New text ad with headline = \"{0}\" and id = \"{1}\" was created.", ((TextAdv200906)tempAdGroupAd.ad).headline, tempAdGroupAd.ad.id)); } } } catch (Exception ex) { Trace.TraceError("Failed to create Ad(s). Exception says \"{0}\"", ex.Message); } GroupAdCount++; Trace.TraceInformation("Text ad" + GroupAdCount + ": " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2); //Trace.TraceInformation("Text ad: " + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2); } catch { //do nothing Trace.TraceError("***Text ad Failed:" + newTextAd.headline + " Text Line1:" + newTextAd.description1 + " Text Line2:" + newTextAd.description2); } } //Add the Product name as a whole phrase AdGroupCriterionServicev200906 criterionService = (AdGroupCriterionServicev200906) user.GetService(ApiServices.v200906.AdGroupCriterionService); foreach (KeywordDensity kd in keywordDensityList) { try { Keywordv200906 newKeyword = new Keywordv200906(); newKeyword.matchTypeSpecified = true; newKeyword.matchType = com.google.api.adwords.v200906.AdGroupCriterionService.KeywordMatchType. BROAD; newKeyword.text = kd.Keywords; BiddableAdGroupCriterion criterion = new BiddableAdGroupCriterion(); criterion.adGroupId = newAdGroup.id; criterion.adGroupIdSpecified = true; criterion.criterion = newKeyword; criterion.destinationUrl = kd.Url; //TODO: Use the Traffic Estimator to determine the // the maxCpc to use //newKeyword.maxCpc = KeywordMaxCpc; //newKeyword.maxCpcSpecified = true; var adGroupCriterionBids = new com.google.api.adwords.v200906.AdGroupCriterionService. ManualCPCAdGroupCriterionBids(); adGroupCriterionBids.maxCpc = new com.google.api.adwords.v200906.AdGroupCriterionService.Bid(); adGroupCriterionBids.maxCpc.amount = KeywordMaxCpc; criterion.bids = adGroupCriterionBids; AdGroupCriterionOperation adGroupCriterionOperation = new AdGroupCriterionOperation(); adGroupCriterionOperation.@operator = com.google.api.adwords.v200906.AdGroupCriterionService.Operator.ADD; adGroupCriterionOperation.operatorSpecified = true; adGroupCriterionOperation.operand = criterion; try { AdGroupCriterionReturnValue results = criterionService.mutate(new AdGroupCriterionOperation[] { adGroupCriterionOperation }); if (results != null && results.value != null && results.value.Length > 0) { Keywordv200906 result = results.value[0].criterion as Keywordv200906; Trace.TraceInformation( String.Format( "New keyword with text = \"{0}\" and id = \"{1}\" was created.", result.text, result.id)); } } catch (Exception ex) { Trace.TraceError( String.Format( "Failed to create keyword at Ad group level. Exception says \"{0}\"", ex.Message)); } } catch { //do nothing Trace.TraceError("***Add Criteria Failed: Keyword" + kd.Keywords); } } if (GroupAdCount >= MaxAdGroups) break; } } } #endregion } #region Check api usage // check api usage ApiUsage apiUsage = new ApiUsage(); APIQuotaValues aPIQuotaValues = apiUsage.GetApiUsage(UseSandbox); Trace.TraceInformation("FreeQuotaUsed:" + aPIQuotaValues.FreeQuotaUsed.ToString() + " FreeUnitsRemaining:" + aPIQuotaValues.FreeUnitsRemaining.ToString() + " SysDefinesQuotaCap:" + aPIQuotaValues.SysDefinesQuotaCap.ToString() + " TotalUsed:" + aPIQuotaValues.TotalUsed.ToString()); #endregion #region Log everything created //AdGroup[] adGroups = adgroupService.getAllAdGroups(campaignId); //foreach (AdGroup adGroup in adGroups) //{ // Trace.TraceInformation("Ad group: " + adGroup.name); // Ad[] ads = adService.getAllAds(new long[] { adGroup.id }); // foreach (Ad ad in ads) // { // if (ad is TextAd) // { // TextAd textAd = (TextAd)ad; // Trace.TraceInformation("Text ad: " + textAd.headline + " Text Line1:" + textAd.description1 + " Text Line2:" + textAd.description2); // } // } //} #endregion } catch (Exception ex) { Trace.TraceError("Error:" + ex.Message); throw ex; } }
private IEnumerator Detonate() { if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = "Detonating..."; Debug.Log(string.Format("Detonator ({0}): {1}", this.name, msg)); } // Wait for next frame to begin to be sure targets have been propegated // This also makes this loop easier to manage. yield return(new WaitForFixedUpdate()); // Because of physics...matters? // START EVENT if (this.OnDetonatingDelegates != null) { this.OnDetonatingDelegates(); } // Keep track of targets which have already been processed so they // aren't hit twice var processedTargetList = new TargetList(); this.range = Vector3.zero; float timer = 0; float progress = 0; // Normalized mount processed 0-1 // The timer can exit the loop if used while (true) { // UPDATE EVENT if (this.OnDetonatingUpdateDelegates != null) { this.OnDetonatingUpdateDelegates(progress); } // Exit? if (timer >= this.durration) { break; } timer += Time.deltaTime; progress = timer / this.durration; this.range = this.maxRange * progress; // Build a list of targets in range which have NOT been processed yet. var newTargets = new TargetList(); foreach (Target target in this.targets) { if (!processedTargetList.Contains(target)) { newTargets.Add(target); } } if (newTargets.Count > 0) { if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format("Detonation hitting targets: {0}", this.targets); Debug.Log(string.Format("Detonator ({0}): {1}", this.name, msg)); } foreach (Target target in newTargets) { target.targetable.OnHit ( this.effectsOnTarget, target, this.perimeter.collider ); processedTargetList.Add(target); } } yield return(new WaitForFixedUpdate()); // Because of physics...matters? } // Prevent being run more than once in a frame where it has already // been destroyed. if (!this.gameObject.activeInHierarchy) { yield break; // Same as return } TargetPro.InstanceManager.Despawn(this.transform); }
/// <summary> /// A delegate run by the EventTrigger component OnFire /// </summary> protected void OnEventTriggerFire(TargetList targets) { // A great place for an explosion effect to be triggered! }
/// <summary> /// Handle tab key being pressed. /// </summary> /// <param name="shift">Was shift key pressed for the tab.</param> public void KeyTab(bool shift) { if (shift) { // If nothing currently selected, then start at end if (_target == null) { KeyEnd(); } else { // Find the currently selected target TargetList targets = ConstructKeyboardTargets(Root); for (int i = targets.Count - 1; i >= 0; i--) { if (targets[i] == _target) { // If at the first item then wrap to the last if (i == 0) { KeyEnd(); } else { SetTarget(targets[i - 1], false); } return; } } // Should never happen! KeyEnd(); } } else { // If nothing currently selected, then start at home if (_target == null) { KeyHome(); } else { // Find the currently selected target TargetList targets = ConstructKeyboardTargets(Root); for (int i = 0; i < targets.Count; i++) { if (targets[i] == _target) { // If at the last item then wrap to the first if (i == (targets.Count - 1)) { KeyHome(); } else { SetTarget(targets[i + 1], false); } return; } } // Should never happen! KeyHome(); } } }
protected override void UpdateDataObject() { SPList targetList = TargetList.Read(); try { switch (ParameterSetName) { case "Exchange": SetListOverlay.AddCalendarOverlay(targetList, ViewName, OwaUrl, WebServiceUrl, OverlayTitle, OverlayDescription, Color, !DoNotAlwaysShow, ClearExisting); break; case "Single": SPList overlayList = OverlayList.Read(); try { SetListOverlay.AddCalendarOverlay(targetList, ViewName, overlayList, OverlayTitle, OverlayDescription, Color, !DoNotAlwaysShow, ClearExisting); } finally { if (overlayList != null) { overlayList.ParentWeb.Dispose(); overlayList.ParentWeb.Site.Dispose(); } } break; case "Multiple": if (OverlayLists.Length > 10) { throw new SPException("You can only have 10 calendar overlays per list."); } for (int i = 0; i < OverlayLists.Length; i++) { SPList ol = OverlayLists[i].Read(); try { SetListOverlay.AddCalendarOverlay(targetList, ViewName, ol, OverlayTitle, OverlayDescription, (CalendarOverlayColor)i, !DoNotAlwaysShow, ClearExisting && i == 0); } finally { if (ol != null) { ol.ParentWeb.Dispose(); ol.ParentWeb.Site.Dispose(); } } } break; } } finally { if (targetList != null) { targetList.ParentWeb.Dispose(); targetList.ParentWeb.Site.Dispose(); } } }
public override void FindTargets(ref Dictionary <string, int> available) { ComponentsRequired.Clear(); if (!IsEnabled()) { return; } if (TargetList.Count >= GetMaximumTargets()) { if (PotentialTargetList.Count > 0) { m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!"; } return; } NaniteConstructionInventory inventoryManager = m_constructionBlock.InventoryManager; Vector3D sourcePosition = m_constructionBlock.ConstructionBlock.GetPosition(); Dictionary <string, int> missing = new Dictionary <string, int>(); using (m_lock.AcquireExclusiveUsing()) { foreach (var item in PotentialTargetList.OrderBy(x => Vector3D.Distance(sourcePosition, EntityHelper.GetBlockPosition((IMySlimBlock)x)))) { if (m_constructionBlock.IsUserDefinedLimitReached()) { m_lastInvalidTargetReason = "User defined maximum nanite limit reached"; return; } if (TargetList.Contains(item)) { continue; } missing = inventoryManager.GetProjectionComponents((IMySlimBlock)item); bool haveComponents = inventoryManager.CheckComponentsAvailable(ref missing, ref available); if (haveComponents && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { if (((IMySlimBlock)item).CubeGrid.GetPosition() == Vector3D.Zero) { m_lastInvalidTargetReason = "Target blocks grid is in an invalid position (Vector3D.Zero, this shouldn't happen!)"; continue; } var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); bool found = false; foreach (var block in blockList) { if (block.GetTarget <NaniteProjectionTargets>().TargetList.Contains(item)) { found = true; break; } } if (found) { m_lastInvalidTargetReason = "Another factory has this block as a target"; continue; } TargetList.Add(item); IMySlimBlock slimBlock = (IMySlimBlock)item; var def = slimBlock.BlockDefinition as MyCubeBlockDefinition; Logging.Instance.WriteLine(string.Format("ADDING Projection Target: conid={0} subtypeid={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, slimBlock.FatBlock != null ? slimBlock.FatBlock.EntityId : 0, slimBlock.Position)); if (TargetList.Count >= GetMaximumTargets()) { break; } } else if (!haveComponents) { m_lastInvalidTargetReason = "Missing components to start projected block"; } else if (!NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { m_lastInvalidTargetReason = "Insufficient power for another target."; } } } }
public void ExitPassenger(Person person) { Passengers.Remove(person); TargetList.Remove(CurrentFloor); }
/// <summary> /// Handles all firing events including target aquisition and firing. /// Events are: /// OnStart() : /// Runs once when the firing system first becomes active /// OnUpdate() : /// Runs each frame while the firing system is active /// OnTargetUpdate() : /// Runs each frame while tracking a target (there is at least one target.) /// OnIdleUpdate() : /// Runs each frame while the firing system is idle (no targets) /// OnFire() : /// Runs when it is time to fire. /// /// Counter Behavior Notes: /// * If there are no targets. the counter will keep running up. /// This means the next target to enter will be fired upon /// immediatly. /// /// * The counter is always active so if the last target exits, then a /// new target enters right after that, there may still be a wait. /// </summary> private IEnumerator FiringSystem() { // While (true) because of the timer, we want this to run all the time, not // start and stop based on targets in range if (this.initIntervalCountdownAtZero) this.fireIntervalCounter = 0; else this.fireIntervalCounter = this.interval; this.targets.Clear(); this.OnStart(); // EVENT TRIGGER while (true) { // if there is no target, counter++, handle idle behavior, and // try next frame. // Will init this.targets for child classes as well. this.targets = this.targetTracker.targets; if (this.targets.Count != 0) { // Let the delegate filter a copy of the list just for the OnFire // Test. We still want this.targets to remain as is. // Do this in here to still trigger OnTargetUpdate var targetsCopy = new TargetList(); targetsCopy.AddRange(this.targets); if (this.onPreFireDelegates != null) this.onPreFireDelegates(targetsCopy); // if all is right, fire if (targetsCopy.Count != 0 && // Incase of pre-fire delegate changes this.fireIntervalCounter <= 0 && this.isLockedOnTarget) { this.OnFire(); this.fireIntervalCounter = this.interval; // Reset } else if (this.debugLevel > DEBUG_LEVELS.Off) { // Just for debug. Show a gizmo line to each target being tracked // OnFire() has another color, so keep this here where this // won't overlay the OnFired line. foreach (Target target in targets) Debug.DrawLine ( this.emitter.position, target.transform.position, Color.gray ); } // Update event while tracking a target this.OnTargetUpdate(targets); // EVENT TRIGGER } else { // Update event while NOT tracking a target this.OnIdleUpdate(); // EVENT TRIGGER } this.fireIntervalCounter -= Time.deltaTime; // Update event no matter what this.OnUpdate(); // EVENT TRIGGER // Stager calls to get Target (the whole system actually) yield return null; } }
public void Should_return_valid_target_list() { TargetList.Count.ShouldBe(1); TargetList.ShouldContain(Object1); }
/// <summary> /// Runs each frame while tracking a target. This.targets is not empty! /// </summary> private void OnTargetUpdate(TargetList targets) { if (this.onTargetUpdateDelegates != null) this.onTargetUpdateDelegates(targets); }
/// <summary> /// Fire on the targets /// </summary> protected void Fire() { #if UNITY_EDITOR // Log a message to show what is being fired on if (this.debugLevel > DEBUG_LEVELS.Off) { string[] names = new string[this.targets.Count]; for (int i = 0; i < this.targets.Count; i++) names[i] = this.targets[i].transform.name; string msg = string.Format ( "Firing on: {0}\nEventInfo: {1}", string.Join(", ", names), this.eventInfoList.ToString() ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif // // Create a new list of targets which have this fire controller reference. // var targetCopies = new TargetList(); Target newTarget; foreach (Target target in this.targets) { // Can't edit a struct in a foreach loop, so need to copy and store newTarget = new Target(target); newTarget.fireController = this; // Add reference. null before this targetCopies.Add(newTarget); } // Write the result over the old target list. This is for output so targets // which are handled at all by this target tracker are stamped with a // reference. this.targets = targetCopies; // // Hnadle delivery // foreach (Target target in this.targets) { switch (this.notifyTargets) { case NOTIFY_TARGET_OPTIONS.Direct: target.targetable.OnHit(this.eventInfoList, target); break; case NOTIFY_TARGET_OPTIONS.PassInfoToEventTrigger: this.SpawnEventTrigger(target, true); break; case NOTIFY_TARGET_OPTIONS.UseEventTriggerInfo: this.SpawnEventTrigger(target, false); break; } } #if UNITY_EDITOR // When in the editor, if debugging, draw a line to each hit target. if (this.debugLevel > DEBUG_LEVELS.Off && this.notifyTargets > NOTIFY_TARGET_OPTIONS.Off) { foreach (Target target in this.targets) Debug.DrawLine(this.spawnEventTriggerAtTransform.position, target.transform.position, Color.red); } #endif // Trigger the delegates if (this.onFireDelegates != null) this.onFireDelegates(this.targets); }
/// <summary> /// A delegate run by the projectile component when this projectile detonates /// </summary> private void OnDetonateProjectile(TargetList targets) { // A great place for an explosion effect to be triggered! }
/* ** Name: getTargets ** ** Description: ** Parses a target list and returns an array of host/port pairs. ** ** (<host>:<port>[,<port>][;<host>:port[,port]]) ** ** Input: ** targetList ** ** Output: ** None. ** ** Returns: ** TargetList ArrayList of host/port pairs. ** ** History: ** 12-May-09 (thoda04) ** Created. */ private TargetList getTargets(String targetListString) { TargetList targetList = new TargetList(); string defaultPorts = "II7"; // Before we start, strip any leading and trailing parentheses, // get the host names inside the list, // and save the default ports after the host list. targetListString = getTargetListString(targetListString, ref defaultPorts); // // First, extract the semi-colon separated host/port targets. // String[] targets = parseList(targetListString, ';'); // // Next, extract host and port list from each target. // for (int i = 0; i < targets.Length; i++) { String host = getHost(targets[i]); String[] ports = getPort(targets[i], defaultPorts); for (int j = 0; j < ports.Length; j++) { targetList.Add(host, ports[j]); } } return( targetList ); }
public void SetSingleTarget(Actor target) { this.Targets = new TargetList(); this.Targets.Actors.Add(target); }
protected void FilterFireTargetList(TargetList targets) { // Get the position expected to be used to fire from. Vector3 fromPos = this.origin.position; #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif this.iterTargets.Clear(); this.iterTargets.AddRange(targets); float dist; for (int i = 0; i < iterTargets.Count; i++) { this.currentTarget = iterTargets[i]; dist = this.currentTarget.targetable.GetDistToPos(fromPos); // Skip if the target is in the distance range if (dist > this.minDistance && dist < this.maxDistance) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine ( fromPos, this.currentTarget.targetable.transform.position, Color.green, 0.01f ); #endif continue; } #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine ( fromPos, this.currentTarget.targetable.transform.position, Color.red, 0.01f ); #endif targets.Remove(this.currentTarget); #if UNITY_EDITOR debugRemoveNames.Add(this.currentTarget.targetable.name); #endif } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) { string msg = string.Format ( "Holding fire due to distance: {0}", string.Join(", ", debugRemoveNames.ToArray()) ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif }
private void FilterTargetList(TargetList targets, LayerMask mask, Vector3 fromPos, Color debugLineColor) { #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif Vector3 toPos; bool isNotLOS; var iterTargets = new List<Target>(targets); foreach (Target target in iterTargets) { isNotLOS = false; toPos = target.targetable.xform.position; if (this.testMode == TEST_MODE.SixPoint) { var sweep = new List<Vector3>(); sweep.Add(new Vector3(toPos.x + this.radius, toPos.y, toPos.z)); sweep.Add(new Vector3(toPos.x, toPos.y + this.radius, toPos.z)); sweep.Add(new Vector3(toPos.x, toPos.y, toPos.z + this.radius)); sweep.Add(new Vector3(toPos.x - this.radius, toPos.y, toPos.z)); sweep.Add(new Vector3(toPos.x, toPos.y - this.radius, toPos.z)); sweep.Add(new Vector3(toPos.x, toPos.y, toPos.z - this.radius)); foreach (Vector3 pos in sweep) { isNotLOS = Physics.Linecast(fromPos, pos, mask); #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(fromPos, pos, debugLineColor, 0.01f); #endif // Quit loop at first positive test if (isNotLOS) continue; else break; } } else { isNotLOS = Physics.Linecast(fromPos, toPos, mask); #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(fromPos, toPos, debugLineColor, 0.01f); #endif } if (isNotLOS) { targets.Remove(target); #if UNITY_EDITOR debugRemoveNames.Add(target.targetable.name); #endif } } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) Debug.Log("Holding fire for LOS: " + string.Join(",", debugRemoveNames.ToArray())); #endif }
private void UpdateHandlers(TargetList targetList) { List<IGestureListener> groupTargetList; string[] eventList; if (targetList == TargetList.ENTERING) { groupTargetList = Group.EnteringTargets; eventList = EnteringEvents; } else if (targetList == TargetList.CURRENT) { groupTargetList = Group.CurrentTargets; eventList = CurrentEvents; } else if (targetList == TargetList.LEAVING) { groupTargetList = Group.LeavingTargets; eventList = LeavingEvents; } else if (targetList == TargetList.INITIAL) { groupTargetList = Group.InitialTargets; eventList = InitialEvents; } else if (targetList == TargetList.NEWINITIAL) { groupTargetList = Group.NewIntialTargets; eventList = NewInitialEvents; } else if (targetList == TargetList.FINAL) { groupTargetList = Group.FinalTargets; eventList = FinalEvents; } else if (targetList == TargetList.INTERSECT) { groupTargetList = Group.IntersectionTargets; eventList = IntersectionEvents; } else if (targetList == TargetList.UNION) { groupTargetList = Group.UnionTargets; eventList = UnionEvents; } else // Using temporary singleton list { // Assign groupTargetList to the cleared temp list if (m_temporaryTargetSingletonList.Count > 0) m_temporaryTargetSingletonList.RemoveAt(0); groupTargetList = m_temporaryTargetSingletonList; if (targetList == TargetList.CLOSEST_ENTERING) { if (Group.ClosestEnteringTarget != null) groupTargetList.Add(Group.ClosestEnteringTarget); eventList = this.ClosestEnteringEvents; } else if (targetList == TargetList.CLOSEST_CURRENT) { if (Group.ClosestCurrentTarget != null) groupTargetList.Add(Group.ClosestCurrentTarget); eventList = this.ClosestCurrentEvents; } else if (targetList == TargetList.CLOSEST_LEAVING) { if (Group.ClosestLeavingTarget != null) groupTargetList.Add(Group.ClosestLeavingTarget); eventList = this.ClosestLeavingEvents; } else if (targetList == TargetList.CLOSEST_INITIAL) { if (Group.ClosestInitialTarget != null) groupTargetList.Add(Group.ClosestInitialTarget); eventList = this.ClosestInitialEvents; } else if (targetList == TargetList.CLOSEST_NEWINITIAL) { if (Group.ClosestNewInitialTarget != null) groupTargetList.Add(Group.ClosestNewInitialTarget); eventList = this.ClosestNewInitialEvents; } else if (targetList == TargetList.CLOSEST_FINAL) { if (Group.ClosestFinalTarget != null) groupTargetList.Add(Group.ClosestFinalTarget); eventList = this.ClosestFinalEvents; } else throw new Exception("Invalid parameter."); } // TODO: optimize EventInfo eventInfo; for (int i = 0; i < eventList.Length; i++) { eventInfo = GetEventInfo(eventList[i]); // Remove old handlers if (targetList != TargetList.UNION) // UNION adds only { if (m_temporaryHandlerTable.ContainsKeys(targetList, eventInfo)) foreach (Delegate handler in m_temporaryHandlerTable[targetList, eventInfo]) { eventInfo.RemoveEventHandler(this, handler); //Console.WriteLine("REMOVED HANDLER " + handler.Target + "." + eventInfo); } } // Add new handlers if (targetList != TargetList.INTERSECT) // INTERSECT removes only { if (m_temporaryHandlerTable.ContainsKeys(targetList, eventInfo)) m_temporaryHandlerTable[targetList, eventInfo].Clear(); else m_temporaryHandlerTable[targetList, eventInfo] = new List<GestureEventHandler>(); foreach (IGestureListener target in groupTargetList) if (m_handlerTable.ContainsKeys(eventInfo, target)) foreach (GestureEventHandler handler in m_handlerTable[eventInfo, target]) { m_temporaryHandlerTable[targetList, eventInfo].Add(handler); eventInfo.AddEventHandler(this, handler); //Console.WriteLine("ADDED HANDLER " + handler.Target + "." + eventInfo); } } } }