public static void AddToDirQueue(int3 dir) { //lock (qShiftDirection) //{ qShiftDirection.Enqueue(dir); //} }
public bool Equals(int3 other) { return (x == other.x && y == other.y && z == other.z); //return (other != null && // other.CustId == this.CustId && // other.CustName == this.CustName); }
public KernelThreadException(IKernel kernel, dim3? gridDim, int3? blockIdx, dim3? blockDim, int3? threadIdx, String workerThread, Exception innerException) : base(null, innerException) { Kernel = kernel.AssertNotNull(); GridDim = gridDim; BlockIdx = blockIdx; BlockDim = blockDim; ThreadIdx = threadIdx; WorkerThread = workerThread.AssertNotNull(); }
public static bool chunkArrayContainsKey(int3 key) { if (key.x >= CONST.worldChunkCount.x || key.y >= CONST.worldChunkCount.y || key.z >= CONST.worldChunkCount.z) { return false; } if (key.x < 0 || key.y < 0 || key.z < 0) { return false; } return true; }
public static int3 GetFromDirQueue() { int3 dir; //lock (qShiftDirection) //{ if (qShiftDirection.Count > 0) { dir = (int3)qShiftDirection.Dequeue(); } else { Debug.Log("GetFromDirQueue was null"); dir = new int3(0, 0, 0); } //} return dir; }
//Get the block positions and stuff here. Do not draw them yet though. public Chunk(int3 chunkposwrld) { chunkOffset = new int3(0, 0, 0); chunkPosWorld = chunkposwrld; Vector3 chunkSize = new Vector3(CONST.chunkSize.x, CONST.chunkSize.y, CONST.chunkSize.z); blockOffset.x = chunkposwrld.x * (chunkSize.x * ((chunkSize.x - 1) / chunkSize.x)); blockOffset.y = chunkposwrld.y * (chunkSize.y * ((chunkSize.y - 1) / chunkSize.y)); blockOffset.z = chunkposwrld.z * (chunkSize.z * ((chunkSize.z - 1) / chunkSize.z)); //Debug.Log(blockOffset.x + " " + blockOffset.y + " " + blockOffset.z); //Debug.Log(cvhdhsdv.x + " " + cvhdhsdv.y + " " + cvhdhsdv.z); //Debug.Log(CONST.chunkSize.x + " " + CONST.chunkSize.y + " " + CONST.chunkSize.z); blocksArray = new BlockType[CONST.chunkSize.x * CONST.chunkSize.y * CONST.chunkSize.z]; //Call the terrain generator. Terrain generator simply tells what blocktypes to put and where. //GenericChunkGen.GenerateChunk(this); TerraGen.CreateLandscape(this); }
/// <summary> /// Increases the voxel data at <paramref name="localPosition"/> by <paramref name="increaseAmount"/>. If <paramref name="localPosition"/> is out of <see cref="Size"/>, an <see cref="IndexOutOfRangeException"/> will be thrown. /// </summary> /// <param name="increaseAmount">How much the voxel data at <paramref name="localPosition"/> should be increased by</param> /// <param name="localPosition">The local position of the voxel data to increase</param> public void IncreaseVoxelData(float increaseAmount, int3 localPosition) { int index = IndexUtilities.XyzToIndex(localPosition, Width, Height); IncreaseVoxelData(increaseAmount, index); }
public void Combine(ref int3 curr, ref int3 value) { curr += value; }
/// <summary> /// Creates a <see cref="VoxelDataVolume"/> /// </summary> /// <param name="size">The 3-dimensional size of this volume</param> /// <param name="allocator">How the memory should be allocated</param> /// <exception cref="ArgumentException">Thrown when any of the dimensions is negative</exception> public VoxelDataVolume(int3 size, Allocator allocator) : this(size.x, size.y, size.z, allocator) { }
/// <summary> /// Tries to get the voxel data at <paramref name="localPosition"/>. If the data exists at <paramref name="localPosition"/>, true will be returned and <paramref name="voxelData"/> will be set to the value (range [0, 1]). If it doesn't exist, false will be returned and <paramref name="voxelData"/> will be set to 0. /// </summary> /// <param name="localPosition">The local position of the voxel data to get</param> /// <param name="voxelData">A voxel data in the range [0, 1] at <paramref name="localPosition"/></param> /// <returns>Does a voxel data point exist at <paramref name="localPosition"/></returns> public bool TryGetVoxelData(int3 localPosition, out float voxelData) { return(TryGetVoxelData(localPosition.x, localPosition.y, localPosition.z, out voxelData)); }
private void zdir(float dirz) { GameObject placeHolder; if (dirz >= 1) { for (int iter = 0; iter < dirz; iter++) { for (int x = 0; x < arraySize.x; x++) { for (int y = 0; y < arraySize.y; y++) { placeHolder = boxColliderGOs[x, y, 0]; for (int z = 0; z < arraySize.z - 1; z++) { boxColliderGOs[x, y, z] = boxColliderGOs[x, y, z + 1]; } placeHolder.transform.position = new Vector3( placeHolder.transform.position.x, placeHolder.transform.position.y, placeHolder.transform.position.z + arraySize.z); int xa = Mathf.CeilToInt(placeHolder.transform.position.x) - 1; int ya = Mathf.CeilToInt(placeHolder.transform.position.y) - 1; int za = Mathf.CeilToInt(placeHolder.transform.position.z) - 1; //Vector3 chunkcoords = new Vector3(0, 0, 0); int3 chunkcoords = new int3(0, 0, 0); int3 blockcoords = new int3(0, 0, 0); int3 offset = InfiniteWorld.ChunkWorldPositionOffset; /* chunkcoords.x = Mathf.CeilToInt(((float)xa / (float)chunkSize.x - (float)offset.x)) - 1; chunkcoords.y = Mathf.CeilToInt(((float)ya / (float)chunkSize.y - (float)offset.y)) - 1; chunkcoords.z = Mathf.CeilToInt(((float)za / (float)chunkSize.z - (float)offset.z)) - 1; */ chunkcoords.x = xa / chunkSize.x - offset.x; chunkcoords.y = ya / chunkSize.y - offset.y; chunkcoords.z = za / chunkSize.z - offset.z; //Debug.Log(xa + " " + chunkcoords.x + " " + chunkSize.x + " " + offset.x); if (WorldInitializer.chunkArrayContainsKey(chunkcoords)) { blockcoords.x = xa % chunkSize.x; blockcoords.y = ya % chunkSize.y; blockcoords.z = za % chunkSize.z; if (blockcoords.x < 0) { blockcoords.x = chunkSize.x - Math.Abs(blockcoords.x); chunkcoords.x -= 1; } if (blockcoords.y < 0) { blockcoords.y = chunkSize.y - Math.Abs(blockcoords.y); chunkcoords.y -= 1; } if (blockcoords.z < 0) { blockcoords.z = chunkSize.z - Math.Abs(blockcoords.z); chunkcoords.z -= 1; } if (chunkcoords.x < 0 || chunkcoords.y < 0 || chunkcoords.z < 0) { placeHolder.GetComponent<BoxCollider>().enabled = false; } else { blockTypes[x, y, arraySize.z - 1] = WorldInitializer.chunkArray[chunkcoords.x, chunkcoords.y, chunkcoords.z]. blocks[blockcoords.x, blockcoords.y, blockcoords.z].blockType; if (blockTypes[x, y, arraySize.z - 1] != BlockType.Air) { placeHolder.GetComponent<BoxCollider>().enabled = true; } else { placeHolder.GetComponent<BoxCollider>().enabled = false; } } } else { placeHolder.GetComponent<BoxCollider>().enabled = false; } boxColliderGOs[x, y, arraySize.z - 1] = placeHolder; } } } } if (dirz <= -1) { for (int iter = 0; iter > dirz; iter--) { for (int y = 0; y < arraySize.y; y++) { for (int x = 0; x < arraySize.x; x++) { placeHolder = boxColliderGOs[x, y, arraySize.z - 1]; for (int z = arraySize.z - 1; z > 0; z--) { boxColliderGOs[x, y, z] = boxColliderGOs[x, y, z - 1]; } placeHolder.transform.position = new Vector3( placeHolder.transform.position.x, placeHolder.transform.position.y, placeHolder.transform.position.z - arraySize.z); int xa = Mathf.CeilToInt(placeHolder.transform.position.x) - 1; int ya = Mathf.CeilToInt(placeHolder.transform.position.y) - 1; int za = Mathf.CeilToInt(placeHolder.transform.position.z) - 1; int3 chunkcoords = new int3(0, 0, 0); int3 blockcoords = new int3(0, 0, 0); int3 offset = InfiniteWorld.ChunkWorldPositionOffset; /* chunkcoords.x = Mathf.CeilToInt(((float)xa / (float)chunkSize.x - (float)offset.x)) - 1; chunkcoords.y = Mathf.CeilToInt(((float)ya / (float)chunkSize.y - (float)offset.y)) - 1; chunkcoords.z = Mathf.CeilToInt(((float)za / (float)chunkSize.z - (float)offset.z)) - 1; */ chunkcoords.x = xa / chunkSize.x - offset.x; chunkcoords.y = ya / chunkSize.y - offset.y; chunkcoords.z = za / chunkSize.z - offset.z; if (WorldInitializer.chunkArrayContainsKey(chunkcoords)) { blockcoords.x = xa % chunkSize.x; blockcoords.y = ya % chunkSize.y; blockcoords.z = za % chunkSize.z; if (blockcoords.x < 0) { blockcoords.x = chunkSize.x - Math.Abs(blockcoords.x); chunkcoords.x -= 1; } if (blockcoords.y < 0) { blockcoords.y = chunkSize.y - Math.Abs(blockcoords.y); chunkcoords.y-= 1; } if (blockcoords.z < 0) { blockcoords.z = chunkSize.z - Math.Abs(blockcoords.z); chunkcoords.z -= 1; } if (chunkcoords.x < 0 || chunkcoords.y < 0 || chunkcoords.z < 0) { placeHolder.GetComponent<BoxCollider>().enabled = false; } else { blockTypes[x, y, 0] = WorldInitializer.chunkArray[chunkcoords.x, chunkcoords.y, chunkcoords.z]. blocks[blockcoords.x, blockcoords.y, blockcoords.z].blockType; //Debug.Log(chunkcoords.x + " " + chunkcoords.y + " " + chunkcoords.z); //Debug.Log(blockcoords.x + " " + blockcoords.y + " " + blockcoords.z); if (blockTypes[x, y, 0] != BlockType.Air) { placeHolder.GetComponent<BoxCollider>().enabled = true; } else { placeHolder.GetComponent<BoxCollider>().enabled = false; } } } boxColliderGOs[x, y, 0] = placeHolder; } } } } }
public static int DownDimension(int3 coord, int2 xysize) { return(coord.z * xysize.y * xysize.x + coord.y * xysize.x + coord.x); }
static bool BoundaryCheck(int chunkSize, int3 position) { return(chunkSize > position.x && chunkSize > position.y && chunkSize > position.z && position.x >= 0 && position.y >= 0 && position.z >= 0); }
public static extern int mono_return_int3 (int3 s, int addend);
public void Execute() { for (int direction = 0; direction < 6; direction++) { for (int depth = 0; depth < chunkSize; depth++) { for (int x = 0; x < chunkSize; x++) { for (int y = 0; y < chunkSize;) { int3 gridPosition = new int3 { [DirectionAlignedX[direction]] = x, [DirectionAlignedY[direction]] = y, [DirectionAlignedZ[direction]] = depth }; int index = VoxelUtil.To1DIndex(gridPosition, chunkSize); Voxel voxel = voxels[index]; VoxelLight light = lightData[index]; if (voxel.data == Voxel.VoxelType.Air) { y++; continue; } int3 neighborPosition = gridPosition + VoxelDirectionOffsets[direction]; if (TransparencyCheck(voxels, neighborPosition, chunkSize)) { y++; continue; } int height; for (height = 1; height + y < chunkSize; height++) { int3 nextPosition = gridPosition; nextPosition[DirectionAlignedY[direction]] += height; int nextIndex = VoxelUtil.To1DIndex(nextPosition, chunkSize); Voxel nextVoxel = voxels[nextIndex]; VoxelLight nextLight = lightData[nextIndex]; if (nextVoxel.data != voxel.data) { break; } if (!light.CompareFace(nextLight, direction)) { break; } } AddQuadByDirection(direction, voxel.data, light, 1.0f, height, gridPosition, counter, vertices, normals, uvs, colors, indices); y += height; } } } } }
public void Execute() { NativeHashMap <int3, Empty> hashMap = new NativeHashMap <int3, Empty>(chunkSize * chunkSize, Allocator.Temp); for (int direction = 0; direction < 6; direction++) { for (int depth = 0; depth < chunkSize; depth++) { for (int x = 0; x < chunkSize; x++) { for (int y = 0; y < chunkSize;) { int3 gridPosition = new int3 { [DirectionAlignedX[direction]] = x, [DirectionAlignedY[direction]] = y, [DirectionAlignedZ[direction]] = depth }; Voxel voxel = voxels[VoxelUtil.To1DIndex(gridPosition, chunkSize)]; if (voxel.data == Voxel.VoxelType.Air) { y++; continue; } if (hashMap.ContainsKey(gridPosition)) { y++; continue; } int3 neighborPosition = gridPosition + VoxelDirectionOffsets[direction]; if (TransparencyCheck(voxels, neighborPosition, chunkSize)) { y++; continue; } VoxelLight light = lightData[VoxelUtil.To1DIndex(gridPosition, chunkSize)]; hashMap.TryAdd(gridPosition, new Empty()); int height; for (height = 1; height + y < chunkSize; height++) { int3 nextPosition = gridPosition; nextPosition[DirectionAlignedY[direction]] += height; Voxel nextVoxel = voxels[VoxelUtil.To1DIndex(nextPosition, chunkSize)]; VoxelLight nextLight = lightData[VoxelUtil.To1DIndex(nextPosition, chunkSize)]; if (nextVoxel.data != voxel.data) { break; } if (!nextLight.CompareFace(light, direction)) { break; } if (hashMap.ContainsKey(nextPosition)) { break; } hashMap.TryAdd(nextPosition, new Empty()); } bool isDone = false; int width; for (width = 1; width + x < chunkSize; width++) { for (int dy = 0; dy < height; dy++) { int3 nextPosition = gridPosition; nextPosition[DirectionAlignedX[direction]] += width; nextPosition[DirectionAlignedY[direction]] += dy; Voxel nextVoxel = voxels[VoxelUtil.To1DIndex(nextPosition, chunkSize)]; VoxelLight nextLight = lightData[VoxelUtil.To1DIndex(nextPosition, chunkSize)]; if (nextVoxel.data != voxel.data || hashMap.ContainsKey(nextPosition) || !nextLight.CompareFace(light, direction)) { isDone = true; break; } } if (isDone) { break; } for (int dy = 0; dy < height; dy++) { int3 nextPosition = gridPosition; nextPosition[DirectionAlignedX[direction]] += width; nextPosition[DirectionAlignedY[direction]] += dy; hashMap.TryAdd(nextPosition, new Empty()); } } AddQuadByDirection(direction, voxel.data, light, width, height, gridPosition, counter, vertices, normals, uvs, colors, indices); y += height; } } hashMap.Clear(); } } hashMap.Dispose(); }
public CubicGrid(int3 dimensions, float valueMin, float valueMax, Dimension gradientDirection, bool centeredSpacing = false) { Dimensions = dimensions; DimensionSet = GetDimensions(Dimensions); if (centeredSpacing) { Margins = new float3(1f / Dimensions.X, 1f / Dimensions.Y, 1f / Dimensions.Z) / 2; if (Dimensions.X == 1) { Margins.X = 0; } if (Dimensions.Y == 1) { Margins.Y = 0; } if (Dimensions.Z == 1) { Margins.Z = 0; } } float Step = valueMax - valueMin; if (gradientDirection == Dimension.X) { Step /= Math.Max(1, dimensions.X - 1); } else if (gradientDirection == Dimension.Y) { Step /= Math.Max(1, dimensions.Y - 1); } else if (gradientDirection == Dimension.Z) { Step /= Math.Max(1, dimensions.Z - 1); } Values = new float[dimensions.Elements()]; for (int z = 0; z < dimensions.Z; z++) { for (int y = 0; y < dimensions.Y; y++) { for (int x = 0; x < dimensions.X; x++) { float Value = valueMin; if (gradientDirection == Dimension.X) { Value += x * Step; } if (gradientDirection == Dimension.Y) { Value += y * Step; } if (gradientDirection == Dimension.Z) { Value += z * Step; } Values[(z * Dimensions.Y + y) * Dimensions.X + x] = Value; } } } Einspline = MakeEinspline(Values, Dimensions, Margins); }
public float[] GetInterpolatedNative(int3 valueGrid, float3 border) { return(GetInterpolated(valueGrid, border)); }
public static int CoordToIndex(int3 coord) { return(coord.z * WorldSettings.chunkDimension.x * WorldSettings.chunkDimension.y + coord.y * WorldSettings.chunkDimension.x + coord.x); }
public static Vector3 ToVector3(int3 v) => new Vector3(v.x, v.y, v.z);
static unsafe void AddQuadByDirection(int direction, Voxel.VoxelType data, VoxelLight voxelLight, float width, float height, int3 gridPosition, NativeCounter.Concurrent counter, NativeArray <float3> vertices, NativeArray <float3> normals, NativeArray <float4> uvs, NativeArray <Color> colors, NativeArray <int> indices) { int numFace = counter.Increment(); int numVertices = numFace * 4; for (int i = 0; i < 4; i++) { float3 vertex; vertex = CubeVertices[CubeFaces[i + direction * 4]]; vertex[DirectionAlignedX[direction]] *= width; vertex[DirectionAlignedY[direction]] *= height; int atlasIndex = (int)data * 6 + direction; int2 atlasPosition = new int2 { x = atlasIndex % AtlasSize.x, y = atlasIndex / AtlasSize.x }; float4 uv = new float4 { x = CubeUVs[i].x * width, y = CubeUVs[i].y * height, z = atlasPosition.x, w = atlasPosition.y }; colors[numVertices + i] = new Color(0, 0, 0, voxelLight.ambient[i + direction * 4]); vertices[numVertices + i] = vertex + gridPosition; normals[numVertices + i] = VoxelDirectionOffsets[direction]; uvs[numVertices + i] = uv; } int numindices = numFace * 6; for (int i = 0; i < 6; i++) { if (voxelLight.ambient[direction * 4] + voxelLight.ambient[direction * 4 + 3] < voxelLight.ambient[direction * 4 + 1] + voxelLight.ambient[direction * 4 + 2]) { indices[numindices + i] = CubeFlipedIndices[direction * 6 + i] + numVertices; } else { indices[numindices + i] = CubeIndices[direction * 6 + i] + numVertices; } } }
void Start() { player = GameObject.FindGameObjectWithTag("Player"); middle = new Vector3((CONST.worldChunkCount.x * CONST.chunkSize.x) / 2 + (CONST.chunkSize.x) / 2, (CONST.worldChunkCount.y * CONST.chunkSize.y) / 2 + (CONST.chunkSize.y) / 2, (CONST.worldChunkCount.z * CONST.chunkSize.z) / 2 + (CONST.chunkSize.z) / 2); player.transform.position = middle; playerChunkPosOld = getPlayerChunkPos(); }
public void Execute(int index) { // Convert from [-0.5,0.5] space to [0,1] var sourcePosition = transform(meshToTarget, vertices[index]) + float3(0.5f, 0.5f, 0.5f); // Determine the negative corner of the lattice cell containing the source position var negativeCorner = new int3((int)(sourcePosition.x * (resolution.x - 1)), (int)(sourcePosition.y * (resolution.y - 1)), (int)(sourcePosition.z * (resolution.z - 1))); // Clamp the corner to an acceptable range in case the source vertex is outside or on the lattice bounds negativeCorner = max(negativeCorner, new int3(0, 0, 0)); negativeCorner = min(negativeCorner, resolution - new int3(2, 2, 2)); int index0 = (negativeCorner.x + 0) + (negativeCorner.y + 0) * resolution.x + (negativeCorner.z + 0) * (resolution.x * resolution.y); int index1 = (negativeCorner.x + 1) + (negativeCorner.y + 0) * resolution.x + (negativeCorner.z + 0) * (resolution.x * resolution.y); int index2 = (negativeCorner.x + 0) + (negativeCorner.y + 1) * resolution.x + (negativeCorner.z + 0) * (resolution.x * resolution.y); int index3 = (negativeCorner.x + 1) + (negativeCorner.y + 1) * resolution.x + (negativeCorner.z + 0) * (resolution.x * resolution.y); int index4 = (negativeCorner.x + 0) + (negativeCorner.y + 0) * resolution.x + (negativeCorner.z + 1) * (resolution.x * resolution.y); int index5 = (negativeCorner.x + 1) + (negativeCorner.y + 0) * resolution.x + (negativeCorner.z + 1) * (resolution.x * resolution.y); int index6 = (negativeCorner.x + 0) + (negativeCorner.y + 1) * resolution.x + (negativeCorner.z + 1) * (resolution.x * resolution.y); int index7 = (negativeCorner.x + 1) + (negativeCorner.y + 1) * resolution.x + (negativeCorner.z + 1) * (resolution.x * resolution.y); var localizedSourcePosition = (sourcePosition) * (resolution - new int3(1, 1, 1)) - negativeCorner; // Clamp the local position outside of the bounds so that our interpolation outside the lattice is clamped localizedSourcePosition = clamp(localizedSourcePosition, float3.zero, new float3(1, 1, 1)); var newPosition = float3.zero; // X-Axis if (sourcePosition.x < 0) { // Outside of lattice (negative in axis) var min1 = lerp(controlPoints[index0].x, controlPoints[index2].x, localizedSourcePosition.y); var min2 = lerp(controlPoints[index4].x, controlPoints[index6].x, localizedSourcePosition.y); var min = lerp(min1, min2, localizedSourcePosition.z); newPosition.x = sourcePosition.x + min; } else if (sourcePosition.x > 1) { // Outside of lattice (positive in axis) var max1 = lerp(controlPoints[index1].x, controlPoints[index3].x, localizedSourcePosition.y); var max2 = lerp(controlPoints[index5].x, controlPoints[index7].x, localizedSourcePosition.y); var max = lerp(max1, max2, localizedSourcePosition.z); newPosition.x = sourcePosition.x + max - 1; } else { // Inside lattice var min1 = lerp(controlPoints[index0].x, controlPoints[index2].x, localizedSourcePosition.y); var max1 = lerp(controlPoints[index1].x, controlPoints[index3].x, localizedSourcePosition.y); var min2 = lerp(controlPoints[index4].x, controlPoints[index6].x, localizedSourcePosition.y); var max2 = lerp(controlPoints[index5].x, controlPoints[index7].x, localizedSourcePosition.y); var min = lerp(min1, min2, localizedSourcePosition.z); var max = lerp(max1, max2, localizedSourcePosition.z); newPosition.x = lerp(min, max, localizedSourcePosition.x); } // Y-Axis if (sourcePosition.y < 0) { // Outside of lattice (negative in axis) var min1 = lerp(controlPoints[index0].y, controlPoints[index1].y, localizedSourcePosition.x); var min2 = lerp(controlPoints[index4].y, controlPoints[index5].y, localizedSourcePosition.x); var min = lerp(min1, min2, localizedSourcePosition.z); newPosition.y = sourcePosition.y + min; } else if (sourcePosition.y > 1) { // Outside of lattice (positive in axis) var max1 = lerp(controlPoints[index2].y, controlPoints[index3].y, localizedSourcePosition.x); var max2 = lerp(controlPoints[index6].y, controlPoints[index7].y, localizedSourcePosition.x); var max = lerp(max1, max2, localizedSourcePosition.z); newPosition.y = sourcePosition.y + max - 1; } else { var min1 = lerp(controlPoints[index0].y, controlPoints[index1].y, localizedSourcePosition.x); var max1 = lerp(controlPoints[index2].y, controlPoints[index3].y, localizedSourcePosition.x); var min2 = lerp(controlPoints[index4].y, controlPoints[index5].y, localizedSourcePosition.x); var max2 = lerp(controlPoints[index6].y, controlPoints[index7].y, localizedSourcePosition.x); var min = lerp(min1, min2, localizedSourcePosition.z); var max = lerp(max1, max2, localizedSourcePosition.z); newPosition.y = lerp(min, max, localizedSourcePosition.y); } // Z-Axis if (sourcePosition.z < 0) { // Outside of lattice (negative in axis) var min1 = lerp(controlPoints[index0].z, controlPoints[index1].z, localizedSourcePosition.x); var min2 = lerp(controlPoints[index2].z, controlPoints[index3].z, localizedSourcePosition.x); var min = lerp(min1, min2, localizedSourcePosition.y); newPosition.z = sourcePosition.z + min; } else if (sourcePosition.z > 1) { // Outside of lattice (positive in axis) var max1 = lerp(controlPoints[index4].z, controlPoints[index5].z, localizedSourcePosition.x); var max2 = lerp(controlPoints[index6].z, controlPoints[index7].z, localizedSourcePosition.x); var max = lerp(max1, max2, localizedSourcePosition.y); newPosition.z = sourcePosition.z + max - 1; } else { var min1 = lerp(controlPoints[index0].z, controlPoints[index1].z, localizedSourcePosition.x); var max1 = lerp(controlPoints[index4].z, controlPoints[index5].z, localizedSourcePosition.x); var min2 = lerp(controlPoints[index2].z, controlPoints[index3].z, localizedSourcePosition.x); var max2 = lerp(controlPoints[index6].z, controlPoints[index7].z, localizedSourcePosition.x); var min = lerp(min1, min2, localizedSourcePosition.y); var max = lerp(max1, max2, localizedSourcePosition.y); newPosition.z = lerp(min, max, localizedSourcePosition.z); } vertices[index] = transform(targetToMesh, newPosition); }
public static extern CUResult cuMemcpyDtoH_v2(ref int3 dstHost, CUdeviceptr srcDevice, SizeT ByteCount);
static Image LoadAndPrepareStack(string path, Image imageGain, decimal scaleFactor, int maxThreads = 8) { Image stack = null; MapHeader header = MapHeader.ReadFromFilePatient(50, 500, path, HeaderlessDims, (int)HeaderlessOffset, ImageFormatsHelper.StringToType(HeaderlessType)); string Extension = Helper.PathToExtension(path).ToLower(); bool IsTiff = header.GetType() == typeof(HeaderTiff); bool IsEER = header.GetType() == typeof(HeaderEER); if (imageGain != null) { if (!IsEER) { if (header.Dimensions.X != imageGain.Dims.X || header.Dimensions.Y != imageGain.Dims.Y) { throw new Exception("Gain reference dimensions do not match image."); } } } int EERSupersample = 1; if (imageGain != null && IsEER) { if (header.Dimensions.X == imageGain.Dims.X) { EERSupersample = 1; } else if (header.Dimensions.X * 2 == imageGain.Dims.X) { EERSupersample = 2; } else if (header.Dimensions.X * 4 == imageGain.Dims.X) { EERSupersample = 3; } else { throw new Exception("Invalid supersampling factor requested for EER based on gain reference dimensions"); } } HeaderEER.SuperResolution = EERSupersample; if (IsEER && imageGain != null) { header.Dimensions.X = imageGain.Dims.X; header.Dimensions.Y = imageGain.Dims.Y; } int NThreads = (IsTiff || IsEER) ? 6 : 2; int GPUThreads = 2; int CurrentDevice = GPU.GetDevice(); if (RawLayers == null || RawLayers.Length != NThreads || RawLayers[0].Length != header.Dimensions.ElementsSlice()) { RawLayers = Helper.ArrayOfFunction(i => new float[header.Dimensions.ElementsSlice()], NThreads); } Image[] GPULayers = Helper.ArrayOfFunction(i => new Image(IntPtr.Zero, header.Dimensions.Slice()), GPUThreads); Image[] GPULayers2 = Helper.ArrayOfFunction(i => new Image(IntPtr.Zero, header.Dimensions.Slice()), GPUThreads); if (scaleFactor == 1M) { stack = new Image(header.Dimensions); float[][] OriginalStackData = stack.GetHost(Intent.Write); object[] Locks = Helper.ArrayOfFunction(i => new object(), GPUThreads); Helper.ForCPU(0, header.Dimensions.Z, NThreads, threadID => GPU.SetDevice(DeviceID), (z, threadID) => { if (IsTiff) { TiffNative.ReadTIFFPatient(50, 500, path, z, true, RawLayers[threadID]); } else if (IsEER) { EERNative.ReadEERPatient(50, 500, path, z * 10, (z + 1) * 10, EERSupersample, RawLayers[threadID]); } else { IOHelper.ReadMapFloatPatient(50, 500, path, HeaderlessDims, (int)HeaderlessOffset, ImageFormatsHelper.StringToType(HeaderlessType), new[] { z }, null, new[] { RawLayers[threadID] }); } int GPUThreadID = threadID % GPUThreads; lock (Locks[GPUThreadID]) { GPU.CopyHostToDevice(RawLayers[threadID], GPULayers[GPUThreadID].GetDevice(Intent.Write), RawLayers[threadID].Length); if (imageGain != null) { GPULayers[GPUThreadID].MultiplySlices(imageGain); } GPU.Xray(GPULayers[GPUThreadID].GetDevice(Intent.Read), GPULayers2[GPUThreadID].GetDevice(Intent.Write), 20f, new int2(header.Dimensions), 1); GPU.CopyDeviceToHost(GPULayers2[GPUThreadID].GetDevice(Intent.Read), OriginalStackData[z], header.Dimensions.ElementsSlice()); } }, null); } else { int3 ScaledDims = new int3((int)Math.Round(header.Dimensions.X * scaleFactor) / 2 * 2, (int)Math.Round(header.Dimensions.Y * scaleFactor) / 2 * 2, header.Dimensions.Z); stack = new Image(ScaledDims); float[][] OriginalStackData = stack.GetHost(Intent.Write); int[] PlanForw = Helper.ArrayOfFunction(i => GPU.CreateFFTPlan(header.Dimensions.Slice(), 1), GPUThreads); int[] PlanBack = Helper.ArrayOfFunction(i => GPU.CreateIFFTPlan(ScaledDims.Slice(), 1), GPUThreads); Image[] GPULayersInputFT = Helper.ArrayOfFunction(i => new Image(IntPtr.Zero, header.Dimensions.Slice(), true, true), GPUThreads); Image[] GPULayersOutputFT = Helper.ArrayOfFunction(i => new Image(IntPtr.Zero, ScaledDims.Slice(), true, true), GPUThreads); Image[] GPULayersScaled = Helper.ArrayOfFunction(i => new Image(IntPtr.Zero, ScaledDims.Slice()), GPUThreads); object[] Locks = Helper.ArrayOfFunction(i => new object(), GPUThreads); Helper.ForCPU(0, ScaledDims.Z, NThreads, threadID => GPU.SetDevice(DeviceID), (z, threadID) => { if (IsTiff) { TiffNative.ReadTIFFPatient(50, 500, path, z, true, RawLayers[threadID]); } else if (IsEER) { EERNative.ReadEERPatient(50, 500, path, z * 10, (z + 1) * 10, EERSupersample, RawLayers[threadID]); } else { IOHelper.ReadMapFloatPatient(50, 500, path, HeaderlessDims, (int)HeaderlessOffset, ImageFormatsHelper.StringToType(HeaderlessType), new[] { z }, null, new[] { RawLayers[threadID] }); } int GPUThreadID = threadID % GPUThreads; lock (Locks[GPUThreadID]) { GPU.CopyHostToDevice(RawLayers[threadID], GPULayers[GPUThreadID].GetDevice(Intent.Write), RawLayers[threadID].Length); if (imageGain != null) { GPULayers[GPUThreadID].MultiplySlices(imageGain); } GPU.Xray(GPULayers[GPUThreadID].GetDevice(Intent.Read), GPULayers2[GPUThreadID].GetDevice(Intent.Write), 20f, new int2(header.Dimensions), 1); GPU.Scale(GPULayers2[GPUThreadID].GetDevice(Intent.Read), GPULayersScaled[GPUThreadID].GetDevice(Intent.Write), header.Dimensions.Slice(), ScaledDims.Slice(), 1, PlanForw[GPUThreadID], PlanBack[GPUThreadID], GPULayersInputFT[GPUThreadID].GetDevice(Intent.Write), GPULayersOutputFT[GPUThreadID].GetDevice(Intent.Write)); GPU.CopyDeviceToHost(GPULayersScaled[GPUThreadID].GetDevice(Intent.Read), OriginalStackData[z], ScaledDims.ElementsSlice()); } }, null); for (int i = 0; i < GPUThreads; i++) { GPU.DestroyFFTPlan(PlanForw[i]); GPU.DestroyFFTPlan(PlanBack[i]); GPULayersInputFT[i].Dispose(); GPULayersOutputFT[i].Dispose(); GPULayersScaled[i].Dispose(); } } foreach (var layer in GPULayers) { layer.Dispose(); } foreach (var layer in GPULayers2) { layer.Dispose(); } return(stack); }
public static (Image[] Halves1, Image[] Halves2, float2[] Stats) TrainOnVolumes(NoiseNet3D network, Image[] halves1, Image[] halves2, Image[] masks, float angpix, float lowpass, float upsample, bool dontFlatten, bool performTraining, int niterations, float startFrom, int batchsize, int gpuprocess, Action <string> progressCallback) { GPU.SetDevice(gpuprocess); #region Mask Debug.Write("Preparing mask... "); progressCallback?.Invoke("Preparing mask... "); int3[] BoundingBox = Helper.ArrayOfFunction(i => new int3(-1), halves1.Length); if (masks != null) { for (int i = 0; i < masks.Length; i++) { Image Mask = masks[i]; Mask.TransformValues((x, y, z, v) => { if (v > 0.5f) { BoundingBox[i].X = Math.Max(BoundingBox[i].X, Math.Abs(x - Mask.Dims.X / 2) * 2); BoundingBox[i].Y = Math.Max(BoundingBox[i].Y, Math.Abs(y - Mask.Dims.Y / 2) * 2); BoundingBox[i].Z = Math.Max(BoundingBox[i].Z, Math.Abs(z - Mask.Dims.Z / 2) * 2); } return(v); }); if (BoundingBox[i].X < 2) { throw new Exception("Mask does not seem to contain any non-zero values."); } BoundingBox[i] += 64; BoundingBox[i].X = Math.Min(BoundingBox[i].X, Mask.Dims.X); BoundingBox[i].Y = Math.Min(BoundingBox[i].Y, Mask.Dims.Y); BoundingBox[i].Z = Math.Min(BoundingBox[i].Z, Mask.Dims.Z); } } Console.WriteLine("done.\n"); #endregion #region Load and prepare data Console.WriteLine("Preparing data:"); List <Image> Maps1 = new List <Image>(); List <Image> Maps2 = new List <Image>(); List <Image> HalvesForDenoising1 = new List <Image>(); List <Image> HalvesForDenoising2 = new List <Image>(); List <float2> StatsForDenoising = new List <float2>(); for (int imap = 0; imap < halves1.Length; imap++) { Debug.Write($"Preparing map {imap}... "); progressCallback?.Invoke($"Preparing map {imap}... "); Image Map1 = halves1[imap]; Image Map2 = halves2[imap]; float MapPixelSize = Map1.PixelSize / upsample; if (!dontFlatten) { Image Average = Map1.GetCopy(); Average.Add(Map2); if (masks != null) { Average.Multiply(masks[imap]); } float[] Spectrum = Average.AsAmplitudes1D(true, 1, (Average.Dims.X + Average.Dims.Y + Average.Dims.Z) / 6); Average.Dispose(); int i10A = Math.Min((int)(angpix * 2 / 10 * Spectrum.Length), Spectrum.Length - 1); float Amp10A = Spectrum[i10A]; for (int i = 0; i < Spectrum.Length; i++) { Spectrum[i] = i < i10A ? 1 : (Amp10A / Math.Max(1e-10f, Spectrum[i])); } Image Map1Flat = Map1.AsSpectrumMultiplied(true, Spectrum); Map1.FreeDevice(); Map1 = Map1Flat; Map1.FreeDevice(); Image Map2Flat = Map2.AsSpectrumMultiplied(true, Spectrum); Map2.FreeDevice(); Map2 = Map2Flat; Map2.FreeDevice(); } if (lowpass > 0) { Map1.Bandpass(0, angpix * 2 / lowpass, true, 0.01f); Map2.Bandpass(0, angpix * 2 / lowpass, true, 0.01f); } if (upsample != 1f) { Image Map1Scaled = Map1.AsScaled(Map1.Dims * upsample / 2 * 2); Map1.FreeDevice(); Map1 = Map1Scaled; Map1.FreeDevice(); Image Map2Scaled = Map2.AsScaled(Map2.Dims * upsample / 2 * 2); Map2.FreeDevice(); Map2 = Map2Scaled; Map2.FreeDevice(); } Image ForDenoising1 = Map1.GetCopy(); Image ForDenoising2 = Map2.GetCopy(); if (BoundingBox[imap].X > 0) { Image Map1Cropped = Map1.AsPadded(BoundingBox[imap]); Map1.FreeDevice(); Map1 = Map1Cropped; Map1.FreeDevice(); Image Map2Cropped = Map2.AsPadded(BoundingBox[imap]); Map2.FreeDevice(); Map2 = Map2Cropped; Map2.FreeDevice(); } float2 MeanStd = MathHelper.MeanAndStd(Helper.Combine(Map1.GetHostContinuousCopy(), Map2.GetHostContinuousCopy())); Map1.TransformValues(v => (v - MeanStd.X) / MeanStd.Y); Map2.TransformValues(v => (v - MeanStd.X) / MeanStd.Y); ForDenoising1.TransformValues(v => (v - MeanStd.X) / MeanStd.Y); ForDenoising2.TransformValues(v => (v - MeanStd.X) / MeanStd.Y); HalvesForDenoising1.Add(ForDenoising1); HalvesForDenoising2.Add(ForDenoising2); StatsForDenoising.Add(MeanStd); GPU.PrefilterForCubic(Map1.GetDevice(Intent.ReadWrite), Map1.Dims); Map1.FreeDevice(); Maps1.Add(Map1); GPU.PrefilterForCubic(Map2.GetDevice(Intent.ReadWrite), Map2.Dims); Map2.FreeDevice(); Maps2.Add(Map2); Debug.WriteLine(" Done."); } if (masks != null) { foreach (var mask in masks) { mask.FreeDevice(); } } #endregion if (batchsize != 4 || Maps1.Count > 1) { if (batchsize < 1) { throw new Exception("Batch size must be at least 1."); } niterations = niterations * 4 / batchsize / Maps1.Count; Console.WriteLine($"Adjusting the number of iterations to {niterations} to match batch size and number of maps.\n"); } int Dim = network.BoxDimensions.X; progressCallback?.Invoke($"0/{niterations}"); if (performTraining) { GPU.SetDevice(gpuprocess); #region Training Random Rand = new Random(123); int NMaps = Maps1.Count; int NMapsPerBatch = Math.Min(128, NMaps); int MapSamples = batchsize; Image[] ExtractedSource = Helper.ArrayOfFunction(i => new Image(new int3(Dim, Dim, Dim * MapSamples)), NMapsPerBatch); Image[] ExtractedTarget = Helper.ArrayOfFunction(i => new Image(new int3(Dim, Dim, Dim * MapSamples)), NMapsPerBatch); Stopwatch Watch = new Stopwatch(); Watch.Start(); Queue <float> Losses = new Queue <float>(); for (int iter = (int)(startFrom * niterations); iter < niterations; iter++) { int[] ShuffledMapIDs = Helper.RandomSubset(Helper.ArrayOfSequence(0, NMaps, 1), NMapsPerBatch, Rand.Next(9999)); for (int m = 0; m < NMapsPerBatch; m++) { int MapID = ShuffledMapIDs[m]; Image Map1 = Maps1[MapID]; Image Map2 = Maps2[MapID]; int3 DimsMap = Map1.Dims; int3 Margin = new int3((int)(Dim / 2 * 1.5f)); //Margin.Z = 0; float3[] Position = Helper.ArrayOfFunction(i => new float3((float)Rand.NextDouble() * (DimsMap.X - Margin.X * 2) + Margin.X, (float)Rand.NextDouble() * (DimsMap.Y - Margin.Y * 2) + Margin.Y, (float)Rand.NextDouble() * (DimsMap.Z - Margin.Z * 2) + Margin.Z), MapSamples); float3[] Angle = Helper.ArrayOfFunction(i => new float3((float)Rand.NextDouble() * 360, (float)Rand.NextDouble() * 360, (float)Rand.NextDouble() * 360) * Helper.ToRad, MapSamples); { ulong[] Texture = new ulong[1], TextureArray = new ulong[1]; GPU.CreateTexture3D(Map1.GetDevice(Intent.Read), Map1.Dims, Texture, TextureArray, true); //Map1.FreeDevice(); GPU.Rotate3DExtractAt(Texture[0], Map1.Dims, ExtractedSource[m].GetDevice(Intent.Write), new int3(Dim), Helper.ToInterleaved(Angle), Helper.ToInterleaved(Position), (uint)MapSamples); //ExtractedSource[MapID].WriteMRC("d_extractedsource.mrc", true); GPU.DestroyTexture(Texture[0], TextureArray[0]); } { ulong[] Texture = new ulong[1], TextureArray = new ulong[1]; GPU.CreateTexture3D(Map2.GetDevice(Intent.Read), Map2.Dims, Texture, TextureArray, true); //Map2.FreeDevice(); GPU.Rotate3DExtractAt(Texture[0], Map2.Dims, ExtractedTarget[m].GetDevice(Intent.Write), new int3(Dim), Helper.ToInterleaved(Angle), Helper.ToInterleaved(Position), (uint)MapSamples); //ExtractedTarget.WriteMRC("d_extractedtarget.mrc", true); GPU.DestroyTexture(Texture[0], TextureArray[0]); } //Map1.FreeDevice(); //Map2.FreeDevice(); } float[] PredictedData = null, Loss = null; { float CurrentLearningRate = 0.0001f * (float)Math.Pow(10, -iter / (float)niterations * 2); for (int m = 0; m < ShuffledMapIDs.Length; m++) { int MapID = m; bool Twist = Rand.Next(2) == 0; if (Twist) { network.Train(ExtractedSource[MapID].GetDevice(Intent.Read), ExtractedTarget[MapID].GetDevice(Intent.Read), CurrentLearningRate, 0, out PredictedData, out Loss); } else { network.Train(ExtractedTarget[MapID].GetDevice(Intent.Read), ExtractedSource[MapID].GetDevice(Intent.Read), CurrentLearningRate, 0, out PredictedData, out Loss); } Losses.Enqueue(Loss[0]); if (Losses.Count > 100) { Losses.Dequeue(); } } } double TicksPerIteration = Watch.ElapsedTicks / (double)(iter + 1); TimeSpan TimeRemaining = new TimeSpan((long)(TicksPerIteration * (niterations - 1 - iter))); string ProgressText = $"{iter + 1}/{niterations}, {TimeRemaining.Hours}:{TimeRemaining.Minutes:D2}:{TimeRemaining.Seconds:D2} remaining, log(loss) = {Math.Log(MathHelper.Mean(Losses)).ToString("F4")}"; if (float.IsNaN(Loss[0]) || float.IsInfinity(Loss[0])) { throw new Exception("The loss function has reached an invalid value because something went wrong during training."); } Debug.WriteLine(ProgressText); progressCallback?.Invoke(ProgressText); } Debug.WriteLine("\nDone training!\n"); #endregion } return(HalvesForDenoising1.ToArray(), HalvesForDenoising2.ToArray(), StatsForDenoising.ToArray()); }
public static int3 signextend(int3 x, int numBits) { Assert.IsBetween(numBits, 1, 31); return((x << (32 - numBits)) >> (32 - numBits)); }
/// <summary> /// Creates a <see cref="VoxelDataVolume"/> with a persistent allocator /// </summary> /// <param name="size">The 3-dimensional size of this volume</param> /// <exception cref="ArgumentException">Thrown when any of the dimensions is negative</exception> public VoxelDataVolume(int3 size) : this(size.x, size.y, size.z, Allocator.Persistent) { }
private BlockType[] getNeighbourBlocks(int x, int y, int z) { int3 offset = InfiniteWorld.ChunkWorldPositionOffset; int3 arrayBasedChunkPos = new int3(chunkPosWorld.x - offset.x, chunkPosWorld.y - offset.y, chunkPosWorld.z - offset.z); BlockType x_minus; BlockType x_plus; BlockType y_minus; BlockType y_plus; BlockType z_minus; BlockType z_plus; int xKey, yKey, zKey; //Xminus if (x - 1 >= 0) { //x_minus = blocks[x - 1, y, z].blockType; x_minus = getBlock(x - 1, y, z); } else { //key = new int3(arrayBasedChunkPos.x - 1, arrayBasedChunkPos.y, arrayBasedChunkPos.z); xKey = arrayBasedChunkPos.x - 1; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { x_minus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(CONST.chunkSize.x - 1, y, z); } else { x_minus = BlockType.Air; } } //Xplus if (x + 1 <= CONST.chunkSize.x - 1) { x_plus = getBlock(x + 1, y, z); } else { xKey = arrayBasedChunkPos.x + 1; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { x_plus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(0, y, z); } else { x_plus = BlockType.Air; } } //Yminus if (y - 1 >= 0) { y_minus = getBlock(x, y - 1, z); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y - 1; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { y_minus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, CONST.chunkSize.y - 1, z); } else { y_minus = BlockType.Air; } } //Yplus if (y + 1 <= CONST.chunkSize.y - 1) { y_plus = getBlock(x, y + 1, z); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y + 1; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { y_plus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, 0, z); } else { y_plus = BlockType.Air; } } //Zminus if (z - 1 >= 0) { z_minus = getBlock(x, y, z - 1); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z - 1; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { z_minus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, y, CONST.chunkSize.z - 1); } else { z_minus = BlockType.Air; } } //Zplus if (z + 1 <= CONST.chunkSize.z - 1) { z_plus = getBlock(x, y, z + 1); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z + 1; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { z_plus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, y, 0); } else { z_plus = BlockType.Air; } } BlockType[] neighbours = new BlockType[6]; neighbours[0] = x_minus; neighbours[1] = x_plus; neighbours[2] = y_minus; neighbours[3] = y_plus; neighbours[4] = z_minus; neighbours[5] = z_plus; return(neighbours); }
/// <summary> /// Stores the <paramref name="voxelData"/> at <paramref name="localPosition"/>. The <paramref name="voxelData"/> will be clamped to be in range [0, 1] /// </summary> /// <param name="voxelData">The new voxel data</param> /// <param name="localPosition">The location of that voxel data</param> public void SetVoxelData(float voxelData, int3 localPosition) { int index = IndexUtilities.XyzToIndex(localPosition, Width, Height); SetVoxelData(voxelData, index); }
public static int3 divrem(int3 dividend, int3 divisor, out int3 remainder) { remainder = dividend % divisor; return(dividend / divisor); }
/// <summary> /// Gets the voxel data at <paramref name="localPosition"/>. If the data doesn't exist at <paramref name="localPosition"/>, an <see cref="IndexOutOfRangeException"/> will be thrown /// </summary> /// <param name="localPosition">The local position of the voxel data to get</param> /// <returns>The voxel data at <paramref name="localPosition"/></returns> public float GetVoxelData(int3 localPosition) { return(GetVoxelData(localPosition.x, localPosition.y, localPosition.z)); }
void Update() { if (!saveInput.isFocused && !loadInput.isFocused) { for (int i = 0; i < blocktypes.Length; i++) { if (Input.GetKeyDown(((i + 1) % 10).ToString())) { currentBlockType = i; RefreshDisplay(); } } transform.Translate(new Vector3(Input.GetAxis("Horizontal1"), Input.GetAxis("Vertical1"), Input.GetAxis("Vertical1")) * Time.deltaTime * 10); Camera.main.orthographicSize *= 1 - Input.GetAxis("Vertical0") * Time.deltaTime; Vector3 center = transform.position - transform.TransformVector(cameraOffset); transform.RotateAround(center, Vector3.up, -Input.GetAxis("Horizontal0") * Time.deltaTime * 90); if (Input.GetKeyDown(KeyCode.R)) { transform.position = center; transform.rotation = originalRotation; transform.Translate(cameraOffset); } } if (placing || deleting) { float scaleFactor = deleting ? 2.01f : 1.99f; Vector3 startVector = selectionStart.ToVector(); if (placing && !Input.GetMouseButton(0)) { placing = false; indicator.transform.localScale = Vector3.one * 2; int blockCount = (int)Vector3.Distance(startVector, selectionEnd) / 2 + 1; Vector3 dirVector = (selectionEnd - startVector).normalized * 2; indicatorMaterial.SetTextureScale("_MainTex", new Vector2(1, 1)); if (blocktypes [currentBlockType].name == "door") { blockCount = 1; } for (int i = 0; i < blockCount; i++) { Vector3 pos = startVector + i * dirVector; int3 intPos = getTile(pos); if (!blocksInScene.ContainsKey(intPos)) { MakeBlock(intPos, blocktypes [currentBlockType], currentDirection); } } } else if (deleting && !Input.GetMouseButton(1)) { deleting = false; indicator.transform.localScale = Vector3.one * 2; int blockCount = (int)Vector3.Distance(startVector, selectionEnd) / 2 + 1; Vector3 dirVector = (selectionEnd - startVector).normalized * 2; indicatorMaterial.SetTextureScale("_MainTex", new Vector2(1, 1)); for (int i = 0; i < blockCount; i++) { int3 pos = getTile(startVector + i * dirVector); if (blocksInScene.ContainsKey(pos) && blocksInScene.Count > 1) { blockData data = blocksInScene [pos]; Destroy(data.obj); blocksInScene.Remove(pos); } } } else { Vector2 screenSpaceStart = Camera.main.WorldToScreenPoint(startVector); Vector2 dir = (Vector2)Input.mousePosition - screenSpaceStart; float theta = Vector2.Angle(Vector2.right, dir); int directionIndex = Mathf.Clamp(Mathf.FloorToInt(theta / 60f), 0, 2); int scaleIndex = directionIndex; if (dir.y < 0) { directionIndex += 3; scaleIndex = 2 - scaleIndex; } Vector3 scaleDirection = directions [scaleIndex]; Vector3 direction = directions [directionIndex]; float stretch = Mathf.Floor(dir.magnitude / Screen.height * 13) * 2; selectionEnd = startVector + direction * stretch; indicator.transform.localScale = Vector3.one * scaleFactor + scaleDirection * ((startVector - selectionEnd).magnitude); indicator.transform.position = (startVector + selectionEnd) / 2; float s = stretch / 2 + 1; indicatorMaterial.SetTextureScale("_MainTex", new Vector2(s, s)); } } else if (connecting) { Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); Vector3 startPos = currentDoor.position.ToVector(); Vector3 endPos = Vector3.zero; GameObject prevButton = currentButton; currentButton = null; if (Physics.Raycast(cameraRay, out hit)) { if (hit.collider.tag == "Button") { currentButton = hit.collider.gameObject; endPos = hit.collider.bounds.center; } else { endPos = hit.point; } } else { endPos = cameraRay.GetPoint(Vector3.Distance(startPos, transform.position)); } line.SetPosition(0, startPos); line.SetPosition(1, endPos); if (currentButton != null && prevButton == null) { currentButton.GetComponent <Renderer> ().material.color = new Color(0.5f, 0.1f, 0.7f); } if (currentButton == null && prevButton != null) { prevButton.GetComponent <Renderer> ().material.color = new Color(0.7f, 0.7f, 0.7f); } if (Input.GetMouseButton(0)) { if (currentButton == null) { blocksInScene.Remove(currentDoor.position); Destroy(currentDoor.obj); } else { currentDoor.index = blocksInScene [new int3(currentButton.transform.position)].index; currentButton.GetComponent <Renderer> ().material.color = new Color(0.7f, 0.7f, 0.7f); } connecting = false; line.enabled = false; } } else { Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(cameraRay, out hit)) { if (hit.collider.name == "BackCollider") { selectionStart = getTile(hit.point - hit.normal); } else { selectionStart = getTile(hit.point + hit.normal); } } else { indicator.SetActive(false); arrow.SetActive(false); return; } selectionEnd = selectionStart.ToVector(); indicator.transform.position = selectionStart.ToVector(); indicator.SetActive(true); arrow.SetActive(true); if (Input.GetMouseButton(0)) { placing = true; } if (Input.GetMouseButton(1)) { selectionStart = getTile(hit.point - hit.normal); selectionEnd = selectionStart.ToVector(); deleting = true; } } if (Input.GetButtonDown("RotateSpell1")) { currentDirection -= (byte)Mathf.RoundToInt(Input.GetAxisRaw("RotateSpell1")); currentDirection = (byte)((currentDirection + 4) % 4); arrow.transform.rotation = Quaternion.LookRotation(blockDirections [currentDirection].ToVector()); } arrow.transform.position = //indicator.transform.position + indicator.transform.TransformPoint(blockDirections [currentDirection].ToVector() * 0.5f) + blockDirections [currentDirection].ToVector() * 0.66f; }
public void GetIdentity(out int3 identity) { identity = new int3(0, 0, 0); }
public int3 NextInt3(int3 min, int3 max) => RngToolkit.AsInt3(NextUInt3(), min, max);
public static int To1DIndex(int3 index, int chunkSize) { return(index.z + index.y * chunkSize + index.x * chunkSize * chunkSize); }
private static void xdirFunction(int xdir, int3 offset, Chunk[, ,] chunks) { if (xdir >= 1) { for (int i = 0; i < xdir; i++) { ChunkWorldPositionOffset.x += 1; for (int x = 0; x < worldChunkSize.x; x++) { for (int y = 0; y < worldChunkSize.y; y++) { for (int z = 0; z < worldChunkSize.z; z++) { if (x == 0) { MeshGeneration.AddToRemoveQueue(WorldInitializer.chunkArray[x, y, z]); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x + 1, y, z].AddChunkDrawdataToMeshQueue)); } if (x == worldChunkSize.x - 1) { int3 pos = new int3(x + ChunkWorldPositionOffset.x, y + ChunkWorldPositionOffset.y, z + ChunkWorldPositionOffset.z); WorldInitializer.chunkArray[x, y, z] = new Chunk(pos, offset); ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x, y, z].AddChunkDrawdataToMeshQueue)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x - 1, y, z].AddChunkDrawdataToMeshQueue)); } else { chunks[x, y, z] = chunks[x + 1, y, z]; } /* //newstuff after this if (x == worldChunkSize.x - 1) { } */ } } } } } else if (xdir <= -1) { for (int i = 0; i > xdir; i--) { ChunkWorldPositionOffset.x -= 1; for (int x = worldChunkSize.x - 1; x >= 0; x--) { for (int y = worldChunkSize.y - 1; y >= 0; y--) { for (int z = worldChunkSize.z - 1; z >= 0; z--) { if (x == (worldChunkSize.x - 1)) { MeshGeneration.AddToRemoveQueue(WorldInitializer.chunkArray[x, y, z]); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x - 1, y, z].AddChunkDrawdataToMeshQueue)); } if (x == 0) { int3 pos = new int3(x + ChunkWorldPositionOffset.x, y + ChunkWorldPositionOffset.y, z + ChunkWorldPositionOffset.z); WorldInitializer.chunkArray[x, y, z] = new Chunk(pos, offset); ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x, y, z].AddChunkDrawdataToMeshQueue)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x + 1, y, z].AddChunkDrawdataToMeshQueue)); } else { chunks[x, y, z] = chunks[x - 1, y, z]; } } } } } } }
public HullTriangle(int a,int b,int c):base(a,b,c) { n = new int3(-1,-1,-1); vmax=-1; rise = 0.0f; }
private BlockType[] getNeighbourBlocks(int x, int y, int z) { int3 offset = InfiniteWorld.ChunkWorldPositionOffset; int3 arrayBasedChunkPos = new int3(chunkPosWorld.x - offset.x, chunkPosWorld.y - offset.y, chunkPosWorld.z - offset.z); BlockType x_minus; BlockType x_plus; BlockType y_minus; BlockType y_plus; BlockType z_minus; BlockType z_plus; int xKey, yKey, zKey; //Xminus if (x - 1 >= 0) { //x_minus = blocks[x - 1, y, z].blockType; x_minus = getBlock(x - 1, y, z); } else { //key = new int3(arrayBasedChunkPos.x - 1, arrayBasedChunkPos.y, arrayBasedChunkPos.z); xKey = arrayBasedChunkPos.x - 1; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { x_minus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(CONST.chunkSize.x - 1, y, z); } else { x_minus = BlockType.Air; } } //Xplus if (x + 1 <= CONST.chunkSize.x - 1) { x_plus = getBlock(x + 1, y, z); } else { xKey = arrayBasedChunkPos.x + 1; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { x_plus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(0, y, z); } else { x_plus = BlockType.Air; } } //Yminus if (y - 1 >= 0) { y_minus = getBlock(x, y - 1, z); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y - 1 ; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { y_minus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, CONST.chunkSize.y - 1, z); } else { y_minus = BlockType.Air; } } //Yplus if (y + 1 <= CONST.chunkSize.y - 1) { y_plus = getBlock(x, y + 1, z); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y + 1; zKey = arrayBasedChunkPos.z; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { y_plus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, 0, z); } else { y_plus = BlockType.Air; } } //Zminus if (z - 1 >= 0) { z_minus = getBlock(x, y, z - 1); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z - 1; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { z_minus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, y, CONST.chunkSize.z - 1); } else { z_minus = BlockType.Air; } } //Zplus if (z + 1 <= CONST.chunkSize.z - 1) { z_plus = getBlock(x, y, z + 1); } else { xKey = arrayBasedChunkPos.x; yKey = arrayBasedChunkPos.y; zKey = arrayBasedChunkPos.z + 1; if (WorldInitializer.chunkArrayContainsKey(xKey, yKey, zKey)) { z_plus = WorldInitializer.getChunk(xKey, yKey, zKey).getBlock(x, y, 0); } else { z_plus = BlockType.Air; } } BlockType[] neighbours = new BlockType[6]; neighbours[0] = x_minus; neighbours[1] = x_plus; neighbours[2] = y_minus; neighbours[3] = y_plus; neighbours[4] = z_minus; neighbours[5] = z_plus; return neighbours; }
private static int ConvertToInt(int3 result) { return(result.x + result.y * 10 + result.z * 100); }
void Start() { int x = Mathf.CeilToInt(transform.position.x) - 1; int y = Mathf.CeilToInt(transform.position.y) - 1; int z = Mathf.CeilToInt(transform.position.z) - 1; //Debug.Log(x); playerLastFrameBlock = new Vector3(x, y, z); for (int xa = 0; xa < arraySize.x; xa++) { for (int ya = 0; ya < arraySize.y; ya++) { for (int za = 0; za < arraySize.z; za++) { blockPositions[xa, ya, za] = new Vector3( xa + loopStartPos.x + x - 0.5f, ya + loopStartPos.y + y + 0.5f, za + loopStartPos.z + z - 0.5f); int ccx = xa + loopStartPos.x + x; int ccy = ya + loopStartPos.y + y; int ccz = za + loopStartPos.z + z; int3 chunkcoords = new int3(0, 0, 0); int3 blockcoords = new int3(0, 0, 0); int3 offset = InfiniteWorld.ChunkWorldPositionOffset; chunkcoords.x = ccx / chunkSize.x - offset.x; chunkcoords.y = ccy / chunkSize.y - offset.y; chunkcoords.z = ccz / chunkSize.z - offset.z; boxColliderGOs[xa, ya, za] = new GameObject(); boxColliderGOs[xa, ya, za].AddComponent<BoxCollider>(); BoxCollider boxCollider = boxColliderGOs[xa, ya, za].GetComponent<BoxCollider>(); boxCollider.enabled = false; boxColliderGOs[xa, ya, za].transform.position = blockPositions[xa, ya, za]; if (WorldInitializer.chunkArrayContainsKey(chunkcoords)) { blockcoords.x = ccx % chunkSize.x; blockcoords.y = ccy % chunkSize.y; blockcoords.z = ccz % chunkSize.z; blockTypes[xa, ya, za] = WorldInitializer.chunkArray[chunkcoords.x, chunkcoords.y, chunkcoords.z]. blocks[blockcoords.x, blockcoords.y, blockcoords.z].blockType; if (blockTypes[xa, ya, za] != BlockType.Air) { boxCollider.enabled = true; } } else { blockTypes[xa, ya, za] = BlockType.Air; } } } } }
void Update() { if(!pushed) { player.transform.position = middle; } if(Input.GetKeyDown(KeyCode.Space)) { pushed = true; } int3 playerChunkPos = getPlayerChunkPos(); if (playerChunkPosOld != playerChunkPos) { Debug.Log("Chunk pos changed: " + playerChunkPos.x + " " + playerChunkPos.y + " " + playerChunkPos.z); int3 change = new int3(playerChunkPos.x - playerChunkPosOld.x, playerChunkPos.y - playerChunkPosOld.y, playerChunkPos.z - playerChunkPosOld.z); playerChunkPosOld = playerChunkPos; Debug.Log("Change: " + change.x + " " + change.y + " " + change.z); onPlayerChunkChanged(change.x, change.y, change.z); } }
public static void Denoise(Image noisy, NoiseNet3D[] networks) { int GPUID = GPU.GetDevice(); int NThreads = networks[0].MaxThreads; int3 Dims = noisy.Dims; int Dim = networks[0].BoxDimensions.X; int BatchSize = networks[0].BatchSize; int3 DimsValid = new int3(Dim) / 2; int3 DimsPositions = (Dims + DimsValid - 1) / DimsValid; float3 PositionStep = new float3(Dims - new int3(Dim)) / new float3(Math.Max(DimsPositions.X - 1, 1), Math.Max(DimsPositions.Y - 1, 1), Math.Max(DimsPositions.Z - 1, 1)); int NPositions = (int)DimsPositions.Elements(); int3[] Positions = new int3[NPositions]; for (int p = 0; p < NPositions; p++) { int X = p % DimsPositions.X; int Y = (p % (int)DimsPositions.ElementsSlice()) / DimsPositions.X; int Z = p / (int)DimsPositions.ElementsSlice(); Positions[p] = new int3((int)(X * PositionStep.X + Dim / 2), (int)(Y * PositionStep.Y + Dim / 2), (int)(Z * PositionStep.Z + Dim / 2)); } float[][] PredictionTiles = new float[Positions.Length][]; Image[] Extracted = Helper.ArrayOfFunction(i => new Image(new int3(Dim, Dim, Dim * BatchSize)), NThreads); Helper.ForCPU(0, (Positions.Length + BatchSize - 1) / BatchSize, NThreads, (threadID) => GPU.SetDevice(GPUID), (ib, threadID) => //for (int b = 0; b < Positions.Length; b += BatchSize) { int b = ib * BatchSize; int CurBatch = Math.Min(BatchSize, Positions.Length - b); int3[] CurPositions = Positions.Skip(b).Take(CurBatch).ToArray(); GPU.Extract(noisy.GetDevice(Intent.Read), Extracted[threadID].GetDevice(Intent.Write), noisy.Dims, new int3(Dim), Helper.ToInterleaved(CurPositions.Select(p => p - new int3(Dim / 2)).ToArray()), (uint)CurBatch); float[] PredictionData = null; networks[0].Predict(Extracted[threadID].GetDevice(Intent.Read), threadID, out PredictionData); for (int i = 0; i < CurBatch; i++) { PredictionTiles[b + i] = PredictionData.Skip(i * Dim * Dim * Dim).Take(Dim * Dim * Dim).ToArray(); } }, null); foreach (var item in Extracted) { item.Dispose(); } noisy.FreeDevice(); float[][] Denoised = noisy.GetHost(Intent.Write); for (int z = 0; z < Dims.Z; z++) { for (int y = 0; y < Dims.Y; y++) { for (int x = 0; x < Dims.X; x++) { int ClosestX = (int)Math.Max(0, Math.Min(DimsPositions.X - 1, (int)(((float)x - Dim / 2) / PositionStep.X + 0.5f))); int ClosestY = (int)Math.Max(0, Math.Min(DimsPositions.Y - 1, (int)(((float)y - Dim / 2) / PositionStep.Y + 0.5f))); int ClosestZ = (int)Math.Max(0, Math.Min(DimsPositions.Z - 1, (int)(((float)z - Dim / 2) / PositionStep.Z + 0.5f))); int ClosestID = (ClosestZ * DimsPositions.Y + ClosestY) * DimsPositions.X + ClosestX; int3 Position = Positions[ClosestID]; int LocalX = Math.Max(0, Math.Min(Dim - 1, x - Position.X + Dim / 2)); int LocalY = Math.Max(0, Math.Min(Dim - 1, y - Position.Y + Dim / 2)); int LocalZ = Math.Max(0, Math.Min(Dim - 1, z - Position.Z + Dim / 2)); Denoised[z][y * Dims.X + x] = PredictionTiles[ClosestID][(LocalZ * Dim + LocalY) * Dim + LocalX]; } } } }
public static Frame Lerp(Frame left, Frame right, float lerp) { Frame f = new Frame(); f.key = false; f.fid = left.fid; if (left.boneinfo != null && right.boneinfo != null && left.bonehash != right.bonehash) { Dictionary<string, int3> rebone = new Dictionary<string, int3>(); for (int i = 0; i < left.boneinfo.Count; i++) { string b = left.boneinfo[i]; int3 it = new int3(rebone.Count, i, -1); rebone[b] = it; } for (int i = 0; i < right.boneinfo.Count; i++) { string b = right.boneinfo[i]; if (rebone.ContainsKey(b) == false) { int3 it = new int3(rebone.Count, -1, i); rebone[b] = it; } else { rebone[b].boneright = i; } } //Debug.LogWarning("bone mix:"+rebone.Count); f.boneinfo = new List<string>(rebone.Keys); f.bonesinfo = new List<PoseBoneMatrix>(new PoseBoneMatrix[rebone.Count]); foreach (var v in rebone.Values) { if (v.boneleft == -1) f.bonesinfo[v.idnew] = right.bonesinfo[v.boneright].Clone() as PoseBoneMatrix; else if (v.boneright == -1) f.bonesinfo[v.idnew] = left.bonesinfo[v.boneleft].Clone() as PoseBoneMatrix; else { //Debug.Log("bc:" + v.idnew + "/" + f.bonesinfo.Count); //Debug.Log("lb:" + v.boneleft + "/" + left.bonesinfo.Count); //Debug.Log("rb:" + v.boneright + "/" + right.bonesinfo.Count); f.bonesinfo[v.idnew] = PoseBoneMatrix.Lerp(left.bonesinfo[v.boneleft], right.bonesinfo[v.boneright], lerp); } } } else {//single mix //f.bonesinfo = new PoseBoneMatrix[left.bonesinfo.Length]; f.bonesinfo = new List<PoseBoneMatrix>(left.bonesinfo); if (left.boneinfo != null) { f.boneinfo = left.boneinfo; f.bonehash = left.bonehash; } for (int i = 0; i < f.bonesinfo.Count; i++) { f.bonesinfo[i] = PoseBoneMatrix.Lerp(left.bonesinfo[i], right.bonesinfo[i], lerp); } } return f; }
public NoiseNet3D(string modelDir, int3 boxDimensions, int nThreads = 1, int batchSize = 8, bool forTraining = true, int deviceID = 0) { lock (TFHelper.DeviceSync[deviceID]) { DeviceID = deviceID; BoxDimensions = boxDimensions; ForTraining = forTraining; ModelDir = modelDir; MaxThreads = nThreads; BatchSize = batchSize; TFSessionOptions SessionOptions = TFHelper.CreateOptions(); TFSession Dummy = new TFSession(new TFGraph(), SessionOptions); Session = TFHelper.FromSavedModel(SessionOptions, null, ModelDir, new[] { forTraining ? "train" : "serve" }, new TFGraph(), $"/device:GPU:{deviceID}"); Graph = Session.Graph; NodeInputSource = Graph["volume_source"][0]; if (forTraining) { NodeInputTarget = Graph["volume_target"][0]; NodeLearningRate = Graph["training_learning_rate"][0]; NodeOpTrain = Graph["train_momentum"][0]; NodeOutputLoss = Graph["l2_loss"][0]; } NodeOutputPredicted = Graph["volume_predict"][0]; TensorSource = Helper.ArrayOfFunction(i => TFTensor.FromBuffer(new TFShape(BatchSize, BoxDimensions.X, BoxDimensions.Y, boxDimensions.Z, 1), new float[BatchSize * BoxDimensions.Elements()], 0, BatchSize * (int)BoxDimensions.Elements()), nThreads); if (ForTraining) { TensorTarget = Helper.ArrayOfFunction(i => TFTensor.FromBuffer(new TFShape(BatchSize, BoxDimensions.X, BoxDimensions.Y, boxDimensions.Z, 1), new float[BatchSize * BoxDimensions.Elements()], 0, BatchSize * (int)BoxDimensions.Elements()), nThreads); TensorLearningRate = Helper.ArrayOfFunction(i => TFTensor.FromBuffer(new TFShape(1), new float[1], 0, 1), nThreads); } ResultPredicted = Helper.ArrayOfFunction(i => new float[BatchSize * BoxDimensions.Elements()], nThreads); ResultLoss = Helper.ArrayOfFunction(i => new float[1], nThreads); //if (!ForTraining) RunnerPrediction = Helper.ArrayOfFunction(i => Session.GetRunner(). AddInput(NodeInputSource, TensorSource[i]). Fetch(NodeOutputPredicted), nThreads); if (ForTraining) { RunnerTraining = Helper.ArrayOfFunction(i => Session.GetRunner(). AddInput(NodeInputSource, TensorSource[i]). AddInput(NodeInputTarget, TensorTarget[i]). AddInput(NodeLearningRate, TensorLearningRate[i]). Fetch(NodeOutputPredicted, NodeOutputLoss, NodeOpTrain), nThreads); } } // Run prediction or training for one batch to claim all the memory needed float[] InitDecoded; float[] InitLoss; //if (!ForTraining) { Predict(new float[BoxDimensions.Elements() * BatchSize], 0, out InitDecoded); } if (ForTraining) { RandomNormal RandN = new RandomNormal(); Train(Helper.ArrayOfFunction(i => RandN.NextSingle(0, 1), BatchSize * (int)BoxDimensions.Elements()), Helper.ArrayOfFunction(i => RandN.NextSingle(0, 1), BatchSize * (int)BoxDimensions.Elements()), 1e-10f, 0, out InitDecoded, out InitLoss); } }
protected override void OnUpdate() { ComponentGroup nodeGroup = GetComponentGroup(typeof(Flycam), typeof(PrecisePosition), typeof(OctantPosition), typeof(Rotation)); EntityArray tempEntityArray = nodeGroup.GetEntityArray(); Entity[] entityArray = new Entity[tempEntityArray.Length]; for (int i = 0; i < entityArray.Length; ++i) { entityArray[i] = tempEntityArray[i]; } ComponentDataArray <Flycam> tempFlycamArray = nodeGroup.GetComponentDataArray <Flycam>(); Flycam[] flycamArray = new Flycam[tempFlycamArray.Length]; for (int i = 0; i < flycamArray.Length; ++i) { flycamArray[i] = tempFlycamArray[i]; } ComponentDataArray <PrecisePosition> tempPosArray = nodeGroup.GetComponentDataArray <PrecisePosition>(); PrecisePosition[] posArray = new PrecisePosition[tempPosArray.Length]; for (int i = 0; i < tempPosArray.Length; ++i) { posArray[i] = tempPosArray[i]; } ComponentDataArray <OctantPosition> tempOPosArray = nodeGroup.GetComponentDataArray <OctantPosition>(); OctantPosition[] oposArray = new OctantPosition[tempOPosArray.Length]; for (int i = 0; i < tempOPosArray.Length; ++i) { oposArray[i] = tempOPosArray[i]; } ComponentDataArray <Rotation> tempRotArray = nodeGroup.GetComponentDataArray <Rotation>(); Rotation[] rotArray = new Rotation[tempRotArray.Length]; for (int i = 0; i < tempRotArray.Length; ++i) { rotArray[i] = tempRotArray[i]; } //Position[] nodeArray = new Position[posArray.Length]; //for (int i = 0; i < posArray.Length; ++i) // nodeArray[i] = posArray[i]; quaternion pitchChange = quaternion.RotateX(Input.GetAxis("Mouse Y") * -flycamArray[0].mouseSensitivity); quaternion yawChange = quaternion.RotateY(Input.GetAxis("Mouse X") * flycamArray[0].mouseSensitivity); quaternion rollChange = quaternion.RotateZ(Input.GetAxis("Roll") * -flycamArray[0].rollSensitivity); quaternion rotChange = math.mul(pitchChange, yawChange); rotChange = math.mul(rollChange, rotChange); rotArray[0] = new Rotation { Value = math.mul(rotArray[0].Value, rotChange) }; Flycam flyCam = flycamArray[0]; float axisScrollWheel = Input.GetAxis("Mouse ScrollWheel"); float octantSize = HyperposStaticReferences.OctantSize; float ospeed = flyCam.octMoveSpeed; float ospeedChange = flyCam.octMoveSpeed * flycamArray[0].moveSpeedChangeMultiplier * axisScrollWheel; ospeed += ospeedChange; float pspeedChange = ospeed % 1f; ospeed -= pspeedChange; pspeedChange *= octantSize; pspeedChange += flyCam.moveSpeed * flycamArray[0].moveSpeedChangeMultiplier * axisScrollWheel; flyCam.moveSpeed += pspeedChange; int overSpeed = (int)(flyCam.moveSpeed / octantSize); flyCam.moveSpeed -= overSpeed * octantSize; flyCam.octMoveSpeed = (int)ospeed + overSpeed; EntityManager.SetComponentData(entityArray[0], flyCam); SystemStaticReferences.SpeedText.text = flyCam.moveSpeed.ToString() + " m/s " + flyCam.octMoveSpeed.ToString() + " oct/s"; float3 forward = math.forward(rotArray[0].Value); float3 right = MathUtils.right(rotArray[0].Value); float3 up = MathUtils.up(rotArray[0].Value); float dt = Time.deltaTime; float axisForeBack = Input.GetAxis("ForeBack"); float axisHorizontal = Input.GetAxis("Horizontal"); float axisVertical = Input.GetAxis("Vertical"); float3 octChangeInitial = forward * axisForeBack * dt * flyCam.octMoveSpeed + right * axisHorizontal * dt * flyCam.octMoveSpeed + up * axisVertical * dt * flyCam.octMoveSpeed; float3 posChange = octChangeInitial % 1f; int3 octChange = (int3)(octChangeInitial - posChange); posChange *= octantSize; posChange += forward * axisForeBack * dt * flyCam.moveSpeed + right * axisHorizontal * dt * flyCam.moveSpeed + up * axisVertical * dt * flyCam.moveSpeed; int3 overPos = (int3)(posChange / octantSize); posChange -= (float3)overPos * octantSize; octChange += overPos; //float3 posChange = forward * Input.GetAxis("ForeBack") * dt * flyCam.moveSpeed // + right * Input.GetAxis("Horizontal") * dt * flyCam.moveSpeed // + up * Input.GetAxis("Vertical") * dt * flyCam.moveSpeed; posArray[0] = new PrecisePosition() { pos = posArray[0].pos + posChange }; oposArray[0] = new OctantPosition() { pos = oposArray[0].pos + octChange }; EntityManager.SetComponentData(entityArray[0], posArray[0]); EntityManager.SetComponentData(entityArray[0], rotArray[0]); EntityManager.SetComponentData(entityArray[0], oposArray[0]); }
private static List<Chunk> xdirFunction(int xdir, int3 offset) { List<Chunk> chunksToBeDrawn = new List<Chunk>(); if (xdir >= 1) { for (int i = 0; i < xdir; i++) { ChunkWorldPositionOffset.x += 1; for (int x = 0; x < worldChunkSize.x; x++) { for (int y = 0; y < worldChunkSize.y; y++) { for (int z = 0; z < worldChunkSize.z; z++) { if (x == 0) { MeshGeneration.AddToRemoveQueue(WorldInitializer.getChunk(x, y, z)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x + 1, y, z].AddChunkDrawdataToMeshQueue)); } else if (x == worldChunkSize.x - 1) { int3 pos = new int3(x + ChunkWorldPositionOffset.x, y + ChunkWorldPositionOffset.y, z + ChunkWorldPositionOffset.z); WorldInitializer.setChunk(x, y, z, new Chunk(pos, offset)); if (!WorldInitializer.getChunk(x, y, z).anyNonAir) continue; chunksToBeDrawn.Add(WorldInitializer.getChunk(x, y, z)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x, y, z].AddChunkDrawdataToMeshQueue)); //WorldInitializer.chunkArray[x, y, z].AddChunkDrawdataToMeshQueue(); //////ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x - 1, y, z].AddChunkDrawdataToMeshQueue)); } else { WorldInitializer.setChunk(x, y, z, WorldInitializer.getChunk(x + 1, y, z)); } /* //newstuff after this if (x == worldChunkSize.x - 1) { } */ } } } } } else if (xdir <= -1) { for (int i = 0; i > xdir; i--) { ChunkWorldPositionOffset.x -= 1; for (int x = worldChunkSize.x - 1; x >= 0; x--) { for (int y = worldChunkSize.y - 1; y >= 0; y--) { for (int z = worldChunkSize.z - 1; z >= 0; z--) { if (x == (worldChunkSize.x - 1)) { //MeshGeneration.AddToRemoveQueue(WorldInitializer.chunkArray[x, y, z]); MeshGeneration.AddToRemoveQueue(WorldInitializer.getChunk(x, y, z)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x - 1, y, z].AddChunkDrawdataToMeshQueue)); } else if (x == 0) { int3 pos = new int3(x + ChunkWorldPositionOffset.x, y + ChunkWorldPositionOffset.y, z + ChunkWorldPositionOffset.z); WorldInitializer.setChunk(x, y, z, new Chunk(pos, offset)); if (!WorldInitializer.getChunk(x, y, z).anyNonAir) continue; chunksToBeDrawn.Add(WorldInitializer.getChunk(x, y, z)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x, y, z].AddChunkDrawdataToMeshQueue)); //ThreadPool.QueueUserWorkItem(new WaitCallback(WorldInitializer.chunkArray[x + 1, y, z].AddChunkDrawdataToMeshQueue)); } else { //chunks[x, y, z] = chunks[x - 1, y, z]; WorldInitializer.setChunk(x, y, z, WorldInitializer.getChunk(x - 1, y, z)); } } } } } } return chunksToBeDrawn; }