public void InfoMap() { //This activates the panel that contains the info of the plan, name lcoation date created, BB and file size MissionManager.guid = guid; MissionManager.importedModel = true; Transform parent = this.transform.parent; string json = File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + guid + ".json.metadata"); MapMetadata metadata = JsonUtility.FromJson <MapMetadata>(json); MissionManager.modificationText = "" + metadata.Date.day + '/' + metadata.Date.month + '/' + metadata.Date.year; MissionManager.mapName = metadata.Name; MissionManager.mapLocation = metadata.Location; MissionManager.modelBoundingBox = metadata.BoundingBox; MissionManager.fileSize = metadata.Byte_Size; while (parent.parent != null) { parent = parent.parent; } parent.GetComponent <MissionManager>().enabled = false; parent.GetComponent <MissionManager>().enabled = true; mapInfoGO.transform.GetChild(3).gameObject.SetActive(false); planSelectionGO.SetActive(false); mapInfoGO.SetActive(true); UnityEngine.Debug.Log("InfoMap"); }
public void setConflictingMaps(MapMetadata Server, MapMetadata Local, GameObject Panel, ClientUnity client) { server = Server; local = Local; panel = Panel; clientUnity = client; }
public MapData(float[,] data, MapMetadata metadata) { this.data = data; scale = 1 / (float)Mathf.Max(data.GetLength(0), data.GetLength(1)); this.metadata = metadata; converter = new CoordinateConverter(this.metadata.GetCellsize()); }
public static bool BlockAboveExists(int mapId, CoordS coord) { MapMetadata mapD = GetMetadata(mapId); coord.Z += Block.BLOCK_SIZE; MapBlock block = mapD.Blocks.FirstOrDefault(x => x.Coord == coord); return(block != null); }
public BasicTileMap(int width = 27, int height = 15) { Metadata = new MapMetadata { MapName = "Test Map", Width = width, Height = height }; TileMap = new ITile[height, width]; }
public static bool BlockExists(int mapId, CoordS coord) { MapMetadata mapD = GetMetadata(mapId); MapBlock block = mapD.Blocks.FirstOrDefault(x => x.Coord == coord); if (block == null) { return(false); } return(true); }
public static bool BlockExists(int mapId, CoordS coord) { MapMetadata mapMetadata = GetMetadata(mapId); if (mapMetadata == null) { return(false); } mapMetadata.Blocks.TryGetValue(coord, out MapBlock block); return(block != null); }
public static MapBlock GetMapBlock(int mapId, CoordS coord) { MapMetadata mapMetadata = GetMetadata(mapId); if (mapMetadata == null) { return(null); } mapMetadata.Blocks.TryGetValue(coord, out MapBlock block); return(block); }
void RebuildEmptyScene() { string json = System.IO.File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MissionManager.guid + ".json.mission"); Map map = JsonUtility.FromJson <Map>(json); //If we want to check if the model alignment was applied, first we would need to upload the anchors and when loading the file, check that the anchors are at the same position. Until then, thsi is ignored map.Alignment_applied = true; GameObject model = GameObject.Find("DaeModel"); // ##CAMBIAR Z POR Y, ROTACION NEGATIVA if (model) { map.unityToAnchors.SetTRS(new Vector3(model.transform.position.x, model.transform.position.z, model.transform.position.y) * 1000, model.transform.localRotation, model.transform.localScale); } else { map.unityToAnchors = Matrix4x4.identity; } map.unityToAnchors.m00 *= 1000; map.unityToAnchors.m11 *= 1000; map.unityToAnchors.m22 *= 1000; //UnityEngine.Debug.Log("Transf Matrix * (0,0,0) = " + (map.unityToAnchors * new Vector3(0, 0, 0))); MissionManager.invMatrix = Matrix4x4.Inverse(map.unityToAnchors); string mapJson = JsonUtility.ToJson(map); System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + map.Guid + ".json.mission", mapJson); Destroy(model); string file = File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata metadata = JsonUtility.FromJson <MapMetadata>(file); if (metadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { pointCloudAskedForMetadata = true; // clientUnity.client.sendTwoPartCommand((byte)Modules.PLAN_LIBRARIAN_MODULE, (byte)PlanLibrarianCommandType.PLAN_LIB_REQUEST_METADATA, MissionManager.guid + "\0"); } // else // { //We check if the map is uploaded, if it is, we check if the metadata is uploaded. If one of them isn't we upload the whole plan PlanSelectionManager.askedForMaps = true; clientUnity.client.sendTwoPartCommand((byte)Modules.PLAN_LIBRARIAN_MODULE, (byte)PlanLibrarianCommandType.PLAN_LIB_REQUEST_MAP, MissionManager.guid + "\0"); LoadingPanel.SetActive(true); LoadingPanel.transform.GetChild(0).GetComponent <Text>().text = "Uploading Plan"; //} //SceneManager.LoadScene("Recording"); }
public void Setup() { GameObject trailDisplayObject = new GameObject(); display = trailDisplayObject.AddComponent <TrailDisplay> (); display.material = new Material(Shader.Find("Unlit/Color")); MapMetadata metadata = MapDataImporter.ReadMetadata("Assets/Resources/testData.txt"); display.mapData = MapDataImporter.ReadMapData("Assets/Resources/testData.txt", metadata); display.labelGameObject = new GameObject(); display.trailName = ""; }
public static MapData ReadMapData(string path, MapMetadata metadata, MapDataType type = MapDataType.ASCIIGrid) { switch (type) { case MapDataType.ASCIIGrid: return(ASCIIGridImporter.ReadMapData(path, (ASCIIGridMetadata)metadata)); case MapDataType.Binary: return(BinaryFileImporter.ReadMapData(path, (BinaryFileMetadata)metadata)); default: throw new System.NotImplementedException("Type " + type + " not implemented!"); } }
protected IEnumerator LoadMetadata() { //var www = new WWW(BaseUrl + "/metadata.xml"); var www = UnityWebRequest.Get(BaseUrl + "/metadata.xml"); //yield return www; yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.LogError("Error while fetching map metadata: " + www.error); yield break; } Metadata = MapMetadata.ReadXml(www.downloadHandler.text); Metadata.CreateIndex(); }
public void Setup() { GameObject nodeGameObject = new GameObject(); GameObject POIDisplayObject = new GameObject(); nodeGameObject.AddComponent <SpriteRenderer> (); display = POIDisplayObject.AddComponent <POIDisplay> (); display.nodeGameObject = nodeGameObject; icon = new Icon(); icon.sprite = new Sprite(); MapMetadata metadata = MapDataImporter.ReadMetadata("Assets/Resources/testData.txt"); display.mapData = MapDataImporter.ReadMapData("Assets/Resources/testData.txt", metadata); }
void Awake() { // Obtencion de componentes topRender = topCam.GetComponent <PostRenderFront>(); frontRender = frontCam.GetComponent <PostRenderFront>(); rect = GetComponent <RectTransform>(); // Add and configurate the delegete to drag the waypoints EventTrigger trigger = GetComponent <EventTrigger>(); EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = EventTriggerType.Drag; entry.callback.AddListener((data) => { OnDragDelegate((PointerEventData)data); }); trigger.triggers.Add(entry); path = Path.Instance; string metadata = File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata metadataFile = JsonUtility.FromJson <MapMetadata>(metadata); boundingBox = metadataFile.BoundingBox; }
public static int GetPlotNumber(int mapId, CoordB coord) { CoordS coordS = coord.ToShort(); MapMetadata mapMetadata = GetMetadata(mapId); for (int i = 0; i < 20; i++) // checking 20 blocks in the same Z axis { mapMetadata.Blocks.TryGetValue(coordS, out MapBlock block); if (block == null) { coordS.Z -= Block.BLOCK_SIZE; continue; } if (block.SaleableGroup > 0) { return(block.SaleableGroup); } coordS.Z -= Block.BLOCK_SIZE; } return(0); }
public static int GetPlotNumber(int mapId, CoordB coord) { CoordS coordS = coord.ToShort(); List <MapBlock> blocks = new List <MapBlock>(); MapMetadata mapD = GetMetadata(mapId); for (int i = 0; i < 20; i++) // checking 20 blocks in the same Z axis { MapBlock block = mapD.Blocks.FirstOrDefault(x => x.Coord == coordS); if (block == null) { coordS.Z -= Block.BLOCK_SIZE; continue; } if (block.SaleableGroup > 0) { return(block.SaleableGroup); } coordS.Z -= Block.BLOCK_SIZE; } return(0); }
// Use this for initialization void Start() { Path path = Path.Instance; this.gameObject.AddComponent <PathPoint>(); //PathPoint point = this.gameObject.GetComponent<PathPoint>(); this.gameObject.GetComponent <PathPoint>().createPathPoint(this.transform); path.AddPointWithGimball(this.GetComponent <PathPoint>().getPoint(), this.GetComponent <PathPoint>()); Map m = new Map(); MapMetadata mapMetadata = new MapMetadata(System.Guid.NewGuid().ToString(), "mapa1", "1L08", MapMetadata.MapType.EmptyBox); m.AddPath(path); string json = JsonUtility.ToJson(m); File.WriteAllText(mapMetadata.Name + ".json", json); json = File.ReadAllText(mapMetadata.Name + ".json"); MapMetadata m2 = JsonUtility.FromJson <MapMetadata>(json); m2.Name = "mapa2"; json = JsonUtility.ToJson(m2); File.WriteAllText(m2.Name + ".json", json); }
private static void GenerateMetadata() { try { var tilefolder = Path.Combine(BaseFolder, "tiles"); var meshfiles = Directory.GetFiles(tilefolder, "*.obj", SearchOption.TopDirectoryOnly); Debug.Log(BaseFolder); var tiles = meshfiles.Select(GenerateTile).ToList(); var metadata = new MapMetadata { UtmProjection = new UtmProjection { Zone = 33, North = true }, Position = new Double2(600160.0, 6403336.0), Rotation = new Double3(-90, 180, 0), AnchorOffset = new Double2(250, 350), BaseTileSize = 120, MaxLevel = tiles.Max(x => x.Level), Tiles = tiles }; var xml = MapMetadata.WriteXml(metadata); Debug.Log(xml); var metafile = Path.Combine(BaseFolder, "metadata.xml"); File.WriteAllText(metafile, xml, Encoding.UTF8); } catch (Exception e) { Debug.LogError(e); Debug.LogError(e.InnerException); throw; } }
/// <summary> /// Gets all points of a map /// </summary> /// <param name="mapId">Map Id</param> /// <returns>Map Points Datatable</returns> public MapMetadata.metaMapPointsDataTable GetMapPoints(int mapId) { try { MapMetadata map = new MapMetadata(); Query query = db.CreateQuery("select [MapPointId], [MapId], [DataSourceTableName], [DataSourceXCoordinateColumnName], [DataSourceYCoordinateColumnName], [DataSourceLabelColumnName], [Size], [Color] from metaMapPoints where [MapId] = @MapId"); query.Parameters.Add(new QueryParameter("@MapId", DbType.Int32, mapId)); map.metaMapPoints.Merge(db.Select(query)); return map.metaMapPoints; } catch (Exception ex) { throw new GeneralException("Could not retrieve map points", ex); } }
/// <summary> /// Gets all layers of a map /// </summary> /// <param name="mapId">Map Id</param> /// <returns>Map Layers Datatable</returns> public MapMetadata.metaMapLayersDataTable GetMapLayers(int mapId) { try { MapMetadata map = new MapMetadata(); Query query = db.CreateQuery("select [MapLayerId], [MapId], [LayerId], [LayerRenderTypeId], [RenderField], [MarkerColor], [RampBeginColor], [RampEndColor], [ClassBreaks], [DataTableName], [DataTableKey], [FeatureKey], [LineColor], [FillColor], [PolygonOutlineColor] from metaMapLayers where [MapId] = @MapId order by [MapLayerId] asc"); query.Parameters.Add(new QueryParameter("@MapId", System.Data.DbType.Int32, mapId)); map.metaMapLayers.Merge(db.Select(query)); foreach (MapMetadata.metaMapLayersRow mapLayer in map.metaMapLayers) { map.metaLayers.ImportRow(GetLayer(mapLayer.LayerId)); } return map.metaMapLayers; } catch (Exception ex) { throw new GeneralException("Could not retrieve map layers", ex); } }
/// <summary> /// Gets a Map Layer /// </summary> /// <param name="mapLayerId">Map Layer Id</param> /// <returns>MapLayersRow</returns> public MapMetadata.metaMapLayersRow GetMapLayer(int mapLayerId) { try { MapMetadata map = new MapMetadata(); Query query = db.CreateQuery("select [MapLayerId], [MapId], [LayerId], [LayerRenderTypeId], [RenderField], [MarkerColor], [RampBeginColor], [RampEndColor], [ClassBreaks] from metaMapLayers where [MapLayerId] = @MapLayerId"); query.Parameters.Add(new QueryParameter("@MapLayerId", System.Data.DbType.Int32, mapLayerId)); map.metaMapLayers.Merge(db.Select(query)); if (map.metaMapLayers.Count > 0) { map.metaLayers.ImportRow(GetLayer(map.metaMapLayers[0].LayerId)); return map.metaMapLayers[0]; } else { throw new GeneralException("Map layer not found"); } } catch (Exception ex) { throw new GeneralException("Could not retrieve map layer", ex); } }
/// <summary> /// Gets a map by its ID /// </summary> /// <param name="mapId">Map Id</param> /// <returns>MapsDataTable</returns> public MapMetadata.metaMapsDataTable GetMap(int mapId) { try { MapMetadata map = new MapMetadata(); Query query = db.CreateQuery("select [MapId], [Name], [Title] from metaMaps where [MapId] = @MapId"); query.Parameters.Add(new QueryParameter("@MapId", DbType.Int32, mapId)); map.metaMaps.Merge(db.Select(query)); return map.metaMaps; } catch (Exception ex) { throw new GeneralException("Could not retrieve map", ex); } }
/// <summary> /// Creates a new shape with the specified type and metadata. /// </summary> /// <param name="type">The shape type.</param> /// <param name="metadata">The shape metadata.</param> public MapShape(MapShapeType type, MapMetadata metadata) { this.type = type; this.metadata = metadata; }
public static MapBlock GetMapBlock(int mapId, CoordS coord) { MapMetadata mapD = GetMetadata(mapId); return(mapD.Blocks.FirstOrDefault(x => x.Coord == coord)); }
/// <summary> /// Creates a new polygon map shape. /// </summary> /// <param name="metadata">The map metadata.</param> /// <param name="bounds">The shape bounds.</param> public MapShapePolygon(MapMetadata metadata, MapRectangle bounds) : base(MapShapeType.Polygon, metadata) { this.bounds = bounds; }
//Old unused function to save PC void CreatePlan(string jsonPointCloud) { bool canBuild = true; UnityEngine.Debug.Log("Creating pointCloud scene"); if (canBuild) { Matrix4x4 mat = Matrix4x4.identity; if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData"); } if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Maps")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Maps"); } UnityEngine.Debug.Log("Creating Map: " + Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map"); //File.Create(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map").Close(); //File.WriteAllText(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map", jsonPointCloud, System.Text.Encoding.ASCII); if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Thumbnails")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Thumbnails"); } MapMetadata MapMetadata = new MapMetadata(MissionManager.guid, "MapMetadata_" + MissionManager.guid, "ImportedLocation_", MapMetadata.MapType.PointCloud); //MapMetadata.MapPath = Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dpl.map"; MapMetadata.BoundingBox = new Vector3(maxX, maxY, maxZ); string metadataJson = JsonUtility.ToJson(MapMetadata); if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Missions")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Missions"); } System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MapMetadata.Guid + ".json.metadata", metadataJson); Map map = new Map(); map.Guid = MissionManager.guid; map.unityToAnchors = Matrix4x4.identity; mat.m00 *= 1000; mat.m11 *= 1000; mat.m22 *= 1000; map.unityToAnchors = mat; MissionManager.invMatrix = Matrix4x4.Inverse(mat); string mapJson = JsonUtility.ToJson(map); System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + map.Guid + ".json.mission", mapJson); //SceneManager.LoadScene("PlanSelection"); //guid = System.Guid.NewGuid().ToString(); //Map m = new Map(); //MapMetadata MapMetadata = new MapMetadata(guid, "MapMetadata_" + guid.Split('-')[0], "EmptyLocation_", MapMetadata.MapType.EmptyBox); //MapMetadata.BoxScale = new Vector3(width / 10, height / 10, depth / 10); //MapMetadata.BoundingBox = new Vector3(width, height, depth); //string json = JsonUtility.ToJson(MapMetadata); // //if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData")) // System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData"); // //if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Missions")) // System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Missions"); // //System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MapMetadata.Name + ".json", json); } SceneManager.LoadScene("General"); }
public MapData(int width, int height, MapMetadata metadata) : this(new float[width, height], metadata) { }
public void onFileCreated(NetMQMessage m) { //UnityEngine.Debug.Log("File created"); //UnityEngine.Debug.Log(System.Text.Encoding.ASCII.GetString(m[1].Buffer)); string[] currentPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer).Split('.'); //string[] currentPath = BitConverter.ToString(m[1].Buffer).Split('.'); //UnityEngine.Debug.Log(currentPath[currentPath.Length - 1]); FileInfo fileInfo; //First we check if we haven't receive already that the files were created switch (currentPath[currentPath.Length - 1]) { case "metadata\0": if (!createdMissionFiles[(int)MissionFileType.Metadata]) { //If we get that the metadata was created, we check that it was created and get the info of the file. Reminder, the file is empty on the server metadataFileServerPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer); UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); createdMissionFiles[(int)MissionFileType.Metadata] = true; //UnityEngine.Debug.Log(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata"); fileInfo = new System.IO.FileInfo(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata"); //UnityEngine.Debug.Log(fileInfo.Length); metadataFileSize = fileInfo.Length; } else { UnityEngine.Debug.Log("Metadata created flag already true"); } break; case "mission\0": if (!createdMissionFiles[(int)MissionFileType.Mission]) { //If we get that the mission was created, we check that it was created and get the info of the file. Reminder, the file is empty on the server missionFileServerPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer); //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); createdMissionFiles[(int)MissionFileType.Mission] = true; fileInfo = new System.IO.FileInfo(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.mission"); missionFileSize = fileInfo.Length; } break; case "map\0": if (!createdMissionFiles[(int)MissionFileType.Map]) { //If we get that the map was created, we check that it was created and get the info of the file. Reminder, the file is empty on the server mapFileServerPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer); //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); createdMissionFiles[(int)MissionFileType.Map] = true; string metadata = File.ReadAllText(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata mapMetadata = JsonUtility.FromJson <MapMetadata>(metadata); if (mapMetadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { fileInfo = new System.IO.FileInfo(ApplicationVariables.persistentDataPath + "Maps/" + MissionManager.guid + ".dpl.map"); } else { fileInfo = new System.IO.FileInfo(ApplicationVariables.persistentDataPath + "Maps/" + MissionManager.guid + ".dae.map"); } mapFileSize = fileInfo.Length; } break; case "thumbnail\0": if (!createdMissionFiles[(int)MissionFileType.Thumbnail]) { //If we get that the thumbnail was created, we check that it was created and get the info of the file. Reminder, the file is empty on the server thumbnailFileServerPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer); //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); createdMissionFiles[(int)MissionFileType.Thumbnail] = true; fileInfo = new System.IO.FileInfo(ApplicationVariables.persistentDataPath + "Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail"); thumbnailFileSize = fileInfo.Length; } break; case "deb\0": //UnityEngine.Debug.Log("Created deb file on server"); updateDebFileServerPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer); //Check if the update package was created on the server // Load file and first 4k bits fileInfo = new System.IO.FileInfo(dataPathUpdate + fileNameUpdate); updateDebFileSize = (long)fileInfo.Length; UnityEngine.Debug.Log(dataPathUpdate + fileNameUpdate); StartSendFile(dataPathUpdate + fileNameUpdate, updateDebFileServerPath); break; default: UnityEngine.Debug.Log("Unhandled file extension (Create File) :" + currentPath[currentPath.Length - 1]); break; } if (createdMissionFiles[(int)MissionFileType.Metadata] && createdMissionFiles[(int)MissionFileType.Mission] && (createdMissionFiles[(int)MissionFileType.Map] || PlanSelectionManager.uploadMapMetadata) && createdMissionFiles[(int)MissionFileType.Thumbnail]) { //If metadata, thumbnail, map and thumbnail was created, then we start sending the content of the files SendJSONStateMachine.pathsSend = true; createdMissionFiles[(int)MissionFileType.Metadata] = false; createdMissionFiles[(int)MissionFileType.Mission] = false; createdMissionFiles[(int)MissionFileType.Map] = false; createdMissionFiles[(int)MissionFileType.Thumbnail] = false; StartSendFile(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata", metadataFileServerPath); } }
//The function that saves the thumbnail, mission and metadata called from saveandgotoplanselection IEnumerator RenderTexture() { ButtonBack.SetActive(false); ButtonNext.SetActive(false); topInfoPanel.SetActive(false); DownInfoPanel.SetActive(false); otherPanel.SetActive(false); infoPanel.SetActive(false); ScanButton.SetActive(false); GameObject Helper = this.gameObject; //Assign the bounding box to the file MissionManager.modelBoundingBox = new Vector3(maxX, maxY, maxZ); //All this comments used to take a photo at the pointcloud, but for a reason unknown, it didn't center the image correctly to take the photo. TODO fix that // Vector3 auxPosition = Camera.main.transform.position; // // Camera.main.transform.parent.position = Vector3.zero; // Camera.main.transform.parent.rotation = Quaternion.Euler(0,0,0); // Camera.main.transform.localPosition = new Vector3(drone.transform.position.x, drone.transform.position.y + maxY * 3, drone.transform.position.z); // float fieldOfVIewHelper = Camera.main.fieldOfView; // float futureFOV = 2.0f * Mathf.Atan((Camera.main.transform.localPosition.y - (drone.transform.position.y - maxY)) * 0.5f / Vector3.Distance(Camera.main.transform.localPosition, drone.transform.position)) * Mathf.Rad2Deg; // futureFOV = Mathf.Clamp(futureFOV + 10.0f, 1.0f, 179.0f); // if (float.IsNaN(futureFOV)) // { // Camera.main.fieldOfView = 40; // Camera.main.transform.localPosition = new Vector3(drone.transform.position.x, drone.transform.position.y * 3, drone.transform.position.z); // } // else // { // Camera.main.fieldOfView = futureFOV; // } // Camera.main.transform.LookAt(drone.transform); // yield return new WaitForSeconds(1.0f); // Resolution auxResolution = Screen.currentResolution; // Screen.SetResolution(256, 256, true); // yield return new WaitForSeconds(1.0f); // yield return new WaitForEndOfFrame(); // Camera.main.targetTexture = modelRenderer; // // Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); // UnityEngine.Debug.Log("CamPos: " + Camera.main.transform.position); // UnityEngine.Debug.Log("CamRot: " + Camera.main.transform.rotation.eulerAngles); // UnityEngine.Debug.Log("Drone: " + drone.transform.position); // UnityEngine.Debug.Log("Fov: " + futureFOV); // Camera.main.Render(); // texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); // texture.Apply(); // byte[] bytes = texture.EncodeToPNG(); // save the image //Remember to create directories if they don't exist if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Thumbnails")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Thumbnails"); } //Create the thumbnail from a jpg that we have. TODO change to a render of the PC File.WriteAllBytes(Application.persistentDataPath + "/PersistentData/Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail", pointCloudThumbnail.texture.EncodeToPNG()); //DestroyObject(texture); // Camera.main.targetTexture.Release(); // Camera.main.targetTexture = null; // Screen.SetResolution(auxResolution.width, auxResolution.height, true); // Camera.main.fieldOfView = fieldOfVIewHelper; // Camera.main.transform.position = auxPosition; //string jsonPointCloud = JsonUtility.ToJson(savedPointCloud); //CreatePlan(jsonPointCloud); bool canBuild = true; //UnityEngine.Debug.Log("Creating pointCloud scene"); if (canBuild) { Matrix4x4 mat = Matrix4x4.identity; if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData"); } if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Maps")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Maps"); } //UnityEngine.Debug.Log("Creating Map: " + Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map"); //File.Create(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map").Close(); //File.WriteAllText(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map", jsonPointCloud, System.Text.Encoding.ASCII); //Need to set loading bigger, in the middle and to rotate it in the next while loop inside this function Loading.SetActive(true); yield return(new WaitForEndOfFrame()); if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Thumbnails")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Thumbnails"); } MapMetadata MapMetadata = new MapMetadata(MissionManager.guid, "MapMetadata_" + MissionManager.guid, "ImportedLocation_", MapMetadata.MapType.PointCloud); //MapMetadata.MapPath = Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dpl.map"; MapMetadata.BoundingBox = new Vector3(maxX, maxY, maxZ); MapMetadata.Location = location; MapMetadata.Name = mapName; MapMetadata.Byte_Size = (ulong)fileSize; string metadataJson = JsonUtility.ToJson(MapMetadata); if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Missions")) { System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Missions"); } System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MapMetadata.Guid + ".json.metadata", metadataJson); yield return(new WaitForEndOfFrame()); Map map = new Map(); map.Guid = MissionManager.guid; //Pozyx is in milimiters, need to convert to that map.unityToAnchors = Matrix4x4.identity; mat.m00 *= 1000; mat.m11 *= 1000; mat.m22 *= 1000; map.unityToAnchors = mat; MissionManager.invMatrix = Matrix4x4.Inverse(mat); string mapJson = JsonUtility.ToJson(map); System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + map.Guid + ".json.mission", mapJson); //yield return new WaitForEndOfFrame(); //SceneManager.LoadScene("PlanSelection"); //guid = System.Guid.NewGuid().ToString(); //Map m = new Map(); //MapMetadata MapMetadata = new MapMetadata(guid, "MapMetadata_" + guid.Split('-')[0], "EmptyLocation_", MapMetadata.MapType.EmptyBox); //MapMetadata.BoxScale = new Vector3(width / 10, height / 10, depth / 10); //MapMetadata.BoundingBox = new Vector3(width, height, depth); //string json = JsonUtility.ToJson(MapMetadata); // //if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData")) // System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData"); // //if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PersistentData/Missions")) // System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PersistentData/Missions"); // //System.IO.File.WriteAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MapMetadata.Name + ".json", json); } //This is for the app that clicked the done button. It exits here and won't enter more than once. PlanSelectionManager.uploadMapMetadata = true; clientUnity.client.SendCommand((byte)Modules.PLAN_LIBRARIAN_MODULE, (byte)PlanLibrarianCommandType.PLAN_LIB_REQUEST_LIBRARY_PATH); done = false; MapperModule.state = MapperModule.MapperState.IDLE; SceneManager.LoadScene("General"); // Screen.SetResolution(auxResolution.width, auxResolution.height, true); }
/// <summary> /// This is the main fucntion that loads the map and the plan waypoints /// </summary> /// <param name="path"></param> void LoadMap(string path) { //We load the main path if (ownPath == null) { ownPath = Path.Instance; } //laod the metadata string json = System.IO.File.ReadAllText(path); MapMetadata metadata = JsonUtility.FromJson <MapMetadata>(json); UnityEngine.Debug.Log("Loading map"); BinaryFormatter bFormatter = new BinaryFormatter(); //if (!AskForMap()) // return; FileStream file; //If it is a pointcloud we load a pointcloud map, and if it isn't a collada if (metadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { file = File.OpenRead(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dpl.map"); } else { file = File.OpenRead(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map"); } //var xmlWriter = new XmlTextWriter(file, Encoding.UTF8); //xmlWriter. XmlDocument doc = new XmlDocument(); string aux; GameObject auxGameObject = new GameObject(); UnityEngine.Debug.Log(MissionManager.invMatrix); //An empty box and a 3d model are the same if (metadata.Map_type == (byte)MapMetadata.MapType.EmptyBox) { using (StreamReader reader = new StreamReader(file)) { aux = reader.ReadToEnd(); } doc.LoadXml(aux); ColladaImporter importer = new ColladaImporter(ref auxGameObject); StartCoroutine(importer.getMesh(doc, cullBackShader)); } else if (metadata.Map_type == (byte)MapMetadata.MapType.Model3D) { using (StreamReader reader = new StreamReader(file)) { aux = reader.ReadToEnd(); } doc.LoadXml(aux); ColladaImporter importer = new ColladaImporter(ref auxGameObject); StartCoroutine(importer.getMesh(doc, shader)); }//But pointclouds are loaded different else { //MapLoader used in mapalignment uses this exact function and they are already explained there createBaseTriangle(); byte[] pclBytes = File.ReadAllBytes(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dpl.map"); GameObject daeModel = new GameObject(); daeModel.name = "DaeModel"; daeModel.transform.parent = auxGameObject.transform; LoadPointCloud(pclBytes, ref daeModel); //SavedPointCloud pointCloud = JsonUtility.FromJson<SavedPointCloud>(aux); // //for (int i = 0; i < pointCloud.PointCloud.Count; i++) //{ // // GameObject gameObject = Instantiate(pcPrefab, auxGameObject.transform); // gameObject.GetComponent<MeshFilter>().sharedMesh = new Mesh(); // gameObject.GetComponent<MeshFilter>().sharedMesh.name = "cmesh" + i.ToString(); // gameObject.GetComponent<MeshFilter>().mesh.vertices = pointCloud.PointCloud[i].vertex; // int[] indices = new int[pointCloud.PointCloud[i].vertex.Length]; // Color[] colors = new Color[indices.Length]; // for (int j = 0; j < pointCloud.PointCloud[i].vertex.Length; j++) // { // indices[j] = j; // colors[j] = new Color(pointCloud.PointCloud[i].colors[j].x, pointCloud.PointCloud[i].colors[j].y, pointCloud.PointCloud[i].colors[j].z, 1); // } // gameObject.GetComponent<MeshFilter>().mesh.colors = colors; // gameObject.GetComponent<MeshFilter>().mesh.RecalculateNormals(); // gameObject.GetComponent<MeshFilter>().mesh.SetIndices(indices, MeshTopology.Triangles, 0, true); // gameObject.GetComponent<MeshFilter>().mesh.RecalculateBounds(); // Matrix4x4 auxMat = pointCloud.PointCloud[i].matrix; // gameObject.transform.rotation = auxMat.rotation; // gameObject.transform.position = new Vector3(auxMat.m03, auxMat.m13, auxMat.m23); // // //} } //Once the maps are loaded, we start with the waypoints. First a mission is loaded auxGameObject.name = "DaemodelChild"; string mapJson = File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MissionManager.guid + ".json.mission"); Map map = JsonUtility.FromJson <Map>(mapJson); Path waypointPath = Path.Instance; //sphereParentGO.transform.position = auxGameObject.transform.position; //If this isn't a new plan, we load the plan selected previously if (MissionManager.planIndex != -1) { //Here we get a plan from all the paths saved in missionmanager waypointPath = map.Paths[MissionManager.planIndex]; ownPath.setPath(waypointPath); //And give them the default parameters previously selected MissionManager.planDefaultHeight = waypointPath.FlightParams.height; MissionManager.planDefaultSpeed = waypointPath.FlightParams.speed; MissionManager.planDefaultDuration = waypointPath.FlightParams.duration; //Here we instantiate the waypoints for (int i = 0; i < waypointPath.Count(); i++) { //waypointPath.GetPoint(i).PointPosition = new Vector3(waypointPath.GetPoint(i).PointPosition.x, waypointPath.GetPoint(i).PointPosition.z, waypointPath.GetPoint(i).PointPosition.y); GameObject auxPoint = Instantiate(pointGO, waypointPath.GetPoint(i).PointPosition, Quaternion.Euler(0, 0, 0), sphereParentGO.transform); //assign them the transform to the script waypointPath.GetPoint(i).PointTransf = auxPoint.transform; auxPoint.SetActive(true); //Scale it TransformSphere(topCam, auxPoint); //And if it is the first one, we assign it the yellow colour, and to the last one, the green colour. The rest use the normal waypoint colour if (i == 0) { auxPoint.transform.GetChild(0).GetComponent <Renderer>().sharedMaterial = homeNotSelectedMaterial; //auxPoint.transform.GetChild(1).GetComponent<Renderer>().sharedMaterial.color = Color.white; } else if (i != waypointPath.Count() - 1) { auxPoint.transform.GetChild(0).GetComponent <Renderer>().sharedMaterial = waypointNotSelectedMaterial; // auxPoint.transform.GetChild(1).GetComponent<Renderer>().sharedMaterial.color = Color.white; //auxPoint.transform.GetChild(0).GetComponent<Renderer>().sharedMaterial = whiteOutlineMaterial; //auxPoint.transform.GetChild(1).GetComponent<Renderer>().sharedMaterial = whiteOutlineMaterial; } else { //auxPoint.transform.GetChild(0).GetComponent<Renderer>().sharedMaterial = landingMaterial; //auxPoint.transform.GetChild(1).GetComponent<Renderer>().sharedMaterial = landingMaterial; auxPoint.transform.GetChild(0).GetComponent <Renderer>().sharedMaterial = landingNotSelectedMaterial; //auxPoint.transform.GetChild(1).GetComponent<Renderer>().sharedMaterial.color = Color.white; } //We assign the monobehaviour that contains the point parameters auxPoint.AddComponent <PathPoint>().createPathPointWithPoint(waypointPath.GetPoint(i), 0, 0); } //here we create the middlepoints that the curve contains for (int i = 0; i < waypointPath.Count() - 1; i++) { lineMat.SetPass(0); if (topCam != null) { CatmullRomSpline.DisplayCatmullRomSpline2(waypointPath, i, ref waypointPath.middlePointsTop, topCam.orthographicSize / 2.0f, true, topCam); } if (frontCam != null) { CatmullRomSpline.DisplayCatmullRomSpline(waypointPath, i, ref waypointPath.middlePointsRight, frontCam.orthographicSize / 2.0f, true, frontCam); } } //This script is also used on recording, where we don't want points of interests. We adjust the path to the adjustmnets doen in model alignment and exit if (GeneralSceneManager.sceneState == GeneralSceneManager.SceneState.Recording) { sphereParentGO.transform.position = new Vector3(map.unityToAnchors.m03 * 0.001f, map.unityToAnchors.m23 * 0.001f, map.unityToAnchors.m13 * 0.001f); sphereParentGO.transform.localScale = new Vector3(map.unityToAnchors.m00 * 0.001f, map.unityToAnchors.m11 * 0.001f, map.unityToAnchors.m22 * 0.001f); return; } //If not we create the points of interest poisCreated = new List <GameObject>(); for (int i = 0; i < waypointPath.wpParametersCount(); i++) { //for each waypoint of interest that the path contains, we assign it to the respective waypoint GimballParameters auxGimballUpdateParameters = waypointPath.getGbUpdateParameter(i); Point auxPoint = waypointPath.GetPoint(auxGimballUpdateParameters.id_pointer); auxPoint.PointTransf.gameObject.GetComponent <PathPoint>().Wp.gimbal_parameters = auxGimballUpdateParameters; //And now depending on the type of point of interest, one behaviour is assigned. It can be a look at point, look at the curve, //locked in yaw only while looking in a direction or looking in a direction without locks switch (auxGimballUpdateParameters.mode) { case 0: GameObject newpoi; //First we search for a POI System.Predicate <GameObject> predicate = (GameObject p) => { return(p.transform.position == auxGimballUpdateParameters.poi_or_angles); }; //If one POI has been placed at least if (poisCreated.Count > 0) { //we find if the POI was already there, just in case multiple waypoints share the same POI newpoi = poisCreated.Find(predicate); if (newpoi == null) { newpoi = Instantiate(poi, auxGimballUpdateParameters.poi_or_angles, Quaternion.Euler(new Vector3(0, 0, 0))); poisCreated.Add(newpoi); newpoi.AddComponent <POI>(); } } else { newpoi = Instantiate(poi, auxGimballUpdateParameters.poi_or_angles, Quaternion.Euler(new Vector3(0, 0, 0))); poisCreated.Add(newpoi); newpoi.AddComponent <POI>(); } //We create a new line that points from the POI to the waypoint. The poi object already has one, but if there is more than one waypoint //related to the POI, we need to create more lines GameObject newLine = newpoi.transform.GetChild(2).gameObject; if (i > 0) { newLine = Instantiate(poi.transform.GetChild(2).gameObject, newpoi.transform.position, Quaternion.Euler(new Vector3(0, 0, 0)), newpoi.transform); } //All of this calculate the rotation, position and size of the line Vector3 centerPos = new Vector3(auxPoint.PointTransf.position.x + newpoi.transform.position.x, auxPoint.PointTransf.position.y + newpoi.transform.position.y, auxPoint.PointTransf.position.z + newpoi.transform.position.z) / 2f; float scaleX = Mathf.Abs((auxPoint.PointTransf.position - newpoi.transform.position).magnitude); newLine.transform.localScale = new Vector3(scaleX, 3f, 3f); //Esto es para rotar las imagenes de las camaras que tienen cada Waypoint Transform cube = auxPoint.PointTransf.Find("CubeTop"); cube.gameObject.SetActive(true); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from = new Vector2(-1, 0); Vector3 aux2 = newpoi.transform.position - auxPoint.PointTransf.position; Vector2 to = new Vector2(aux2.x, aux2.z).normalized; float angle = Vector2.SignedAngle(from, to); Transform cube2 = auxPoint.PointTransf.Find("CubeFront"); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from2 = new Vector2(-1, 0); Vector3 aux3 = newpoi.transform.position - auxPoint.PointTransf.position; Vector2 to2 = new Vector2(aux3.x, aux3.y).normalized; float angle2 = Vector2.SignedAngle(from2, to2); //float angle = Mathf.Acos(distance2 / distance); //item.transform.Rotate(new Vector3(0, 1, 0), Vector2.Angle(from, to)); cube.transform.rotation = Quaternion.Euler(new Vector3(0, -angle, 0)); cube2.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle2)); cube.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.white; cube2.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.white; auxPoint.PointTransf.GetComponent <PathPoint>().Poi = newpoi.transform; newpoi.GetComponent <POI>().addPoint(auxPoint.PointTransf.GetComponent <PathPoint>(), newLine); //UnityEngine.Debug.Log(newpoi.GetComponent<POI>().Referenced.Count); float sineC = (auxPoint.PointTransf.position.y - newpoi.transform.position.y) / scaleX; newLine.transform.rotation = Quaternion.Euler(0, -angle, Mathf.Asin(sineC) * Mathf.Rad2Deg); newLine.transform.position = newpoi.transform.position; var rotation = Quaternion.Euler(0, -angle, Mathf.Asin(sineC) * Mathf.Rad2Deg).eulerAngles; auxPoint.PointTransf.GetComponent <PathPoint>().GimbalRotation = new Vector3(rotation.z, rotation.y, rotation.x + 90); auxPoint.PointTransf.GetComponent <PathPoint>().getGimballMode = 0; TransformSphere(topCam, newpoi); break; case 1: //This is the case where the direction will always point to the curve float angle3 = 0; float angle4 = 0; int middlePointsIndexTop = 0; int middlePointsIndexRight = 0; //We iterate through the array to see the closest point from the curve to the waypoint. The signal that indicates this mode is activated is a green camera looking at that point on the waypoint. for (i = 0; i < waypointPath.Count(); i++) { if (waypointPath.GetPoint(i) == auxPoint) { break; } middlePointsIndexTop += waypointPath.GetPoint(i).SegmentsTop; middlePointsIndexRight += waypointPath.GetPoint(i).SegmentsRight; } //If this is the last point, there is no curve to look at anymore if (middlePointsIndexRight >= waypointPath.middlePointsRight.Count) { break; } //Now from here we calculate the rotation of the camera mentioned above Vector3 pointRight = waypointPath.middlePointsRight[middlePointsIndexRight]; Vector3 pointTop = waypointPath.middlePointsTop[middlePointsIndexTop]; //Esto es para rotar las imagenes de las camaras que tienen cada Waypoint Transform cube3 = auxPoint.PointTransf.Find("CubeTop"); cube3.gameObject.SetActive(true); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from3 = new Vector2(-1, 0); Vector3 aux4 = pointTop - auxPoint.PointTransf.position; Vector2 to3 = new Vector2(aux4.x, aux4.z).normalized; angle3 = Vector2.SignedAngle(from3, to3); Transform cube4 = auxPoint.PointTransf.Find("CubeFront"); cube4.gameObject.SetActive(true); cube3.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.green; cube4.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.green; //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from4 = new Vector2(-1, 0); Vector3 aux5 = pointRight - auxPoint.PointTransf.position; Vector2 to4 = new Vector2(aux5.x, aux5.y).normalized; angle4 = Vector2.SignedAngle(from4, to4); //float angle = Mathf.Acos(distance2 / distance); //item.transform.Rotate(new Vector3(0, 1, 0), Vector2.Angle(from, to)); cube3.transform.rotation = Quaternion.Euler(new Vector3(0, -angle3, 0)); cube4.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle4)); //UnityEngine.Debug.Log(newpoi.GetComponent<POI>().Referenced.Count); break; case 2: //This mode is for a direction with the yaw? locked //We only show a line in this mode, so even if we instantiate a poi, is not shown GameObject newpoi2 = Instantiate(poi, auxGimballUpdateParameters.poi_or_angles + auxPoint.PointTransf.position, Quaternion.Euler(new Vector3(0, 0, 0))); //UnityEngine.Debug.Log(" POI POS: " + auxGimballUpdateParameters.poi_or_angles + " ITEM POS: " + auxPoint.PointTransf.position); /* * if (Input.mousePosition.x < Camera.main.pixelWidth / 2) * { * newpoi.transform.position = new Vector3(newpoi.transform.position.x, 0, newpoi.transform.position.z); * * } * else * { * newpoi.transform.position = new Vector3(newpoi.transform.position.x, newpoi.transform.position.y, 1); * * }*/ newpoi2.SetActive(true); newpoi2.transform.GetChild(0).gameObject.SetActive(false); newpoi2.transform.GetChild(1).gameObject.SetActive(false); newpoi2.AddComponent <POI>(); newpoi2.GetComponent <POI>().Direction = true; float angle5 = 0; float angle6 = 0; float sineC5 = 0; //from now on, we isntantiate a line and calculate position and direction GameObject newLine2 = newpoi2.transform.GetChild(2).gameObject; if (i > 0) { newLine2 = Instantiate(poi.transform.GetChild(2).gameObject, newpoi2.transform.position, Quaternion.Euler(new Vector3(0, 0, 90)), newpoi2.transform); } newLine2.transform.GetChild(0).GetComponent <Renderer>().material.color = Color.grey; newLine2.transform.GetChild(0).gameObject.layer = 10; //Que tamaño tendra float scaleX5 = Mathf.Abs((auxPoint.PointTransf.position - newpoi2.transform.position).magnitude); newLine2.transform.localScale = new Vector3(scaleX5, 3f, 3f); //Esto es para rotar las imagenes de las camaras que tienen cada Waypoint Transform cube5 = auxPoint.PointTransf.Find("CubeTop"); cube5.gameObject.SetActive(false); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from5 = new Vector2(-1, 0); Vector3 aux6 = newpoi2.transform.position - auxPoint.PointTransf.position; Vector2 to5 = new Vector2(aux6.x, aux6.z).normalized; if (i == 0) { angle5 = Vector2.SignedAngle(from5, to5); } Transform cube6 = auxPoint.PointTransf.Find("CubeFront"); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from6 = new Vector2(-1, 0); Vector3 aux7 = newpoi2.transform.position - auxPoint.PointTransf.position; Vector2 to6 = new Vector2(aux7.x, aux7.y).normalized; if (i == 0) { angle6 = Vector2.SignedAngle(from6, to6); } //float angle = Mathf.Acos(distance2 / distance); //item.transform.Rotate(new Vector3(0, 1, 0), Vector2.Angle(from, to)); cube5.transform.rotation = Quaternion.Euler(new Vector3(0, -angle5, 0)); cube6.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle6)); cube5.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.white; cube6.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.white; auxPoint.PointTransf.GetComponent <PathPoint>().Poi = newpoi2.transform; newpoi2.GetComponent <POI>().addPoint(auxPoint.PointTransf.GetComponent <PathPoint>(), newLine2); //UnityEngine.Debug.Log(newpoi.GetComponent<POI>().Referenced.Count); sineC5 = (auxPoint.PointTransf.transform.position.y - newpoi2.transform.position.y) / scaleX5; newLine2.transform.rotation = Quaternion.Euler(0, -angle5, Mathf.Asin(sineC5) * Mathf.Rad2Deg); newLine2.transform.position = auxPoint.PointTransf.transform.position; var rotation2 = Quaternion.Euler(0, -angle5, Mathf.Asin(sineC5) * Mathf.Rad2Deg).eulerAngles; break; case 3: //Same as above without locking yaw GameObject newpoi3 = Instantiate(poi, auxGimballUpdateParameters.poi_or_angles + auxPoint.PointTransf.position, Quaternion.Euler(new Vector3(0, 0, 0))); newpoi3.transform.GetChild(0).gameObject.SetActive(false); newpoi3.transform.GetChild(1).gameObject.SetActive(false); newpoi3.AddComponent <POI>(); newpoi3.GetComponent <POI>().Direction = true; float angle7 = 0; float angle8 = 0; float sineC7 = 0; //Creamos una nueva linea que apunta del waypoint al POI GameObject newLine3 = newpoi3.transform.GetChild(2).gameObject; //newLine3 = Instantiate(poi.transform.GetChild(2).gameObject, newpoi3.transform.position, Quaternion.Euler(new Vector3(0, 0, 0)), newpoi3.transform); newLine3.transform.GetChild(0).GetComponent <Renderer>().material.color = Color.gray; //Que tamaño tendra float scaleX7 = Mathf.Abs((auxPoint.PointTransf.position - newpoi3.transform.position).magnitude); newLine3.transform.localScale = new Vector3(scaleX7, 3f, 3f); //Esto es para rotar las imagenes de las camaras que tienen cada Waypoint Transform cube7 = auxPoint.PointTransf.Find("CubeTop"); cube7.gameObject.SetActive(true); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from7 = new Vector2(-1, 0); Vector3 aux8 = newpoi3.transform.position - auxPoint.PointTransf.position; Vector2 to7 = new Vector2(aux8.x, aux8.z).normalized; if (i == 0) { angle7 = Vector2.SignedAngle(from7, to7); } Transform cube8 = auxPoint.PointTransf.Find("CubeFront"); //float distance = Vector3.Distance(item.transform.position, newpoi.transform.position); //float distance2 = Vector3.Distance(cube.position, item.transform.position) * 2; Vector2 from8 = new Vector2(-1, 0); Vector3 aux9 = newpoi3.transform.position - auxPoint.PointTransf.position; Vector2 to8 = new Vector2(aux8.x, aux8.y).normalized; if (i == 0) { angle2 = Vector2.SignedAngle(from8, to8); } //float angle = Mathf.Acos(distance2 / distance); //item.transform.Rotate(new Vector3(0, 1, 0), Vector2.Angle(from, to)); cube7.transform.rotation = Quaternion.Euler(new Vector3(0, -angle7, 0)); cube8.transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle8)); cube7.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.white; cube8.GetChild(0).GetComponent <MeshRenderer>().material.color = Color.white; auxPoint.PointTransf.GetComponent <PathPoint>().Poi = newpoi3.transform; newpoi3.GetComponent <POI>().addPoint(auxPoint.PointTransf.GetComponent <PathPoint>(), newLine3); //UnityEngine.Debug.Log(newpoi.GetComponent<POI>().Referenced.Count); sineC7 = (auxPoint.PointTransf.position.y - newpoi3.transform.position.y) / scaleX7; newLine3.transform.rotation = Quaternion.Euler(0, -angle7, Mathf.Asin(sineC7) * Mathf.Rad2Deg); newLine3.transform.position = auxPoint.PointTransf.transform.position; break; default: break; } } //This assigns reccam parameters to the waypoints that had them for (int i = 0; i < waypointPath.rcParametersCount(); i++) { RecCamParameters auxRcUpdateParameters = waypointPath.getRcUpdateParameter(i); reSetRecCamGuis(auxRcUpdateParameters, waypointPath.GetPoint(auxRcUpdateParameters.id_pointer).PointTransf.gameObject.GetComponent <PathPoint>()); } if (poiEditorPanel != null) { poiEditorPanel.GetComponent <POIEditor>().Deactivate(); } //activate every panel. If we saved a path, there has to be enough points to make sure this can be done if (editPointButton != null) { editPointButton.interactable = true; editPOIButton.interactable = true; previewButton.interactable = true; CurveButton.interactable = true; } } else //We assign an index to the new path { if (waypointPath != null) { MissionManager.planIndex = map.Paths.Count; } } //importedGO.name = "DaeModel"; }
/// <summary> /// Gets all the maps of a project /// </summary> /// <returns>MapsDataTable</returns> public MapMetadata.metaMapsDataTable GetMaps() { try { MapMetadata map = new MapMetadata(); Query query = db.CreateQuery("select [MapId], [Name], [Title] from metaMaps"); map.metaMaps.Merge(db.Select(query)); return map.metaMaps; } catch (Exception ex) { throw new GeneralException("Could not retrieve maps", ex); } }
IEnumerator RenderTexture() { GameObject Helper = GameObject.Find("DaeModel"); //Camera.main.transform.position = new Vector3(Helper.transform.position.x, Helper.transform.position.y + MissionManager.modelBoundingBox.y * 2, Helper.transform.position.z); //Vector3 auxPosition = Camera.main.transform.position; //float fieldOfVIewHelper = Camera.main.fieldOfView; //float futureFOV = 2.0f * Mathf.Atan((Camera.main.transform.position.y - (Helper.transform.position.y - MissionManager.modelBoundingBox.y)) * 0.5f / Vector3.Distance(Camera.main.transform.position, Helper.transform.position)) * Mathf.Rad2Deg; ////It can happen that the fov is really small or not a number //if (float.IsNaN(futureFOV)) //{ // Camera.main.fieldOfView = 40; // Camera.main.transform.position = new Vector3(Helper.transform.position.x, Helper.transform.position.y + 2, Helper.transform.position.z); // //} //else //{ // Camera.main.fieldOfView = futureFOV; //} //Resolution auxResolution = Screen.currentResolution; //Screen.SetResolution(256, 256, true); yield return(new WaitForEndOfFrame()); //Camera.main.targetTexture = modelRenderer; // //Texture2D texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //Camera.main.Render(); //texture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0); //texture.Apply(); //byte[] bytes = texture.EncodeToPNG(); // //// save the image //File.WriteAllBytes(Application.persistentDataPath + "/PersistentData/Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail", bytes); //DestroyObject(texture); //Camera.main.targetTexture.Release(); //Camera.main.targetTexture = null; //Destroy(GameObject.Find("DaeModel")); //Screen.SetResolution(auxResolution.width, auxResolution.height, true); //Camera.main.fieldOfView = fieldOfVIewHelper; //Camera.main.transform.position = auxPosition; //SceneManager.LoadScene("Recording"); string file = File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata metadata = JsonUtility.FromJson <MapMetadata>(file); if (metadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { pointCloudAskedForMetadata = true; // clientUnity.client.sendTwoPartCommand((byte)Modules.PLAN_LIBRARIAN_MODULE, (byte)PlanLibrarianCommandType.PLAN_LIB_REQUEST_METADATA, MissionManager.guid + "\0"); } // else // { PlanSelectionManager.askedForMaps = true; clientUnity.client.sendTwoPartCommand((byte)Modules.PLAN_LIBRARIAN_MODULE, (byte)PlanLibrarianCommandType.PLAN_LIB_REQUEST_MAP, MissionManager.guid + "\0"); LoadingPanel.SetActive(true); LoadingPanel.transform.GetChild(0).GetComponent <Text>().text = "Uploading Plan"; //} // Screen.SetResolution(auxResolution.width, auxResolution.height, true); }
void MapButton(string id) { //With a short touch on a map button, this creates a button for each plan int it = 0; PlanSelectionManager.animationsState = PlanSelectionManager.PanelAnimations.FIRST_PATH; Vector2 buttonSize = new Vector2(Screen.width / 5, Screen.height / 4.5f); //UnityEngine.Debug.Log(id); MissionManager.guid = id; string metadataJson = System.IO.File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + id + ".json.metadata"); MapMetadata metadata = JsonUtility.FromJson <MapMetadata>(metadataJson); if (metadata.Map_type == (byte)MapMetadata.MapType.EmptyBox) { MissionManager.importedModel = false; } else if (metadata.Map_type == (byte)MapMetadata.MapType.Model3D) { MissionManager.importedModel = true; } string json = System.IO.File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + id + ".json.mission"); Map m = JsonUtility.FromJson <Map>(json); MissionManager.invMatrix = Matrix4x4.Inverse(m.unityToAnchors); // First we delete all the plans, just in case somebody changed of map, to delete the previous plans buttons foreach (Transform child in BackgroundClicks.plansContainer.transform) { Destroy(child.gameObject); } //We get every plan PlanSelectionManager.planCount = m.Paths.Count; if (m.Paths.Count == 0 && GeneralSceneManager.appState == GeneralSceneManager.ApplicationState.Recording) { noPlansText.SetActive(true); } else { noPlansText.SetActive(false); } string mapJson = System.IO.File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + metadata.Guid + ".json.mission"); Map map = JsonUtility.FromJson <Map>(mapJson); //We print every plan for (it = 0; it < PlanSelectionManager.planCount; it++) { GameObject button = Instantiate(planButtonPrefab, BackgroundClicks.plansContainer.gameObject.transform); button.GetComponent <RectTransform>().anchoredPosition = new Vector2(-buttonOffset + (buttonOffset * it), 0); button.GetComponent <RectTransform>().sizeDelta = buttonSize; button.name = it.ToString(); button.GetComponent <PlanSelectionButtons>().planName = it.ToString(); button.GetComponent <PlanSelectionButtons>().pleaseConnectToTheDronePanel = pleaseConnectToTheDronePanel; button.GetComponent <PlanSelectionButtons>().downloadingMapPanel = downloadingMapPanel; GameObject nameOfPlanGameObject = new GameObject(); nameOfPlanGameObject.transform.parent = button.transform; //The name the user selected for the map is printed in the left down corner of the button Text nameOfPlanText = nameOfPlanGameObject.AddComponent <Text>(); nameOfPlanText.font = Rubik; if (map.Paths[it].Path_metadata.Name.Length > 20) { nameOfPlanText.text = map.Paths[it].Path_metadata.Name.Substring(0, 20); } else { nameOfPlanText.text = map.Paths[it].Path_metadata.Name; } nameOfPlanText.verticalOverflow = VerticalWrapMode.Overflow; nameOfPlanText.transform.SetSiblingIndex(1); nameOfPlanText.rectTransform.pivot = new Vector2(0, 0); nameOfPlanText.fontSize = Screen.width / 60; nameOfPlanText.rectTransform.anchorMin = new Vector2(0, 0f); nameOfPlanText.rectTransform.anchorMax = new Vector2(0, 0f); nameOfPlanText.rectTransform.sizeDelta = new Vector2(buttonSize.x, Screen.height / 20); nameOfPlanText.rectTransform.anchoredPosition = new Vector2(0, -50); //button.transform.GetChild(0).GetComponent<Button>().onClick.AddListener(() => PlanButton(button.name)); } //This is for the create a plan button if (GeneralSceneManager.appState == GeneralSceneManager.ApplicationState.Planning) { // Creación de un botón al final para añadir planes GameObject createPlanB = Instantiate(planButtonPrefab, BackgroundClicks.plansContainer.gameObject.transform); createPlanB.GetComponent <RectTransform>().anchoredPosition = new Vector2(-buttonOffset + (buttonOffset * it), 0); createPlanB.GetComponent <RectTransform>().sizeDelta = buttonSize; createPlanB.name = "CreatePlan"; createPlanB.GetComponent <PlanSelectionButtons>().newPlanButton = true; //createPlanB.transform.GetChild(0).GetComponent<Button>().onClick.AddListener(() => CreatePlan()); GameObject createPlanText = new GameObject(); createPlanText.transform.parent = createPlanB.transform.GetChild(0); createPlanText.name = "CreatePlanText"; createPlanText.AddComponent <RectTransform>().anchoredPosition = new Vector2(0, 0); createPlanText.AddComponent <Text>().text = "New Plan"; createPlanText.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); createPlanText.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); Text planBText = createPlanText.GetComponent <Text>(); planBText.font = Rubik; planBText.fontSize = Screen.height / 32; planBText.alignment = TextAnchor.MiddleCenter; } else { PlanSelectionManager.planCount--; } //If there are more than 3, we create an arrow so the user can cycle between plans if (PlanSelectionManager.planCount > 3) { planRightB.interactable = true; } }
void Awake() { modelLoadingPanel = GameObject.Find("ModelLoadingPanel"); modelLoadingPanel.transform.GetChild(0).GetComponent <RectTransform>().anchoredPosition = new Vector2(0, Screen.height / 7); modelLoadingPanel.transform.GetChild(0).GetComponent <RectTransform>().sizeDelta = new Vector2(Screen.width / 1.5f, Screen.height / 3); modelLoadingPanel.transform.GetChild(1).GetComponent <RectTransform>().anchoredPosition = new Vector2(0, -Screen.height / 7); modelLoadingPanel.transform.GetChild(1).GetComponent <RectTransform>().sizeDelta = new Vector2(Screen.height / 8, Screen.height / 8); modelLoadingPanel.transform.GetChild(0).GetComponent <Text>().fontSize = (int)(Screen.width * 0.05f); //We wait here for the collada to be loaded, and once it's loaded, the loading panel disappears StartCoroutine(WaitForModel()); GeneralSceneManager.sceneState = GeneralSceneManager.SceneState.ModelAlignment; BinaryFormatter bFormatter = new BinaryFormatter(); // Open the file using the path string json = System.IO.File.ReadAllText(Application.persistentDataPath + "/PersistentData/Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata metadata = JsonUtility.FromJson <MapMetadata>(json); if (metadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { //If it's a pointcloud, we use the shader to load a previous saved map GameObject auxGameObject = new GameObject(); auxGameObject.name = "DaemodelChild"; FileStream file = File.OpenRead(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dpl.map"); createBaseTriangle(); byte[] pclBytes = File.ReadAllBytes(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dpl.map"); GameObject daeModel = new GameObject(); daeModel.name = "DaeModel"; daeModel.transform.parent = auxGameObject.transform; LoadPointCloud(pclBytes, ref daeModel); } else { //If it's not we used the collada loader FileStream file = File.OpenRead(Application.persistentDataPath + "/PersistentData/Maps/" + MissionManager.guid + ".dae.map"); //var xmlWriter = new XmlTextWriter(file, Encoding.UTF8); //xmlWriter. XmlDocument doc = new XmlDocument(); string aux; using (StreamReader reader = new StreamReader(file)) { aux = reader.ReadToEnd(); } doc.LoadXml(aux); if (MissionManager.importedModel) { LoadDOC(doc, Shader.Find("Custom/ObjectsShader")); } else { LoadDOC(doc, Shader.Find("Airt/CullBackShader")); } } }
/// <summary> /// Creates a new map shape of the specified type and with an empty metadata collection. /// </summary> /// <param name="type">The shape type.</param> public MapShape(MapShapeType type) { this.type = type; this.metadata = new MapMetadata(); }
/// <summary> /// Creates a new point map shape. /// </summary> /// <param name="metadata">The map metadata.</param> /// <param name="point">The map point.</param> public MapShapePoint(MapMetadata metadata, MapPoint point) : base(MapShapeType.Point, metadata) { this.point = point; }
public FieldManager(int mapId, long instanceId) { MapId = mapId; InstanceId = instanceId; BoundingBox = MapEntityStorage.GetBoundingBox(mapId); // Load default npcs for map from config foreach (MapNpc npc in MapEntityStorage.GetNpcs(mapId)) { IFieldObject <Npc> fieldNpc = RequestFieldObject(new Npc(npc.Id) { ZRotation = (short)(npc.Rotation.Z * 10) }); if (fieldNpc.Value.Friendly == 2) { fieldNpc.Coord = npc.Coord.ToFloat(); AddNpc(fieldNpc); } else { // NPC is an enemy IFieldObject <Mob> fieldMob = RequestFieldObject(new Mob(npc.Id) { ZRotation = (short)(npc.Rotation.Z * 10) }); fieldMob.Coord = npc.Coord.ToFloat(); AddMob(fieldMob); } } // Spawn map's mobs at the mob spawners foreach (MapMobSpawn mobSpawn in MapEntityStorage.GetMobSpawns(mapId)) { if (mobSpawn.SpawnData == null) { Debug.WriteLine($"Missing mob spawn data: {mobSpawn}"); continue; } IFieldObject <MobSpawn> fieldMobSpawn = RequestFieldObject(new MobSpawn(mobSpawn)); fieldMobSpawn.Coord = mobSpawn.Coord.ToFloat(); State.AddMobSpawn(fieldMobSpawn); SpawnMobs(fieldMobSpawn); } // Load default portals for map from config foreach (MapPortal portal in MapEntityStorage.GetPortals(mapId)) { IFieldObject <Portal> fieldPortal = RequestFieldObject(new Portal(portal.Id) { IsVisible = portal.IsVisible, IsEnabled = portal.Enable, IsMinimapVisible = portal.MinimapVisible, Rotation = portal.Rotation.ToFloat(), TargetMapId = portal.Target, PortalType = portal.PortalType }); fieldPortal.Coord = portal.Coord.ToFloat(); AddPortal(fieldPortal); } // Load default InteractObjects List <IFieldObject <InteractObject> > actors = new List <IFieldObject <InteractObject> > { }; foreach (MapInteractObject interactObject in MapEntityStorage.GetInteractObject(mapId)) { // TODO: Group these fieldActors by their correct packet type. actors.Add(RequestFieldObject(new InteractObject(interactObject.Uuid, interactObject.Name, interactObject.Type) { })); } AddInteractObject(actors); MapMetadata mapMetadata = MapMetadataStorage.GetMetadata(mapId); if (mapMetadata != null) { string xBlockName = mapMetadata.XBlockName; Triggers = TriggerLoader.GetTriggers(xBlockName).Select(initializer => { TriggerContext context = new TriggerContext(this, Logger); TriggerState startState = initializer.Invoke(context); return(new TriggerScript(context, startState)); }).ToArray(); } foreach (MapTriggerMesh mapTriggerMesh in MapEntityStorage.GetTriggerMeshes(mapId)) { if (mapTriggerMesh != null) { TriggerMesh triggerMesh = new TriggerMesh(mapTriggerMesh.Id, mapTriggerMesh.IsVisible); State.AddTriggerObject(triggerMesh); } } foreach (MapTriggerEffect mapTriggerEffect in MapEntityStorage.GetTriggerEffects(mapId)) { if (mapTriggerEffect != null) { TriggerEffect triggerEffect = new TriggerEffect(mapTriggerEffect.Id, mapTriggerEffect.IsVisible); State.AddTriggerObject(triggerEffect); } } foreach (MapTriggerActor mapTriggerActor in MapEntityStorage.GetTriggerActors(mapId)) { if (mapTriggerActor != null) { TriggerActor triggerActor = new TriggerActor(mapTriggerActor.Id, mapTriggerActor.IsVisible, mapTriggerActor.InitialSequence); State.AddTriggerObject(triggerActor); } } foreach (MapTriggerCamera mapTriggerCamera in MapEntityStorage.GetTriggerCameras(mapId)) { if (mapTriggerCamera != null) { TriggerCamera triggerCamera = new TriggerCamera(mapTriggerCamera.Id, mapTriggerCamera.IsEnabled); State.AddTriggerObject(triggerCamera); } } foreach (MapTriggerCube mapTriggerCube in MapEntityStorage.GetTriggerCubes(mapId)) { if (mapTriggerCube != null) { TriggerCube triggerCube = new TriggerCube(mapTriggerCube.Id, mapTriggerCube.IsVisible); State.AddTriggerObject(triggerCube); } } foreach (MapTriggerLadder mapTriggerLadder in MapEntityStorage.GetTriggerLadders(mapId)) { if (mapTriggerLadder != null) { TriggerLadder triggerLadder = new TriggerLadder(mapTriggerLadder.Id, mapTriggerLadder.IsVisible); State.AddTriggerObject(triggerLadder); } } foreach (MapTriggerRope mapTriggerRope in MapEntityStorage.GetTriggerRopes(mapId)) { if (mapTriggerRope != null) { TriggerRope triggerRope = new TriggerRope(mapTriggerRope.Id, mapTriggerRope.IsVisible); State.AddTriggerObject(triggerRope); } } foreach (MapTriggerSound mapTriggerSound in MapEntityStorage.GetTriggerSounds(mapId)) { if (mapTriggerSound != null) { TriggerSound triggerSound = new TriggerSound(mapTriggerSound.Id, mapTriggerSound.IsEnabled); State.AddTriggerObject(triggerSound); } } // Load breakables foreach (MapBreakableActorObject mapActor in MapEntityStorage.GetBreakableActors(mapId)) { if (mapActor != null) { BreakableActorObject actor = new BreakableActorObject(mapActor.EntityId, mapActor.IsEnabled, mapActor.HideDuration, mapActor.ResetDuration); State.AddBreakable(actor); } } foreach (MapBreakableNifObject mapNif in MapEntityStorage.GetBreakableNifs(mapId)) { if (mapNif != null) { BreakableNifObject nif = new BreakableNifObject(mapNif.EntityId, mapNif.IsEnabled, mapNif.TriggerId, mapNif.HideDuration, mapNif.ResetDuration); State.AddBreakable(nif); } } if (MapEntityStorage.HasHealingSpot(MapId)) { List <CoordS> healingSpots = MapEntityStorage.GetHealingSpot(MapId); if (State.HealingSpots.IsEmpty) { foreach (CoordS coord in healingSpots) { int objectId = GuidGenerator.Int(); State.AddHealingSpot(RequestFieldObject(new HealingSpot(objectId, coord))); } } } }
public void onChunkWrite(NetMQMessage m) { ulong size = BitConverter.ToUInt64(m[0].Buffer, 3); //bytesSent += (long)size; //UnityEngine.Debug.Log("Bytes sent: " + bytesSent); //We received that a chunk was written on the server string[] currentPath = System.Text.Encoding.ASCII.GetString(m[1].Buffer).Split('.'); //string[] currentPath = BitConverter.ToString(m[1].Buffer).Split('.'); //UnityEngine.Debug.Log(currentPath[currentPath.Length - 1]); //We find which file was written first switch (currentPath[currentPath.Length - 1]) { case "metadata\0": //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); //SendChunk returns true if the whole file was ulpoaded. If it is we continue onto the mission if (SendChunk(metadataFileServerPath, metadataFileSize, ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata")) { StartSendFile(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.mission", missionFileServerPath); } break; case "mission\0": //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); //If the mission is uploaded, we check if is needed for the map to be uploaded. If it is not needed we upload the thumbnail, if it is, we upload the map if (SendChunk(missionFileServerPath, missionFileSize, ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.mission")) { if (PlanSelectionManager.uploadMapMetadata) { StartSendFile(ApplicationVariables.persistentDataPath + "Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail", thumbnailFileServerPath); } else { string metadata1 = File.ReadAllText(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata mapMetadata1 = JsonUtility.FromJson <MapMetadata>(metadata1); if (mapMetadata1.Map_type == (byte)MapMetadata.MapType.PointCloud) { StartSendFile(ApplicationVariables.persistentDataPath + "Maps/" + MissionManager.guid + ".dpl.map", mapFileServerPath); } else { StartSendFile(ApplicationVariables.persistentDataPath + "Maps/" + MissionManager.guid + ".dae.map", mapFileServerPath); } } } break; case "map\0": //Upload the thumbnail once the map finishes uploading //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); string metadata = File.ReadAllText(ApplicationVariables.persistentDataPath + "Missions/" + MissionManager.guid + ".json.metadata"); MapMetadata mapMetadata = JsonUtility.FromJson <MapMetadata>(metadata); if (mapMetadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { if (SendChunk(mapFileServerPath, mapFileSize, ApplicationVariables.persistentDataPath + "Maps/" + MissionManager.guid + ".dpl.map")) { StartSendFile(ApplicationVariables.persistentDataPath + "Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail", thumbnailFileServerPath); } } else { if (SendChunk(mapFileServerPath, mapFileSize, ApplicationVariables.persistentDataPath + "Maps/" + MissionManager.guid + ".dae.map")) { StartSendFile(ApplicationVariables.persistentDataPath + "Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail", thumbnailFileServerPath); } } break; case "thumbnail\0": //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); //The chain ends here //SendJSONStateMachine.pathsSend = true; if (SendChunk(thumbnailFileServerPath, thumbnailFileSize, ApplicationVariables.persistentDataPath + "Thumbnails/" + MissionManager.guid + ".jpeg.thumbnail")) { UnityEngine.Debug.Log("All files sent"); SendJSONStateMachine.allFilesSent = true; PlanSelectionManager.uploadMapMetadata = false; } break; case "deb\0": //UnityEngine.Debug.Log("File Created: " + BitConverter.ToString(m[1].Buffer)); //While the server hasn't been updated and the file hasn't been uploaded, the update package gets uploaded. Once it is uploaded, we quit atreyu to update it. if (!isUpdated && SendChunk(updateDebFileServerPath, updateDebFileSize, dataPathUpdate + fileNameUpdate)) { clientUnity.client.SendCommand((byte)Modules.STD_COMMANDS_MODULE, (byte)CommandType.QUIT); isUpdated = true; } break; default: UnityEngine.Debug.Log("Unhandled file extension (Chunk Write)"); break; } }
public FieldManager(Player player) { MapId = player.MapId; InstanceId = player.InstanceId; BoundingBox = MapEntityStorage.GetBoundingBox(MapId); // Load default npcs for map from config foreach (MapNpc npc in MapEntityStorage.GetNpcs(MapId)) { IFieldObject <Npc> fieldNpc = RequestFieldObject(new Npc(npc.Id) { ZRotation = (short)(npc.Rotation.Z * 10) }); if (fieldNpc.Value.Friendly == 2) { fieldNpc.Coord = npc.Coord.ToFloat(); AddNpc(fieldNpc); } else { // NPC is an enemy IFieldObject <Mob> fieldMob = RequestFieldObject(new Mob(npc.Id) { ZRotation = (short)(npc.Rotation.Z * 10) }); fieldMob.Coord = npc.Coord.ToFloat(); AddMob(fieldMob); } } // Spawn map's mobs at the mob spawners foreach (MapMobSpawn mobSpawn in MapEntityStorage.GetMobSpawns(MapId)) { if (mobSpawn.SpawnData == null) { Debug.WriteLine($"Missing mob spawn data: {mobSpawn}"); continue; } IFieldObject <MobSpawn> fieldMobSpawn = RequestFieldObject(new MobSpawn(mobSpawn)); fieldMobSpawn.Coord = mobSpawn.Coord.ToFloat(); State.AddMobSpawn(fieldMobSpawn); SpawnMobs(fieldMobSpawn); } // Load default portals for map from config foreach (MapPortal portal in MapEntityStorage.GetPortals(MapId)) { IFieldObject <Portal> fieldPortal = RequestFieldObject(new Portal(portal.Id) { IsVisible = portal.IsVisible, IsEnabled = portal.Enable, IsMinimapVisible = portal.MinimapVisible, Rotation = portal.Rotation.ToFloat(), TargetMapId = portal.Target, TargetPortalId = portal.TargetPortalId, PortalType = portal.PortalType }); fieldPortal.Coord = portal.Coord.ToFloat(); AddPortal(fieldPortal); } MapMetadata mapMetadata = MapMetadataStorage.GetMetadata(MapId); if (mapMetadata != null) { string xBlockName = mapMetadata.XBlockName; Triggers = TriggerLoader.GetTriggers(xBlockName).Select(initializer => { TriggerContext context = new TriggerContext(this, Logger); TriggerState startState = initializer.Invoke(context); return(new TriggerScript(context, startState)); }).ToArray(); } foreach (MapTriggerMesh mapTriggerMesh in MapEntityStorage.GetTriggerMeshes(MapId)) { if (mapTriggerMesh != null) { TriggerMesh triggerMesh = new TriggerMesh(mapTriggerMesh.Id, mapTriggerMesh.IsVisible); State.AddTriggerObject(triggerMesh); } } foreach (MapTriggerEffect mapTriggerEffect in MapEntityStorage.GetTriggerEffects(MapId)) { if (mapTriggerEffect != null) { TriggerEffect triggerEffect = new TriggerEffect(mapTriggerEffect.Id, mapTriggerEffect.IsVisible); State.AddTriggerObject(triggerEffect); } } foreach (MapTriggerActor mapTriggerActor in MapEntityStorage.GetTriggerActors(MapId)) { if (mapTriggerActor != null) { TriggerActor triggerActor = new TriggerActor(mapTriggerActor.Id, mapTriggerActor.IsVisible, mapTriggerActor.InitialSequence); State.AddTriggerObject(triggerActor); } } foreach (MapTriggerCamera mapTriggerCamera in MapEntityStorage.GetTriggerCameras(MapId)) { if (mapTriggerCamera != null) { TriggerCamera triggerCamera = new TriggerCamera(mapTriggerCamera.Id, mapTriggerCamera.IsEnabled); State.AddTriggerObject(triggerCamera); } } foreach (MapTriggerCube mapTriggerCube in MapEntityStorage.GetTriggerCubes(MapId)) { if (mapTriggerCube != null) { TriggerCube triggerCube = new TriggerCube(mapTriggerCube.Id, mapTriggerCube.IsVisible); State.AddTriggerObject(triggerCube); } } foreach (MapTriggerLadder mapTriggerLadder in MapEntityStorage.GetTriggerLadders(MapId)) { if (mapTriggerLadder != null) { TriggerLadder triggerLadder = new TriggerLadder(mapTriggerLadder.Id, mapTriggerLadder.IsVisible); State.AddTriggerObject(triggerLadder); } } foreach (MapTriggerRope mapTriggerRope in MapEntityStorage.GetTriggerRopes(MapId)) { if (mapTriggerRope != null) { TriggerRope triggerRope = new TriggerRope(mapTriggerRope.Id, mapTriggerRope.IsVisible); State.AddTriggerObject(triggerRope); } } foreach (MapTriggerSound mapTriggerSound in MapEntityStorage.GetTriggerSounds(MapId)) { if (mapTriggerSound != null) { TriggerSound triggerSound = new TriggerSound(mapTriggerSound.Id, mapTriggerSound.IsEnabled); State.AddTriggerObject(triggerSound); } } foreach (MapTriggerSkill mapTriggerSkill in MapEntityStorage.GetTriggerSkills(MapId)) { if (mapTriggerSkill != null) { TriggerSkill triggerSkill = new TriggerSkill(mapTriggerSkill.Id, mapTriggerSkill.SkillId, mapTriggerSkill.SkillLevel, mapTriggerSkill.Count, mapTriggerSkill.Position); IFieldObject <TriggerSkill> fieldTriggerSkill = RequestFieldObject(triggerSkill); fieldTriggerSkill.Coord = fieldTriggerSkill.Value.Position; State.AddTriggerSkills(fieldTriggerSkill); } } // Load breakables foreach (MapBreakableActorObject mapActor in MapEntityStorage.GetBreakableActors(MapId)) { if (mapActor != null) { BreakableActorObject actor = new BreakableActorObject(mapActor.EntityId, mapActor.IsEnabled, mapActor.HideDuration, mapActor.ResetDuration); State.AddBreakable(actor); } } foreach (MapBreakableNifObject mapNif in MapEntityStorage.GetBreakableNifs(MapId)) { if (mapNif != null) { BreakableNifObject nif = new BreakableNifObject(mapNif.EntityId, mapNif.IsEnabled, mapNif.TriggerId, mapNif.HideDuration, mapNif.ResetDuration); State.AddBreakable(nif); } } // Load interact objects foreach (MapInteractObject mapInteract in MapEntityStorage.GetInteractObjects(MapId)) { if (mapInteract != null) { InteractObject interactObject = new InteractObject(mapInteract.EntityId, mapInteract.InteractId, mapInteract.Type, InteractObjectState.Default); State.AddInteractObject(interactObject); } } // Load cubes if (MapId == (int)Map.PrivateResidence) { Home home = GameServer.HomeManager.GetHomeById(player.VisitingHomeId); if (home != null) { // Add cubes to state Dictionary <long, Cube> cubes = home.FurnishingInventory; foreach (Cube cube in cubes.Values.Where(x => x.PlotNumber == 1)) { IFieldObject <Cube> ugcCube = RequestFieldObject(cube); ugcCube.Coord = cube.CoordF; ugcCube.Rotation = cube.Rotation; State.AddCube(ugcCube); } // Add portals to state IEnumerable <Cube> cubePortals = cubes.Values.Where(x => x.Item.Id == 50400158); foreach (Cube cubePortal in cubePortals) { Portal portal = new Portal(GuidGenerator.Int()) { IsVisible = true, IsEnabled = true, IsMinimapVisible = false, Rotation = cubePortal.Rotation, PortalType = PortalTypes.Home }; IFieldObject <Portal> fieldPortal = RequestFieldObject(portal); fieldPortal.Coord = cubePortal.CoordF; fieldPortal.Value.UGCPortalMethod = cubePortal.PortalSettings.Method; if (!string.IsNullOrEmpty(cubePortal.PortalSettings.DestinationTarget)) { switch (cubePortal.PortalSettings.Destination) { case UGCPortalDestination.PortalInHome: fieldPortal.Value.TargetMapId = (int)Map.PrivateResidence; break; case UGCPortalDestination.SelectedMap: fieldPortal.Value.TargetMapId = int.Parse(cubePortal.PortalSettings.DestinationTarget); break; case UGCPortalDestination.FriendHome: fieldPortal.Value.TargetHomeAccountId = long.Parse(cubePortal.PortalSettings.DestinationTarget); break; } } cubePortal.PortalSettings.PortalObjectId = fieldPortal.ObjectId; AddPortal(fieldPortal); } } } else { List <Home> homes = GameServer.HomeManager.GetPlots(MapId); foreach (Home home in homes) { Dictionary <long, Cube> cubes = home.FurnishingInventory; foreach (Cube cube in cubes.Values.Where(x => x.PlotNumber != 1)) { IFieldObject <Cube> ugcCube = RequestFieldObject(cube); ugcCube.Coord = cube.CoordF; ugcCube.Rotation = cube.Rotation; State.AddCube(ugcCube); } } } if (MapEntityStorage.HasHealingSpot(MapId)) { List <CoordS> healingSpots = MapEntityStorage.GetHealingSpot(MapId); if (State.HealingSpots.IsEmpty) { foreach (CoordS coord in healingSpots) { int objectId = GuidGenerator.Int(); State.AddHealingSpot(RequestFieldObject(new HealingSpot(objectId, coord))); } } } }
public void onContentReceived(NetMQMessage m) { ulong offset = BitConverter.ToUInt64(m[0].Buffer, 3); ulong size = BitConverter.ToUInt64(m[0].Buffer, 11); //UnityEngine.Debug.Log("Start writing file"); string currentFile = System.Text.Encoding.ASCII.GetString(m[1].Buffer); currentFile = currentFile.Substring(0, currentFile.Length - 1); if (!bytesPathDict.ContainsKey(currentFile)) { return; } //If the file has already been added ina a dictionary with the filename + chunks dowloaded, we continue downloading if (chunkPathDict.ContainsKey(currentFile)) { byte[] array1 = chunkPathDict[currentFile]; byte[] array2 = m[2].Buffer; if (array1.Length >= array2.Length) { //byte[] aux = new byte[array2.Length]; //Array.Copy(array1, array1.Length - array2.Length, aux, 0, array2.Length); //if (array2 == aux) //{ // return; //} //if we already received the bytes, just in case there are two tablets receveing the same map, we exit if ((ulong)array1.Length >= offset) { return; } //bool partAlreadyIn = true; // //for (int i = array2.Length - 1, j = array1.Length; i >= 0; i--, j--) //{ // if (array2[i] != array1[j]) // { // partAlreadyIn = false; // break; // // } // //} //if (partAlreadyIn) //{ // return; //} } //We write the chunk received after the previous chunks byte[] newArray = new byte[(ulong)chunkPathDict[currentFile].Length + size]; Array.Copy(array1, newArray, array1.Length); Array.Copy(array2, 0, newArray, array1.Length, array2.Length); chunkPathDict[currentFile] = newArray; //UnityEngine.Debug.Log("Writing file"); } else { //Else, we add it to the dictionary //UnityEngine.Debug.Log("Began writing"); chunkPathDict.Add(currentFile, new byte[size]); chunkPathDict[currentFile] = m[2].Buffer; } //If every byte has been written if ((ulong)chunkPathDict[currentFile].Length >= bytesPathDict[currentFile]) { String objectString = ""; string[] extensionName = currentFile.Split('.'); string[] path = extensionName[extensionName.Length - 3].Split('/'); //Pointclouds aren't strings, so we don't convert yet for every type if (!extensionName[extensionName.Length - 1].Equals("map")) { objectString = System.Text.Encoding.UTF8.GetString(chunkPathDict[currentFile]); } //UnityEngine.Debug.Log(extensionName[extensionName.Length - 1]); if (extensionName[extensionName.Length - 1].Equals("metadata")) { //UnityEngine.Debug.Log("It was metadata"); metadataFiles.Enqueue(objectString); } else if (extensionName[extensionName.Length - 1].Equals("thumbnail")) { UnityEngine.Debug.Log(ApplicationVariables.persistentDataPath + "Thumbnails/" + path[path.Length - 1] + ".jpeg.thumbnail"); System.IO.File.WriteAllBytes(ApplicationVariables.persistentDataPath + "Thumbnails/" + path[path.Length - 1] + ".jpeg.thumbnail", chunkPathDict[currentFile]); //UnityEngine.Debug.Log("Did it hang here?"); clientUnity.client.sendTwoPartCommand((byte)Modules.PLAN_LIBRARIAN_MODULE, (byte)PlanLibrarianCommandType.PLAN_LIB_REQUEST_MISSION, path[path.Length - 1] + '\0'); } else if (extensionName[extensionName.Length - 1].Equals("mission")) { //UnityEngine.Debug.Log("It was mission"); System.IO.File.WriteAllText(ApplicationVariables.persistentDataPath + "Missions/" + path[path.Length - 1] + ".json.mission", objectString); guidToCreateButtons.Enqueue(path[path.Length - 1]); } else if (extensionName[extensionName.Length - 1].Equals("map")) { //UnityEngine.Debug.Log("It was map"); if (GeneralSceneManager.sceneState == GeneralSceneManager.SceneState.Mapping) { System.IO.File.WriteAllBytes(ApplicationVariables.persistentDataPath + "Maps/" + path[path.Length - 1] + ".dpl.map", chunkPathDict[currentFile]); } else { string metadata = File.ReadAllText(ApplicationVariables.persistentDataPath + "Missions/" + path[path.Length - 1] + ".json.metadata"); MapMetadata mapMetadata = JsonUtility.FromJson <MapMetadata>(metadata); if (mapMetadata.Map_type == (byte)MapMetadata.MapType.PointCloud) { System.IO.File.WriteAllBytes(ApplicationVariables.persistentDataPath + "Maps/" + path[path.Length - 1] + ".dpl.map", chunkPathDict[currentFile]); } else { objectString = System.Text.Encoding.UTF8.GetString(chunkPathDict[currentFile]); System.IO.File.WriteAllText(ApplicationVariables.persistentDataPath + "Maps/" + path[path.Length - 1] + ".dae.map", objectString); } } MapLoader.mapDownloaded = true; PlanSelectionManager.askedForMaps = false; } chunkPathDict.Remove(currentFile); bytesPathDict.Remove(currentFile); } else { //UnityEngine.Debug.Log("ContentReceived"); clientUnity.client.sendTwoPartCommand((byte)Modules.OS_MODULE, (byte)OSCommandType.OS_REQUEST_FILE_CONTENT, offset + size, size, System.Text.Encoding.ASCII.GetString(m[1].Buffer)); } }