public bool Equals(Int3 p) { if ((object)p == null) return false; return (x == p.x) && (y == p.y) && (z == p.z); }
/// <summary> /// Removes redundant points. Two points are redundant if they occupy the same hash grid cell. /// </summary> /// <param name="points">List of points to prune.</param> /// <param name="cellSize">Size of cells to determine redundancy.</param> public static void RemoveRedundantPoints(ref QuickList<Vector3> points, double cellSize) { var set = new QuickSet<Int3>(BufferPools<Int3>.Locking, BufferPools<int>.Locking, BufferPool.GetPoolIndex(points.Count)); for (int i = points.Count - 1; i >= 0; --i) { var element = points.Elements[i]; var cell = new Int3 { X = (int)Math.Floor(element.X / cellSize), Y = (int)Math.Floor(element.Y / cellSize), Z = (int)Math.Floor(element.Z / cellSize) }; if (set.Contains(cell)) { points.FastRemoveAt(i); } else { set.Add(cell); //TODO: Consider adding adjacent cells to guarantee that a point on the border between two cells will still detect the presence //of a point on the opposite side of that border. } } set.Dispose(); }
public GeneLinkNEAT(Int3 fromID, Int3 toID, float weight, bool enabled, int inno, int gen) { fromNodeID = fromID; toNodeID = toID; this.weight = weight; this.enabled = enabled; innov = inno; birthGen = gen; }
protected override async Task LoadContent() { await base.LoadContent(); spriteBatch = new SpriteBatch(GraphicsDevice); inputTexture = Asset.Load<Texture>("uv"); var groupCounts = new Int3(inputTexture.Width / ReductionRatio, inputTexture.Height / ReductionRatio, 1); outputTexture = Texture.New2D(GraphicsDevice, groupCounts.X, groupCounts.Y, 1, PixelFormat.R8G8B8A8_UNorm, TextureFlags.UnorderedAccess | TextureFlags.ShaderResource); displayedTexture = outputTexture; drawEffectContext = RenderContext.GetShared(Services); computeShaderEffect = new ComputeEffectShader(drawEffectContext) { ShaderSourceName = "ComputeShaderTestEffect", ThreadGroupCounts = groupCounts }; }
public ComputeEffectShader(RenderContext context) : base(context, null) { pipelineState = new MutablePipelineState(context.GraphicsDevice); // Setup the effect compiler EffectInstance = new DynamicEffectInstance("ComputeEffectShader", Parameters); EffectInstance.Initialize(context.Services); // We give ComputeEffectShader a higher priority, since they are usually executed serially and blocking EffectInstance.EffectCompilerParameters.TaskPriority = -1; ThreadNumbers = new Int3(1); ThreadGroupCounts = new Int3(1); SetDefaultParameters(); }
public ComputeEffectShader(RenderContext context, params ParameterCollection[] sharedParameterCollections) : base(context, null) { parameterCollections = new List<ParameterCollection> { context.Parameters }; if (sharedParameterCollections != null) { parameterCollections.AddRange(sharedParameterCollections); } parameterCollections.Add(Parameters); appliedParameterCollections = new List<ParameterCollection>(); // Setup the effect compiler EffectInstance = new DefaultEffectInstance(parameterCollections); effectCompiler = new DynamicEffectCompiler(context.Services, "ComputeEffectShader"); ThreadNumbers = new Int3(1); ThreadGroupCounts = new Int3(1); SetDefaultParameters(); }
public Model(Assembly operatorAssembly, bool enabledLogging) { OperatorsAssembly = operatorAssembly; // generic enum value from json function, must be local function object JsonToEnumValue <T>(JToken jsonToken) where T : struct // todo: use 7.3 and replace with enum { string value = jsonToken.Value <string>(); if (Enum.TryParse(value, out T enumValue)) { return(enumValue); } else { return(null); } } InputValue InputDefaultValueCreator <T>() => new InputValue <T>(); // build-in default types RegisterType(typeof(bool), "bool", InputDefaultValueCreator <bool>, (writer, obj) => writer.WriteValue((bool)obj), jsonToken => jsonToken.Value <bool>()); RegisterType(typeof(int), "int", InputDefaultValueCreator <int>, (writer, obj) => writer.WriteValue((int)obj), jsonToken => jsonToken.Value <int>()); RegisterType(typeof(float), "float", InputDefaultValueCreator <float>, (writer, obj) => writer.WriteValue((float)obj), jsonToken => jsonToken.Value <float>()); RegisterType(typeof(string), "string", () => new InputValue <string>(string.Empty), (writer, value) => writer.WriteValue((string)value), jsonToken => jsonToken.Value <string>()); // system types RegisterType(typeof(System.Collections.Generic.List <float>), "List<float>", () => new InputValue <List <float> >(new List <float>()), (writer, obj) => { var list = (List <float>)obj; writer.WriteStartObject(); writer.WritePropertyName("Values"); writer.WriteStartArray(); list.ForEach(writer.WriteValue); writer.WriteEndArray(); writer.WriteEndObject(); }, jsonToken => { var entries = jsonToken["Values"]; var list = new List <float>(entries.Count()); list.AddRange(entries.Select(entry => entry.Value <float>())); return(list); }); RegisterType(typeof(System.Collections.Generic.List <string>), "List<string>", () => new InputValue <List <string> >(new List <string>()), (writer, obj) => { var list = (List <string>)obj; writer.WriteStartObject(); writer.WritePropertyName("Values"); writer.WriteStartArray(); list.ForEach(writer.WriteValue); writer.WriteEndArray(); writer.WriteEndObject(); }, jsonToken => { var entries = jsonToken["Values"]; var list = new List <string>(entries.Count()); list.AddRange(entries.Select(entry => entry.Value <string>())); return(list); }); RegisterType(typeof(System.Numerics.Quaternion), "Quaternion", () => new InputValue <System.Numerics.Quaternion>(System.Numerics.Quaternion.Identity), (writer, obj) => { var quat = (System.Numerics.Quaternion)obj; writer.WriteStartObject(); writer.WriteValue("X", quat.X); writer.WriteValue("Y", quat.Y); writer.WriteValue("Z", quat.Z); writer.WriteValue("W", quat.W); writer.WriteEndObject(); }, jsonToken => { float x = jsonToken["X"].Value <float>(); float y = jsonToken["Y"].Value <float>(); float z = jsonToken["Z"].Value <float>(); float w = jsonToken["W"].Value <float>(); return(new System.Numerics.Quaternion(x, y, z, w)); }); RegisterType(typeof(System.Numerics.Vector2), "Vector2", InputDefaultValueCreator <System.Numerics.Vector2>, (writer, obj) => { var vec = (System.Numerics.Vector2)obj; writer.WriteStartObject(); writer.WriteValue("X", vec.X); writer.WriteValue("Y", vec.Y); writer.WriteEndObject(); }, jsonToken => { float x = jsonToken["X"].Value <float>(); float y = jsonToken["Y"].Value <float>(); return(new System.Numerics.Vector2(x, y)); }); RegisterType(typeof(System.Numerics.Vector3), "Vector3", InputDefaultValueCreator <System.Numerics.Vector3>, (writer, obj) => { var vec = (System.Numerics.Vector3)obj; writer.WriteStartObject(); writer.WriteValue("X", vec.X); writer.WriteValue("Y", vec.Y); writer.WriteValue("Z", vec.Z); writer.WriteEndObject(); }, jsonToken => { float x = jsonToken["X"].Value <float>(); float y = jsonToken["Y"].Value <float>(); float z = jsonToken["Z"].Value <float>(); return(new System.Numerics.Vector3(x, y, z)); }); RegisterType(typeof(System.Numerics.Vector4), "Vector4", () => new InputValue <Vector4>(new Vector4(1.0f, 1.0f, 1.0f, 1.0f)), (writer, obj) => { var vec = (Vector4)obj; writer.WriteStartObject(); writer.WriteValue("X", vec.X); writer.WriteValue("Y", vec.Y); writer.WriteValue("Z", vec.Z); writer.WriteValue("W", vec.W); writer.WriteEndObject(); }, jsonToken => { float x = jsonToken["X"].Value <float>(); float y = jsonToken["Y"].Value <float>(); float z = jsonToken["Z"].Value <float>(); float w = jsonToken["W"].Value <float>(); return(new Vector4(x, y, z, w)); }); RegisterType(typeof(System.Text.StringBuilder), "StringBuilder", () => new InputValue <StringBuilder>(new StringBuilder())); RegisterType(typeof(DateTime), "DateTime", () => new InputValue <DateTime>(new DateTime())); // t3 core types RegisterType(typeof(BufferWithViews), "BufferWithViews", () => new InputValue <BufferWithViews>(null)); RegisterType(typeof(Command), "Command", () => new InputValue <Command>(null)); RegisterType(typeof(Animation.Curve), "Curve", InputDefaultValueCreator <Animation.Curve>, (writer, obj) => { Animation.Curve curve = (Animation.Curve)obj; writer.WriteStartObject(); curve?.Write(writer); writer.WriteEndObject(); }, jsonToken => { Animation.Curve curve = new Animation.Curve(); if (jsonToken == null || !jsonToken.HasValues) { curve.AddOrUpdateV(0, new VDefinition() { Value = 0 }); curve.AddOrUpdateV(1, new VDefinition() { Value = 1 }); } else { curve.Read(jsonToken); } return(curve); }); RegisterType(typeof(T3.Core.Operator.GizmoVisibility), "GizmoVisibility", InputDefaultValueCreator <T3.Core.Operator.GizmoVisibility>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <T3.Core.Operator.GizmoVisibility>); RegisterType(typeof(DataTypes.Gradient), "Gradient", InputDefaultValueCreator <Gradient>, (writer, obj) => { Gradient gradient = (Gradient)obj; writer.WriteStartObject(); gradient?.Write(writer); writer.WriteEndObject(); }, jsonToken => { Gradient gradient = new Gradient(); if (jsonToken == null || !jsonToken.HasValues) { gradient = new Gradient(); } else { gradient.Read(jsonToken); } return(gradient); }); RegisterType(typeof(ParticleSystem), "ParticleSystem", () => new InputValue <ParticleSystem>(null)); RegisterType(typeof(Point[]), "Point", () => new InputValue <Point[]>()); RegisterType(typeof(RenderTargetReference), "RenderTargetRef", () => new InputValue <RenderTargetReference>()); RegisterType(typeof(Object), "Object", () => new InputValue <Object>()); RegisterType(typeof(StructuredList), "StructuredList", () => new InputValue <StructuredList>()); RegisterType(typeof(Texture3dWithViews), "Texture3dWithViews", () => new InputValue <Texture3dWithViews>(new Texture3dWithViews())); RegisterType(typeof(MeshBuffers), "MeshBuffers", () => new InputValue <MeshBuffers>(null)); // sharpdx types RegisterType(typeof(SharpDX.Direct3D.PrimitiveTopology), "PrimitiveTopology", InputDefaultValueCreator <PrimitiveTopology>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <PrimitiveTopology>); RegisterType(typeof(SharpDX.Direct3D11.BindFlags), "BindFlags", InputDefaultValueCreator <BindFlags>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <BindFlags>); RegisterType(typeof(SharpDX.Direct3D11.BlendOperation), "BlendOperation", InputDefaultValueCreator <BlendOperation>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <BlendOperation>); RegisterType(typeof(SharpDX.Direct3D11.BlendOption), "BlendOption", InputDefaultValueCreator <BlendOption>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <BlendOption>); RegisterType(typeof(SharpDX.Direct3D11.BlendState), "BlendState", () => new InputValue <BlendState>(null)); RegisterType(typeof(SharpDX.Direct3D11.Buffer), "Buffer", () => new InputValue <Buffer>(null)); RegisterType(typeof(SharpDX.Direct3D11.ColorWriteMaskFlags), "ColorWriteMaskFlags", InputDefaultValueCreator <ColorWriteMaskFlags>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <ColorWriteMaskFlags>); RegisterType(typeof(SharpDX.Direct3D11.Comparison), "Comparison", InputDefaultValueCreator <Comparison>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <Comparison>); RegisterType(typeof(SharpDX.Direct3D11.ComputeShader), "ComputeShader", () => new InputValue <ComputeShader>(null)); RegisterType(typeof(SharpDX.Direct3D11.CpuAccessFlags), "CpuAccessFlags", InputDefaultValueCreator <CpuAccessFlags>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <CpuAccessFlags>); RegisterType(typeof(SharpDX.Direct3D11.CullMode), "CullMode", InputDefaultValueCreator <CullMode>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <CullMode>); RegisterType(typeof(SharpDX.Direct3D11.DepthStencilState), "DepthStencilState", () => new InputValue <DepthStencilState>(null)); RegisterType(typeof(SharpDX.Direct3D11.DepthStencilView), "DepthStencilView", () => new InputValue <DepthStencilView>(null)); RegisterType(typeof(SharpDX.Direct3D11.FillMode), "FillMode", InputDefaultValueCreator <FillMode>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <FillMode>); RegisterType(typeof(SharpDX.Direct3D11.Filter), "Filter", InputDefaultValueCreator <Filter>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <Filter>); RegisterType(typeof(SharpDX.Direct3D11.GeometryShader), "GeometryShader", () => new InputValue <GeometryShader>(null)); RegisterType(typeof(SharpDX.Direct3D11.InputLayout), "InputLayout", () => new InputValue <InputLayout>(null)); RegisterType(typeof(SharpDX.Direct3D11.PixelShader), "PixelShader", () => new InputValue <PixelShader>(null)); RegisterType(typeof(SharpDX.Direct3D11.RenderTargetBlendDescription), "RenderTargetBlendDescription", () => new InputValue <RenderTargetBlendDescription>()); RegisterType(typeof(SharpDX.Direct3D11.RasterizerState), "RasterizerState", () => new InputValue <RasterizerState>(null)); RegisterType(typeof(SharpDX.Direct3D11.RenderTargetView), "RenderTargetView", () => new InputValue <RenderTargetView>(null)); RegisterType(typeof(SharpDX.Direct3D11.ResourceOptionFlags), "ResourceOptionFlags", InputDefaultValueCreator <ResourceOptionFlags>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <ResourceOptionFlags>); RegisterType(typeof(SharpDX.Direct3D11.ResourceUsage), "ResourceUsage", InputDefaultValueCreator <ResourceUsage>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <ResourceUsage>); RegisterType(typeof(SharpDX.Direct3D11.SamplerState), "SamplerState", () => new InputValue <SamplerState>(null)); RegisterType(typeof(SharpDX.Direct3D11.ShaderResourceView), "ShaderResourceView", () => new InputValue <ShaderResourceView>(null)); RegisterType(typeof(SharpDX.Direct3D11.Texture2D), "Texture2D", () => new InputValue <Texture2D>(null)); RegisterType(typeof(SharpDX.Direct3D11.Texture3D), "Texture3D", () => new InputValue <Texture3D>(null)); RegisterType(typeof(SharpDX.Direct3D11.TextureAddressMode), "TextureAddressMode", InputDefaultValueCreator <TextureAddressMode>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <TextureAddressMode>); RegisterType(typeof(SharpDX.Direct3D11.UnorderedAccessView), "UnorderedAccessView", () => new InputValue <UnorderedAccessView>(null)); RegisterType(typeof(SharpDX.Direct3D11.UnorderedAccessViewBufferFlags), "UnorderedAccessViewBufferFlags", InputDefaultValueCreator <UnorderedAccessViewBufferFlags>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <UnorderedAccessViewBufferFlags>); RegisterType(typeof(SharpDX.Direct3D11.VertexShader), "VertexShader", () => new InputValue <VertexShader>(null)); RegisterType(typeof(SharpDX.DXGI.Format), "Format", InputDefaultValueCreator <Format>, (writer, obj) => writer.WriteValue(obj.ToString()), JsonToEnumValue <Format>); RegisterType(typeof(SharpDX.Int3), "Int3", InputDefaultValueCreator <Int3>, (writer, obj) => { Int3 vec = (Int3)obj; writer.WriteStartObject(); writer.WriteValue("X", vec.X); writer.WriteValue("Y", vec.Y); writer.WriteValue("Z", vec.Z); writer.WriteEndObject(); }, jsonToken => { int x = jsonToken["X"].Value <int>(); int y = jsonToken["Y"].Value <int>(); int z = jsonToken["Z"].Value <int>(); return(new Int3(x, y, z)); }); RegisterType(typeof(SharpDX.Mathematics.Interop.RawRectangle), "RawRectangle", () => new InputValue <RawRectangle>(new RawRectangle { Left = -100, Right = 100, Bottom = -100, Top = 100 })); RegisterType(typeof(SharpDX.Mathematics.Interop.RawViewportF), "RawViewportF", () => new InputValue <RawViewportF>(new RawViewportF { X = 0.0f, Y = 0.0f, Width = 100.0f, Height = 100.0f, MinDepth = 0.0f, MaxDepth = 10000.0f })); RegisterType(typeof(SharpDX.Size2), "Size2", InputDefaultValueCreator <Size2>, (writer, obj) => { Size2 vec = (Size2)obj; writer.WriteStartObject(); writer.WriteValue("Width", vec.Width); writer.WriteValue("Height", vec.Height); writer.WriteEndObject(); }, jsonToken => { int width = jsonToken["Width"].Value <int>(); int height = jsonToken["Height"].Value <int>(); return(new Size2(width, height)); }); RegisterType(typeof(SharpDX.Vector4[]), "Vector4[]", () => new InputValue <SharpDX.Vector4[]>(new SharpDX.Vector4[0])); }
public bool PickPosition(Ray pickingRay, out Int3 pickedPosition) { // context knowledge: // - map is centered on x and z // - cubes size is 0.5 lin every direction Vector3 currentPosition = pickingRay.Position; currentPosition.X += (float)SizeX / 2; currentPosition.Z += (float)SizeZ / 2; float startOffset = Math.Max(Math.Max((MathUtil.Clamp(currentPosition.X, 0.5f, SizeX - 0.5f) - currentPosition.X) / pickingRay.Direction.X, (MathUtil.Clamp(currentPosition.Y, 0.5f, SizeY - 0.5f) - currentPosition.Y) / pickingRay.Direction.Y), (MathUtil.Clamp(currentPosition.Z, 0.5f, SizeZ - 0.5f) - currentPosition.Z) / pickingRay.Direction.Z); if (startOffset > 0.000001f) startOffset += 0.01f; currentPosition += pickingRay.Direction * startOffset; Vector3 step = pickingRay.Direction * 0.1f; pickedPosition = new Int3((int)(currentPosition.X + 0.5f), (int)(currentPosition.Y + 0.5f), (int)(currentPosition.Z + 0.5f)); while (currentPosition.X > -0.5f && currentPosition.Y > -0.5f && currentPosition.Z > -0.5f && currentPosition.X < SizeX - 0.5f && currentPosition.Y < SizeY - 0.5f && currentPosition.Z < SizeZ - 0.5f) { Int3 currentVoxel = new Int3((int)(currentPosition.X + 0.5f), (int)(currentPosition.Y + 0.5f), (int)(currentPosition.Z + 0.5f)); if (Get(currentVoxel) != VoxelType.EMPTY) return true; pickedPosition = currentVoxel; currentPosition += step; } return false; }
public static Int3 GetCellSize(int level, Int3 blocksPerBatch) { // Our own implementation for BatchCells.GetCellSize, that works on the server and client. return(blocksPerBatch / GetCellsPerBlock(level)); }
public static Int3 ToLocalUnclamped (Vector3 vPos) { Int3[] nearest = new Int3[active.grids.Length]; for (int i=0;i<active.grids.Length;i++) { Grid grid = active.grids[i]; Vector3 vPos2 = vPos; vPos2 -= new Vector3(grid.offset.x,0,grid.offset.z); Int3 pos = new Int3(0,0,0); pos.x = Mathf.Clamp (Mathf.RoundToInt (vPos2.x/(float)grid.nodeSize-0.5F) ,0, grid.width-1); pos.z = Mathf.Clamp (Mathf.RoundToInt (vPos2.z/(float)grid.nodeSize-0.5F) ,0, grid.depth-1); pos.y = i; nearest[i] = pos; } Int3 nearestPos = new Int3(0,0,0); float minDist = Mathf.Infinity; for (int i=0;i<nearest.Length;i++) { float dist = (GetNode(nearest[i]).vectorPos-vPos).sqrMagnitude; Debug.DrawRay (GetNode(nearest[i]).vectorPos,Vector3.up*2,Color.red); if (dist < minDist) { minDist = dist; nearestPos = nearest[i]; } } return nearestPos; }
private void ConstructionCompleted(ConstructionCompletedEvent constructionCompleted) { GameObject constructing = NitroxEntity.RequireObjectFrom(constructionCompleted.PieceId); ConstructableBase constructableBase = constructing.GetComponent <ConstructableBase>(); // For bases, we need to transfer the GUID off of the ghost and onto the finished piece. // Furniture just re-uses the same piece. if (constructableBase) { Int3 latestCell = default(Int3); Base latestBase = null; // must fetch BEFORE setState or else the BaseGhost gets destroyed BaseGhost baseGhost = constructing.GetComponentInChildren <BaseGhost>(); if (baseGhost) { latestCell = baseGhost.TargetOffset; latestBase = baseGhost.TargetBase; } constructableBase.constructedAmount = 1f; constructableBase.SetState(true, true); if (latestBase == null) { Optional <object> opConstructedBase = TransientLocalObjectManager.Get(TransientObjectType.BASE_GHOST_NEWLY_CONSTRUCTED_BASE_GAMEOBJECT); latestBase = ((GameObject)opConstructedBase.Value).GetComponent <Base>(); Validate.NotNull(latestBase, "latestBase can not be null"); } Transform cellTransform = latestBase.GetCellObject(latestCell); if (latestCell == default(Int3) || cellTransform == null) { Vector3 worldPosition; float distance; latestBase.GetClosestCell(constructing.gameObject.transform.position, out latestCell, out worldPosition, out distance); cellTransform = latestBase.GetCellObject(latestCell); Validate.NotNull(cellTransform, "Must have a cell transform, one not found near " + constructing.gameObject.transform.position + " for latestcell " + latestCell); } GameObject finishedPiece = null; // There can be multiple objects in a cell (such as a corridor with hatces built into it) // we look for a object that is able to be deconstucted that hasn't been tagged yet. foreach (Transform child in cellTransform) { bool isNewBasePiece = (child.GetComponent <NitroxEntity>() == null && child.GetComponent <BaseDeconstructable>() != null); if (isNewBasePiece) { finishedPiece = child.gameObject; break; } } Validate.NotNull(finishedPiece, "Could not find finished piece in cell " + latestCell + " when constructing " + constructionCompleted.PieceId); Log.Info("Construction completed on a base piece: " + constructionCompleted.PieceId + " " + finishedPiece.name); UnityEngine.Object.Destroy(constructableBase.gameObject); NitroxEntity.SetNewId(finishedPiece, constructionCompleted.PieceId); BasePieceSpawnProcessor customSpawnProcessor = BasePieceSpawnProcessor.From(finishedPiece.GetComponent <BaseDeconstructable>()); customSpawnProcessor.SpawnPostProcess(latestBase, latestCell, finishedPiece); } else { Constructable constructable = constructing.GetComponent <Constructable>(); constructable.constructedAmount = 1f; constructable.SetState(true, true); Log.Info("Construction completed on a piece of furniture: " + constructionCompleted.PieceId + " " + constructable.gameObject.name); } if (constructionCompleted.BaseId != null && !NitroxEntity.GetObjectFrom(constructionCompleted.BaseId).HasValue) { Log.Info("Creating base: " + constructionCompleted.BaseId); ConfigureNewlyConstructedBase(constructionCompleted.BaseId); } }
public Int3 RayCheckCube(Vector3 eye, Vector3 dir, out Int3 setIdx) { Ray ray = new Ray(eye, dir.normalized); RaycastHit hit; Physics.Raycast(ray, out hit, 3); Int3 hitIdx; if (hit.collider != null) { //forward if (Mathf.Approximately(hit.normal.x, Vector3.forward.x) && Mathf.Approximately(hit.normal.y, Vector3.forward.y) && Mathf.Approximately(hit.normal.z, Vector3.forward.z)) { Int3 idx = hitIdx = PositionToIndex(hit.point + new Vector3(0, 0, -0.5f)); idx.z++; setIdx = idx; } //up else if (Mathf.Approximately(hit.normal.x, Vector3.up.x) && Mathf.Approximately(hit.normal.y, Vector3.up.y) && Mathf.Approximately(hit.normal.z, Vector3.up.z)) { Int3 idx = hitIdx = PositionToIndex(hit.point + new Vector3(0, -0.5f, 0)); idx.y--; setIdx = idx; } //right else if (Mathf.Approximately(hit.normal.x, Vector3.right.x) && Mathf.Approximately(hit.normal.y, Vector3.right.y) && Mathf.Approximately(hit.normal.z, Vector3.right.z)) { Int3 idx = hitIdx = PositionToIndex(hit.point + new Vector3(-0.5f, 0, 0)); idx.x++; setIdx = idx; } //back else if (Mathf.Approximately(hit.normal.x, Vector3.back.x) && Mathf.Approximately(hit.normal.y, Vector3.back.y) && Mathf.Approximately(hit.normal.z, Vector3.back.z)) { Int3 idx = hitIdx = PositionToIndex(hit.point + new Vector3(0, 0, 0.5f)); idx.z--; setIdx = idx; } //down else if (Mathf.Approximately(hit.normal.x, Vector3.down.x) && Mathf.Approximately(hit.normal.y, Vector3.down.y) && Mathf.Approximately(hit.normal.z, Vector3.down.z)) { Int3 idx = hitIdx = PositionToIndex(hit.point + new Vector3(0, 0.5f, 0)); idx.y++; setIdx = idx; } //left else { Int3 idx = hitIdx = PositionToIndex(hit.point + new Vector3(0.5f, 0, 0)); idx.x--; setIdx = idx; } return hitIdx; } setIdx = new Int3(-1, -1, -1); return new Int3(-1,-1,-1); }
public bool hasCubeInfo(Int3 index) { return hasCubeInfo(index.x, index.y, index.z); }
public static NitroxInt3 ToDto(this Int3 v) { return(new NitroxInt3(v.x, v.y, v.z)); }
void UpdateSelectedMap() { if (lvMaps.View == View.Tile || lvMaps.SelectedItems.Count == 0 || lvMaps.SelectedItems.Count > 1) { lMapName.Text = ""; lUID.Text = ""; lAuthor.Text = ""; lSize.Text = ""; lDecoration.Text = ""; lMedals.Text = ""; lAuthorM.Text = ""; lGoldM.Text = ""; lSilverM.Text = ""; lBronzeM.Text = ""; lMapType.Text = ""; lBlockRange.Text = ""; lBlockRange.BackColor = Color.Transparent; ttBlockRange.SetToolTip(lBlockRange, ""); pbThumbnail.Image = null; } if (Maps.Count == 0) { bConvertAll.Enabled = false; } else if (MapsLoading.Count == 0) { bConvertAll.Enabled = true; } bConvertSelected.Enabled = false; if (lvMaps.SelectedItems.Count > 0) { if (MapsLoading.Count == 0) { bConvertSelected.Enabled = true; } bConvertSelected.Text = "Convert selected maps"; if (lvMaps.SelectedItems.Count == 1) { bConvertSelected.Text = "Convert selected map"; var item = lvMaps.SelectedItems[0]; if (Maps.TryGetValue(item.Name, out GameBox <CGameCtnChallenge> gbx)) { var map = gbx.MainNode; lMapName.Text = Formatter.Deformat(map.MapName); lUID.Text = "UID: " + map.MapUid; lAuthor.Text = "Author: " + Formatter.Deformat(map.AuthorLogin); lSize.Text = "Size: " + map.Size.ToString(); if (map.Size == (45, 36, 45)) { lSize.Text += " (made in TMUF)"; } else if (map.Size == (36, 36, 36)) { lSize.Text += " (made in TMU or Sunrise)"; } else { lSize.Text += " (made in China)"; } lDecoration.Text = "Decoration: " + map.Decoration.ID; lMedals.Text = "Medals:"; lAuthorM.Text = "Author: " + (map.ChallengeParameters.AuthorTime.HasValue ? map.ChallengeParameters.AuthorTime.Value.ToString("m':'ss':'fff") : "None"); lGoldM.Text = "Gold: " + (map.ChallengeParameters.GoldTime.HasValue ? map.ChallengeParameters.GoldTime.Value.ToString("m':'ss':'fff") : "None"); lSilverM.Text = "Silver: " + (map.ChallengeParameters.SilverTime.HasValue ? map.ChallengeParameters.SilverTime.Value.ToString("m':'ss':'fff") : "None"); lBronzeM.Text = "Bronze: " + (map.ChallengeParameters.BronzeTime.HasValue ? map.ChallengeParameters.BronzeTime.Value.ToString("m':'ss':'fff") : "None"); lMapType.Text = "Map type: " + map.Mode.ToString(); blockRange = IslandConverter.DefineMapRange(map.Blocks.ToArray(), out minCoord); if (blockRange.X <= 32 && blockRange.Z <= 32) { lBlockRange.BackColor = Color.Lime; ttBlockRange.SetToolTip(lBlockRange, "This map fits the default Stadium64x64 base! You can choose your map base size just fine without issues."); x32Button.Text = "32x32 area with normal border with Island background, doesn\'t require OpenPlanet to work (recommended)"; x45Button.Text = "45x45 area with small border with Island background, requires OpenPlanet to work (also recommended)"; } else { lBlockRange.BackColor = Color.Yellow; ttBlockRange.SetToolTip(lBlockRange, "This map is bigger than the default Stadium64x64 base! Choose the map base size wisely."); x32Button.Text = "32x32 area with normal border with Island background, doesn\'t require OpenPlanet to work"; x45Button.Text = "45x45 area with small border with Island background, requires OpenPlanet to work (recommended)"; } lBlockRange.Text = "Block range: " + blockRange; if (map.Thumbnail != null) { pbThumbnail.Image = map.Thumbnail.Result; } } }
/** Write an Int3 */ public void SerializeInt3(Int3 v) { writer.Write(v.x); writer.Write(v.y); writer.Write(v.z); }
VoxelizedMesh VoxelizeMesh(Transform t, float voxelResolution, int voxelizeLayer) { // TODO ray cast from right / left and top/ down Physics.queriesHitBackfaces = false; MeshRenderer mr = t.GetComponent <MeshRenderer>(); if (mr == null) { return(null); } MeshFilter mf = t.GetComponent <MeshFilter>(); if (mf == null) { return(null); } Mesh mesh = mf.sharedMesh; if (mesh == null) { return(null); } VoxelizedMesh vm = new VoxelizedMesh(); voxelizedLookup[mesh] = vm; Transform oldParent = t.parent; Vector3 oldPos = t.position; Quaternion oldRot = t.rotation; Vector3 oldScale = t.localScale; t.parent = null; t.position = Vector3.zero; t.rotation = Quaternion.identity; t.localScale = Vector3.one; int oldLayer = t.gameObject.layer; t.gameObject.layer = voxelizeLayer; LayerMask voxelizeLayerMask = 1 << voxelizeLayer; Bounds bounds = mr.bounds; Vector3 size = bounds.size; Int3 voxels = new Int3(Mathf.CeilToInt(size.x / voxelResolution), Mathf.CeilToInt(size.y / voxelResolution), Mathf.CeilToInt(size.z / voxelResolution)); voxels += new Int3(2, 2, 2); int voxelsX = Mathf.CeilToInt(voxels.x / 8f); vm.voxels = voxels; size = new Vector3(voxels.x * voxelResolution, voxels.y * voxelResolution, voxels.z * voxelResolution); bounds.size = size; vm.bounds = bounds; byte[,,] volume = new byte[voxelsX, voxels.y, voxels.z]; Ray ray = new Ray(); Ray ray2 = new Ray(); ray.direction = Vector3.forward; ray2.direction = Vector3.back; Vector3 pos = bounds.min; Vector3 pos2 = pos; pos2.z = bounds.max.z; Debug.Log(PrintVector3(mr.bounds.size) + " new size " + PrintVector3(size) + " voxels " + voxels.ToString()); int voxelCount = 0; Vector3 halfVoxel = Vector3.one * voxelResolution * 0.5f; Vector3 minBoundsVoxel = pos + halfVoxel; // voxels.y = 2; try { for (int x = 0; x < voxels.x; x++) { int xGrid = x / 8; byte bit = bits[x - (xGrid * 8)]; for (int y = 0; y < voxels.y; y++) { Vector3 origin = pos + new Vector3((x + 0.5f) * voxelResolution, (y + 0.5f) * voxelResolution, 0); ray.origin = origin; origin.z = pos2.z; ray2.origin = origin; intersectList.Clear(); MultiCast(ray, intersectList, 0.001f, size.z, voxelizeLayerMask); MultiCast(ray2, intersectList, -0.001f, size.z, voxelizeLayerMask); intersectList.Sort(); float half = (float)intersectList.Count / 2; if (half != (int)half) { continue; } // Debug.Log(hitInfos.Length + " " + hitInfos2.Length + " " + list.Count); for (int i = 0; i < intersectList.Count; i += 2) { int z1 = Mathf.RoundToInt((intersectList[i] - pos.z) / voxelResolution); int z2 = Mathf.RoundToInt((intersectList[i + 1] - pos.z) / voxelResolution); for (int z = z1; z < z2; z++) { Vector3 voxelPos = new Vector3(x * voxelResolution, y * voxelResolution, z * voxelResolution) + minBoundsVoxel; voxelPos = t.TransformPoint(voxelPos); volume[xGrid, y, z] |= bit; ++voxelCount; //if (!Physics.CheckBox(voxelPos, halfVoxel, Quaternion.identity, voxelizeLayerMask)) //{ // volume[xGrid, y, z] |= bit; // ++voxelCount; //} } } } } } catch (Exception e) { Debug.LogError(e.ToString()); } Debug.Log(t.name + " voxels " + voxelCount); vm.volume = volume; t.gameObject.layer = oldLayer; t.parent = oldParent; t.position = oldPos; t.rotation = oldRot; t.localScale = oldScale; return(vm); }
public void DrawVolume(Transform t, float voxelResolution) { MeshRenderer mr = t.GetComponent <MeshRenderer>(); if (mr == null) { return; } MeshFilter mf = t.GetComponent <MeshFilter>(); if (mf == null) { return; } Mesh m = mf.sharedMesh; if (m == null) { return; } VoxelizedMesh vm; voxelizedLookup.TryGetValue(m, out vm); if (vm == null) { return; } byte[,,] volume = vm.volume; if (volume == null) { return; } Vector3 pos = vm.bounds.min; Vector3 voxel = t.lossyScale * voxelResolution; Vector3 halfVoxel = Vector3.one * voxelResolution * 0.5f; Int3 voxels = vm.voxels; // Debug.Log(voxels); // Debug.Log(volume.Length); Gizmos.DrawWireCube(mr.bounds.center, mr.bounds.size); for (int x = 0; x < voxels.x; x++) { int xGrid = x / 8; int bit = x - (xGrid * 8); for (int y = 0; y < voxels.y; y++) { for (int z = 0; z < voxels.z; z++) { if ((volume[xGrid, y, z] & bits[bit]) > 0) { Vector3 localPos = new Vector3(pos.x + (x * voxelResolution), pos.y + (y * voxelResolution), pos.z + (z * voxelResolution)) + halfVoxel; Gizmos.DrawWireCube(t.TransformPoint(localPos), voxel); } } } } }
public void SetBlock(Int3 absoluteIndex, byte voxel) => _chunkUpdater.SetVoxel(absoluteIndex, voxel);
public static float Length(Int3 v) { return Mathf.Sqrt((v.x * v.x) + (v.y * v.y) + (v.z * v.z)); }
void OpenAreaCheck(Int3 nowAreaIdx) { //인접한 구역 탐색 Queue<Int3> stackData = new Queue<Int3>(); if (hasAreaInfo(nowAreaIdx)) stackData.Enqueue(nowAreaIdx); while (stackData.Count != 0) { Int3 areaIdx = stackData.Dequeue(); if (area[areaIdx.x, areaIdx.y, areaIdx.z].isIn) { area[areaIdx.x, areaIdx.y, areaIdx.z].isIn = false; area[areaIdx.x, areaIdx.y, areaIdx.z].Draw(true); Int3 adjacentIdx; //Forward if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.FORWARD) != 0) { adjacentIdx = areaIdx + new Int3(0, 0, 1); if (hasAreaInfo(adjacentIdx)) { if (area[adjacentIdx.x, adjacentIdx.y, adjacentIdx.z].isIn) { stackData.Enqueue(adjacentIdx); } } } //Back if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.BACK) != 0) { adjacentIdx = areaIdx + new Int3(0, 0, -1); if (hasAreaInfo(adjacentIdx)) { if (area[adjacentIdx.x, adjacentIdx.y, adjacentIdx.z].isIn) { stackData.Enqueue(adjacentIdx); } } } //Up if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.UP) != 0) { adjacentIdx = areaIdx + new Int3(0, -1, 0); if (hasAreaInfo(adjacentIdx)) { if (area[adjacentIdx.x, adjacentIdx.y, adjacentIdx.z].isIn) { stackData.Enqueue(adjacentIdx); } } } //Down if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.DOWN) != 0) { adjacentIdx = areaIdx + new Int3(0, 1, 0); if (hasAreaInfo(adjacentIdx)) { if (area[adjacentIdx.x, adjacentIdx.y, adjacentIdx.z].isIn) { stackData.Enqueue(adjacentIdx); } } } //Right if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.RIGHT) != 0) { adjacentIdx = areaIdx + new Int3(1, 0, 0); if (hasAreaInfo(adjacentIdx)) { if (area[adjacentIdx.x, adjacentIdx.y, adjacentIdx.z].isIn) { stackData.Enqueue(adjacentIdx); } } } //Left if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.LEFT) != 0) { adjacentIdx = areaIdx + new Int3(-1, 0, 0); if (hasAreaInfo(adjacentIdx)) { if (area[adjacentIdx.x, adjacentIdx.y, adjacentIdx.z].isIn) { stackData.Enqueue(adjacentIdx); } } } } } int areaFar = (Area.farSize / Area.divideSize); Int3 minIdx = nowAreaIdx - new Int3(areaFar, areaFar, areaFar); minIdx.x = Mathf.Max(minIdx.x, 0); minIdx.y = Mathf.Max(minIdx.y, 0); minIdx.z = Mathf.Max(minIdx.z, 0); Int3 maxIdx = nowAreaIdx + new Int3(areaFar, areaFar, areaFar); maxIdx.x = Mathf.Min(maxIdx.x, area.GetLength(0)); maxIdx.y = Mathf.Min(maxIdx.y, area.GetLength(1)); maxIdx.z = Mathf.Min(maxIdx.z, area.GetLength(2)); int x = 0, y = 0, z = 0; for (x = minIdx.x; x < maxIdx.x; x++) { for (y = minIdx.y; y < maxIdx.y; y++) { for (z = minIdx.z; z < maxIdx.z; z++) { if (area[x, y, z].isIn) { area[x, y, z].Draw(false); } } } } }
public override int GetHashCode() { int num = 1; if (EventType != 0) { num ^= EventType.GetHashCode(); } if (EventId != 0) { num ^= EventId.GetHashCode(); } if (parentEventId_.HasValue) { num ^= ParentEventId.GetHashCode(); } if (Int1 != 0) { num ^= Int1.GetHashCode(); } if (Int2 != 0) { num ^= Int2.GetHashCode(); } if (Int3 != 0) { num ^= Int3.GetHashCode(); } if (Int4 != 0) { num ^= Int4.GetHashCode(); } if (Int5 != 0) { num ^= Int5.GetHashCode(); } if (Int6 != 0) { num ^= Int6.GetHashCode(); } if (Int7 != 0) { num ^= Int7.GetHashCode(); } if (String1.Length != 0) { num ^= String1.GetHashCode(); } if (Bool1) { num ^= Bool1.GetHashCode(); } if (cellCoord1_ != null) { num ^= CellCoord1.GetHashCode(); } if (cellCoord2_ != null) { num ^= CellCoord2.GetHashCode(); } if (CompanionReserveState1 != 0) { num ^= CompanionReserveState1.GetHashCode(); } if (CompanionReserveState2 != 0) { num ^= CompanionReserveState2.GetHashCode(); } if (DamageReductionType1 != 0) { num ^= DamageReductionType1.GetHashCode(); } if (FightResult1 != 0) { num ^= FightResult1.GetHashCode(); } if (gameStatistics1_ != null) { num ^= GameStatistics1.GetHashCode(); } if (TeamsScoreModificationReason1 != 0) { num ^= TeamsScoreModificationReason1.GetHashCode(); } if (optInt1_.HasValue) { num ^= OptInt1.GetHashCode(); } if (optInt2_.HasValue) { num ^= OptInt2.GetHashCode(); } if (optInt3_.HasValue) { num ^= OptInt3.GetHashCode(); } if (optInt4_.HasValue) { num ^= OptInt4.GetHashCode(); } num ^= ((object)cellCoordList1_).GetHashCode(); num ^= ((object)spellMovementList1_).GetHashCode(); num ^= ((object)castTargetList1_).GetHashCode(); num ^= ((object)intList1_).GetHashCode(); num ^= ((object)intList2_).GetHashCode(); if (_unknownFields != null) { num ^= ((object)_unknownFields).GetHashCode(); } return(num); }
public Vector3 IndexToPosition(Int3 index) { return new Vector3(-size.x * 0.5f + index.x, (int)(size.y) - index.y, -size.z * 0.5f + index.z); }
public static void ConvertBoundsToEncodingValues(InstanciedMeshHolders instanciedMeshHolders, Bounds meshBounds, out Int3 center, out Int3 size) { int x = (int)(meshBounds.center.x * instanciedMeshHolders.Max16BitValueOverBBoxExtent.x); int y = (int)(meshBounds.center.y * instanciedMeshHolders.Max16BitValueOverBBoxExtent.y); int z = (int)(meshBounds.center.z * instanciedMeshHolders.Max16BitValueOverBBoxExtent.z); int x2 = (int)(meshBounds.size.x * instanciedMeshHolders.Max16BitValueOverBBoxExtent.x); int y2 = (int)(meshBounds.size.y * instanciedMeshHolders.Max16BitValueOverBBoxExtent.y); int z2 = (int)(meshBounds.size.z * instanciedMeshHolders.Max16BitValueOverBBoxExtent.z); center = new Int3(x, y, z); size = new Int3(x2, y2, z2); }
//큐브 파기 public void grubCube(Int3 cubeIdx) { map[cubeIdx.x, cubeIdx.y, cubeIdx.z].isEnable = 0; map[cubeIdx.x, cubeIdx.y, cubeIdx.z].mapinfo = CubeInfo.None; if (!isOverMap(cubeIdx)) { RenewalAdjacentCubeObject(cubeIdx); Int3 areaIdx = PositionToAreaIndex(IndexToPosition(cubeIdx)); area[areaIdx.x, areaIdx.y, areaIdx.z].cubeArea.GenerateMesh(area[areaIdx.x, areaIdx.y, areaIdx.z]); area[areaIdx.x, areaIdx.y, areaIdx.z].OpenCheck(); if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.FORWARD) != 0 && areaIdx.z + 1 < area.GetLength(2)) { area[areaIdx.x, areaIdx.y, areaIdx.z + 1].cubeArea.GenerateMesh(area[areaIdx.x, areaIdx.y, areaIdx.z + 1]); area[areaIdx.x, areaIdx.y, areaIdx.z + 1].cubeArea.gameObject.SetActive(true); } if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.BACK) != 0 && areaIdx.z - 1 >= 0) { area[areaIdx.x, areaIdx.y, areaIdx.z - 1].cubeArea.GenerateMesh(area[areaIdx.x, areaIdx.y, areaIdx.z - 1]); area[areaIdx.x, areaIdx.y, areaIdx.z - 1].cubeArea.gameObject.SetActive(true); } if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.RIGHT) != 0 && areaIdx.x + 1 < area.GetLength(0)) { area[areaIdx.x + 1, areaIdx.y, areaIdx.z].cubeArea.GenerateMesh(area[areaIdx.x + 1, areaIdx.y, areaIdx.z]); area[areaIdx.x + 1, areaIdx.y, areaIdx.z].cubeArea.gameObject.SetActive(true); } if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.LEFT) != 0 && areaIdx.x - 1 >= 0) { area[areaIdx.x - 1, areaIdx.y, areaIdx.z].cubeArea.GenerateMesh(area[areaIdx.x - 1, areaIdx.y, areaIdx.z]); area[areaIdx.x - 1, areaIdx.y, areaIdx.z].cubeArea.gameObject.SetActive(true); } if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.UP) != 0 && areaIdx.y - 1 >= 0) { area[areaIdx.x, areaIdx.y - 1, areaIdx.z].cubeArea.GenerateMesh(area[areaIdx.x, areaIdx.y - 1, areaIdx.z]); area[areaIdx.x, areaIdx.y - 1, areaIdx.z].cubeArea.gameObject.SetActive(true); } if ((area[areaIdx.x, areaIdx.y, areaIdx.z].openFlag & (int)OpenSide.DOWN) != 0 && areaIdx.y + 1 < area.GetLength(1)) { area[areaIdx.x, areaIdx.y + 1, areaIdx.z].cubeArea.GenerateMesh(area[areaIdx.x, areaIdx.y + 1, areaIdx.z]); area[areaIdx.x, areaIdx.y + 1, areaIdx.z].cubeArea.gameObject.SetActive(true); } } }
/// <summary> /// Converts cube based hex coordinates to axial hex /// coordinates. Basically just seems to discard the z value. /// </summary> /// <returns>hex coordinates.</returns> public static Hex CubeToAxial(Int3 cube) { return(new Hex(cube.x, cube.y)); }
public static Node GetNode (Int3 pos) { return AstarPath.active.staticNodes[pos.y][pos.x,pos.z];//Height, Width, Depth }
public bool Contains(Int3 point) { return((((point.x >= this.xMin) && (point.x < this.xMax)) && (point.y >= this.yMin)) && (point.y < this.yMax)); }
public static Int3 Transform(Int3 point, ref Int3 axis_x, ref Int3 axis_y, ref Int3 axis_z, ref Int3 trans) { return(new Int3(Divide((int)(((axis_x.x * point.x) + (axis_y.x * point.y)) + (axis_z.x * point.z)), 1000) + trans.x, Divide((int)(((axis_x.y * point.x) + (axis_y.y * point.y)) + (axis_z.y * point.z)), 1000) + trans.y, Divide((int)(((axis_x.z * point.x) + (axis_y.z * point.y)) + (axis_z.z * point.z)), 1000) + trans.z)); }
public static Int2 FromInt3XZ(Int3 o) { return(new Int2(o.x, o.z)); }
public void ConstructionComplete(GameObject ghost, Optional <Base> lastTargetBase, Int3 lastTargetBaseOffset) { NitroxId baseId = null; Optional <object> opConstructedBase = TransientLocalObjectManager.Get(TransientObjectType.BASE_GHOST_NEWLY_CONSTRUCTED_BASE_GAMEOBJECT); NitroxId id = NitroxEntity.GetId(ghost); Log.Info("Construction complete on " + id + " " + ghost.name); if (opConstructedBase.HasValue) { GameObject constructedBase = (GameObject)opConstructedBase.Value; baseId = NitroxEntity.GetId(constructedBase); } // For base pieces, we must switch the id from the ghost to the newly constructed piece. // Furniture just uses the same game object as the ghost for the final product. if (ghost.GetComponent <ConstructableBase>() != null) { Int3 latestCell = lastTargetBaseOffset; Base latestBase = (lastTargetBase.HasValue) ? lastTargetBase.Value : ((GameObject)opConstructedBase.Value).GetComponent <Base>(); baseId = NitroxEntity.GetId(latestBase.gameObject); Transform cellTransform = latestBase.GetCellObject(latestCell); // This check ensures that the latestCell actually leads us to the correct entity. The lastTargetBaseOffset is unreliable as the base shape // can change which makes the target offset change. It may be possible to fully deprecate lastTargetBaseOffset and only rely on GetClosestCell; // however, there may still be pieces were the ghost base's target offset is authoratitive due to incorrect game object positioning. if (latestCell == default(Int3) || cellTransform == null) { Vector3 worldPosition; float distance; latestBase.GetClosestCell(ghost.transform.position, out latestCell, out worldPosition, out distance); cellTransform = latestBase.GetCellObject(latestCell); Validate.NotNull(cellTransform, "Unable to find cell transform at " + latestCell); } GameObject finishedPiece = null; // There can be multiple objects in a cell (such as a corridor with hatces built into it) // we look for a object that is able to be deconstucted that hasn't been tagged yet. foreach (Transform child in cellTransform) { bool isNewBasePiece = (child.GetComponent <NitroxEntity>() == null && child.GetComponent <BaseDeconstructable>() != null); if (isNewBasePiece) { finishedPiece = child.gameObject; break; } } Validate.NotNull(finishedPiece, "Could not find finished piece in cell " + latestCell); Log.Info("Setting id to finished piece: " + finishedPiece.name + " " + id); UnityEngine.Object.Destroy(ghost); NitroxEntity.SetNewId(finishedPiece, id); BasePieceSpawnProcessor customSpawnProcessor = BasePieceSpawnProcessor.From(finishedPiece.GetComponent <BaseDeconstructable>()); customSpawnProcessor.SpawnPostProcess(latestBase, latestCell, finishedPiece); } Log.Info("Construction Completed " + id + " in base " + baseId); ConstructionCompleted constructionCompleted = new ConstructionCompleted(id, baseId); packetSender.Send(constructionCompleted); }
public AnchoredFaceRotationMetadata(Int3 cell, int facedirection, int facetype) : base(typeof(BaseAddFaceGhost)) { Cell = cell.Model(); Direction = facedirection; FaceType = facetype; }
public void UpdateFromContext(VoxelStorageContext context) { var virtualResolution = context.Resolution(); var largestDimension = (double)Math.Max(virtualResolution.X, Math.Max(virtualResolution.Y, virtualResolution.Z)); ClipMapCount = (int)Math.Log(largestDimension / Math.Min(largestDimension, (double)ClipResolution), 2) + 1; ClipMapCurrent++; if (ClipMapCurrent >= ClipMapCount) { ClipMapCurrent = 0; } float FinestClipMapScale = (float)Math.Pow(2, ClipMapCount - 1); ClipMapResolution = new Vector3(virtualResolution.X, virtualResolution.Y, virtualResolution.Z) / FinestClipMapScale; MipMapCount = (int)Math.Floor(Math.Log(Math.Min(ClipMapResolution.X, Math.Min(ClipMapResolution.Y, ClipMapResolution.Z)), 2)); int voxelScale = 1; for (int i = 0; i < (ClipMapCount + MipMapCount); i++) { Vector3 SnappedVolumeTranslation = context.VoxelSpaceTranslation; SnappedVolumeTranslation.X = (float)Math.Floor(SnappedVolumeTranslation.X / voxelScale) * voxelScale; SnappedVolumeTranslation.Y = (float)Math.Floor(SnappedVolumeTranslation.Y / voxelScale) * voxelScale; SnappedVolumeTranslation.Z = (float)Math.Floor(SnappedVolumeTranslation.Z / voxelScale) * voxelScale; if (ShouldUpdateClipIndex(i)) { PerMapSnappingOffset[i] = -SnappedVolumeTranslation *context.RealVoxelSize(); MippingOffsetTranslation[i] = new Int3((int)SnappedVolumeTranslation.X, (int)SnappedVolumeTranslation.Y, (int)SnappedVolumeTranslation.Z); } voxelScale *= 2; } float extentScale = (float)Math.Pow(2f, ClipMapCount - 1); voxelScale = 1; for (int i = 0; i < (ClipMapCount + MipMapCount); i++) { if (ShouldUpdateClipIndex(i)) { Vector3 offset = (PerMapSnappingOffset[i]) * extentScale / context.Extents + 0.5f; PerMapOffsetScale[i] = new Vector4(offset, (1.0f / context.Extents.X) * extentScale); } if (i + 1 == ClipMapCurrent || ShouldUpdateClipIndex(i)) { MippingOffset[i] = (Vector3)((MippingOffsetTranslation[i] - MippingOffsetTranslation[i + 1]) / voxelScale); } if (i < ClipMapCount - 1) { extentScale /= 2; } voxelScale *= 2; } }
protected static void UpdateSelectionOnCloserIntersection(BoundingBox box, Ray clickRay, Int3 element, ref float minHitDistance, ref Int3 newSelection) { float hitDistance; if (box.Intersects(ref clickRay, out hitDistance) && hitDistance < minHitDistance) { minHitDistance = hitDistance; newSelection = element; } }
public static int LengthSq(Int3 v) { return (v.x * v.x) + (v.y * v.y) + (v.z * v.z); }
public void PostNew(Int3 startPos, Int3 endPos) { float startTime = Time.realtimeSinceStartup; if (startPos == new Int3(-1, -1, -1)) { Debug.LogWarning("Start is not inside any grids"); error = true; return; } if (endPos == new Int3(-1, -1, -1)) { Debug.LogWarning("Target is not inside any grids"); error = true; return; } start = GetNode(startPos); end = GetNode(endPos); if (!start.walkable) { if (start.neighbours.Length > 0) { start = start.neighbours[0]; Debug.LogWarning("Start point is not walkable, setting a node close to start as start"); } else { Debug.LogWarning("Starting from non walkable node"); error = true; return; } } current = start; if (!end.walkable) { if (end.neighbours.Length > 0) { end = end.neighbours[0]; Debug.LogWarning("Target point is not walkable, setting a node close to target as target"); } else { Debug.LogWarning("Target point is not walkable"); error = true; return; } } if (end.area != start.area) { Debug.LogWarning("We can't walk from start to end, differend areas"); error = true; return; } t += Time.realtimeSinceStartup - startTime; }
IEnumerator AreaCulling() { int areaFarSq = (Area.farSize / Area.divideSize); areaFarSq *= areaFarSq; Int3 oldAreaIdx = new Int3(-999, -999, -999); while (true) { Int3 nowAreaIdx = PositionToAreaIndex(player.position); if (nowAreaIdx != oldAreaIdx) { for (int y = 0; y < area.GetLength(1); y++) { for (int x = 0; x < area.GetLength(0); x++) { for (int z = 0; z < area.GetLength(2); z++) { Int3 areaToNowArea = nowAreaIdx - new Int3(x, y, z); int lengthSq = Int3.LengthSq(areaToNowArea); if ((area[x, y, z].isIn = (lengthSq < areaFarSq)) == false) { area[x, y, z].Draw(false); } } } } OpenAreaCheck(nowAreaIdx); oldAreaIdx = nowAreaIdx; yield return new WaitForSeconds(0.1f); } yield return null; } }
private void CutPoly(Int3[] verts, int[] tris, ref Int3[] outVertsArr, ref int[] outTrisArr, out int outVCount, out int outTCount, Int3[] extraShape, Int3 cuttingOffset, Bounds realBounds, TileHandler.CutMode mode = (TileHandler.CutMode) 3, int perturbate = 0) { if (verts.Length == 0 || tris.Length == 0) { outVCount = 0; outTCount = 0; outTrisArr = new int[0]; outVertsArr = new Int3[0]; return; } List <IntPoint> list = null; if (extraShape == null && (mode & TileHandler.CutMode.CutExtra) != (TileHandler.CutMode) 0) { throw new Exception("extraShape is null and the CutMode specifies that it should be used. Cannot use null shape."); } if ((mode & TileHandler.CutMode.CutExtra) != (TileHandler.CutMode) 0) { list = new List <IntPoint>(extraShape.Length); for (int i = 0; i < extraShape.Length; i++) { list.Add(new IntPoint((long)(extraShape[i].x + cuttingOffset.x), (long)(extraShape[i].z + cuttingOffset.z))); } } List <IntPoint> list2 = new List <IntPoint>(5); Dictionary <TriangulationPoint, int> dictionary = new Dictionary <TriangulationPoint, int>(); List <PolygonPoint> list3 = new List <PolygonPoint>(); IntRect b = new IntRect(verts[0].x, verts[0].z, verts[0].x, verts[0].z); for (int j = 0; j < verts.Length; j++) { b = b.ExpandToContain(verts[j].x, verts[j].z); } List <Int3> list4 = ListPool <Int3> .Claim(verts.Length * 2); List <int> list5 = ListPool <int> .Claim(tris.Length); PolyTree polyTree = new PolyTree(); List <List <IntPoint> > list6 = new List <List <IntPoint> >(); Stack <Polygon> stack = new Stack <Polygon>(); if (this.clipper == null) { this.clipper = new Clipper(0); } this.clipper.ReverseSolution = true; List <NavmeshCut> list7; if (mode == TileHandler.CutMode.CutExtra) { list7 = ListPool <NavmeshCut> .Claim(); } else { list7 = NavmeshCut.GetAllInRange(realBounds); } List <int> list8 = ListPool <int> .Claim(); List <IntRect> list9 = ListPool <IntRect> .Claim(); List <Int2> list10 = ListPool <Int2> .Claim(); List <List <IntPoint> > list11 = new List <List <IntPoint> >(); List <bool> list12 = ListPool <bool> .Claim(); List <bool> list13 = ListPool <bool> .Claim(); if (perturbate > 10) { Debug.LogError("Too many perturbations aborting : " + mode); Debug.Break(); outVCount = verts.Length; outTCount = tris.Length; outTrisArr = tris; outVertsArr = verts; return; } Random random = null; if (perturbate > 0) { random = new Random(); } for (int k = 0; k < list7.Count; k++) { Bounds bounds = list7[k].GetBounds(); Int3 @int = (Int3)bounds.min + cuttingOffset; Int3 int2 = (Int3)bounds.max + cuttingOffset; IntRect a = new IntRect(@int.x, @int.z, int2.x, int2.z); if (IntRect.Intersects(a, b)) { Int2 int3 = new Int2(0, 0); if (perturbate > 0) { int3.x = random.Next() % 6 * perturbate - 3 * perturbate; if (int3.x >= 0) { int3.x++; } int3.y = random.Next() % 6 * perturbate - 3 * perturbate; if (int3.y >= 0) { int3.y++; } } int count = list11.Count; list7[k].GetContour(list11); for (int l = count; l < list11.Count; l++) { List <IntPoint> list14 = list11[l]; if (list14.Count == 0) { Debug.LogError("Zero Length Contour"); list9.Add(default(IntRect)); list10.Add(new Int2(0, 0)); } else { IntRect item = new IntRect((int)list14[0].X + cuttingOffset.x, (int)list14[0].Y + cuttingOffset.y, (int)list14[0].X + cuttingOffset.x, (int)list14[0].Y + cuttingOffset.y); for (int m = 0; m < list14.Count; m++) { IntPoint value = list14[m]; value.X += (long)cuttingOffset.x; value.Y += (long)cuttingOffset.z; if (perturbate > 0) { value.X += (long)int3.x; value.Y += (long)int3.y; } list14[m] = value; item = item.ExpandToContain((int)value.X, (int)value.Y); } list10.Add(new Int2(@int.y, int2.y)); list9.Add(item); list12.Add(list7[k].isDual); list13.Add(list7[k].cutsAddedGeom); } } } } List <NavmeshAdd> allInRange = NavmeshAdd.GetAllInRange(realBounds); Int3[] array = verts; int[] array2 = tris; int num = -1; int n = -3; Int3[] array3 = null; Int3[] array4 = null; Int3 int4 = Int3.zero; if (allInRange.Count > 0) { array3 = new Int3[7]; array4 = new Int3[7]; int4 = (Int3)realBounds.extents; } for (;;) { n += 3; while (n >= array2.Length) { num++; n = 0; if (num >= allInRange.Count) { array = null; break; } if (array == verts) { array = null; } allInRange[num].GetMesh(cuttingOffset, ref array, out array2); } if (array == null) { break; } Int3 int5 = array[array2[n]]; Int3 int6 = array[array2[n + 1]]; Int3 int7 = array[array2[n + 2]]; IntRect a2 = new IntRect(int5.x, int5.z, int5.x, int5.z); a2 = a2.ExpandToContain(int6.x, int6.z); a2 = a2.ExpandToContain(int7.x, int7.z); int num2 = Math.Min(int5.y, Math.Min(int6.y, int7.y)); int num3 = Math.Max(int5.y, Math.Max(int6.y, int7.y)); list8.Clear(); bool flag = false; for (int num4 = 0; num4 < list11.Count; num4++) { int x = list10[num4].x; int y = list10[num4].y; if (IntRect.Intersects(a2, list9[num4]) && y >= num2 && x <= num3 && (list13[num4] || num == -1)) { Int3 int8 = int5; int8.y = x; Int3 int9 = int5; int9.y = y; list8.Add(num4); flag |= list12[num4]; } } if (list8.Count == 0 && (mode & TileHandler.CutMode.CutExtra) == (TileHandler.CutMode) 0 && (mode & TileHandler.CutMode.CutAll) != (TileHandler.CutMode) 0 && num == -1) { list5.Add(list4.Count); list5.Add(list4.Count + 1); list5.Add(list4.Count + 2); list4.Add(int5); list4.Add(int6); list4.Add(int7); } else { list2.Clear(); if (num == -1) { list2.Add(new IntPoint((long)int5.x, (long)int5.z)); list2.Add(new IntPoint((long)int6.x, (long)int6.z)); list2.Add(new IntPoint((long)int7.x, (long)int7.z)); } else { array3[0] = int5; array3[1] = int6; array3[2] = int7; int num5 = Utility.ClipPolygon(array3, 3, array4, 1, 0, 0); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array4, num5, array3, -1, 2 * int4.x, 0); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array3, num5, array4, 1, 0, 2); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array4, num5, array3, -1, 2 * int4.z, 2); if (num5 == 0) { continue; } for (int num6 = 0; num6 < num5; num6++) { list2.Add(new IntPoint((long)array3[num6].x, (long)array3[num6].z)); } } dictionary.Clear(); Int3 int10 = int6 - int5; Int3 int11 = int7 - int5; Int3 int12 = int10; Int3 int13 = int11; int12.y = 0; int13.y = 0; for (int num7 = 0; num7 < 16; num7++) { if ((mode >> (num7 & 31) & TileHandler.CutMode.CutAll) != (TileHandler.CutMode) 0) { if (1 << num7 == 1) { this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); for (int num8 = 0; num8 < list8.Count; num8++) { this.clipper.AddPolygon(list11[list8[num8]], 1); } polyTree.Clear(); this.clipper.Execute(2, polyTree, 0, 1); } else if (1 << num7 == 2) { if (!flag) { goto IL_1161; } this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); for (int num9 = 0; num9 < list8.Count; num9++) { if (list12[list8[num9]]) { this.clipper.AddPolygon(list11[list8[num9]], 1); } } list6.Clear(); this.clipper.Execute(0, list6, 0, 1); this.clipper.Clear(); for (int num10 = 0; num10 < list6.Count; num10++) { this.clipper.AddPolygon(list6[num10], (!Clipper.Orientation(list6[num10])) ? 0 : 1); } for (int num11 = 0; num11 < list8.Count; num11++) { if (!list12[list8[num11]]) { this.clipper.AddPolygon(list11[list8[num11]], 1); } } polyTree.Clear(); this.clipper.Execute(2, polyTree, 0, 1); } else if (1 << num7 == 4) { this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); this.clipper.AddPolygon(list, 1); polyTree.Clear(); this.clipper.Execute(0, polyTree, 0, 1); } for (int num12 = 0; num12 < polyTree.ChildCount; num12++) { PolyNode polyNode = polyTree.Childs[num12]; List <IntPoint> contour = polyNode.Contour; List <PolyNode> childs = polyNode.Childs; if (childs.Count == 0 && contour.Count == 3 && num == -1) { for (int num13 = 0; num13 < contour.Count; num13++) { Int3 item2 = new Int3((int)contour[num13].X, 0, (int)contour[num13].Y); double num14 = (double)(int6.z - int7.z) * (double)(int5.x - int7.x) + (double)(int7.x - int6.x) * (double)(int5.z - int7.z); if (num14 == 0.0) { Debug.LogWarning("Degenerate triangle"); } else { double num15 = ((double)(int6.z - int7.z) * (double)(item2.x - int7.x) + (double)(int7.x - int6.x) * (double)(item2.z - int7.z)) / num14; double num16 = ((double)(int7.z - int5.z) * (double)(item2.x - int7.x) + (double)(int5.x - int7.x) * (double)(item2.z - int7.z)) / num14; item2.y = (int)Math.Round(num15 * (double)int5.y + num16 * (double)int6.y + (1.0 - num15 - num16) * (double)int7.y); list5.Add(list4.Count); list4.Add(item2); } } } else { Polygon polygon = null; int num17 = -1; for (List <IntPoint> list15 = contour; list15 != null; list15 = ((num17 >= childs.Count) ? null : childs[num17].Contour)) { list3.Clear(); for (int num18 = 0; num18 < list15.Count; num18++) { PolygonPoint polygonPoint = new PolygonPoint((double)list15[num18].X, (double)list15[num18].Y); list3.Add(polygonPoint); Int3 item3 = new Int3((int)list15[num18].X, 0, (int)list15[num18].Y); double num19 = (double)(int6.z - int7.z) * (double)(int5.x - int7.x) + (double)(int7.x - int6.x) * (double)(int5.z - int7.z); if (num19 == 0.0) { Debug.LogWarning("Degenerate triangle"); } else { double num20 = ((double)(int6.z - int7.z) * (double)(item3.x - int7.x) + (double)(int7.x - int6.x) * (double)(item3.z - int7.z)) / num19; double num21 = ((double)(int7.z - int5.z) * (double)(item3.x - int7.x) + (double)(int5.x - int7.x) * (double)(item3.z - int7.z)) / num19; item3.y = (int)Math.Round(num20 * (double)int5.y + num21 * (double)int6.y + (1.0 - num20 - num21) * (double)int7.y); dictionary[polygonPoint] = list4.Count; list4.Add(item3); } } Polygon polygon2; if (stack.Count > 0) { polygon2 = stack.Pop(); polygon2.AddPoints(list3); } else { polygon2 = new Polygon(list3); } if (polygon == null) { polygon = polygon2; } else { polygon.AddHole(polygon2); } num17++; } try { P2T.Triangulate(polygon); } catch (PointOnEdgeException) { Debug.LogWarning(string.Concat(new object[] { "PointOnEdgeException, perturbating vertices slightly ( at ", num7, " in ", mode, ")" })); this.CutPoly(verts, tris, ref outVertsArr, ref outTrisArr, out outVCount, out outTCount, extraShape, cuttingOffset, realBounds, mode, perturbate + 1); return; } for (int num22 = 0; num22 < polygon.Triangles.Count; num22++) { DelaunayTriangle delaunayTriangle = polygon.Triangles[num22]; list5.Add(dictionary[delaunayTriangle.Points._0]); list5.Add(dictionary[delaunayTriangle.Points._1]); list5.Add(dictionary[delaunayTriangle.Points._2]); } if (polygon.Holes != null) { for (int num23 = 0; num23 < polygon.Holes.Count; num23++) { polygon.Holes[num23].Points.Clear(); polygon.Holes[num23].ClearTriangles(); if (polygon.Holes[num23].Holes != null) { polygon.Holes[num23].Holes.Clear(); } stack.Push(polygon.Holes[num23]); } } polygon.ClearTriangles(); if (polygon.Holes != null) { polygon.Holes.Clear(); } polygon.Points.Clear(); stack.Push(polygon); } } } IL_1161 :; } } } Dictionary <Int3, int> dictionary2 = this.cached_Int3_int_dict; dictionary2.Clear(); if (this.cached_int_array.Length < list4.Count) { this.cached_int_array = new int[Math.Max(this.cached_int_array.Length * 2, list4.Count)]; } int[] array5 = this.cached_int_array; int num24 = 0; for (int num25 = 0; num25 < list4.Count; num25++) { int num26; if (!dictionary2.TryGetValue(list4[num25], out num26)) { dictionary2.Add(list4[num25], num24); array5[num25] = num24; list4[num24] = list4[num25]; num24++; } else { array5[num25] = num26; } } outTCount = list5.Count; if (outTrisArr == null || outTrisArr.Length < outTCount) { outTrisArr = new int[outTCount]; } for (int num27 = 0; num27 < outTCount; num27++) { outTrisArr[num27] = array5[list5[num27]]; } outVCount = num24; if (outVertsArr == null || outVertsArr.Length < outVCount) { outVertsArr = new Int3[outVCount]; } for (int num28 = 0; num28 < outVCount; num28++) { outVertsArr[num28] = list4[num28]; } for (int num29 = 0; num29 < list7.Count; num29++) { list7[num29].UsedForCut(); } ListPool <Int3> .Release(list4); ListPool <int> .Release(list5); ListPool <int> .Release(list8); ListPool <Int2> .Release(list10); ListPool <bool> .Release(list12); ListPool <bool> .Release(list13); ListPool <IntRect> .Release(list9); ListPool <NavmeshCut> .Release(list7); }
public int tileEnable(Int3 index) { return tileEnable(index.x, index.y, index.z); }
public TileHandler.TileType RegisterTileType(Mesh source, Int3 centerOffset, int width = 1, int depth = 1) { TileHandler.TileType tileType = new TileHandler.TileType(source, new Int3(this.graph.tileSizeX, 1, this.graph.tileSizeZ) * (1000f * this.graph.cellSize), centerOffset, width, depth); this.tileTypes.Add(tileType); return(tileType); }
public bool isOverMap(Int3 idx) { return isOverMap(idx.x, idx.y, idx.z); }
public static int ClipPolygon (Int3[] vIn, int n, Int3[] vOut, int multi, int offset, int axis) { int[] d = clipPolygonIntCache; for (int i = 0; i < n; i++) { d[i] = multi*vIn[i][axis]+offset; } //Number of resulting vertices int m = 0; for (int i = 0, j = n-1; i < n; j = i, i++) { bool prev = d[j] >= 0; bool curr = d[i] >= 0; if (prev != curr) { double s = (double)d[j] / (d[j] - d[i]); vOut[m] = vIn[j] + (vIn[i]-vIn[j])*s; m++; } if (curr) { vOut[m] = vIn[i]; m++; } } return m; }
public bool hasAreaInfo(Int3 index) { return hasAreaInfo(index.x, index.y, index.z); }
private GeneralConvexPairTester GetPair( ref Int3 position ) { var pair = testerPool.Take(); var boxCollidable = boxCollidablePool.Take(); boxCollidable.Shape.Width = voxelBlob.Shape.CellWidth; boxCollidable.Shape.Height = voxelBlob.Shape.CellWidth; boxCollidable.Shape.Length = voxelBlob.Shape.CellWidth; pair.Initialize( convex, boxCollidable ); boxCollidable.WorldTransform = new RigidTransform( new Vector3( voxelBlob.Position.X + ( position.X + 0.5f ) * voxelBlob.Shape.CellWidth, voxelBlob.Position.Y + ( position.Y + 0.5f ) * voxelBlob.Shape.CellWidth, voxelBlob.Position.Z + ( position.Z + 0.5f ) * voxelBlob.Shape.CellWidth ) ); return pair; }
public void RenewalAdjacentCubeObject(Int3 cubeIdx) { Int3 up = cubeIdx; up.y--; Int3 forward = cubeIdx; forward.z++; Int3 right = cubeIdx; right.x++; Int3 down = cubeIdx; down.y++; Int3 back = cubeIdx; back.z--; Int3 left = cubeIdx; left.x--; int tempEnable; if (hasCubeInfo(up)) { tempEnable = tileEnable(up); map[up.x, up.y, up.z].isEnable = tempEnable; } if (hasCubeInfo(forward)) { tempEnable = tileEnable(forward); map[forward.x, forward.y, forward.z].isEnable = tempEnable; } if (hasCubeInfo(right)) { tempEnable = tileEnable(right); map[right.x, right.y, right.z].isEnable = tempEnable; } if (hasCubeInfo(down)) { tempEnable = tileEnable(down); map[down.x, down.y, down.z].isEnable = tempEnable; } if (hasCubeInfo(back)) { tempEnable = tileEnable(back); map[back.x, back.y, back.z].isEnable = tempEnable; } if (hasCubeInfo(left)) { tempEnable = tileEnable(left); map[left.x, left.y, left.z].isEnable = tempEnable; } }
//Nvp = Maximum allowed vertices per polygon public void BuildPolyMesh (VoxelContourSet cset, int nvp, out VoxelMesh mesh) { nvp = 3; int maxVertices = 0; int maxTris = 0; int maxVertsPerCont = 0; for (int i = 0; i < cset.conts.Length; i++) { // Skip null contours. if (cset.conts[i].nverts < 3) continue; maxVertices += cset.conts[i].nverts; maxTris += cset.conts[i].nverts - 2; maxVertsPerCont = Mathfx.Max (maxVertsPerCont, cset.conts[i].nverts); } if (maxVertices >= 65534) { Debug.LogWarning ("To many vertices for unity to render - Unity might screw up rendering, but hopefully the navmesh will work ok"); //mesh = new VoxelMesh (); //yield break; //return; } //int[] vflags = new int[maxVertices]; Int3[] verts = new Int3[maxVertices]; int[] polys = new int[maxTris*nvp];//@Why *2*2 //int[] regs = new int[maxTris]; //int[] areas = new int[maxTris]; #if ASTAR_MEMCPY Pathfinding.Util.Memory.MemSet<int> (polys, 0xff, sizeof(int)); #else for (int i=0;i<polys.Length;i++) { polys[i] = 0xff; } #endif //int[] nexVert = new int[maxVertices]; //int[] firstVert = new int[VERTEX_BUCKET_COUNT]; int[] indices = new int[maxVertsPerCont]; int[] tris = new int[maxVertsPerCont*3]; //ushort[] polys int vertexIndex = 0; int polyIndex = 0; for (int i=0;i<cset.conts.Length;i++) { VoxelContour cont = cset.conts[i]; //Skip null contours if (cont.nverts < 3) { continue; } for (int j=0; j < cont.nverts;j++) { indices[j] = j; cont.verts[j*4+2] /= voxelArea.width; } //yield return (GameObject.FindObjectOfType (typeof(MonoBehaviour)) as MonoBehaviour).StartCoroutine ( //Triangulate (cont.nverts, cont.verts, indices, tris); int ntris = Triangulate (cont.nverts, cont.verts, ref indices, ref tris); /*if (ntris > cont.nverts-2) { Debug.LogError (ntris + " "+cont.nverts+" "+cont.verts.Length+" "+(cont.nverts-2)); } if (ntris > maxVertsPerCont) { Debug.LogError (ntris*3 + " "+maxVertsPerCont); } int tmp = polyIndex; Debug.Log (maxTris + " "+polyIndex+" "+polys.Length+" "+ntris+" "+(ntris*3) + " " + cont.nverts);*/ int startIndex = vertexIndex; for (int j=0;j<ntris*3; polyIndex++, j++) { //@Error sometimes polys[polyIndex] = tris[j]+startIndex; } /*int tmp2 = polyIndex; if (tmp+ntris*3 != tmp2) { Debug.LogWarning (tmp+" "+(tmp+ntris*3)+" "+tmp2+" "+ntris*3); }*/ for (int j=0;j<cont.nverts; vertexIndex++, j++) { verts[vertexIndex] = new Int3(cont.verts[j*4],cont.verts[j*4+1],cont.verts[j*4+2]); } } mesh = new VoxelMesh (); //yield break; Int3[] trimmedVerts = new Int3[vertexIndex]; for (int i=0;i<vertexIndex;i++) { trimmedVerts[i] = verts[i]; } int[] trimmedTris = new int[polyIndex]; #if ASTAR_MEMCPY System.Buffer.BlockCopy (polys, 0, trimmedTris, 0, polyIndex*sizeof(int)); #else for (int i=0;i<polyIndex;i++) { trimmedTris[i] = polys[i]; } #endif mesh.verts = trimmedVerts; mesh.tris = trimmedTris; /*for (int i=0;i<mesh.tris.Length/3;i++) { int p = i*3; int p1 = mesh.tris[p]; int p2 = mesh.tris[p+1]; int p3 = mesh.tris[p+2]; //Debug.DrawLine (ConvertPosCorrZ (mesh.verts[p1].x,mesh.verts[p1].y,mesh.verts[p1].z),ConvertPosCorrZ (mesh.verts[p2].x,mesh.verts[p2].y,mesh.verts[p2].z),Color.yellow); //Debug.DrawLine (ConvertPosCorrZ (mesh.verts[p1].x,mesh.verts[p1].y,mesh.verts[p1].z),ConvertPosCorrZ (mesh.verts[p3].x,mesh.verts[p3].y,mesh.verts[p3].z),Color.yellow); //Debug.DrawLine (ConvertPosCorrZ (mesh.verts[p3].x,mesh.verts[p3].y,mesh.verts[p3].z),ConvertPosCorrZ (mesh.verts[p2].x,mesh.verts[p2].y,mesh.verts[p2].z),Color.yellow); //Debug.DrawLine (ConvertPosCorrZ (verts[p1],0,verts[p1+2]),ConvertPosCorrZ (verts[p2],0,verts[p2+2]),Color.blue); //Debug.DrawLine (ConvertPosCorrZ (verts[p1],0,verts[p1+2]),ConvertPosCorrZ (verts[p3],0,verts[p3+2]),Color.blue); //Debug.DrawLine (ConvertPosCorrZ (verts[p2],0,verts[p2+2]),ConvertPosCorrZ (verts[p3],0,verts[p3+2]),Color.blue); }*/ }
private void DelaunayRefinement(Int3[] verts, int[] tris, ref int vCount, ref int tCount, bool delaunay, bool colinear, Int3 worldOffset) { if (tCount % 3 != 0) { throw new Exception("Triangle array length must be a multiple of 3"); } Dictionary <Int2, int> dictionary = this.cached_Int2_int_dict; dictionary.Clear(); for (int i = 0; i < tCount; i += 3) { if (!Polygon.IsClockwise(verts[tris[i]], verts[tris[i + 1]], verts[tris[i + 2]])) { int num = tris[i]; tris[i] = tris[i + 2]; tris[i + 2] = num; } dictionary[new Int2(tris[i], tris[i + 1])] = i + 2; dictionary[new Int2(tris[i + 1], tris[i + 2])] = i; dictionary[new Int2(tris[i + 2], tris[i])] = i + 1; } int num2 = 9; for (int j = 0; j < tCount; j += 3) { for (int k = 0; k < 3; k++) { int num3; if (dictionary.TryGetValue(new Int2(tris[j + (k + 1) % 3], tris[j + k % 3]), out num3)) { Int3 @int = verts[tris[j + (k + 2) % 3]]; Int3 int2 = verts[tris[j + (k + 1) % 3]]; Int3 int3 = verts[tris[j + (k + 3) % 3]]; Int3 int4 = verts[tris[num3]]; @int.y = 0; int2.y = 0; int3.y = 0; int4.y = 0; bool flag = false; if (!Polygon.Left(@int, int3, int4) || Polygon.LeftNotColinear(@int, int2, int4)) { if (!colinear) { goto IL_439; } flag = true; } if (colinear && AstarMath.DistancePointSegment(@int, int4, int2) < (float)num2 && !dictionary.ContainsKey(new Int2(tris[j + (k + 2) % 3], tris[j + (k + 1) % 3])) && !dictionary.ContainsKey(new Int2(tris[j + (k + 1) % 3], tris[num3]))) { tCount -= 3; int num4 = num3 / 3 * 3; tris[j + (k + 1) % 3] = tris[num3]; if (num4 != tCount) { tris[num4] = tris[tCount]; tris[num4 + 1] = tris[tCount + 1]; tris[num4 + 2] = tris[tCount + 2]; dictionary[new Int2(tris[num4], tris[num4 + 1])] = num4 + 2; dictionary[new Int2(tris[num4 + 1], tris[num4 + 2])] = num4; dictionary[new Int2(tris[num4 + 2], tris[num4])] = num4 + 1; tris[tCount] = 0; tris[tCount + 1] = 0; tris[tCount + 2] = 0; } else { tCount += 3; } dictionary[new Int2(tris[j], tris[j + 1])] = j + 2; dictionary[new Int2(tris[j + 1], tris[j + 2])] = j; dictionary[new Int2(tris[j + 2], tris[j])] = j + 1; } else if (delaunay && !flag) { float num5 = Int3.Angle(int2 - @int, int3 - @int); float num6 = Int3.Angle(int2 - int4, int3 - int4); if (num6 > 6.28318548f - 2f * num5) { tris[j + (k + 1) % 3] = tris[num3]; int num7 = num3 / 3 * 3; int num8 = num3 - num7; tris[num7 + (num8 - 1 + 3) % 3] = tris[j + (k + 2) % 3]; dictionary[new Int2(tris[j], tris[j + 1])] = j + 2; dictionary[new Int2(tris[j + 1], tris[j + 2])] = j; dictionary[new Int2(tris[j + 2], tris[j])] = j + 1; dictionary[new Int2(tris[num7], tris[num7 + 1])] = num7 + 2; dictionary[new Int2(tris[num7 + 1], tris[num7 + 2])] = num7; dictionary[new Int2(tris[num7 + 2], tris[num7])] = num7 + 1; } } } IL_439 :; } } }
public static Int3 Transform(ref Int3 point, ref Int3 axis_x, ref Int3 axis_y, ref Int3 axis_z, ref Int3 trans, ref Int3 scale) { long num = point.x * scale.x; long num2 = point.y * scale.x; long num3 = point.z * scale.x; return(new Int3(((int)Divide((long)(((axis_x.x * num) + (axis_y.x * num2)) + (axis_z.x * num3)), (long)0xf4240L)) + trans.x, ((int)Divide((long)(((axis_x.y * num) + (axis_y.y * num2)) + (axis_z.y * num3)), (long)0xf4240L)) + trans.y, ((int)Divide((long)(((axis_x.z * num) + (axis_y.z * num2)) + (axis_z.z * num3)), (long)0xf4240L)) + trans.z)); }
public static Vector3 ToVector3(this Int3 lhs) => new(lhs.X, lhs.Y, lhs.Z);
public ID(int[] array, int offset) { ShardID = new Int3(array, offset); Generation = array[offset + 3]; }
public void GetOverlaps( Vector3 gridPosition, BoundingBox boundingBox, ref QuickList<Int3> overlaps ) { Vector3.Subtract( ref boundingBox.Min, ref gridPosition, out boundingBox.Min ); Vector3.Subtract( ref boundingBox.Max, ref gridPosition, out boundingBox.Max ); var inverseWidth = 1f / CellWidth; var min = new Int3 { X = Math.Max( 0, (uint)( boundingBox.Min.X * inverseWidth ) ), Y = Math.Max( 0, (uint)( boundingBox.Min.Y * inverseWidth ) ), Z = Math.Max( 0, (uint)( boundingBox.Min.Z * inverseWidth ) ) }; var max = new Int3 { X = Math.Min( VoxelSector.ZVOXELBLOCSIZE_X - 1, (uint)( boundingBox.Max.X * inverseWidth ) ), Y = Math.Min( VoxelSector.ZVOXELBLOCSIZE_Y - 1, (uint)( boundingBox.Max.Y * inverseWidth ) ), Z = Math.Min( VoxelSector.ZVOXELBLOCSIZE_Z - 1, (uint)( boundingBox.Max.Z * inverseWidth ) ) }; for( uint i = min.X; i <= max.X; ++i ) { for( uint j = min.Y; j <= max.Y; ++j ) { for( uint k = min.Z; k <= max.Z; ++k ) { uint offset = i * VoxelSector.ZVOXELBLOCSIZE_Y + j + k * VoxelSector.ZVOXELBLOCSIZE_X * VoxelSector.ZVOXELBLOCSIZE_Y; if( Cells[offset] != VoxelShape.Empty ) { overlaps.Add( new Int3 { X = i, Y = j, Z = k } ); } } } } }
public ID(Int3 shardID, int generation) { this.ShardID = shardID; this.Generation = generation; }
/** Checks if \a p is inside the node * * The default implementation uses XZ space and is in large part got from the website linked below * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5) */ public virtual bool ContainsPoint (Int3 p) { bool inside = false; int count = GetVertexCount(); for (int i = 0, j=count-1; i < count; j = i++) { if ( ((GetVertex(i).z <= p.z && p.z < GetVertex(j).z) || (GetVertex(j).z <= p.z && p.z < GetVertex(i).z)) && (p.x < (GetVertex(j).x - GetVertex(i).x) * (p.z - GetVertex(i).z) / (GetVertex(j).z - GetVertex(i).z) + GetVertex(i).x)) inside = !inside; } return inside; }
public float RealVoxelSize() { Int3 resolution = Resolution(); return(Extents.X / (float)resolution.X); }
public void FillWithNode (Node node, Int3 pos,int w) { Grid grid = grids[pos.y]; for (int x=pos.x;x<pos.x+w;x++) { for (int z=pos.z;z<pos.z+w;z++) { if (x >= grid.width || z >= grid.depth) { Debug.LogError ("Out of range!! X: "+x+" Z: "+z+" Pos: "+pos+" Width: "+w); } staticNodes[pos.y][x,z] = node; } } }
public void Uniform3(int location, Int3 value) { GL.Uniform3(location, value.X, value.Y, value.Z); }
public void PostNew (Int3 startPos,Int3 endPos) { float startTime = Time.realtimeSinceStartup; realStartTime = startTime; if (startPos == new Int3 (-1,-1,-1)) { Debug.LogWarning ("Start Point : No nearby Nodes Were found (Position not inside any grids or no nodes were close enough"); error = true; return; } if (endPos == new Int3 (-1,-1,-1)) { Debug.LogWarning ("Target Point : No nearby Nodes Were found (Position not inside any grids or no nodes were close enough"); error = true; return; } start = GetNode (startPos); end = GetNode (endPos); if (!start.walkable) { start = GetNearest (start,true,120); if (start == null) { Debug.LogWarning ("Cannot find any valid start nodes (the start is on unwalkable ground)"); } forceStartSnap = true; /*if (start.enabledConnections.Length > 0) { start = start.enabledConnections[0]; Debug.LogWarning ("Start point is not walkable, setting a node close to start as start"); } else { Debug.LogWarning ("Starting from non walkable node"); error= true; return; }*/ } current = start; if (!end.walkable || end.area != start.area) { end = GetNearest (end,true,start.area,400); if (end == null) { Debug.LogWarning ("Cannot find any valid target nodes"); error = true; return; } if (end.area != start.area) { Debug.LogError ("WUT!!?!?"); } forceEndSnap = true; /*if (end.enabledConnections.Length > 0) { end = end.enabledConnections[0]; Debug.LogWarning ("Target point is not walkable, setting a node close to target as target"); } else { Debug.LogWarning ("Target point is not walkable"); error= true; return; }*/ } if (end.area != start.area) { Debug.LogWarning ("We can't walk from start to end, differend areas"); error= true; return; } t += Time.realtimeSinceStartup-startTime; }
private void HighlightGUI() { if (HighlightTF && ( Event.current.type == EventType.MouseMove || (Event.current.type == EventType.MouseDrag && Event.current.button == 0) || Event.current.type == EventType.MouseUp || Event.current.type == EventType.ScrollWheel || Event.current.type == EventType.MouseDown )) { HoveringVoxelPosition = null; if (!ViewRect.Contains(Event.current.mousePosition)) { if (HighlightTF.gameObject.activeSelf) { HighlightTF.gameObject.SetActive(false); Repaint(); } return; } ViewCastHit((hit) => { string hitName = hit.transform.name; if (hitName == "Cube") { // Cube HighlightTF.gameObject.SetActive(true); HighlightTF.position = hit.point; HighlightTF.localScale = hit.transform.localScale * 0.5f; HighlightTF.rotation = Quaternion.LookRotation(-hit.normal); Repaint(); } else if (IsRigging) { if (PaintingBoneIndex == -1 || CurrentBrushType == BrushType.Rect) { if (HighlightTF.gameObject.activeSelf) { HighlightTF.gameObject.SetActive(false); Repaint(); } } else { // Editing Bone if (hitName == "Voxel") { HighlightTF.gameObject.SetActive(true); HighlightTF.position = hit.transform.position; HighlightTF.localScale = hit.transform.localScale; HighlightTF.rotation = Quaternion.LookRotation(-hit.normal); HoveringVoxelPosition = hit.transform.parent.localPosition; HoveredVoxelPosition = HoveringVoxelPosition; Repaint(); } else if (hitName == "Box") { HighlightTF.gameObject.SetActive(true); int maxAxis = Util.MaxAxis(hit.normal); Vector3 offset = ContainerTF.position; var newPos = new Vector3( Mathf.Round(hit.point.x - offset.x) + offset.x, Mathf.Round(hit.point.y - offset.y) + offset.y, Mathf.Round(hit.point.z - offset.z) + offset.z ); newPos[maxAxis] = hit.point[maxAxis]; HighlightTF.position = newPos; HighlightTF.localScale = Vector3.one; HighlightTF.rotation = Quaternion.LookRotation(-hit.normal); HoveringVoxelPosition = HighlightTF.localPosition - ContainerTF.localPosition; HoveredVoxelPosition = HoveringVoxelPosition; Repaint(); } else { if (HighlightTF.gameObject.activeSelf) { HighlightTF.gameObject.SetActive(false); Repaint(); } } } } else { if (HighlightTF.gameObject.activeSelf) { HighlightTF.gameObject.SetActive(false); Repaint(); } } }, () => { if (HighlightTF.gameObject.activeSelf) { HighlightTF.gameObject.SetActive(false); Repaint(); } }); } }
public static SharpDX.Direct3D11.Buffer CreateVertexBuffer(Device device, RoomAliveToolkit.Kinect2Calibration kinect2Calibration) { // generate depthFrameToCameraSpace table var depthFrameToCameraSpaceTable = kinect2Calibration.ComputeDepthFrameToCameraSpaceTable(Kinect2Calibration.depthImageWidth, Kinect2Calibration.depthImageHeight); int numVertices = 6 * (Kinect2Calibration.depthImageWidth - 1) * (Kinect2Calibration.depthImageHeight - 1); var vertices = new VertexPosition[numVertices]; Int3[] quadOffsets = new Int3[] { new Int3(0, 0, 0), new Int3(1, 0, 0), new Int3(0, 1, 0), new Int3(1, 0, 0), new Int3(1, 1, 0), new Int3(0, 1, 0), }; int vertexIndex = 0; for (int y = 0; y < Kinect2Calibration.depthImageHeight - 1; y++) for (int x = 0; x < Kinect2Calibration.depthImageWidth - 1; x++) for (int i = 0; i < 6; i++) { int vertexX = x + quadOffsets[i].X; int vertexY = y + quadOffsets[i].Y; var point = depthFrameToCameraSpaceTable[Kinect2Calibration.depthImageWidth * vertexY + vertexX]; var vertex = new VertexPosition(); vertex.position = new SharpDX.Vector4(point.X, point.Y, vertexX, vertexY); vertices[vertexIndex++] = vertex; } var stream = new DataStream(numVertices * VertexPosition.SizeInBytes, true, true); stream.WriteRange(vertices); stream.Position = 0; var vertexBufferDesc = new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, Usage = ResourceUsage.Default, SizeInBytes = numVertices * VertexPosition.SizeInBytes, }; var vertexBuffer = new SharpDX.Direct3D11.Buffer(device, stream, vertexBufferDesc); stream.Dispose(); return vertexBuffer; }
public Int3 GetCellSize(Int3 blocksPerBatch) { return(GetCellSize(Level, blocksPerBatch)); }