//--------------------------------------------------------------------------- #region Private Member Data //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Accessors and Mutators //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void TransferBlock(Vector3i?origin, Vector3i?destination) { if (origin.HasValue && destination.HasValue) { OCMap map = OCMap.Instance; //(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); foreach (Transform battery in map.BatteriesSceneObject.transform) { if (VectorUtil.AreVectorsEqual(battery.position, new Vector3((float)origin.Value.x, (float)origin.Value.y, (float)origin.Value.z))) { battery.position = new Vector3((float)destination.Value.x, (float)destination.Value.y, (float)destination.Value.z); } } OCBlockData block = map.GetBlock(origin.Value); map.SetBlockAndRecompute(block, destination.Value); map.SetBlockAndRecompute(OCBlockData.CreateInstance <OCBlockData>().Init(null, origin.Value), origin.Value); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == block.block) { goalController.FindGoalBlockPositionInChunks(map.GetChunks()); } } } }
private IEnumerator Building() { building = true; Vector3 pos = Camera.mainCamera.transform.position; Vector3i current = Chunk.ToChunkPosition((int)pos.x, (int)pos.y, (int)pos.z); Vector3i?column = columnMap.GetClosestEmptyColumn(current.x, current.z, 7); if (column.HasValue) { int cx = column.Value.x; int cz = column.Value.z; columnMap.SetBuilt(cx, cz); yield return(StartCoroutine(GenerateColumn(cx, cz))); yield return(null); ChunkSunLightComputer.ComputeRays(map, cx, cz); ChunkSunLightComputer.Scatter(map, columnMap, cx, cz); terrainGenerator.GeneratePlants(cx, cz); yield return(StartCoroutine(BuildColumn(cx, cz))); } building = false; }
public Vector3i?GetClosestEmptyColumn(int cx, int cz, int rad) { Vector3i center = new Vector3i(cx, 0, cz); Vector3i?closest = null; for (int z = cz - rad; z <= cz + rad; z++) { for (int x = cx - rad; x <= cx + rad; x++) { Vector3i current = new Vector3i(x, 0, z); int dis = center.DistanceSquared(current); if (dis > rad * rad) { continue; } if (IsBuilt(x, z)) { continue; } if (!closest.HasValue) { closest = current; } else { int oldDis = center.DistanceSquared(closest.Value); if (dis < oldDis) { closest = current; } } } } return(closest); }
public static WorldEditBlock CreateNew(Block pBlock, Vector3i pPosition, Vector3i?pSourcePosition) { WorldEditBlock web = new WorldEditBlock(); web.Position = pPosition; web.Type = pBlock.GetType(); var constuctor = web.Type.GetConstructor(Type.EmptyTypes); if (constuctor == null) { if (pBlock is PlantBlock) { web.Data = EcoSerializer.Serialize(PlantBlock.GetPlant(pPosition)).ToArray(); } if (pBlock is WorldObjectBlock) { WorldObjectBlock wob = (WorldObjectBlock)pBlock; if (wob.WorldObjectHandle.Object.Position3i == pSourcePosition) { web.Data = EcoSerializer.Serialize(wob.WorldObjectHandle.Object).ToArray(); } } } return(web); }
public bool Damage(Vector3i position, Vector3i face, byte block, float damage) { Debug.Assert(damage >= 0f); if (position == _position) { _health -= damage; } else { _position = position; _health = 1f - damage; } _health = Mathf.Clamp01(_health); _particles.EmitDamage(position, face, block, _health); if (_health == 0f) { Initialize(); return(true); } else { _lastDamageTime = Time.time; _surfaces.UpdateHealth(position, _health); return(false); } }
//NOTE: this function pulls the weight of actually destroying blocks for us. It is applied to the OCActions of a character; not to blocks themselves. public void DestroyBlock(Vector3i?point) { if (point.HasValue) { OCMap map = OCMap.Instance; //(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); //for updating goal controllers after deletion. OCBlock blockType = map.GetBlock(point.Value).block; OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); //actually sets the block to null and recomputes the chunk. Debug.Log(OCLogSymbol.DEBUG + "DeleteSelectedVoxel called from CreateBlockEffect"); GameManager.world.voxels.DeleteSelectedVoxel(point.Value); //re-update goals concerned with this block type foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == blockType) { goalController.FindGoalBlockPositionInChunks(map.GetChunks()); } } blocksDestroyed++; } }
// Update is called once per frame void Update() { //If the cursor is visible; don't select anything if (Cursor.visible) { return; } //Delecte the current block if (Input.GetMouseButtonDown(0)) { if (!ItemHandler.Instance.UseHeldItem()) { Vector3i?point = GetCursor(true); if (point.HasValue) { Map.Instance.SetBlockAndRecompute(null, point.Value); } } } //Place the selected block if (Input.GetMouseButtonDown(1)) { Vector3i?point = GetCursor(false); if (point.HasValue) { //Increment the number of placed blocks _blocksPlaced++; BlockData block = new BlockData(GetSelectedBlock()); block.SetRotation(GetRotation(-transform.forward)); Map.Instance.SetBlockAndRecompute(block, point.Value); } } }
public void Initialize() { _position = null; _health = 1f; _lastDamageTime = null; _surfaces.ResetDamage(); }
//--------------------------------------------------------------------------- #region Private Member Data //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Accessors and Mutators //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void DestroyBlock(Vector3i?point) { if (point.HasValue) { OCMap map = (OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); map.SetBlockAndRecompute(new OpenCog.Map.OCBlockData(), point.Value); } }
public bool ShiftSelection(Vector3i pDirection) { if (!FirstPos.HasValue || !SecondPos.HasValue) { return(false); } FirstPos = FirstPos + pDirection; SecondPos = SecondPos + pDirection; return(true); }
//Draw a cube around the selected block void OnDrawGizmos() { if (!Application.isPlaying) { return; } Vector3i?cursor = GetCursor(true); if (cursor.HasValue) { Gizmos.color = gizmoColor; Gizmos.DrawWireCube(new Vector3(cursor.Value.x, cursor.Value.y, cursor.Value.z), Vector3.one * _gizmoSize); } }
//--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Accessors and Mutators //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void CreateBlock(Vector3i?point) { if (point.HasValue) { OCMap map = (OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); OCBlock block = map.GetBlockSet().GetBlock(_BlockType); //block.SetDirection(GetDirection(-gameObject.transform.forward)); OCBlockData blockData = new OCBlockData(block, VectorUtil.Vector3ToVector3i(point.Value)); map.SetBlockAndRecompute(blockData, point.Value); } }
private void LoadQueuedChunks() { while (_chunksToLoad.TryDequeue(out Vector3i coordinates)) { _chunkBeingLoaded = coordinates; Chunk chunk; if (_storage.ChunkExists(coordinates)) { chunk = _storage.LoadChunk(coordinates); } else { chunk = _generator.GenerateChunk(coordinates); } _chunksToAdd.Enqueue(chunk); } _chunkBeingLoaded = null; }
private IEnumerator Building() { if (MapName == String.Empty) { building = true; Vector3 pos = Camera.mainCamera.transform.position; Vector3i current = OpenCog.Map.OCChunk.ToChunkPosition((int)pos.x, (int)pos.y, (int)pos.z); Vector3i?column = columnMap.GetClosestEmptyColumn(current.x, current.z, worldGenerationRadius); if (column == null) { // No more columns to create...let's update the colliders map.AddColliders(); collidersUpToDate = true; } else { if (column.HasValue) { int cx = column.Value.x; int cz = column.Value.z; columnMap.SetBuilt(cx, cz); yield return(StartCoroutine(GenerateColumn(cx, cz))); yield return(null); OpenCog.Map.Lighting.OCChunkSunLightComputer.ComputeRays(map, cx, cz); OpenCog.Map.Lighting.OCChunkSunLightComputer.Scatter(map, columnMap, cx, cz); terrainGenerator.GeneratePlants(cx, cz); collidersUpToDate = false; yield return(StartCoroutine(BuildColumn(cx, cz))); } } building = false; } }
//--------------------------------------------------------------------------- #region Private Member Data //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Accessors and Mutators //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void DestroyBlock(Vector3i?point) { if (point.HasValue) { OCMap map = OCMap.Instance; //(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); OCBlock blockType = map.GetBlock(point.Value).block; map.SetBlockAndRecompute(OCBlockData.CreateInstance <OCBlockData>().Init(null, point.Value), point.Value); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == blockType) { goalController.FindGoalBlockPositionInChunks(map.GetChunks()); } } } }
public bool ExpandSelection(Vector3i pDirection, bool pContract = false) { SortedVectorPair svp = GetSortedVectors(); if (svp == null) { return(false); } Vector3i pos1 = FirstPos.Value; Vector3i pos2 = SecondPos.Value; int typeOfVolume = FindTypeOfVolume(ref pos1, ref pos2, out Vector3i lower, out Vector3i higher); var firstResult = SumAllAxis(pDirection * FirstPos.Value); var secondResult = SumAllAxis(pDirection * SecondPos.Value); bool useFirst = firstResult > secondResult; if (typeOfVolume == 1) { useFirst = !useFirst; } if (pContract) { useFirst = !useFirst; } if (useFirst) { FirstPos = FirstPos + pDirection; } else { SecondPos = SecondPos + pDirection; } return(true); }
protected Vector3 TryFindLand(Vector3i center) { Vector3i?land = null; for (int x = center.x - 20; x <= center.x + 20; x++) { for (int z = center.z - 20; z <= center.z + 20; z++) { int height = MapLight.GetRaySafe(x, z); Block surface = Map.GetBlockSafe(x, height - 1, z); if (!surface.IsFluid()) { Vector3i current = new Vector3i(x, height, z); if (!land.HasValue) { land = current; } else { int dis = center.DistanceSquared(current); int oldDis = center.DistanceSquared(land.Value); if (dis < oldDis) { land = current; } } } } } if (land.HasValue) { return(land.Value.ToVector3()); } return(new Vector3(center.x, MapLight.GetRay(center.x, center.z), center.z)); }
//--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void CreateBlock(Vector3i?point) { if (point.HasValue) { OCMap map = OCMap.Instance; //(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); OCBlock block = map.GetBlockSet().GetBlock(_BlockType); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == block) { goalController.FindGoalBlockPositionInChunks(map.GetChunks()); } } Debug.Log(OCLogSymbol.DEBUG + "AddSelectedVoxel called from CreateBlockEffect"); GameManager.world.voxels.AddSelectedVoxel(point.Value, -transform.forward, block); } }
//--------------------------------------------------------------------------- #endregion //--------------------------------------------------------------------------- #region Public Member Functions //--------------------------------------------------------------------------- public void CreateBlock(Vector3i?point) { if (point.HasValue) { OCMap map = OCMap.Instance; //(OCMap)GameObject.FindSceneObjectsOfType(typeof(OCMap)).FirstOrDefault(); OCBlock block = map.GetBlockSet().GetBlock(_BlockType); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == block) { goalController.FindGoalBlockPositionInChunks(map.GetChunks()); } } //block.SetDirection(GetDirection(-gameObject.transform.forward)); OCBlockData blockData = OCBlockData.CreateInstance <OCBlockData>().Init(block, VectorUtil.Vector3ToVector3i(point.Value)); map.SetBlockAndRecompute(blockData, point.Value); } }
/// <summary> /// Generate terrain around the position.</summary> /// <param name="pos"> Terrain will be generated around this position.</param> /// <param name="threaded"> If true, terrain generation & building will be multithreaded.</param> public void UpdateAround(Vector3 pos, bool threaded) { try { int posX = Mathf.RoundToInt(pos.x / Utils.Chunk.SIZE_X_BLOCK); int posY = Mathf.RoundToInt(pos.y / Utils.Chunk.SIZE_Y_BLOCK); int posZ = Mathf.RoundToInt(pos.z / Utils.Chunk.SIZE_Z_BLOCK); Vector3i current = Utils.Chunk.ToChunkPosition(posX, posY, posZ); if (current != LastUpdatedPosition) { genDone = false; buildDone = false; grassDone = false; } // Hide chunks far away this.FreeColumns(current.x, current.z); // Generate dynamically /*if (!genDone) * { * List<Vector3i> nearEmpties = LazyFindNearestNotGeneratedColumn(current.x, current.z, map.buildDistance + 1, 1, 1); * if (nearEmpties.Count != 0) * { * for (int i = 0; i < nearEmpties.Count; i++) * { * Vector3i nearEmpty = nearEmpties[i]; * int cx = nearEmpty.x; * int cz = nearEmpty.z; * if (threaded) * GenerateColumnThreaded(GetChunk2D(cx, cz)); * else * GenerateColumn(cx, cz); * } * } * else * { * genDone = true; * } * }*/ // Build dynamically if (!buildDone) { List <Vector3i> nearEmpties = LazyFindNearestNotBuiltColumn(current.x, current.z, map.buildDistance, 1, 1); if (nearEmpties.Count != 0) { for (int i = 0; i < nearEmpties.Count; i++) { Vector3i nearEmpty = nearEmpties[i]; int cx = nearEmpty.x; int cz = nearEmpty.z; if (NeighbourColumnsAreGenerated(cx, cz)) { if (threaded) { BuildColumnThreaded(GetChunk2D(cx, cz)); } else { BuildColumn(cx, cz); } } } } else { buildDone = true; } } // Display grass if (threaded && !grassDone) { Vector3i?nearEmpty = LazyFindNearestNoGrassColumn(current.x, current.z, (int)(map.grassDrawDistance / (Chunk.SIZE_AVERAGE_BLOCK * Chunk.SIZE_X)) + 1, 1); if (nearEmpty.HasValue) { int cx = nearEmpty.Value.x; int cz = nearEmpty.Value.z; BuildGrassColumn(cx, cz); } else { grassDone = true; } } LastUpdatedPosition = current; } catch (Exception e) { Debug.LogWarning("TerraVol Editor Tool tried to execute terrain generation while it was null: " + e.Message); } }
private void UpdatePicking() { bool left = Mouse[OpenTK.Input.MouseButton.Left];//destruct bool middle = Mouse[OpenTK.Input.MouseButton.Middle];//clone material as active bool right = Mouse[OpenTK.Input.MouseButton.Right];//build if (!leftpressedpicking) { if (mouseleftclick) { leftpressedpicking = true; } else { left = false; } } else { if (mouseleftdeclick) { leftpressedpicking = false; left = false; } } if (!left) { currentAttackedBlock = null; } float pick_distance = PICK_DISTANCE; if (cameratype == CameraType.Tpp) { pick_distance = tppcameradistance * 2; } if (cameratype == CameraType.Overhead) { pick_distance = overheadcameradistance; } float unit_x = 0; float unit_y = 0; int NEAR = 1; int FOV = 600; float ASPECT = 640f / 480; float near_height = NEAR * (float)(Math.Tan(FOV * Math.PI / 360.0)); Vector3 ray = new Vector3(unit_x * near_height * ASPECT, unit_y * near_height, 1);//, 0); Vector3 ray_start_point = new Vector3(0, 0, 0); if (overheadcamera) { float mx = (float)mouse_current.X / Width - 0.5f; float my = (float)mouse_current.Y / Height - 0.5f; //ray_start_point = new Vector3(mx * 1.4f, -my * 1.1f, 0.0f); ray_start_point = new Vector3(mx * 3f, -my * 2.2f, -1.0f); } //Matrix4 the_modelview; //Read the current modelview matrix into the array the_modelview //GL.GetFloat(GetPName.ModelviewMatrix, out the_modelview); if (d_The3d.ModelViewMatrix.Equals(new Matrix4())) { return; } Matrix4 theModelView = d_The3d.ModelViewMatrix; theModelView.Invert(); //the_modelview = new Matrix4(); ray = Vector3.Transform(ray, theModelView); ray_start_point = Vector3.Transform(ray_start_point, theModelView); Line3D pick = new Line3D(); Vector3 raydir = -(ray - ray_start_point); raydir.Normalize(); pick.Start = ray + Vector3.Multiply(raydir, 1f); //do not pick behind pick.End = ray + Vector3.Multiply(raydir, pick_distance * 2); //pick models selectedmodelid = -1; foreach (var m in Models) { Vector3 closestmodelpos = new Vector3(int.MaxValue, int.MaxValue, int.MaxValue); foreach (var t in m.TrianglesForPicking) { Vector3 intersection; if (Collisions.Intersection.RayTriangle(pick, t, out intersection) == 1) { if ((pick.Start - intersection).Length > pick_distance) { continue; } if ((pick.Start - intersection).Length < (pick.Start - closestmodelpos).Length) { closestmodelpos = intersection; selectedmodelid = m.Id; } } } } if (selectedmodelid != -1) { pickcubepos = new Vector3(-1, -1, -1); if (mouseleftclick) { ModelClick(selectedmodelid); } mouseleftclick = false; leftpressedpicking = false; return; } if (left) { d_Weapon.SetAttack(true, false); } else if (right) { d_Weapon.SetAttack(true, true); } //if (iii++ % 2 == 0) { //To improve speed, update picking only every second frame. //return; } //pick terrain var s = new BlockOctreeSearcher(); s.StartBox = new Box3D(0, 0, 0, BitTools.NextPowerOfTwo((uint)Math.Max(d_Map.MapSizeX, Math.Max(d_Map.MapSizeY, d_Map.MapSizeZ)))); List<BlockPosSide> pick2 = new List<BlockPosSide>(s.LineIntersection(IsTileEmptyForPhysics, getblockheight, pick)); pick2.Sort((a, b) => { return (a.pos - ray_start_point).Length.CompareTo((b.pos - ray_start_point).Length); }); if (overheadcamera && pick2.Count > 0 && left) { //if not picked any object, and mouse button is pressed, then walk to destination. playerdestination = pick2[0].pos; } bool pickdistanceok = pick2.Count > 0 && (pick2[0].pos - (player.playerposition)).Length <= pick_distance; bool playertileempty = IsTileEmptyForPhysics( (int)ToMapPos(player.playerposition).X, (int)ToMapPos(player.playerposition).Y, (int)ToMapPos(player.playerposition).Z); bool playertileemptyclose = IsTileEmptyForPhysicsClose( (int)ToMapPos(player.playerposition).X, (int)ToMapPos(player.playerposition).Y, (int)ToMapPos(player.playerposition).Z); BlockPosSide pick0; if (pick2.Count > 0 && ((pickdistanceok && (playertileempty || (playertileemptyclose))) || overheadcamera) ) { pickcubepos = pick2[0].Current(); pickcubepos = new Vector3((int)pickcubepos.X, (int)pickcubepos.Y, (int)pickcubepos.Z); pick0 = pick2[0]; } else { pickcubepos = new Vector3(-1, -1, -1); pick0.pos = new Vector3(-1, -1, -1); pick0.side = TileSide.Front; } if (FreeMouse) { if (pick2.Count > 0) { OnPick(pick0); } return; } var ntile = pick0.Current(); if(IsUsableBlock(d_Map.GetBlock((int)ntile.X, (int)ntile.Z, (int)ntile.Y))) { currentAttackedBlock = new Vector3i((int)ntile.X, (int)ntile.Z, (int)ntile.Y); } if ((DateTime.Now - lastbuild).TotalSeconds >= BuildDelay) { if (left && d_Inventory.RightHand[ActiveMaterial] == null) { PacketClientHealth p = new PacketClientHealth { CurrentHealth = (int)(2 + rnd.NextDouble() * 4) }; SendPacket(Serialize(new PacketClient() { PacketId = ClientPacketId.MonsterHit, Health = p })); } if (left && !fastclicking) { //todo animation fastclicking = false; } if (left || right || middle) { lastbuild = DateTime.Now; } if (pick2.Count > 0) { if (middle) { var newtile = pick0.Current(); if (MapUtil.IsValidPos(d_Map, (int)newtile.X, (int)newtile.Z, (int)newtile.Y)) { int clonesource = d_Map.GetBlock((int)newtile.X, (int)newtile.Z, (int)newtile.Y); int clonesource2 = (int)d_Data.WhenPlayerPlacesGetsConvertedTo[(int)clonesource]; //find this block in another right hand. for (int i = 0; i < 10; i++) { if (d_Inventory.RightHand[i] != null && d_Inventory.RightHand[i].ItemClass == ItemClass.Block && (int)d_Inventory.RightHand[i].BlockId == clonesource2) { ActiveMaterial = i; goto done; } } int? freehand = d_InventoryUtil.FreeHand(ActiveMaterial); //find this block in inventory. foreach (var k in d_Inventory.Items) { if (k.Value.ItemClass == ItemClass.Block && k.Value.BlockId == clonesource2) { //free hand if (freehand != null) { d_InventoryController.WearItem( InventoryPosition.MainArea(k.Key.ToPoint()), InventoryPosition.MaterialSelector(freehand.Value)); goto done; } //try to replace current slot if (d_Inventory.RightHand[ActiveMaterial] != null && d_Inventory.RightHand[ActiveMaterial].ItemClass == ItemClass.Block) { d_InventoryController.MoveToInventory( InventoryPosition.MaterialSelector(ActiveMaterial)); d_InventoryController.WearItem( InventoryPosition.MainArea(k.Key.ToPoint()), InventoryPosition.MaterialSelector(ActiveMaterial)); } } } done: d_Audio.Play(d_Data.CloneSound[clonesource][0]); //todo sound cycle } } if (left || right) { BlockPosSide tile = pick0; Console.Write(tile.pos + ":" + Enum.GetName(typeof(TileSide), tile.side)); Vector3 newtile = right ? tile.Translated() : tile.Current(); if (MapUtil.IsValidPos(d_Map, (int)newtile.X, (int)newtile.Z, (int)newtile.Y)) { Console.WriteLine(". newtile:" + newtile + " type: " + d_Map.GetBlock((int)newtile.X, (int)newtile.Z, (int)newtile.Y)); if (pick0.pos != new Vector3(-1, -1, -1)) { int blocktype; if (left) { blocktype = d_Map.GetBlock((int)newtile.X, (int)newtile.Z, (int)newtile.Y); } else { blocktype = materialSlots[ActiveMaterial]; } if (left && blocktype == d_Data.BlockIdAdminium) { goto end; } string[] sound = left ? d_Data.BreakSound[blocktype] : d_Data.BuildSound[blocktype]; if (sound != null && sound.Length > 0) { d_Audio.Play(sound[0]); //todo sound cycle } } //normal attack if (!right) { //attack var pos = new Vector3i((int)newtile.X, (int)newtile.Z, (int)newtile.Y); currentAttackedBlock = new Vector3i(pos.x,pos.y,pos.z); if (!blockhealth.ContainsKey(pos)) { blockhealth[pos] = GetCurrentBlockHealth(pos.x, pos.y, pos.z); } blockhealth[pos] -= WeaponAttackStrength(); float health = GetCurrentBlockHealth(pos.x,pos.y,pos.z); if (health <= 0) { if (currentAttackedBlock != null) { blockhealth.Remove(currentAttackedBlock.Value); } currentAttackedBlock = null; goto broken; } goto end; } if (!right) { particleEffectBlockBreak.StartParticleEffect(newtile);//must be before deletion - gets ground type. } if (!MapUtil.IsValidPos(d_Map, (int)newtile.X, (int)newtile.Z, (int)newtile.Y)) { throw new Exception(); } broken: OnPick(new Vector3((int)newtile.X, (int)newtile.Z, (int)newtile.Y), new Vector3((int)tile.Current().X, (int)tile.Current().Z, (int)tile.Current().Y), tile.pos, right); //network.SendSetBlock(new Vector3((int)newtile.X, (int)newtile.Z, (int)newtile.Y), // right ? BlockSetMode.Create : BlockSetMode.Destroy, (byte)MaterialSlots[activematerial]); } } } } end: fastclicking = false; if (!(left || right || middle)) { lastbuild = new DateTime(); fastclicking = true; } }
// Update is called once per frame void Update() { if (Screen.showCursor) { return; } if (Input.GetKeyDown(KeyCode.LeftControl)) { Vector3i?point = GetCursor(false); if (point.HasValue) { byte sun = map.GetSunLightmap().GetLight(point.Value); byte light = map.GetLightmap().GetLight(point.Value); Debug.Log("Sun " + " " + sun + " Light " + light); } } if (Input.GetKeyDown(KeyCode.RightControl)) { Vector3i?point = GetCursor(true); if (point.HasValue) { byte sun = map.GetSunLightmap().GetLight(point.Value); byte light = map.GetLightmap().GetLight(point.Value); Debug.Log("Sun " + sun + " Light " + light); } } if (Input.GetMouseButtonDown(0)) { Vector3i?point = GetCursor(true); if (point.HasValue) { map.SetBlockAndRecompute(new BlockData(), point.Value); } } if (Input.GetMouseButtonDown(1)) { Vector3i?point = GetCursor(false); if (point.HasValue) { bool empty = !BlockCharacterCollision.GetContactBlockCharacter(point.Value, transform.position, characterCollider).HasValue; if (empty) { BlockData block = new BlockData(selectedBlock); block.SetDirection(GetDirection(-transform.forward)); map.SetBlockAndRecompute(block, point.Value); } } } Vector3i?cursor = GetCursor(true); this.cursor.active = cursor.HasValue; if (cursor.HasValue) { this.cursor.transform.position = cursor.Value; } }
/// <summary> /// Update is called once per frame. /// </summary> public void Update() { if (UnityEngine.Screen.showCursor) { return; } if (UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.LeftControl)) { Vector3i?point = GetCursor(false); if (point.HasValue) { byte sun = _map.GetSunLightmap().GetLight(point.Value); byte light = _map.GetLightmap().GetLight(point.Value); Debug.Log(OCLogSymbol.DETAILEDINFO + "Sun " + " " + sun + " Light " + light); } } if (UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.RightControl)) { Vector3i?point = GetCursor(true); if (point.HasValue) { byte sun = _map.GetSunLightmap().GetLight(point.Value); byte light = _map.GetLightmap().GetLight(point.Value); Debug.Log(OCLogSymbol.DETAILEDINFO + "Sun " + sun + " Light " + light); } } if (UnityEngine.Input.GetMouseButtonDown(0)) { Vector3i?point = GetCursor(true); if (point.HasValue) { // Vector3i above = point.Value; // above.y += 1; // OCBlockData blockAbove = _map.GetBlock(above); // OCBlockData blockData = _map.GetBlock (point.Value); // if(blockAbove.IsEmpty() && !blockData.IsEmpty()) // { // _map.SetBlockAndRecompute(blockData, above); // _map.SetBlockAndRecompute(OCBlockData.CreateInstance<OCBlockData>().Init(null, point.Value), point.Value); // } // else Debug.Log(OCLogSymbol.DEBUG + "DeleteSelectedVoxel called from CreateBlockEffect"); GameManager.world.voxels.DeleteSelectedVoxel(point.Value); } } if (UnityEngine.Input.GetMouseButtonDown(1)) { Vector3i?point = GetCursor(false); if (point.HasValue) { bool empty = !BlockCharacterCollision.GetContactBlockCharacter(point.Value, transform.position, gameObject.GetComponent <CharacterController>()).HasValue; if (empty) { Debug.Log(OCLogSymbol.DEBUG + "AddSelectedVoxel called from OCBuilder"); GameManager.world.voxels.AddSelectedVoxel(point.Value, -transform.forward, _selectedBlock); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == _selectedBlock) { Vector3 sourcePos = goalController.gameObject.transform.position; Vector3 oldDistanceVec = ((Vector3)goalController.GoalBlockPos) - sourcePos; Vector3 newDistanceVec = point.Value - sourcePos; if (newDistanceVec.sqrMagnitude < oldDistanceVec.sqrMagnitude) { goalController.GoalBlockPos = point.Value; goalController.MoveTargetsIfNecessary(); } } } } } } Vector3i?cursor = GetCursor(true); _cursor.SetActive(cursor.HasValue); if (cursor.HasValue) { _cursor.transform.position = cursor.Value; } //System.Console.WriteLine(OCLogSymbol.DETAILEDINFO +gameObject.name + " is updated."); }
public void OnPick(Vector3 blockpos, Vector3 blockposold, Vector3 pos3d, bool right) { float xfract = pos3d.X - (float)Math.Floor(pos3d.X); float zfract = pos3d.Z - (float)Math.Floor(pos3d.Z); int activematerial = (byte)viewport.MaterialSlots[viewport.activematerial]; int railstart = GameDataTilesManicDigger.railstart; if (activematerial == railstart + (int)RailDirectionFlags.TwoHorizontalVertical || activematerial == railstart + (int)RailDirectionFlags.Corners) { RailDirection dirnew; if (activematerial == railstart + (int)RailDirectionFlags.TwoHorizontalVertical) { dirnew = PickHorizontalVertical(xfract, zfract); } else { dirnew = PickCorners(xfract, zfract); } RailDirectionFlags dir = data.GetRail(GetTerrainBlock((int)blockposold.X, (int)blockposold.Y, (int)blockposold.Z)); if (dir != RailDirectionFlags.None) { blockpos = blockposold; } activematerial = railstart + (int)(dir | DirectionUtils.ToRailDirectionFlags(dirnew)); //Console.WriteLine(blockposold); //Console.WriteLine(xfract + ":" + zfract + ":" + activematerial + ":" + dirnew); } int x = (short)blockpos.X; int y = (short)blockpos.Y; int z = (short)blockpos.Z; var mode = right ? BlockSetMode.Create : BlockSetMode.Destroy; { if (IsAnyPlayerInPos(blockpos)) { return; } Vector3i v = new Vector3i(x, y, z); Vector3i? oldfillstart = fillstart; Vector3i? oldfillend = fillend; if (mode == BlockSetMode.Create) { if (activematerial == (int)TileTypeManicDigger.Cuboid) { ClearFillArea(); if (fillstart != null) { //todo! check distance FillFill(v, fillstart.Value); } fillend = v; terrain.UpdateTile(v.x, v.y, v.z); return; } if (activematerial == (int)TileTypeManicDigger.FillStart) { ClearFillArea(); fillstart = v; fillend = null; terrain.UpdateTile(v.x, v.y, v.z); return; } if (fillarea.ContainsKey(v) && fillarea[v]) { foreach (var p in fillarea) { if (p.Value) { SendSetBlock(new Vector3(p.Key.x, p.Key.y, p.Key.z), BlockSetMode.Create, activematerial); } } ClearFillArea(); fillstart = null; fillend = null; return; } } else { //delete fill start if (fillstart != null && fillstart == v) { ClearFillArea(); fillstart = null; fillend = null; return; } //delete fill end if (fillend != null && fillend == v) { ClearFillArea(); fillend = null; return; } } if (mode == BlockSetMode.Create && activematerial == (int)TileTypeManicDigger.Minecart) { /* CommandRailVehicleBuild cmd2 = new CommandRailVehicleBuild(); cmd2.x = (short)x; cmd2.y = (short)y; cmd2.z = (short)z; TrySendCommand(MakeCommand(CommandId.RailVehicleBuild, cmd2)); */ return; } //if (TrySendCommand(MakeCommand(CommandId.Build, cmd))) SendSetBlockAndUpdateSpeculative(activematerial, x, y, z, mode); } }
private void ClearFillArea() { var oldfillstart = fillstart; fillstart = null; if (oldfillstart != null) { terrain.UpdateTile(oldfillstart.Value.x, oldfillstart.Value.y, oldfillstart.Value.z); } fillstart = oldfillstart; var oldfillend = fillend; fillend = null; if (oldfillend != null) { terrain.UpdateTile(oldfillend.Value.x, oldfillend.Value.y, oldfillend.Value.z); } fillend = oldfillend; var oldfillarea = fillarea.Keys; fillarea.Clear(); foreach (Vector3i vv in oldfillarea) { terrain.UpdateTile(vv.x, vv.y, vv.z); } }
/// <summary> /// Update is called once per frame. /// </summary> public void Update() { if (UnityEngine.Screen.showCursor) { return; } if (UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.LeftControl)) { Vector3i?point = GetCursor(false); if (point.HasValue) { byte sun = _map.GetSunLightmap().GetLight(point.Value); byte light = _map.GetLightmap().GetLight(point.Value); OCLogger.Info("Sun " + " " + sun + " Light " + light); } } if (UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.RightControl)) { Vector3i?point = GetCursor(true); if (point.HasValue) { byte sun = _map.GetSunLightmap().GetLight(point.Value); byte light = _map.GetLightmap().GetLight(point.Value); OCLogger.Info("Sun " + sun + " Light " + light); } } if (UnityEngine.Input.GetMouseButtonDown(0)) { Vector3i?point = GetCursor(true); if (point.HasValue) { // Vector3i above = point.Value; // above.y += 1; // OCBlockData blockAbove = _map.GetBlock(above); // OCBlockData blockData = _map.GetBlock (point.Value); // if(blockAbove.IsEmpty() && !blockData.IsEmpty()) // { // _map.SetBlockAndRecompute(blockData, above); // _map.SetBlockAndRecompute(OCBlockData.CreateInstance<OCBlockData>().Init(null, point.Value), point.Value); // } // else _map.SetBlockAndRecompute(OCBlockData.CreateInstance <OCBlockData>().Init(null, point.Value), point.Value); } } if (UnityEngine.Input.GetMouseButtonDown(1)) { Vector3i?point = GetCursor(false); if (point.HasValue) { bool empty = !BlockCharacterCollision.GetContactBlockCharacter(point.Value, transform.position, gameObject.GetComponent <CharacterController>()).HasValue; if (empty) { OpenCog.Map.OCBlockData block = OCBlockData.CreateInstance <OCBlockData>().Init(_selectedBlock, OpenCog.Utility.VectorUtil.Vector3ToVector3i(point.Value)); block.SetDirection(GetDirection(-transform.forward)); _map.SetBlockAndRecompute(block, point.Value); OCGoalController[] goalControllers = (OCGoalController[])GameObject.FindObjectsOfType(typeof(OCGoalController)); foreach (OCGoalController goalController in goalControllers) { if (goalController.GoalBlockType == _selectedBlock) { Vector3 sourcePos = goalController.gameObject.transform.position; Vector3 oldDistanceVec = ((Vector3)goalController.GoalBlockPos) - sourcePos; Vector3 newDistanceVec = point.Value - sourcePos; if (newDistanceVec.sqrMagnitude < oldDistanceVec.sqrMagnitude) { goalController.GoalBlockPos = point.Value; goalController.MoveTargetsIfNecessary(); } } } } } } Vector3i?cursor = GetCursor(true); _cursor.SetActive(cursor.HasValue); if (cursor.HasValue) { _cursor.transform.position = cursor.Value; } OCLogger.Fine(gameObject.name + " is updated."); }
// Update is called once per frame void OnGUI() { if (GameStateManager.IsPaused) { return; } if (InputManager.inputManager().IsKeyDown(KeyCode.LeftControl)) { Vector3i?point = GetCursor(false); if (point.HasValue) { byte sun = map.GetSunLightmap().GetLight(point.Value); byte light = map.GetLightmap().GetLight(point.Value); Debug.Log("Sun " + " " + sun + " Light " + light); } } if (InputManager.inputManager().IsKeyDown(KeyCode.RightControl)) { Vector3i?point = GetCursor(true); if (point.HasValue) { byte sun = map.GetSunLightmap().GetLight(point.Value); byte light = map.GetLightmap().GetLight(point.Value); Debug.Log("Sun " + sun + " Light " + light); } } //Remove block if (InputManager.inputManager().canBreakBlocks&& ((InputManager.inputManager().LeftClick&& (Time.time - lastTimeDestroy > 0.1f)) || (InputManager.inputManager().isLeftClickHold&& (Time.time - lastTimeDestroy > 0.200f)))) { Vector3i?point = GetCursor(true); if (point.HasValue && point.Value.y >= 2) { if (Network.peerType == NetworkPeerType.Disconnected) { map.SetBlockAndRecompute(new BlockData(), point.Value); } else { this.DestroyBlock(point.Value); } Vector3i around = new Vector3i(point.Value.x, point.Value.y, point.Value.z); around.y += 1; if (map.GetBlock(around).IsFluid()) { spreadingList.Add(new SpreadingInstruction(0.5f, around, this, map, map.GetBlock(around), 15)); } around.y -= 1; for (int j = -1; j <= 1; j += 2) { around.x += j; if (map.GetBlock(around).IsFluid()) { spreadingList.Add(new SpreadingInstruction(0.5f, around, this, map, map.GetBlock(around), 15)); } around.x -= j; } for (int j = -1; j <= 1; j += 2) { around.z += j; if (map.GetBlock(around).IsFluid()) { spreadingList.Add(new SpreadingInstruction(0.5f, around, this, map, map.GetBlock(around), 15)); } around.z -= j; } } lastTimeDestroy = Time.time; } //Spawn block if ((InputManager.inputManager().RightClick&& (Time.time - lastTimeBuild > 0.1f)) || (InputManager.inputManager().isRightClickHold&& (Time.time - lastTimeBuild > 0.200f))) { Vector3i?point = GetCursor(false); if (point.HasValue) { bool empty = !BlockCharacterCollision.GetContactBlockCharacter(point.Value, transform.position, characterCollider).HasValue; if (empty && selectedBlock != null) { BlockData block = new BlockData(selectedBlock); block.SetDirection(GetDirection(-transform.forward)); if (Network.peerType == NetworkPeerType.Disconnected) { map.SetBlockAndRecompute(block, point.Value); } else { this.SpawnBlock(point.Value); } if (block.IsFluid()) { spreadingList.Add(new SpreadingInstruction(0.5f, point.Value, this, map, block, 15)); } } } lastTimeBuild = Time.time; } ArrayList delList = new ArrayList(); foreach (SpreadingInstruction si in spreadingList) { if (si.canSpread()) { si.spreading(); } else { delList.Add(si); } } foreach (SpreadingInstruction si in delList) { spreadingList.Remove(si); } Vector3i?cursor = GetCursor(true); this.cursor.SetActive(cursor.HasValue); if (cursor.HasValue) { this.cursor.transform.position = cursor.Value; } }
public void AddBlockChangedEntry(Block pBlock, Vector3i pPosition, Vector3i?pSourcePosition = null) { pSourcePosition = pSourcePosition ?? pPosition; mLastCommandBlocks.Push(WorldEditBlock.CreateNew(pBlock, pPosition, pSourcePosition)); }
public static void SetBlock(Type pType, Vector3i pPosition, UserSession pSession = null, Vector3i?pSourcePosition = null, Block pSourceBlock = null, byte[] pData = null) { if (pType == null || pType.DerivesFrom <PickupableBlock>()) { pType = typeof(EmptyBlock); } WorldObjectBlock worldObjectBlock = Eco.World.World.GetBlock(pPosition) as WorldObjectBlock; if (worldObjectBlock != null) { if (worldObjectBlock.WorldObjectHandle.Object.Position3i == pPosition) { worldObjectBlock.WorldObjectHandle.Object.Destroy(); } } if (pType == typeof(EmptyBlock)) { Eco.World.World.DeleteBlock(pPosition); return; } var constuctor = pType.GetConstructor(Type.EmptyTypes); if (constuctor != null) { Eco.World.World.SetBlock(pType, pPosition); return; } Type[] types = new Type[1]; types[0] = typeof(WorldPosition3i); constuctor = pType.GetConstructor(types); if (constuctor != null) { object obj = null; if (pData != null) { MemoryStream ms = new MemoryStream(pData); obj = EcoSerializer.Deserialize(ms); } if (pType.DerivesFrom <PlantBlock>()) { PlantSpecies ps = null; Plant pb = null; if (obj != null) { pb = (Plant)obj; ps = pb.Species; } else { ps = WorldUtils.GetPlantSpecies(pType); if (pSourceBlock != null) { pb = PlantBlock.GetPlant(pPosition); } } Plant newplant = EcoSim.PlantSim.SpawnPlant(ps, pPosition); if (pb != null) { newplant.YieldPercent = pb.YieldPercent; newplant.Dead = pb.Dead; newplant.DeadType = pb.DeadType; newplant.GrowthPercent = pb.GrowthPercent; newplant.DeathTime = pb.DeathTime; newplant.Tended = pb.Tended; } return; } AsphaltLog.WriteLine("Unknown Type: " + pType); } types[0] = typeof(WorldObject); constuctor = pType.GetConstructor(types); if (constuctor != null) { WorldObject wObject = null; if (pSourceBlock != null) { wObject = ((WorldObjectBlock)pSourceBlock).WorldObjectHandle.Object; //if this is not the "main block" of an object do nothing if (wObject.Position3i != pSourcePosition.Value) { return; } } else if (pData != null) { MemoryStream ms = new MemoryStream(pData); var obj = EcoSerializer.Deserialize(ms); if (obj is WorldObject) { wObject = obj as WorldObject; } else { throw new InvalidOperationException("obj is not WorldObjectBlock"); } } if (wObject == null) { return; } // WorldObject newObject = WorldObjectUtil.Spawn(wObject.GetType().Name, wObject.Creator.User, pPosition); // newObject.Rotation = wObject.Rotation; WorldObject newObject = (WorldObject)Activator.CreateInstance(wObject.GetType(), true); newObject = WorldObjectManager.Add(newObject, wObject.Creator.User, pPosition, wObject.Rotation); { StorageComponent newSC = newObject.GetComponent <StorageComponent>(); if (newSC != null) { StorageComponent oldPSC = wObject.GetComponent <StorageComponent>(); newSC.Inventory.AddItems(oldPSC.Inventory.Stacks); // newSC.Inventory.OnChanged.Invoke(null); } } { CustomTextComponent newTC = newObject.GetComponent <CustomTextComponent>(); if (newTC != null) { CustomTextComponent oldTC = wObject.GetComponent <CustomTextComponent>(); typeof(CustomTextComponent).GetProperty("Text", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).SetValue(newTC, oldTC.Text); } } return; } AsphaltLog.WriteLine("Unknown Type: " + pType); }
private void DrawBlockInfo() { int x = (int)pickcubepos.X; int y = (int)pickcubepos.Z; int z = (int)pickcubepos.Y; //string info = "None"; if (!MapUtil.IsValidPos(d_Map, x, y, z)) { return; } int blocktype = d_Map.GetBlock(x, y, z); if (!d_Data.IsValid[blocktype]) { return; } currentAttackedBlock = new Vector3i(x, y, z); DrawEnemyHealthBlock(); /* int blocktype = d_Map.GetBlock(x, y, z); if (d_Data.IsValid[blocktype]) { info = d_Data.Name[blocktype]; } d_The3d.Draw2dText(info, Width * 0.5f - d_The3d.TextSize(info, 18f).Width / 2, 30f, 18f, Color.White); */ }
/// <summary> /// Update is called once per frame. /// </summary> public void Update() { if (UnityEngine.Screen.showCursor) { return; } if (UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.LeftControl)) { Vector3i?point = GetCursor(false); if (point.HasValue) { byte sun = _map.GetSunLightmap().GetLight(point.Value); byte light = _map.GetLightmap().GetLight(point.Value); OCLogger.Info("Sun " + " " + sun + " Light " + light); } } if (UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.RightControl)) { Vector3i?point = GetCursor(true); if (point.HasValue) { byte sun = _map.GetSunLightmap().GetLight(point.Value); byte light = _map.GetLightmap().GetLight(point.Value); OCLogger.Info("Sun " + sun + " Light " + light); } } if (UnityEngine.Input.GetMouseButtonDown(0)) { Vector3i?point = GetCursor(true); if (point.HasValue) { _map.SetBlockAndRecompute(new OpenCog.Map.OCBlockData(), point.Value); } } if (UnityEngine.Input.GetMouseButtonDown(1)) { Vector3i?point = GetCursor(false); if (point.HasValue) { bool empty = !BlockCharacterCollision.GetContactBlockCharacter(point.Value, transform.position, gameObject.GetComponent <CharacterController>()).HasValue; if (empty) { OpenCog.Map.OCBlockData block = new OpenCog.Map.OCBlockData(_selectedBlock, OpenCog.Utility.VectorUtil.Vector3ToVector3i(point.Value)); block.SetDirection(GetDirection(-transform.forward)); _map.SetBlockAndRecompute(block, point.Value); } } } Vector3i?cursor = GetCursor(true); _cursor.SetActive(cursor.HasValue); if (cursor.HasValue) { _cursor.transform.position = cursor.Value; } OCLogger.Fine(gameObject.name + " is updated."); }