public System.Threading.Tasks.Task Execute(PoiService poiService, PoI poi, List<Point> zone) { return System.Threading.Tasks.Task.Run(() => { if (Items == null || Items.Count == 0) return; foreach (var sqlQuery in Items.OfType<SqlQuery>()) { sqlQuery.Execute(poiService, poi, zone); } }); }
public bool handlePoIDestroy(PoI poi) { foreach (PoI p in PoIList) { if (p.Equals(poi)) { p.gameObject.SetActive(false); return(true); } } return(false); }
void Update() { if (GlobalSettingsManager.clickActionActive) { if (Input.GetMouseButtonDown(0)) { RaycastHit hitInfo; Vector3 lookDir = (cam.position + objectCenter.position).normalized; float distance = Vector3.Distance(cam.position, objectCenter.position); if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hitInfo, distance, collisionMask)) { GameObject colliderObject = hitInfo.collider.gameObject; Debug.Log(colliderObject); if (colliderObject.activeSelf) { Interactable current = colliderObject.GetComponent <Interactable>(); Interactable parent = GlobalMethods.FindParentWithTag(colliderObject, "TreeLogic")?.GetComponent <Interactable>(); if (current is Spawned spawn) { int curID = spawn.PoolNumber; spawn.SpawnMaster.despawnObjectWithID(curID); } else if (parent is Trees tree /*&& colliderObject.name.EndsWith("0")*/) { //Debug.Log($"Got called because of {colliderObject}"); tree.Controller.handleTreeDestroy(tree); } else if (colliderObject.CompareTag("PointOfInterest")) { PoI p = colliderObject.GetComponent <PoI>(); p.Controller.handlePoIDestroy(p); } else { } } } else { print("Nothing there to interact with!"); } ownRender.material = normalMat; } } }
//private ObservableCollection<Point> RetreivePoints(IDataRecord dr) //{ // return string.IsNullOrEmpty(pointsField) // ? null // : new ObservableCollection<Point>(dr[pointsField].ToString().ConvertToPointCollection().ToList()); //} /// <summary> /// Replace the parameter placeholders in the query with their values. /// </summary> /// <returns></returns> private string DefineParametrizedQuery(PoI poi, List<Point> zone) { var query = Query; for (var i = 0; i < InputParameters.Count; i++) { var inputParameter = InputParameters[i]; inputParameter.SetValue(poi, zone); query = query.Replace(string.Format("{{{0}}}", i), inputParameter.SqlParameterValue); } return query; }
private static void SetGeometry(PoI poi) { if (poi.Geometry == null) return; if (poi.Geometry as csPoint != null) { var g = poi.Geometry as csCommon.Types.Geometries.Point; if (g != null) poi.Position = new Position(g.X, g.Y); poi.DrawingMode = DrawingModes.Point; } else if (poi.Geometry as LineString != null) { var gl = poi.Geometry as LineString; if (gl != null) foreach (var p in gl.Line) poi.Points.Add(new Point(p.X, p.Y)); poi.DrawingMode = DrawingModes.Polyline; } else if (poi.Geometry as Polygon != null) { poi.DrawingMode = DrawingModes.Polygon; } else if (poi.Geometry as MultiPolygon != null) { poi.DrawingMode = DrawingModes.MultiPolygon; } }
/// <summary> /// Execute the SQL query and update the service. /// </summary> /// <param name="service"></param> /// <param name="refPoi"></param> /// <param name="zone"></param> /// <param name="isQueueAble"></param> /// <param name="forceExecute"></param> /// <returns></returns> public async void Execute(PoiService service, PoI refPoi, List<Point> zone, bool isQueueAble = false, bool forceExecute = false) { Caliburn.Micro.Execute.OnUIThread(() => { var layer = service.Layer as dsStaticLayer; if (layer == null) return; var l = layer.GetSubLayer(Layer); if (l != null) IsEnabled = l.Visible; }); if (!IsEnabled && !forceExecute) return; lock (myLock) { // Cancel the last task, if any. if (cts != null) { if (refPoi != null && isQueueAble) { if (queue.ContainsKey(refPoi) && queue[refPoi] != null) queue[refPoi].Cancel(); } else cts.Cancel(); } // Create Cancellation Token for this task. cts = new CancellationTokenSource(); if (isQueueAble && refPoi != null) queue[refPoi] = cts; } var token = cts.Token; try { await System.Threading.Tasks.Task.Run(() => { while (isExecuting) { token.ThrowIfCancellationRequested(); Thread.Sleep(100); } isExecuting = true; var query = DefineParametrizedQuery(refPoi, zone); token.ThrowIfCancellationRequested(); var poiList = new List<PoI>(); using (var conn = new NpgsqlConnection(ConnectionString)) { try { token.ThrowIfCancellationRequested(); conn.Open(); var command = new NpgsqlCommand(query, conn); // EV Specify in connection string. {CommandTimeout = 30}; var dr = command.ExecuteReader(); token.ThrowIfCancellationRequested(); InitializeFieldNames(dr); #region Processing an iterative SQL query if (Options != null && refPoi != null) { try { var tries = 0; var maxTries = (int)Math.Round(refPoi.LabelToDouble(InputParameters[Options.MaxTriesInputParameterIndex].LabelName), 0); var desiredResult = Options.ComputeDesiredResult(refPoi, InputParameters); var desiredAccurcy = refPoi.LabelToDouble(InputParameters[Options.DesiredAccuracyInputParameterIndex].LabelName); var acceptableDiff = desiredResult * desiredAccurcy / 100; var outputName = OutputParameters[Options.ActualResultOutputParameterIndex].Name; var currentResult = refPoi.LabelToDouble(outputName); var success = Math.Abs(currentResult - desiredResult) <= acceptableDiff; if (success) { dr.Close(); return; } var controlLabelName = InputParameters[Options.ControlInputParameterIndex].LabelName; var control = refPoi.LabelToDouble(controlLabelName); var origControl = control; do { var actualResult = 0.0; while (dr.Read()) { token.ThrowIfCancellationRequested(); var result = dr[outputName].ToString(); if (string.IsNullOrEmpty(result)) continue; actualResult = double.Parse(result, NumberStyles.Any, CultureInfo.InvariantCulture); success = Math.Abs(actualResult - desiredResult) <= acceptableDiff; } if (success) continue; switch (Options.Relationship) { case SqlInputOutputRelationship.Linear: // actual = control * alpha var alpha1 = actualResult / (control.IsZero() ? 0.0001 : control); control = alpha1.IsZero() ? 2 * control : desiredResult / alpha1; break; case SqlInputOutputRelationship.Quadratic: // actual = control^2 * alpha var alpha2 = actualResult / Math.Pow(control.IsZero() ? 0.0001 : control, 2); control = alpha2.IsZero() ? 2 * control : Math.Sqrt(desiredResult / alpha2); break; } refPoi.Labels[controlLabelName] = control.ToString(CultureInfo.InvariantCulture); query = DefineParametrizedQuery(refPoi, zone); command = new NpgsqlCommand(query, conn) { CommandTimeout = 30 }; dr = command.ExecuteReader(); if (++tries > maxTries) { Logger.Log("SqlProcessing.SqlQuery", refPoi.Name + ": " + "Could not resolve query", refPoi.Name + ": Max tries exceeded", Logger.Level.Warning, true); return; } tries++; } while (!success); if (Math.Abs(origControl - control) > 0.001) Caliburn.Micro.Execute.OnUIThread(() => refPoi.TriggerLabelChanged(controlLabelName)); // NOTE I need to redo the same query again to be able to continue, // as I cannot find a way to reset dr. dr = command.ExecuteReader(); } catch (SystemException e) { Logger.Log("SqlProcessing.SqlQuery", refPoi.Name + ": " + "Error running iterative query", e.Message, Logger.Level.Error, true); } } #endregion Processing an iterative SQL query while (dr.Read()) { token.ThrowIfCancellationRequested(); var contentId = RetreiveId(dr); var position = RetreivePosition(dr); var geometry = String.IsNullOrEmpty(pointsField) ? null : dr[pointsField].ToString().ConvertFromWkt(); if (position == null && geometry == null) { AddOutputsAsLabel(refPoi, dr); conn.Close(); isExecuting = false; return; } if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) contentId = refPoi.ContentId + "_" + contentId; var poi = new PoI { ContentId = contentId, Service = service, Name = RetreiveName(dr), PoiTypeId = PoiTypeId, UserId = Id.ToString(), Layer = Layer, Position = position, Style = PoiType == null ? null : PoiType.Style, Geometry = geometry, WktText = dr[pointsField].ToString(), }; SetGeometry(poi); AddOutputsAsLabel(poi, dr); poi.UpdateEffectiveStyle(); poiList.Add(poi); } var currPois = service.PoIs.Where(k => k.PoiTypeId == PoiTypeId).ToList(); Caliburn.Micro.Execute.OnUIThread(() => { service.PoIs.StartBatch(); switch (UpdateType) { case UpdateTypes.Add: poiList.ForEach(p => service.PoIs.Add(p)); break; case UpdateTypes.AutoClear: currPois.ForEach(p => service.PoIs.Remove(p)); poiList.ForEach(p => service.PoIs.Add(p)); break; case UpdateTypes.Diff: //Remove Pois that are no longer needed var poicheck = ""; if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) poicheck = refPoi.ContentId + "_"; var remlist = currPois.Where(k => k.ContentId.StartsWith(poicheck) && poiList.All(g => g.ContentId != k.ContentId)).ToList(); remlist.ForEach(p => service.RemovePoi((PoI)p)); poiList.ForEach( p => { if (currPois.All(c => c.ContentId != p.ContentId)) service.PoIs.Add(p); }); break; case UpdateTypes.DiffGeo: var addDiffGeo = new List<PoI>(); foreach (var p in poiList) { var first = currPois.FirstOrDefault(k => k.ContentId.ToString() == p.ContentId.ToString()); if (first == null || first.WktText == p.WktText) continue; addDiffGeo.Add(p); } var rem = currPois.Where(k => !string.IsNullOrEmpty(k.UserId) && addDiffGeo.Any(g => g.ContentId == k.ContentId)).ToList(); foreach (var r in rem) { service.RemovePoi((PoI)r); } foreach (var a in addDiffGeo) { service.PoIs.Add(a); } //Remove pois wich are no longer needed poicheck = ""; if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) poicheck = refPoi.ContentId + "_"; remlist = currPois.Where(k => k.ContentId.StartsWith(poicheck) && poiList.All(g => g.ContentId != k.ContentId)).ToList(); remlist.ForEach(p => service.RemovePoi((PoI)p)); //Add pois which are new poiList.ForEach(p => { if (currPois.All(c => c.ContentId != p.ContentId)) service.PoIs.Add(p); }); break; } UpdateMinMax(service); service.PoIs.FinishBatch(); //if (refPoi != null && !String.IsNullOrEmpty(refPoi.ContentId)) // poicheck = refPoi.ContentId + "_"; //var remlist =currPoi.Where(k =>k.ContentId.StartsWith(poicheck) && poiList.All(g => g.ContentId != k.ContentId)).ToList(); }); } catch (OperationCanceledException) { } catch (SystemException e) { Logger.Log("SqlProcessing.SqlQuery", refPoi.Name + ": " + "Error accessing PostgreSQL server", e.Message, Logger.Level.Error, true); } finally { lock (myLock) { if (isQueueAble && refPoi != null) queue[refPoi] = null; } isExecuting = false; } } }, token); } catch (OperationCanceledException) { isExecuting = false; } }
// Update is called once per frame void FixedUpdate() { Collider[] hits = Physics.OverlapSphere(centerOfSphere.position, radius, checkLayers); if (hits.Length != 0) { foreach (Collider c in hits) { if (lastTreeCollisions.Select(items => items.c).Contains(c)) { break; } if (c.gameObject.layer == LayerMask.NameToLayer("PoI")) { PoI parent = GlobalMethods.FindParentWithTag(c.gameObject, "PoI")?.GetComponent <PoI>(); if (parent is FallenBigTree fallen) { BrokenTreePart brokenPart = c.gameObject.GetComponent <BrokenTreePart>(); if (brokenPart.Alive) { fallen.DestroyPart(brokenPart); ColliderInfo cInfo = new ColliderInfo(); cInfo.Setup(c, TypeOfParent.P_POI, parent); lastTreeCollisions.Add(cInfo); } } } else if (c.gameObject.layer == LayerMask.NameToLayer("Interactable")) { Interactable parent = GlobalMethods.FindParentWithTag(c.gameObject, "TreeLogic")?.GetComponent <Interactable>(); if (parent is Trees tree) { if (c.name.EndsWith("0") && !tree.lDis.isDissolving) { tree.Controller.handleTreeDestroy(tree); ColliderInfo cInfo = new ColliderInfo(); cInfo.Setup(c, TypeOfParent.P_INT, parent); lastTreeCollisions.Add(cInfo); } } } } Collider[] tempCopy = lastTreeCollisions.Select(item => item.c).ToArray(); for (int i = 0; i < tempCopy.Length; i++) { Collider c = tempCopy[i]; Collider found = hits.FirstOrDefault(pC => pC.name.Equals(c.name)); if (found == null) { lastTreeCollisions.RemoveAt(i); } } /* * foreach(Collider c in tempCopy) * { * Collider found = hits.FirstOrDefault(pC => pC.name.Equals(c.name)); * if(found == null) * { * lastTreeCollisions.Remove(c); * } * } */ } else { lastTreeCollisions.Clear(); } }
void CompositionGUI() { GUILayout.BeginVertical("box"); drawStructurePos = GUILayout.Toggle(drawStructurePos, "Composition", "Button", GUILayout.ExpandWidth(true)); if (drawStructurePos && structure.validFullBlocks != null) { int selectedPos = structure.validFullBlocks[currentBlock].pos; GUILayout.Label(string.Format("Selected position: {0}", selectedPos)); currentBlock = EditorGUILayout.IntSlider(currentBlock, 0, structure.validFullBlocks.Count - 1); GUILayout.BeginHorizontal(); if (currentBlock == 0) { GUI.enabled = false; } if (GUILayout.Button("Previous block")) { currentBlock--; } GUI.enabled = currentBlock < structure.validFullBlocks.Count - 1; if (GUILayout.Button("Next block")) { currentBlock++; } GUI.enabled = true; GUILayout.EndHorizontal(); if (GUILayout.Button("Go to invalid block")) { FindInvalidBlock(); } if (structure.palette.Count == 0) { GUI.enabled = false; } GUILayout.BeginHorizontal(); if (GUILayout.Button("Change all to...")) { DisplayPaletteMenu(PaintingMode.All); } if (GUILayout.Button("Change invalid to...")) { DisplayPaletteMenu(PaintingMode.InvalidOnly); } GUILayout.EndHorizontal(); GUIStyle red = new GUIStyle(EditorStyles.textArea); GUIStyle green = new GUIStyle(EditorStyles.textArea); red.normal.textColor = Color.red; green.normal.textColor = Color.green; GUILayout.BeginHorizontal(); GUILayout.Label(string.Format("Palette value: {0}", structure.validFullBlocks[currentBlock].displayValue), (structure.validFullBlocks[currentBlock].IsInvalid())? red : green); if (GUILayout.Button("Change to...")) { DisplayPaletteMenu(PaintingMode.SelectedOnly); } GUILayout.EndHorizontal(); GUI.enabled = true; GUILayout.BeginHorizontal(); bool isMaster = structure.masterPos == selectedPos; if (GUILayout.Toggle(isMaster, "Make master", "Button") && structure.masterPos != selectedPos) { structure.masterPos = selectedPos; } bool isDisabled = structure.ignoredPositions2.Contains(selectedPos); if (GUILayout.Toggle(isDisabled, "Disable position", "Button") != isDisabled) { isDisabled = !isDisabled; if (isDisabled && !structure.ignoredPositions2.Contains(selectedPos)) { structure.ignoredPositions2.Add(selectedPos); if (structure.masterPos == selectedPos) { structure.masterPos = 0; } } else if (structure.ignoredPositions2.Contains(selectedPos)) { structure.ignoredPositions2.Remove(selectedPos); } } if (GUILayout.Button("Add PoI Entry")) { PoI newEntry = new PoI(); newEntry.pos = selectedPos; structure.pointsOfInterest.Add(newEntry); SceneView.RepaintAll(); } GUILayout.EndHorizontal(); PoIPosition = EditorGUILayout.BeginScrollView(PoIPosition); foreach (PoI point in structure.pointsOfInterest) { if (point.pos != selectedPos) { continue; } GUI.backgroundColor = point.isValid ? Color.green : Color.red; GUILayout.BeginVertical("box"); GUI.backgroundColor = Color.white; point.id = EditorGUILayout.TextField("ID:", point.id); point.isValid = point.id.Length > 0; point.SetFacing((Facing)EditorGUILayout.EnumPopup("Facing:", point.facing)); GUILayout.BeginHorizontal(); point.HideArrow(GUILayout.Toggle(point.hide, "Hide Arrow", "Button")); if (GUILayout.Button("Remove Entry")) { structure.pointsOfInterest.Remove(point); SceneView.RepaintAll(); return; } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } EditorGUILayout.EndScrollView(); } GUILayout.EndVertical(); }
public bool SetValue(PoI poi, List<Point> zone) { var isSucces = false; switch (Type) { case SqlParameterTypes.ExtentRD: case SqlParameterTypes.RegionRD: if (zone != null) { SqlParameterValue = zone.ConvertPointsToWkt(CoordinateType.Rd); isSucces = true; } break; case SqlParameterTypes.PointWGS84: if (poi != null) { SqlParameterValue = poi.Position.Longitude.ToString(CultureInfo.InvariantCulture)+","+poi.Position.Latitude.ToString(CultureInfo.InvariantCulture); isSucces = true; } break; case SqlParameterTypes.ShapeWKT: if (poi != null) { if (!string.IsNullOrEmpty(poi.WktText)) { SqlParameterValue = poi.WktText; } else if (poi.Points != null && poi.Points.Count > 3) SqlParameterValue = poi.Points.ToList().ConvertPointsToWkt(CoordinateType.Rd); isSucces = true; } break; case SqlParameterTypes.ShapeEWKT: if (poi != null) { if (!string.IsNullOrEmpty(poi.WktText)) { SqlParameterValue = poi.WktText; } else if (poi.Points != null && poi.Points.Count > 3) SqlParameterValue = poi.Points.ToList().ConvertPointsToEwkt(); isSucces = true; } break; case SqlParameterTypes.PointRD: if (poi != null) { var coordinate = CoordinateUtils.LatLon2Rd(new Point(poi.Position.Longitude, poi.Position.Latitude)); SqlParameterValue = coordinate.X.ToString(CultureInfo.InvariantCulture) + "," + coordinate.Y.ToString(CultureInfo.InvariantCulture); isSucces = true; } break; case SqlParameterTypes.ExtentWGS84: case SqlParameterTypes.RegionWGS84: if (zone != null) { SqlParameterValue = zone.ConvertPointsToWkt(CoordinateType.Degrees); isSucces = true; } break; case SqlParameterTypes.RadiusInMeter: case SqlParameterTypes.Label: if (poi == null) break; if (poi.Labels.ContainsKey(LabelName)) { SqlParameterValue = poi.Labels[LabelName]; isSucces = true; } else if (poi.Service != null && poi.Service.Settings != null && poi.Service.Settings.Labels.ContainsKey(LabelName)) { SqlParameterValue = poi.Service.Settings.Labels[LabelName]; isSucces = true; } break; } return isSucces; }