public void Launch(Character owner, Vector3 direction, float speed, float damage, bool canFriendlyFire, float splashRange) { this.Owner = owner; this.Speed = speed; this.Direction = direction; this.Damage = damage; this.CanFriendlyFire = canFriendlyFire; _splashRange = splashRange; _frameCountStart = Time.frameCount; transform.position = this.Owner.Pawn.GetWeaponPosition(); transform.rotation = this.Owner.Pawn.rotation; _timer = new AutoTimer(Lifetime); var colorer = GetComponent <ProjectileColorer>(); if (colorer != null) { colorer.Apply(Owner.IsEnemy()); } enabled = true; }
private byte[] FindNearFeatures(int layerID, IPoint location, double distance) { if (layerID < 0) { throw new ArgumentOutOfRangeException("layerID"); } if (distance <= 0.0) { throw new ArgumentOutOfRangeException("distance"); } IGeometry queryGeometry = ((ITopologicalOperator)location).Buffer(distance); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = queryGeometry; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IQueryResultOptions resultOptions = new QueryResultOptionsClass(); resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; AutoTimer timer = new AutoTimer(); //starts the timer IMapTableDescription tableDesc = GetTableDesc(layerID); this.serverLog.LogMessage(ServerLogger.msgType.infoDetailed, "FindNearFeatures", -1, timer.Elapsed, "Finding table description elapsed this much."); IQueryResult result = this.ms.QueryData(this.ms.DefaultMapName, tableDesc, filter, resultOptions); return(result.MimeData); }
public void Construct(IPropertySet props) { AutoTimer timer = new AutoTimer(); serverLog.LogMessage(ServerLogger.msgType.infoSimple, "Construct", -1, soeName + " Construct has started."); configProps = props; //TODO - put any construct-time logic here serverLog.LogMessage(ServerLogger.msgType.infoSimple, "Construct", -1, timer.Elapsed, soeName + " Construct has completed."); }
private IEnumerator Start() { var timer = new AutoTimer(fadeInDuration); while (timer.ValueNormalized < 1f) { transform.localScale = Vector3.one * scaleCurve.Evaluate(timer.ValueNormalized); yield return(null); } }
private IEnumerator Approach() { var timer = new AutoTimer(2f); var initialPosition = transform.position; var targetPosition = initialPosition.Set(x: AttackTarget.transform.position.x + Random.Range(-2f, 2f)); while (timer.ValueNormalized < 1f) { transform.position = Vector3.Lerp(initialPosition, targetPosition, Mathf.Sqrt(timer.ValueNormalized)); yield return(null); } }
private IEnumerable HealingCoroutine(float duration, float speed) { yield return(null); var timer = new AutoTimer(duration); while (timer.ValueNormalized != 1f) { Character.Heal(speed * Time.deltaTime); yield return(null); } }
public override IEnumerable GetEvaluationBlock() { (character as EMCharacter).RemoveFromGrid(); var timer = new AutoTimer(typedInfo._removeDelay); while (timer.ValueNormalized < 1) { yield return(null); } character.Destroy(); }
private void StartButton_Click(object sender, EventArgs e) { _isRunning = !_isRunning; SetUI(_isRunning); if (_isRunning) { AutoTimer.Start(); } else { AutoTimer.Stop(); } }
private IEnumerable LerpToDistance() { var timer = new AutoTimer(1f); var from = transform.localPosition; var to = transform.localPosition + Vector3.up * deathOffset; while (timer.ValueNormalized < 1f) { transform.localPosition = Vector3.Lerp(from, to, timer.ValueNormalized); yield return(null); } }
private IEnumerator Start() { var timer = new AutoTimer( fadeInDuration ); var currentPosition = localPosition; while ( timer.ValueNormalized < 1f ) { transform.localScale = Vector3.one * scaleCurve.Evaluate( timer.ValueNormalized ); //transform.localPosition = currentPosition + transform.up * positionCurve.Evaluate( timer.ValueNormalized ); yield return null; } }
private IEnumerator ScaleAnimation(GameObject target, Vector3 from, Vector3 to) { target.SetActive(true); var initialScale = target.transform.localScale; var timer = new AutoTimer(_duration); while (timer.ValueNormalized != 1f) { target.transform.localScale = Vector3.Lerp(from, to, Mathf.Sqrt(timer.ValueNormalized)); yield return(null); } }
public override IEnumerable GetEvaluationBlock() { var character = stateController.character; var potion = character.Inventory.GetItems().FirstOrDefault(where => where.info == typedInfo.potionItemInfo); potion.Apply(); var timer = new AutoTimer(typedInfo.duration); while (timer.ValueNormalized < 1f) { yield return(null); } }
private IEnumerable LerpToDistance() { var timer = new AutoTimer( 1f ); var from = transform.localPosition; var to = transform.localPosition + Vector3.up * deathOffset; while ( timer.ValueNormalized < 1f ) { transform.localPosition = Vector3.Lerp( from, to, timer.ValueNormalized ); yield return null; } }
public IEnumerable Fade(bool isOut) { var duration = _fadeSpeed; var timer = new AutoTimer(duration); var toColor = Color.black; toColor.a = 0; while (timer.ValueNormalized < 1) { _spriteRenderer.color = Color.Lerp(Color.white, toColor, isOut ? 1 - timer.ValueNormalized : timer.ValueNormalized); yield return(null); } }
public void Launch( Character owner, Vector3 direction, float speed, int damage ) { this.owner = owner; this.speed = speed; this.direction = direction; this.damage = damage; _planetTransform = new PlanetSurfaceTransform( Planet.instance ); _planetTransform.SetHeight( owner.pawn.planetTransform.height ); transform.position = this.owner.pawn.position; transform.rotation = this.owner.pawn.rotation; timer = new AutoTimer( lifetime ); enabled = true; }
public void Launch(Character owner, Vector3 direction, float speed, float damage, bool canFriendlyFire, float splashRange) { this.Owner = owner; this.Speed = speed; this.Direction = direction; this.Damage = damage; this.CanFriendlyFire = canFriendlyFire; _splashRange = splashRange; _frameCountStart = Time.frameCount; transform.position = owner.Pawn.position; transform.rotation = this.Owner.Pawn.rotation; _timer = new AutoTimer(Lifetime); enabled = true; }
// Use this for initialization IEnumerator Start() { yield return(new WaitForSeconds(Delay)); var from = TextMesh.color; var to = TextMesh.color; to.a = 0; var timer = new AutoTimer(Duration); while (timer.ValueNormalized < 1f) { TextMesh.color = Color.Lerp(from, to, timer.ValueNormalized); yield return(null); } }
private IEnumerable MoveAnimation(float duration, int targetX, int targetY) { var emCharacter = character as EMCharacter; emCharacter.SetPosition(targetX, targetY, updatePawnPosition: false); var fromPosition = character.Pawn.position; var toPosition = emCharacter.BattleGrid.GridToWorldPosition(targetX, targetY); var timer = new AutoTimer(duration); while (timer.ValueNormalized < 1) { character.Pawn.position = Vector3.Slerp(fromPosition, toPosition, timer.ValueNormalized); yield return(null); } }
//postavi slučajni timer kad se UFO pojavljuje public UFO() { Random rnd = new Random(); IntervalPojavljivanja = new AutoTimer(rnd.Next(1000, 2000)); if (Neprijatelj.SePomaknuo) { IntervalPojavljivanja.Start(); } BoxCollider collider = new BoxCollider(24, 24, Oznake.Ufo); Visible = false; Collidable = false; Bodovi = rnd.Next(0, 3) * 50; AddCollider(collider); AddGraphic(IkonaNeprijatelja); }
private IEnumerable RegenAcorns(Character target) { var timer = default(AutoTimer); while (true) { var acornRegenValue = target.Status.ModifierCalculator.CalculateFinalValue(ModifierType.BaseAcornRegen, 0f); if (acornRegenValue <= 0) { yield return(null); continue; } if (timer != null) { if (timer.ValueNormalized == 1f) { var acornCount = target.Inventory.GetItemCount <AcornAmmoItemInfo.AcornAmmo>(); if (acornCount >= target.Status.ModifierCalculator.CalculateFinalValue(ModifierType.MaxAcorns, 0f)) { yield return(null); continue; } target.Inventory.AddItem(AcornAmmoItemInfo.GetItem()); timer = null; } } else { var regenDuration = 1f / acornRegenValue; timer = new AutoTimer(regenDuration); } yield return(null); } }
//Sets a random timer when UFO appears public UFO() { Random rnd = new Random(); MainScene scene = Program.game.GetScene <MainScene>(); AppearTimer = new AutoTimer(rnd.Next(1000, 2000)); if (Enemy.hasMoved) { AppearTimer.Start(); } BoxCollider collider = new BoxCollider(24, 24, Tags.Ufo); Visible = false; Collidable = false; Score = rnd.Next(0, 3) * 50; AddCollider(collider); AddGraphic(EnemyImage); }
/// <summary> /// construct() is called only once, when the SOE is created, after IServerObjectExtension.init() is called. This /// method hands back the configuration properties for the SOE as a property set. You should include any expensive /// initialization logic for your SOE within your implementation of construct(). /// </summary> /// <param name="props">object propertySet</param> public void Construct(IPropertySet props) { AutoTimer timer = new AutoTimer(); this.LogInfoSimple(this.soeName + ": il costruttore è stato avviato.", MethodBase.GetCurrentMethod().Name); try { this.configProps = props; if (this.configProps.GetProperty("workspaceId") is string) { this.workspaceId = this.configProps.GetProperty("workspaceId") as string; } if (this.configProps.GetProperty("connectionString") is string) { this.workspace = Helper.OpenFileGdbWorkspace(this.configProps.GetProperty("connectionString") as string); } IMapServer3 mapServer = this.serverObjectHelper.ServerObject as IMapServer3; IMapServerInit mapServerInit = mapServer as IMapServerInit; string hostnameWebAdaptor = string.Empty; if (this.configProps.GetProperty("rootWebAdaptor") is string) { hostnameWebAdaptor = this.configProps.GetProperty("rootWebAdaptor") as string; } this.pathOutputVirtualAGS = Helper.CombineUri(hostnameWebAdaptor, mapServerInit.VirtualOutputDirectory); // c'è il replace perchè se il nome del servizio è in una cartella ags il percorso restituito ha '/' nel path tra folder ags e nome servizio this.pathOutputAGS = mapServerInit.PhysicalOutputDirectory.Replace('/', '\\'); } catch (Exception ex) { this.LogError(this.soeName + ": " + ex.Message, MethodBase.GetCurrentMethod().Name); } this.LogInfoSimple(this.soeName + ": il costruttore ha concluso", MethodBase.GetCurrentMethod().Name, timer.Elapsed); }
private IEnumerator Loop() { var timer = new AutoTimer(EnemyInfo.TimeToActivateEffect); while (timer.ValueNormalized < 1) { Debug.Log((EnemyInfo.TimeToActivateEffect - timer.Value) + " until " + EnemyInfo.ActivatedEffect); if (_isTurnActive) { OnFinish(); yield break; } yield return(null); } OnFinish(); AttackTarget.Damage(EnemyInfo.SpeedPenalty); }
private IEnumerator PlayAnimation() { var from = transform.position; var to = transform.position + Vector3.up * _distanceDelta; var fromColor = _value.color; var toColor = _value.color; toColor.a = 0; var timer = new AutoTimer(_duration); while (timer.ValueNormalized < 1) { transform.position = Vector3.Lerp(from, to, timer.ValueNormalized); _value.color = Color.Lerp(fromColor, toColor, timer.ValueNormalized); yield return(null); } Destroy(gameObject); }
public override IEnumerable GetEvaluationBlock() { var timer = new AutoTimer(typedInfo.duration / character.StatModifier); _roomDevice.IsBeingRepared = true; while (timer.ValueNormalized < 1) { yield return(null); } if (_roomDevice.IsBroken()) { _roomDevice.SetFixed(); } else { _roomDevice.Interact(character); } _roomDevice.IsBeingRepared = false; _roomDevice = null; }
///<summary> /// @copydoc HardwarePixelBuffer.BlitFromMemory ///</summary> public override void BlitFromMemory(PixelBox src, BasicBox dstBox) { using (AutoTimer timer = new AutoTimer(timingMeter)) { BlitFromMemoryImpl(src, dstBox); } }
private static void ParseDataToContainer(AutoActionContainer container, JsonData content) { for (int i = 0; i < content.Count; i++) { string key = content[i].TryGetString("name"); JsonData data = content[i]["data"]; AutoAction action = null; switch (key) { case "Container": action = Parse(data); break; case "WaitScene": string waitSceneName = data.TryGetString("scene_name"); action = new AutoWaitScene(waitSceneName); break; case "WaitObjectAppear": string objectAppear = data.TryGetString("object_name"); action = new AutoWaitObjectAppear(objectAppear); break; case "WaitObjectDisappear": string objectDisappear = data.TryGetString("object_name"); action = new AutoWaitObjectAppear(objectDisappear); break; case "WaitComponentAppear": string componentAppear = data.TryGetString("component_name"); action = new AutoWaitComponentAppear(Type.GetType(componentAppear)); break; case "WaitComponentDisappear": string componentDisappear = data.TryGetString("component_name"); action = new AutoWaitComponentDisappear(Type.GetType(componentDisappear)); break; case "LabelTextAppear": string labelObjectName = data.TryGetString("object_name"); string textContent = data.TryGetString("content"); action = new AutoLabelTextAppear(labelObjectName, textContent); break; case "Timer": string time = data.TryGetString("time_length"); action = new AutoTimer(float.Parse(time)); break; case "WaitButtonAccessible": string buttonName = data.TryGetString("button_name"); action = new AutoWaitButtonAccessiable(buttonName); break; case "Click": float x = float.Parse(data.TryGetString("pos_x")); float y = float.Parse(data.TryGetString("pos_y")); float z = float.Parse(data.TryGetString("pos_z")); action = new AutoClick(new UnityEngine.Vector3(x, y, z)); break; case "PressUI": string uiName = data.TryGetString("ui_name"); action = new AutoPressUI(uiName); break; case "LoadScene": string loadSceneName = data.TryGetString("scene_name"); action = new AutoLoadScene(loadSceneName); break; } if (action != null) { container.AddAction(action); } } }
/// <summary> /// /// </summary> private void LoadVolumeTexture() { Debug.Assert(this.TextureType == TextureType.ThreeD); using (AutoTimer auto = new AutoTimer(textureLoadMeter)) { // DDS load? if (name.EndsWith(".dds")) { Stream stream = TextureManager.Instance.FindResourceData(name); // use D3DX to load the image directly from the stream int numMips = numRequestedMipmaps + 1; // check if mip map volume textures are supported if (!(devCaps.TextureCaps.SupportsMipVolumeMap)) { // no mip map support for this kind of textures :( numMipmaps = 0; numMips = 1; } // Determine D3D pool to use D3D.Pool pool; if ((usage & TextureUsage.Dynamic) != 0) pool = D3D.Pool.Default; else pool = D3D.Pool.Managed; Debug.Assert(volumeTexture == null); Debug.Assert(texture == null); // load the cube texture from the image data stream directly volumeTexture = TextureLoader.FromVolumeStream(device, stream, (int)stream.Length, 0, 0, 0, numMips, D3D.Usage.None, D3D.Format.Unknown, pool, Filter.Triangle | Filter.Dither, Filter.Box, 0); // store off a base reference texture = volumeTexture; // set the image data attributes VolumeDescription desc = volumeTexture.GetLevelDescription(0); d3dPool = desc.Pool; // set src and dest attributes to the same, we can't know SetSrcAttributes(desc.Width, desc.Height, desc.Depth, D3DHelper.ConvertEnum(desc.Format)); SetFinalAttributes(desc.Width, desc.Height, desc.Depth, D3DHelper.ConvertEnum(desc.Format)); isLoaded = true; internalResourcesCreated = true; stream.Dispose(); } else { // find & load resource data into stream Stream stream = TextureManager.Instance.FindResourceData(name); int pos = name.LastIndexOf('.'); string ext = name.Substring(pos + 1); Image img = Image.FromStream(stream, ext); LoadImage(img); stream.Dispose(); } } // using }
public static string ExportScene() { var current = SaveLoadScript.m_Instance.SceneFile; string safeHumanName = FileUtils.SanitizeFilename(current.HumanName); string basename = FileUtils.SanitizeFilename( (current.Valid && (safeHumanName != "")) ? safeHumanName : "Untitled"); string parent = FileUtils.GenerateNonexistentFilename(App.UserExportPath(), basename, ""); if (!FileUtils.InitializeDirectoryWithUserError( parent, "Failed to create export directory")) { return(""); } // Set up progress bar. var progress = new Progress(); if (App.PlatformConfig.EnableExportJson) { progress.SetWork("json"); } #if FBX_SUPPORTED if (App.PlatformConfig.EnableExportFbx) { progress.SetWork("fbx"); } #endif #if USD_SUPPORTED if (App.PlatformConfig.EnableExportUsd) { progress.SetWork("usd"); } #endif #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (Config.IsExperimental) { progress.SetWork("wrl"); progress.SetWork("stl"); #if FBX_SUPPORTED progress.SetWork("obj"); #endif } #endif if (App.PlatformConfig.EnableExportGlb) { progress.SetWork("glb"); } string filename; if (App.PlatformConfig.EnableExportJson && (filename = MakeExportPath(parent, basename, "json")) != null) { using (var unused = new AutoTimer("raw export")) { OverlayManager.m_Instance.UpdateProgress(0.1f); ExportRaw.Export(filename); } } progress.CompleteWork("json"); #if FBX_SUPPORTED if (App.PlatformConfig.EnableExportFbx && (filename = MakeExportPath(parent, basename, "fbx")) != null) { using (var unused = new AutoTimer("fbx export")) { OverlayManager.m_Instance.UpdateProgress(0.3f); ExportFbx.Export(filename, App.UserConfig.Export.ExportBinaryFbx ? ExportFbx.kFbxBinary : ExportFbx.kFbxAscii, App.UserConfig.Export.ExportFbxVersion); OverlayManager.m_Instance.UpdateProgress(0.5f); } } progress.CompleteWork("fbx"); #endif #if USD_SUPPORTED if (App.PlatformConfig.EnableExportUsd && (filename = MakeExportPath(parent, basename, "usd")) != null) { using (var unused = new AutoTimer("usd export")) { ExportUsd.ExportPayload(filename); } } progress.CompleteWork("usd"); #endif #if (UNITY_EDITOR || EXPERIMENTAL_ENABLED) if (Config.IsExperimental && (filename = MakeExportPath(parent, basename, "wrl")) != null) { ExportVrml.Export(filename); progress.CompleteWork("wrl"); } if (Config.IsExperimental && (filename = MakeExportPath(parent, basename, "stl")) != null) { ExportStl.Export(filename); progress.CompleteWork("stl"); } #if FBX_SUPPORTED if (Config.IsExperimental && App.PlatformConfig.EnableExportFbx && (filename = MakeExportPath(parent, basename, "obj")) != null) { // This has never been tested with the new fbx export style and may not work ExportFbx.Export(filename, ExportFbx.kObj); progress.CompleteWork("obj"); } #endif #endif var results = new ExportGlTF.ExportResults(); if (App.PlatformConfig.EnableExportGlb) { string extension = App.Config.m_EnableGlbVersion2 ? "glb" : "glb1"; int gltfVersion = App.Config.m_EnableGlbVersion2 ? 2 : 1; filename = MakeExportPath(parent, basename, extension); if (filename != null) { using (var unused = new AutoTimer("glb export")) { OverlayManager.m_Instance.UpdateProgress(0.7f); var exporter = new ExportGlTF(); // TBT doesn't need (or want) brush textures in the output because it replaces all // the materials, so it's fine to keep those http:. However, Sketchfab doesn't support // http textures so if uploaded, this glb will have missing textures. results = exporter.ExportBrushStrokes( filename, AxisConvention.kGltf2, binary: true, doExtras: false, includeLocalMediaContent: true, gltfVersion: gltfVersion); progress.CompleteWork("glb"); } } } OutputWindowScript.m_Instance.CreateInfoCardAtController( InputManager.ControllerName.Brush, basename + " exported! Your download will begin in 5 seconds."); ControllerConsoleScript.m_Instance.AddNewLine("Located in " + App.UserExportPath()); string readmeFilename = Path.Combine(App.UserExportPath(), kExportReadmeName); if (!File.Exists(readmeFilename) && !Directory.Exists(readmeFilename)) { File.WriteAllText(readmeFilename, kExportReadmeBody); } return(results.exportedFiles[0]); }
private Byte[] GetUserSiteFeatures(String userID) { SqlCommand cmd = new SqlCommand("_IWC_GetUserSites", sqlConn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter param = cmd.Parameters.AddWithValue("@userID", userID); SqlDataReader reader = cmd.ExecuteReader(); String siteCodes = null; if (reader.HasRows) { while (reader.Read()) { siteCodes = siteCodes + "'" + reader.GetString(0) + "',"; } siteCodes = siteCodes.Substring(0, siteCodes.Length - 1); } reader.Close(); IMapServer3 mapServer = serverObjectHelper.ServerObject as IMapServer3; if (mapServer == null) throw new Exception("Unable to access the map server."); IQueryFilter filter = new QueryFilterClass(); filter.WhereClause = "WI_Sitecode IN (" + siteCodes + ")"; IQueryResultOptions resultOptions = new QueryResultOptionsClass(); resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; AutoTimer timer = new AutoTimer(); //starts the timer IMapTableDescription tableDesc = GetTableDesc(mapServer, 0); logger.LogMessage(ServerLogger.msgType.infoDetailed, "GetUserSiteFeatures", -1, timer.Elapsed, "Finding table description elapsed this much."); IQueryResult result = mapServer.QueryData(mapServer.DefaultMapName, tableDesc, filter, resultOptions); return result.MimeData; }
private void OnGUI() { if (GUI.Button(new Rect(50, 50, 50, 50), "test")) { AutoActionContainer container = new AutoActionContainer(); AutoLoadScene loadScene = new AutoLoadScene("test"); AutoClick click = new AutoClick(new Vector3(10, 20, 30)); AutoTimer timer = new AutoTimer(5); AutoPressUI pressUI = new AutoPressUI("bg"); container.AddAction(loadScene); container.AddAction(click); container.AddAction(timer); container.AddAction(pressUI); AutoActionContainer container2 = new AutoActionContainer(); AutoWaitObjectAppear objectAppear = new AutoWaitObjectAppear("page"); AutoWaitObjectAppear objectDisappear = new AutoWaitObjectAppear("pageDis"); AutoWaitComponentAppear componentAppear = new AutoWaitComponentAppear(typeof(Image)); AutoWaitComponentDisappear componentDisappear = new AutoWaitComponentDisappear(typeof(Button)); AutoLabelTextAppear labelText = new AutoLabelTextAppear("label", "hello world"); container2.AddAction(container); container2.AddAction(objectAppear); container2.AddAction(labelText); container2.AddAction(objectDisappear); container2.AddAction(componentAppear); container2.AddAction(componentDisappear); string json = AutoActionJsonWriter.Write(container2); Debug.Log("json is:" + json); JsonData data = JsonMapper.ToObject(json); AutoActionContainer newContainer = AutoActionJsonParser.Parse(data) as AutoActionContainer; foreach (AutoAction action in newContainer.ActionList) { Debug.Log(action.GetType().Name); if (action.GetType().Name == "AutoActionContainer") { foreach (AutoAction childAction in (action as AutoActionContainer).ActionList) { Debug.Log(childAction.GetType().Name); } } } } }
/// <summary> /// Creates and Serves vector tiles /// </summary> /// <param name="boundVariables"></param> /// <param name="operationInput"></param> /// <param name="outputFormat"></param> /// <param name="requestProperties"></param> /// <param name="responseProperties"></param> /// <returns></returns> private byte[] VectorTileHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { //responseProperties = null; responseProperties = null; //"Content-Type:application/json"; ESRI.ArcGIS.SOESupport.AutoTimer timer = new AutoTimer(); const string methodName = "VectorTileHandler"; try { long? layerIndex; long? zoom; long? row; long? col; string jsonFormatParam; TileFormat jsonFormat = TileFormat.EsriJson; // Defaulting to EsriJson if (!operationInput.TryGetAsLong("l", out layerIndex)) throw new ArgumentNullException("layer"); if (!operationInput.TryGetAsLong("z", out zoom)) throw new ArgumentNullException("zoom"); if (!operationInput.TryGetAsLong("y", out row)) throw new ArgumentNullException("row"); if (!operationInput.TryGetAsLong("x", out col)) throw new ArgumentNullException("col"); if (operationInput.TryGetString("jf", out jsonFormatParam)) { if (!string.IsNullOrEmpty(jsonFormatParam)) { jsonFormatParam = jsonFormatParam.ToLower().Trim(); Enum.GetNames(typeof(TileFormat)).ToList().ForEach(n => { if (n.ToLower() == jsonFormatParam) { jsonFormat = (TileFormat)Enum.Parse(typeof(TileFormat), jsonFormatParam, true); } }); } } //System.Diagnostics.Debug.WriteLine(string.Format("l:{0}, r:{1}, c:{2}", zoom, row, col)); // Check to see if the tile exists on disk... // <cache-root>\<layerId>\<zoom>\<row>\<col>.esrijson; //i.e. to be consistent with Esri tile caching structure string tilePath = string.Format(@"{0}\{1}\{2}\{3}\{4}.{5}", _vectorCacheRootDirectory, layerIndex, zoom.Value, row.Value, col.Value, jsonFormat.ToString().ToLower()); if (File.Exists(tilePath)) { // Fetch tile contents from disk _dtsLogger.LogInfo(soe_name, methodName, "Time: " + timer.Elapsed.ToString()); logger.LogMessage(ServerLogger.msgType.infoSimple, methodName, -1, "Time: " + timer.Elapsed.ToString()); return this.ReadTileFile(tilePath); } else { // Write new files to disk IMapServer3 mapServer = serverObjectHelper.ServerObject as IMapServer3; if (mapServer == null) { throw new InvalidOperationException("Unable to access the map server."); } // Get the bbox. Returns an envelope in WGS84 (4326). IEnvelope env102100 = TileUtil.GetEnvelopeFromZoomRowCol((int)zoom.Value, (int)row.Value, (int)col.Value); //_dtsLogger.LogInfo(soe_name, methodName, this.GeometryToXml(env4326)); // Convert envelope to polygon b/c QueryData does not support spatialfilter geometry using envelope IPolygon polygon102100 = this.CreatePolygonFromEnvelope(env102100); // Use QueryData and generalize result geometries based on zoom level IQueryResultOptions resultOptions = new QueryResultOptionsClass(); // i.e; IRecordSet to support BOTH json and geojson resultOptions.Format = esriQueryResultFormat.esriQueryResultRecordSetAsObject; IMapTableDescription tableDescription = this.GetTableDescription(mapServer, (int)layerIndex, (int)zoom); // Create spatial filter ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = polygon102100; spatialFilter.GeometryField = "Shape"; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; //TODO: Subfields should be configurable spatialFilter.SubFields = "*"; // Execute query IQueryResult result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, spatialFilter, resultOptions); byte[] json = null; // TODO: Support writing tiles for no data // Need a way to do this for GeoJson; parse Esri JSON recordset into GeoJson if (result == null || !this.RecordsetHasFeatures(result.Object as IRecordSet)) { // Write "no data" tile if (jsonFormat == TileFormat.EsriJson) { resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, spatialFilter, resultOptions); json = result.MimeData; } else { json = StrToByteArray(NO_DATA_GEOJSON); } } else { //We have features... IRecordSet features = result.Object as IRecordSet; // Get geometry type for query layer esriGeometryType geometryType = this.GetLayerGeometryType(mapServer.GetServerInfo(mapServer.DefaultMapName).MapLayerInfos, (int)layerIndex); switch (geometryType) { case esriGeometryType.esriGeometryPoint: // Do nothing... already intersected json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features); break; case esriGeometryType.esriGeometryPolyline: // Polylines must be clipped to envelope IFeatureCursor cursor = null; this.ClipFeaturesToTile(ref cursor, ref features, env102100); json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features); this.ReleaseComObject(cursor); break; case esriGeometryType.esriGeometryMultipoint: case esriGeometryType.esriGeometryPolygon: // Get IDs of features whose centroid is contained by tile envelope List<int> ids = this.GetIdsOfContainedFeatureCentroids(features, polygon102100); if (ids.Count == 0) { // Write no data tile if (jsonFormat == TileFormat.EsriJson) { // Query to get empty featureset and serialize to disk resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = "*"; queryFilter.WhereClause = "1=2"; result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, queryFilter, resultOptions); json = result.MimeData; } else { json = StrToByteArray(NO_DATA_GEOJSON); } } else { // Execute new query for IDs IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = "*"; // TODO: Account for sql query syntax based on datasource // FGDB/Shapefile then "OBJECTID"; quotes required // PGDB then [OBJECTID]; brackets required // SDE then OBJECTID; nothing but the fieldname queryFilter.WhereClause = string.Format("\"OBJECTID\" IN({0})", ids.ToDelimitedString<int>(",")); // FGDB result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, queryFilter, resultOptions); features = result.Object as IRecordSet; // Do some checking here... var featureCount = this.GetRecordsetFeatureCount(features); if (featureCount != ids.Count) { System.Diagnostics.Debug.WriteLine(string.Format("Query Problem: ID search results IS NOT EQUAL to contained IDs count - [{0}:{1}]", featureCount, ids.Count)); System.Diagnostics.Debug.WriteLine("Query: " + queryFilter.WhereClause); } json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features); } break; default: throw new NotSupportedException(string.Format("Geometry type {0} is not supported by {1}", geometryType.ToString(), soe_name)); } } //store the json to disk this.WriteTileFile(json, tilePath, (int)layerIndex, (int)zoom, (int)row); _dtsLogger.LogInfo(soe_name, methodName,"Time: " + timer.Elapsed.ToString()); logger.LogMessage(ServerLogger.msgType.infoSimple,methodName,-1,"Time: " + timer.Elapsed.ToString()); return json; } } catch (Exception ex) { // Log the error _dtsLogger.LogError(soe_name, methodName, "n/a", ex); logger.LogMessage(ServerLogger.msgType.error, methodName, 9999, ex.StackTrace); return StrToByteArray("{}"); } }
/// <summary> /// Creates and Serves vector tiles /// </summary> /// <param name="boundVariables"></param> /// <param name="operationInput"></param> /// <param name="outputFormat"></param> /// <param name="requestProperties"></param> /// <param name="responseProperties"></param> /// <returns></returns> private byte[] VectorTileHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { //responseProperties = null; responseProperties = null; //"Content-Type:application/json"; ESRI.ArcGIS.SOESupport.AutoTimer timer = new AutoTimer(); const string methodName = "VectorTileHandler"; try { long? layerIndex; long? zoom; long? row; long? col; string jsonFormatParam; TileFormat jsonFormat = TileFormat.EsriJson; // Defaulting to EsriJson if (!operationInput.TryGetAsLong("l", out layerIndex)) { throw new ArgumentNullException("layer"); } if (!operationInput.TryGetAsLong("z", out zoom)) { throw new ArgumentNullException("zoom"); } if (!operationInput.TryGetAsLong("y", out row)) { throw new ArgumentNullException("row"); } if (!operationInput.TryGetAsLong("x", out col)) { throw new ArgumentNullException("col"); } if (operationInput.TryGetString("jf", out jsonFormatParam)) { if (!string.IsNullOrEmpty(jsonFormatParam)) { jsonFormatParam = jsonFormatParam.ToLower().Trim(); Enum.GetNames(typeof(TileFormat)).ToList().ForEach(n => { if (n.ToLower() == jsonFormatParam) { jsonFormat = (TileFormat)Enum.Parse(typeof(TileFormat), jsonFormatParam, true); } }); } } //System.Diagnostics.Debug.WriteLine(string.Format("l:{0}, r:{1}, c:{2}", zoom, row, col)); // Check to see if the tile exists on disk... // <cache-root>\<layerId>\<zoom>\<row>\<col>.esrijson; //i.e. to be consistent with Esri tile caching structure string tilePath = string.Format(@"{0}\{1}\{2}\{3}\{4}.{5}", _vectorCacheRootDirectory, layerIndex, zoom.Value, row.Value, col.Value, jsonFormat.ToString().ToLower()); if (File.Exists(tilePath)) { // Fetch tile contents from disk _dtsLogger.LogInfo(soe_name, methodName, "Time: " + timer.Elapsed.ToString()); logger.LogMessage(ServerLogger.msgType.infoSimple, methodName, -1, "Time: " + timer.Elapsed.ToString()); return(this.ReadTileFile(tilePath)); } else { // Write new files to disk IMapServer3 mapServer = serverObjectHelper.ServerObject as IMapServer3; if (mapServer == null) { throw new InvalidOperationException("Unable to access the map server."); } // Get the bbox. Returns an envelope in WGS84 (4326). IEnvelope env102100 = TileUtil.GetEnvelopeFromZoomRowCol((int)zoom.Value, (int)row.Value, (int)col.Value); //_dtsLogger.LogInfo(soe_name, methodName, this.GeometryToXml(env4326)); // Convert envelope to polygon b/c QueryData does not support spatialfilter geometry using envelope IPolygon polygon102100 = this.CreatePolygonFromEnvelope(env102100); // Use QueryData and generalize result geometries based on zoom level IQueryResultOptions resultOptions = new QueryResultOptionsClass(); // i.e; IRecordSet to support BOTH json and geojson resultOptions.Format = esriQueryResultFormat.esriQueryResultRecordSetAsObject; IMapTableDescription tableDescription = this.GetTableDescription(mapServer, (int)layerIndex, (int)zoom); // Create spatial filter ISpatialFilter spatialFilter = new SpatialFilterClass(); spatialFilter.Geometry = polygon102100; spatialFilter.GeometryField = "Shape"; spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; //TODO: Subfields should be configurable spatialFilter.SubFields = "*"; // Execute query IQueryResult result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, spatialFilter, resultOptions); byte[] json = null; // TODO: Support writing tiles for no data // Need a way to do this for GeoJson; parse Esri JSON recordset into GeoJson if (result == null || !this.RecordsetHasFeatures(result.Object as IRecordSet)) { // Write "no data" tile if (jsonFormat == TileFormat.EsriJson) { resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, spatialFilter, resultOptions); json = result.MimeData; } else { json = StrToByteArray(NO_DATA_GEOJSON); } } else { //We have features... IRecordSet features = result.Object as IRecordSet; // Get geometry type for query layer esriGeometryType geometryType = this.GetLayerGeometryType(mapServer.GetServerInfo(mapServer.DefaultMapName).MapLayerInfos, (int)layerIndex); switch (geometryType) { case esriGeometryType.esriGeometryPoint: // Do nothing... already intersected json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features); break; case esriGeometryType.esriGeometryPolyline: // Polylines must be clipped to envelope IFeatureCursor cursor = null; this.ClipFeaturesToTile(ref cursor, ref features, env102100); json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features); this.ReleaseComObject(cursor); break; case esriGeometryType.esriGeometryMultipoint: case esriGeometryType.esriGeometryPolygon: // Get IDs of features whose centroid is contained by tile envelope List <int> ids = this.GetIdsOfContainedFeatureCentroids(features, polygon102100); if (ids.Count == 0) { // Write no data tile if (jsonFormat == TileFormat.EsriJson) { // Query to get empty featureset and serialize to disk resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = "*"; queryFilter.WhereClause = "1=2"; result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, queryFilter, resultOptions); json = result.MimeData; } else { json = StrToByteArray(NO_DATA_GEOJSON); } } else { // Execute new query for IDs IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.SubFields = "*"; // TODO: Account for sql query syntax based on datasource // FGDB/Shapefile then "OBJECTID"; quotes required // PGDB then [OBJECTID]; brackets required // SDE then OBJECTID; nothing but the fieldname queryFilter.WhereClause = string.Format("\"OBJECTID\" IN({0})", ids.ToDelimitedString <int>(",")); // FGDB result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, queryFilter, resultOptions); features = result.Object as IRecordSet; // Do some checking here... var featureCount = this.GetRecordsetFeatureCount(features); if (featureCount != ids.Count) { System.Diagnostics.Debug.WriteLine(string.Format("Query Problem: ID search results IS NOT EQUAL to contained IDs count - [{0}:{1}]", featureCount, ids.Count)); System.Diagnostics.Debug.WriteLine("Query: " + queryFilter.WhereClause); } json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features); } break; default: throw new NotSupportedException(string.Format("Geometry type {0} is not supported by {1}", geometryType.ToString(), soe_name)); } } //store the json to disk this.WriteTileFile(json, tilePath, (int)layerIndex, (int)zoom, (int)row); _dtsLogger.LogInfo(soe_name, methodName, "Time: " + timer.Elapsed.ToString()); logger.LogMessage(ServerLogger.msgType.infoSimple, methodName, -1, "Time: " + timer.Elapsed.ToString()); return(json); } } catch (Exception ex) { // Log the error _dtsLogger.LogError(soe_name, methodName, "n/a", ex); logger.LogMessage(ServerLogger.msgType.error, methodName, 9999, ex.StackTrace); return(StrToByteArray("{}")); } }
private byte[] FindNearFeatures(int layerID, IPoint location, double distance) { if (layerID < 0) throw new ArgumentOutOfRangeException("layerID"); if (distance <= 0.0) throw new ArgumentOutOfRangeException("distance"); IGeometry queryGeometry = ((ITopologicalOperator)location).Buffer(distance); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = queryGeometry; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IQueryResultOptions resultOptions = new QueryResultOptionsClass(); resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime; AutoTimer timer = new AutoTimer(); //starts the timer IMapTableDescription tableDesc = GetTableDesc(layerID); this.serverLog.LogMessage(ServerLogger.msgType.infoDetailed, "FindNearFeatures", -1, timer.Elapsed, "Finding table description elapsed this much."); IQueryResult result = this.ms.QueryData(this.ms.DefaultMapName, tableDesc, filter, resultOptions); return result.MimeData; }