/// <summary> /// Set or remove a voxel /// </summary> /// <param name="colorIndex">Number 0 will clear the voxel</param> public void SetVoxel(int x, int y, int z, byte colorIndex) { if (x >= 0 && y >= 0 && z >= 0 && x < this.X && y < this.Y && z < this.Z) { string key = x + "_" + y + "_" + z; // Set if (colorIndex != 0) { if (!Voxels.ContainsKey(key)) { VCount++; } Voxels[key] = colorIndex; } // Clear else { if (Voxels.ContainsKey(key)) { VCount--; } Voxels.Remove(key); } } }
private void ClampBody(Body body) { bool inZone = Voxels.Any(v => VoxelHelpers.GetVoxelAbove(v).GetBoundingBox().Contains(body.Position) == ContainmentType.Contains); if (!inZone) { float minDist = float.MaxValue; VoxelHandle minVoxel = VoxelHandle.InvalidHandle; foreach (var voxel in Voxels) { float dist = (voxel.GetBoundingBox().Center() - body.Position).LengthSquared(); if (dist < minDist) { minDist = dist; minVoxel = voxel; } } if (minDist < float.MaxValue) { body.LocalPosition = body.LocalPosition * 0.5f + (minVoxel.WorldPosition + Vector3.Up + Vector3.One) * 0.5f; var creature = body.GetRoot().GetComponent <CreatureAI>(); if (creature != null) { creature.CancelCurrentTask(); } } } }
protected override async Task OnLoadedAsync(Document Model) { await Voxels.LoadAsync(Model.Voxels); Voxels.Ceiling = SizeZ; await Palette.LoadAsync(Model.Palette); }
/// <summary> /// Set or remove a voxel /// </summary> /// <param name="v">Index 0 will clear the voxel</param> public void SetVoxel(Voxel v) { if (v.X <= this.X && v.Y <= this.Y && v.Z <= this.Z) { string key = v.GetKey(); // Set if (v.Index != 0) { if (!Voxels.ContainsKey(key)) { VCount++; } Voxels[key] = v; } // Clear else { if (Voxels.ContainsKey(key)) { VCount--; } Voxels.Remove(key); } } }
private void OnVoxelInitialized(object sender, EventArgs args) { Voxels.Add((Voxel)sender); if (Voxels.Count % 10 == 0 || Voxels.Count == Bounds.X * Bounds.Y * Bounds.Z) { Debug.WriteLine($"{Voxels.Count}\t== {Bounds.X * Bounds.Y * Bounds.Z} ? {Voxels.Count == Bounds.X * Bounds.Y * Bounds.Z}"); } }
public IWorld Tick(float delta) { Voxels.ToList().ForEach(e => e.OnTick(delta)); LoadedEntities.ToList().ForEach(e => e.OnTick(delta)); UnloadedEntities.ToList().ForEach(e => e.OnTick(delta)); return(this); }
public IWorld GameplayStart() { Voxels.ToList().ForEach(e => e.OnGameplayStart()); LoadedEntities.ToList().ForEach(e => e.OnGameplayStart()); UnloadedEntities.ToList().ForEach(e => e.OnGameplayStart()); return(this); }
public override global::System.Data.DataSet Clone() { Voxels cln = ((Voxels)(base.Clone())); cln.InitVars(); cln.SchemaSerializationMode = this.SchemaSerializationMode; return(cln); }
// Note: now this function is invoked to mod/dig terrain public void AlterVoxelInBuild(int vx, int vy, int vz, VFVoxel voxel) { Voxels.SafeWrite(vx, vy, vz, voxel); int n = Voxels.DirtyChunkList.Count; for (int i = 0; i < n; i++) { SaveLoad.AddChunkToSaveList(Voxels.DirtyChunkList[i]); } }
private void UpdateVoxelVisuals() { foreach (VoxelCell voxel in Voxels) { voxel.InitializeVisuals(); } foreach (var component in Voxels.SelectMany(item => item.Visuals.Components)) { component.InitializeNeighbors(); } }
public void Remove(Model3D model) { if (!ModelToVoxel.ContainsKey(model)) { return; } var v = ModelToVoxel[model]; Voxels.Remove(v); UpdateModel(); }
public Mesh GenerateMesh(Voxels.Objects.PlanetRegion region, int planetSize, int verticals, int horizontals) { Vector3[] verts; Vector2[] uvs; BuildVerts(region, planetSize, verticals, horizontals, out verts, out uvs); var result = new Mesh { vertices = verts, uv = uvs }; result.SetTriangles(BuildIndexes(verts, verticals, horizontals), 0); return result; }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) { Voxels ds = new Voxels(); global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny(); any.Namespace = ds.Namespace; sequence.Items.Add(any); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
public void AlterVoxel(int vx, int vy, int vz, VFVoxel voxel, bool writeType, bool writeVolume) { // Tip: Switch between Voxels.Read and Voxels.SafeRead (with bounds check) to enabled/disable falling through the world. VFVoxel existingVoxel = Voxels.SafeRead(vx, vy, vz); if (existingVoxel.Volume < VoxelTerrainConstants._isolevel) { existingVoxel.Volume = 0; } Voxels.SafeWrite(vx, vy, vz, new VFVoxel((byte)Mathf.Clamp((int)existingVoxel.Volume + (writeVolume ? (int)voxel.Volume : 0), 0, 255), writeType ? voxel.Type : existingVoxel.Type)); }
public void Dispose() { if (Voxels != null) { Voxels.Release(); } Voxels = null; if (FilledVoxelInstances != null) { FilledVoxelInstances.Release(); } FilledVoxelInstances = null; }
public void Add(ulong x, ulong y, ulong z, byte c) { ulong f = Fuse(x, y, z); if (Voxels.ContainsKey(f)) { Voxels[f] = c; } else { Voxels.Add(f, c); Full.Add(f); } }
public override INifti <float> DeepCopy() { var copy = new NiftiFloat32() { Header = Header.DeepCopy(), Voxels = new float[Voxels.Length] }; Voxels.CopyTo(copy.Voxels, 0); copy.ColorMap = new Color[ColorMap.Length]; ColorMap.CopyTo(copy.ColorMap, 0); return(copy); }
public void BuildVerts(Voxels.Objects.PlanetRegion region, int planetSize, int verticals, int horizontals, out Vector3[] verts, out Vector2[] uvs) { // determine range and stepping variable var range = region.ToRadians(); var verticalStep = (range.North - range.South) / (verticals - 1); var horizontalStep = (range.East - range.West) / (horizontals - 1); //range.South -= verticalStep; //range.East += horizontalStep; // define result containers var vertList = new List<Vector3>(); var uvList = new List<Vector2>(); // ok lets do this for (double inc = range.North; inc >= range.South; inc -= verticalStep) { for (double az = range.West; az <= range.East; az += horizontalStep) { // translate the angles to cartesian space for this point vertList.Add(new Vector3( (float)(planetSize * Math.Sin(az) * Math.Cos(inc)), (float)(planetSize * Math.Sin(inc)), (float)(planetSize * Math.Cos(az) * Math.Cos(inc))) ); /* * Ok by knowing the start and end of our range, and the current pos * we calc the angular distance and that gets projected to our texture as a uv * var start = new SphericalPosition(planetSize, (float)range.South, (float)range.West); var end = new SphericalPosition(planetSize, (float)range.North, (float)range.East); var currentPoint = new SphericalPosition(planetSize, (float)inc, (float)az); var u = (currentPoint.Azimuth - end.Azimuth) / (end.Azimuth - start.Azimuth); var v = (currentPoint.Inclination - end.Inclination) / (end.Inclination - start.Inclination); */ uvList.Add(new Vector2( (float)Math.Abs((az - range.East) / (range.East - range.West)), (float)Math.Abs((inc - range.North) / (range.North - range.South))) ); } } verts = vertList.ToArray(); uvs = uvList.ToArray(); }
/// <summary> /// Initialise a pattern, setting the block voxels, the connection voxels and their normals in relation to index 0,0,0 /// </summary> public void InitialisePattern() { // temporary hard coded pattern. This should be imported from rhino List <Vector3Int> walkableFaces = new List <Vector3Int> { new Vector3Int(0, 0, 1), new Vector3Int(0, 0, -1) }; for (int y = 0; y < 6; y++) { for (int x = -1; x <= 1; x++) { Voxels.Add(new Voxel(x, y, 0, VoxelType.Block, PatternOrientation, this, walkableFaces)); } } var conVox = new List <Voxel>(); foreach (var voxel in Voxels.Where(s => s.Type == VoxelType.Block && s.Index.y != 2 && s.Index.y != 3)) { conVox.Add(new Voxel(voxel.Index.x, voxel.Index.y, voxel.Index.z + 1, VoxelType.Connection, new Vector3Int(270, 0, 0), this)); conVox.Add(new Voxel(voxel.Index.x, voxel.Index.y, voxel.Index.z - 1, VoxelType.Connection, new Vector3Int(90, 0, 0), this)); } Voxels.AddRange(conVox); Voxels.Add(new Voxel(-1, 6, 0, VoxelType.Connection, Vector3Int.zero, this)); Voxels.Add(new Voxel(0, 6, 0, VoxelType.Connection, Vector3Int.zero, this)); Voxels.Add(new Voxel(1, 6, 0, VoxelType.Connection, Vector3Int.zero, this)); Voxels.Add(new Voxel(-1, -1, 0, VoxelType.Connection, new Vector3Int(0, 0, 180), this)); Voxels.Add(new Voxel(0, -1, 0, VoxelType.Connection, new Vector3Int(0, 0, 180), this)); Voxels.Add(new Voxel(1, -1, 0, VoxelType.Connection, new Vector3Int(0, 0, 180), this)); for (int i = 0; i < 6; i++) { if (i != 2 && i != 3) { Voxels.Add(new Voxel(-2, i, 0, VoxelType.Connection, Vector3Int.zero, this)); Voxels.Add(new Voxel(2, i, 0, VoxelType.Connection, Vector3Int.zero, this)); } } }
public int GetPixelColor(int x, int y, int z, SliceType sliceType) { var voxelIndex = GetVoxelIndex(x, y, z, sliceType); var voxelValue = (int)Voxels[voxelIndex]; switch (Header.datatype) { case NiftiType.FLOAT32: case NiftiType.UINT8: // Standard intensity TODO: Make good. case NiftiType.INT16: // GrayScale 16bit if (Math.Abs(Header.cal_min - Header.cal_max) < .1) { Header.cal_min = Voxels.Min(); Header.cal_max = Voxels.Max(); } var range = Header.cal_max - Header.cal_min; var scale = ColorMap.Length / range; var bias = -(Header.cal_min); int idx = (int)((GetValue(x, y, z, sliceType) + bias) * scale); if (idx < 0) { idx = 0; } else if (idx > ColorMap.Length - 1) { idx = ColorMap.Length - 1; } return(ColorMap[idx].ToArgb()); case NiftiType.RGB24: // RGB 24bit case NiftiType.RGBA32: // ARGB 32bit return(voxelValue); default: throw new NotImplementedException($"datatype {Header.datatype} not suported!"); } }
/** * Resets the order of potentially-visible voxels as used by the rotation-related methods; since this order is not * changed by normal {@link #Add(int, byte)} and {@link #remove(int)}, this method must be used to complete any * changes to the structure of the VoxelSeq. */ public VoxelSeq Hollow() { Order.Clear(); int sz = Full.Count; ulong k, x, y, z; for (int i = 0; i < sz; i++) { k = Full[i]; x = ExtractX(k); y = ExtractY(k); z = ExtractZ(k); if (x <= 0 || x >= SizeX - 1 || y <= 0 || y >= SizeY - 1 || z <= 0 || z >= SizeZ - 1 || !Voxels.ContainsKey(Fuse(x - 1, y, z)) || !Voxels.ContainsKey(Fuse(x + 1, y, z)) || !Voxels.ContainsKey(Fuse(x, y - 1, z)) || !Voxels.ContainsKey(Fuse(x, y + 1, z)) || !Voxels.ContainsKey(Fuse(x, y, z - 1)) || !Voxels.ContainsKey(Fuse(x, y, z + 1))) { Order.Add(k); } } return(this); }
public void RemoveChunk(Chunk chunk) { var pos = new IntVector3(chunk.Start); for (pos.X = chunk.Start.X; pos.X < chunk.End.X; pos.X++) { for (pos.Y = chunk.Start.Y; pos.Y < chunk.End.Y; pos.Y++) { for (pos.Z = chunk.Start.Z; pos.Z < chunk.End.Z; pos.Z++) { if (Voxels.ContainsKey(pos)) { Voxels.Remove(pos); } } } } if (ChunkRemoved != null) { ChunkRemoved(chunk); } }
public void Unbind(VoxelRenderer renderer) { renderer.Deregister(this); Voxels.Clear(); }
public void Clear() { Voxels.Clear(); UpdateModel(); }
public override void RecalcHeaderMinMax() { Header.cal_min = Voxels.Min(); Header.cal_max = Voxels.Max(); }
private List <VoxelHandle> SpiralVoxels() { // Process voxels into a neat grid. if (Voxels.Count == 0) { throw new InvalidOperationException(); } var bounds = this.GetBoundingBox(); var voxelGrid = new VoxelHandle[(int)(bounds.Max.X - bounds.Min.X), (int)(bounds.Max.Z - bounds.Min.Z)]; foreach (var voxel in Voxels) { voxelGrid[(int)(voxel.Coordinate.X - bounds.Min.X), (int)(voxel.Coordinate.Z - bounds.Min.Z)] = voxel; } // if any invalid voxels in grid, go ahead and abort. foreach (var voxel in voxelGrid) { if (!voxel.IsValid) { return(Voxels); } } // Find center voxel. Actually want to round UP - or - spiral in positive direction? var center_c = GlobalVoxelCoordinate.FromVector3(bounds.Center()); var current_v = Voxels.FirstOrDefault(v => v.Coordinate == center_c); if (!current_v.IsValid) { return(Voxels); } var direction = Direction.East; var results = new List <VoxelHandle>(); results.Add(current_v); // Starting at center, spiral around, starting to the right. while (true) { var next_voxel = Voxels.FirstOrDefault(v => v.Coordinate == current_v.Coordinate + GetDirectionOffset(direction)); if (next_voxel.IsValid) { results.Add(next_voxel); current_v = next_voxel; var possible_turn = TurnRight(direction); var possible_ahead = Voxels.FirstOrDefault(v => v.Coordinate == current_v.Coordinate + GetDirectionOffset(possible_turn)); if (possible_ahead.IsValid && !results.Any(v => v.Coordinate == possible_ahead.Coordinate)) { direction = possible_turn; } } else { break; } } // Recover any voxels we missed. foreach (var voxel in Voxels) { if (!results.Any(v => v.Coordinate == voxel.Coordinate)) { results.Add(voxel); } } return(results); // For each voxel - step one in the current direction and return. // If we've hit an edge - try and turn. // If the next direction is unvisited - turn }
bool AttackVoxel(int vx, int vy, int vz, byte volumeDec) { // Tip: Switch between Voxels.Read and Voxels.SafeRead (with bounds check) to enabled/disable falling through the world. VFVoxel existingVoxel = Voxels.SafeRead(vx, vy, vz); NaturalResAsset.NaturalRes res = NaturalResAsset.NaturalRes.GetTerrainResData(existingVoxel.Type); if (res == null) { Debug.LogWarning("Failed to get NaturalRes !! ResType = " + existingVoxel.Type + " ---> position = " + vx + " " + vy + "" + vz); return(false); } float curTimePoint = Time.time; IntVector3 voxelPos = new IntVector3(vx, vy, vz); VoxelInAttack voxelInAtk = null; if (listVoxelInAttack.TryGetValue(voxelPos, out voxelInAtk)) { int volumeLeft = (curTimePoint < voxelInAtk.invalidTimePoint && existingVoxel.Type == voxelInAtk.type) ? (int)(voxelInAtk.volume - volumeDec * res.m_duration) : (int)(existingVoxel.Volume - volumeDec * res.m_duration); if (volumeLeft > 0) { voxelInAtk.invalidTimePoint = curTimePoint + atkActiveTime; voxelInAtk.volume = (byte)volumeLeft; voxelInAtk.type = existingVoxel.Type; return(false); } else { listVoxelInAttack.Remove(voxelPos); Voxels.SafeWrite(vx, vy, vz, new VFVoxel(0)); //AlterVoxelInBuild() return(true); } } else { int volumeLeft = (int)(existingVoxel.Volume - volumeDec * res.m_duration); if (volumeLeft > 0) { voxelInAtk = new VoxelInAttack(); voxelInAtk.invalidTimePoint = curTimePoint + atkActiveTime; voxelInAtk.volume = (byte)volumeLeft; voxelInAtk.type = existingVoxel.Type; List <IntVector3> keyList = new List <IntVector3>(); for (int i = 0; i < listVoxelInAttack.Count; i++) { KeyValuePair <IntVector3, VoxelInAttack> keyValue = listVoxelInAttack.ElementAt(i); if (curTimePoint < keyValue.Value.invalidTimePoint) { break; } keyList.Add(keyValue.Key); } for (int i = 0; i < keyList.Count; i++) { listVoxelInAttack.Remove(keyList[i]); } listVoxelInAttack.Add(voxelPos, voxelInAtk); return(false); } else { Voxels.SafeWrite(vx, vy, vz, new VFVoxel(0)); return(true); } } // return false; }
public byte GetRotated(ulong x, ulong y, ulong z) { Voxels.TryGetValue(Rotate(Fuse(x, y, z), ((-Rotation) & 3) | Rotation & 0xFC), out byte v); return(v); }
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) { global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType(); global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence(); Voxels ds = new Voxels(); global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny(); any1.Namespace = "http://www.w3.org/2001/XMLSchema"; any1.MinOccurs = new decimal(0); any1.MaxOccurs = decimal.MaxValue; any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any1); global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny(); any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"; any2.MinOccurs = new decimal(1); any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax; sequence.Items.Add(any2); global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute1.Name = "namespace"; attribute1.FixedValue = ds.Namespace; type.Attributes.Add(attribute1); global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute(); attribute2.Name = "tableTypeName"; attribute2.FixedValue = "VoxelDataDataTable"; type.Attributes.Add(attribute2); type.Particle = sequence; global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable(); if (xs.Contains(dsSchema.TargetNamespace)) { global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream(); global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream(); try { global::System.Xml.Schema.XmlSchema schema = null; dsSchema.Write(s1); for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();) { schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current)); s2.SetLength(0); schema.Write(s2); if ((s1.Length == s2.Length)) { s1.Position = 0; s2.Position = 0; for (; ((s1.Position != s1.Length) && (s1.ReadByte() == s2.ReadByte()));) { ; } if ((s1.Position == s1.Length)) { return(type); } } } } finally { if ((s1 != null)) { s1.Close(); } if ((s2 != null)) { s2.Close(); } } } xs.Add(dsSchema); return(type); }
public void ShiftPattern(Vector3Int vecShift) { Voxels.ForEach(v => v.Index += vecShift); }
private Model3D createMapModel(HeightMap map) { var geometry = Voxels.CreateMeshFrom(map); return(createModel(geometry)); }
public override void GenerateVoxels(float voxelSize) { if (m_MeshRenderer != null && m_MeshFilter != null) { Mesh mesh = m_MeshFilter.sharedMesh; int[] triangles = mesh.triangles; // mesh vertices in World Space Vector3[] verticesWS; Vector3[] trianglesNormals; InitializeVerticesAndNormals(m_MeshRenderer.transform, mesh.vertices, triangles, out verticesWS, out trianglesNormals); Bounds meshBoundsWS = m_MeshRenderer.bounds; Octree.MeshParams meshParams = new Octree.MeshParams() { Triangles = triangles, VerticesWS = verticesWS, TrianglesNormals = trianglesNormals, Colors = mesh.colors, UVs = mesh.uv }; Vector3Int meshDimensionInVoxels = Vector3Int.CeilToInt(meshBoundsWS.size / voxelSize); // In order to keep voxels with uniform size, the max dimension is used as bounds dimension. int maxDimension = Mathf.Max(meshDimensionInVoxels.x, Mathf.Max(meshDimensionInVoxels.y, meshDimensionInVoxels.z)); Vector3 maxPointInVoxelsVolume = meshBoundsWS.min + Vector3.one * maxDimension * voxelSize; m_Octree = new Octree(meshBoundsWS.min, maxPointInVoxelsVolume, voxelSize, meshParams); Queue <Octree.OctreeNode> nodes = new Queue <Octree.OctreeNode>(); if (m_Octree.Root != null) { nodes.Enqueue(m_Octree.Root); } while (nodes.Count > 0) { Octree.OctreeNode currentNode = nodes.Dequeue(); // If node is leaf and has triangles inside it, create a voxel. if (currentNode.IsLeaf && currentNode.Occupied) { Color color = Material.Color * currentNode.Color; VoxelRenderer.Voxel voxel = new VoxelRenderer.Voxel { Center = currentNode.CenterPoint, Size = currentNode.Dimensions.x, Color = new Vector3(color.r, color.g, color.b), UV = currentNode.UV }; Voxels.Add(voxel); } else { if (currentNode.ChildrenNodes != null) { foreach (Octree.OctreeNode octreeNode in currentNode.ChildrenNodes) { if (octreeNode != null) { nodes.Enqueue(octreeNode); } } } } } } }