Here are the examples of the csharp api System.Array.GetLength(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2072 Examples
19
Source : Helper.cs
with MIT License
from amidos2006
with MIT License
from amidos2006
public static bool checkIsSolvable(Cell[,] map, Cell start, HashSet<Cell> visited = null)
{
List<int[]> directions = new List<int[]>{new int[]{-1, 0}, new int[]{1, 0},
new int[]{0, -1}, new int[]{0, 1}};
List<Cell> queue = new List<Cell>();
List<Cell> locks = new List<Cell>();
if (visited == null){
visited = new HashSet<Cell>();
}
visited.Add(start);
if(start.type == CellType.Normal && start.node.type != NodeType.Lever){
foreach (int[] dir in directions){
int[] newPos = new int[]{start.x + dir[0], start.y + dir[1]};
if(newPos[0] < 0 || newPos[1] < 0 || newPos[0] >= map.GetLength(0) || newPos[1] >= map.GetLength(1)){
continue;
}
if(map[newPos[0], newPos[1]] != null){
queue.Add(map[newPos[0], newPos[1]]);
}
}
}
int keys = 0;
while (queue.Count > 0)
{
Cell current = queue[0];
queue.RemoveAt(0);
if (visited.Contains(current)){
continue;
}
if (current.type == CellType.Normal && current.node.type == NodeType.Lock){
locks.Add(current);
}
else
{
if (current.type == CellType.Normal && current.node.type == NodeType.End)
{
return true;
}
else if (current.type == CellType.Normal && current.node.type == NodeType.Key)
{
keys += 1;
}
visited.Add(current);
if(current.type == CellType.Normal && current.node.type != NodeType.Lever){
foreach (int[] dir in directions){
int[] newPos = new int[]{current.x + dir[0], current.y + dir[1]};
if(newPos[0] < 0 || newPos[1] < 0 || newPos[0] >= map.GetLength(0) || newPos[1] >= map.GetLength(1)){
continue;
}
if(map[newPos[0], newPos[1]] != null){
queue.Add(map[newPos[0], newPos[1]]);
}
}
}
}
}
int requiredKeys = 0;
foreach (Cell l in locks)
{
HashSet<Cell> newVisited = new HashSet<Cell>();
foreach (Cell v in visited){
newVisited.Add(v);
}
if (!checkIsSolvable(map, l, newVisited)){
requiredKeys += 1;
}
}
if (requiredKeys < keys)
{
return true;
}
return false;
}
19
Source : TableMaker.cs
with MIT License
from Amine-Smahi
with MIT License
from Amine-Smahi
private static int GetMaxCellWidth(string[,] arrValues)
{
var maxWidth = 1;
for (var i = 0; i < arrValues.GetLength(0); i++)
{
for (var j = 0; j < arrValues.GetLength(1); j++)
{
var length = arrValues[i, j].Length;
if (length > maxWidth)
{
maxWidth = length;
}
}
}
return maxWidth;
}
19
Source : TableMaker.cs
with MIT License
from Amine-Smahi
with MIT License
from Amine-Smahi
private static string GetDataInTableFormat(string[,] arrValues)
{
var formattedString = string.Empty;
if (arrValues == null)
return formattedString;
var dimension1Length = arrValues.GetLength(0);
var dimension2Length = arrValues.GetLength(1);
var maxCellWidth = GetMaxCellWidth(arrValues);
var indentLength = (dimension2Length * maxCellWidth) + (dimension2Length - 1);
//printing top line;
formattedString = $"{CellLeftTop}{Indent(indentLength)}{CellRightTop}{Environment.NewLine}";
for (var i = 0; i < dimension1Length; i++)
{
var lineWithValues = CellVerticalLine;
var line = CellVerticalJointLeft;
for (var j = 0; j < dimension2Length; j++)
{
var value = arrValues[i, j].PadLeft(maxCellWidth, ' ');
lineWithValues += string.Format("{0}{1}", value, CellVerticalLine);
line += Indent(maxCellWidth);
if (j < (dimension2Length - 1))
{
line += CellTJoint;
}
}
line += CellVerticalJointRight;
formattedString += string.Format("{0}{1}", lineWithValues, Environment.NewLine);
if (i < (dimension1Length - 1))
{
formattedString += string.Format("{0}{1}", line, Environment.NewLine);
}
}
//printing bottom line
formattedString += $"{CellLeftBottom}{Indent(indentLength)}{CellRightBottom}{Environment.NewLine}";
return formattedString;
}
19
Source : Util.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
public static void print<T>(T[,,] values) {
for (int i = 0; i < values.GetLength(0); i++) {
Console.Write("{\n");
for (int j = 0; j < values.GetLength(1); j++) {
Console.Write("\t{");
for (int k = 0; k < values.GetLength(2); k++) {
Console.Write(values[i, j, k]);
if (k != (values.GetLength(2) - 1)) { Console.Write(", "); }
}
Console.WriteLine("}");
}
Console.WriteLine("}");
}
Console.WriteLine();
}
19
Source : DataManagerConverters.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
public static string ColorArrayToString(Color[] colors)
{
if(colors != null && colors.GetLength(0) > 0)
{
ColorConverter colorConverter = new ColorConverter();
string result = string.Empty;
foreach(Color color in colors)
{
if(result.Length > 0)
{
result += "; ";
}
result += colorConverter.ConvertToInvariantString(color);
}
return result;
}
return string.Empty;
}
19
Source : TimeSeriesAndForecasting.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
private double Determinant( double [][] inputDeterminant )
{
double sum = 0;
double sign = 1.0;
// Determinant is 2X2 - calculate value
if( inputDeterminant.Length == 2 )
{
return inputDeterminant[0][0]*inputDeterminant[1][1] - inputDeterminant[0][1]*inputDeterminant[1][0];
}
// Determinant is biger than 2X2. Go to recursive
// call of Determinant method
for( int column = 0; column < inputDeterminant.GetLength(0); column++ )
{
// Make sub determinant
double [][] newDeterminant = MakeSubDeterminant( inputDeterminant, column );
sum += sign * Determinant( newDeterminant ) * inputDeterminant[column][0];
sign *= -1.0;
}
return sum;
}
19
Source : TimeSeriesAndForecasting.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
private double [][] MakeSubDeterminant( double [][] inputDeterminant, int columnPos )
{
// Get Determinant Size
int size = inputDeterminant.GetLength(0);
// Prepare sub Determinant
double [][] newDeterminant = new double [size - 1][];
for(int arrayIndex = 0; arrayIndex < size - 1; arrayIndex++)
{
newDeterminant[arrayIndex] = new double [size - 1];
}
int newColumn = 0;
// Copy columns
for( int column = 0; column < size; column++ )
{
// Skeep this column
if( column == columnPos )
continue;
// Copy rows
for( int row = 1; row < size; row++ )
{
newDeterminant[newColumn][row-1] = inputDeterminant[column][row];
}
// Go to new column for new determinant
newColumn++;
}
// Return new determinant
return newDeterminant;
}
19
Source : TimeSeriesAndForecasting.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
private double [][] CopyDeterminant( double [][] inputDeterminant )
{
// Get Determinant Size
int size = inputDeterminant.GetLength(0);
// Prepare sub Determinant
double [][] newDeterminant = new double [size][];
for(int arrayIndex = 0; arrayIndex < size; arrayIndex++)
{
newDeterminant[arrayIndex] = new double [size];
}
// Copy columns
for( int column = 0; column < size; column++ )
{
// Copy rows
for( int row = 0; row < size; row++ )
{
newDeterminant[column][row] = inputDeterminant[column][row];
}
}
// Return new determinant
return newDeterminant;
}
19
Source : Program.cs
with MIT License
from AnkitSharma-007
with MIT License
from AnkitSharma-007
internal static void MulreplacedoSingle(int[,] array)
{
//Convert 2-D array to 1-D array
/*Input: { { 1, 2, 3 }, { 4, 5, 6 } }, output: 1 4 2 5 3 6
*
* */
int index = 0;
int width = array.GetLength(0);
int height = array.GetLength(1);
int[] single = new int[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
single[index] = array[x, y];
Console.Write(single[index] + " ");
index++;
}
}
}
19
Source : RegionOfInterest.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public bool[,] ContainsXYCoordsInterpolated(double[,][] xy, double z)
{
BinaryMask mask = GetInterpolatedMask(z);
int cols = xy.GetLength(1);
int rows = xy.GetLength(0);
bool[,] pointsInside = new bool[rows, cols];
for (int col = 0; col < cols; col++)
{
for (int row = 0; row < rows; row++)
{
pointsInside[row, col] = mask.ContainsPoint(xy[row, col][0], xy[row, col][1]);
}
}
return pointsInside;
}
19
Source : EnvironmentHelper.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
private static string GetPublicKeyToken(
replacedembly replacedembly)
{
var bytes = replacedembly.GetName().GetPublicKeyToken();
if (bytes == null || bytes.Length == 0)
{
return "None";
}
var publicKeyToken = string.Empty;
for (int i = 0; i < bytes.GetLength(0); i++)
{
publicKeyToken += string.Format("{0:x2}", bytes[i]);
}
return publicKeyToken;
}
19
Source : EntityExtensions.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private static object ToDataArray(Array array, HashSet<object> visited)
{
var dataArray = Array.CreateInstance(array.GetType().GetElementType(), array.GetLength(0));
for (int i = 0; i < dataArray.GetLength(0); i++)
{
dataArray.SetValue(ToData(array.GetValue(i), visited), i);
}
return dataArray;
}
19
Source : Utils.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
static string PrintArray2D(Array a)
{
int I = a.GetLength(0), J = a.GetLength(1);
var sb = new StringBuilder("{");
for (int i = 0; i < I; i++)
{
sb.Append("\n {");
for (int j = 0; j < J; j++)
{
if (j != 0) sb.Append(", ");
sb.Append(a.GetValue(i, j));
}
sb.Append("},");
}
sb.Append("\n}");
return sb.ToString();
}
19
Source : Utils.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
public static bool Equal<T>(T a, T b)
{
if (a is IEquatable<T> aieq) return aieq.Equals(b);
else if (a is Array aa2 && b is Array ba2 && aa2.Rank == 2)
{
int I = aa2.GetLength(0), J = aa2.GetLength(1);
if (I != ba2.GetLength(0) || J != ba2.GetLength(1)) return false;
for (int i = 0; i < I; i++)
for (int j = 0; j < J; j++)
if (!aa2.GetValue(i, j).Equals(ba2.GetValue(i, j)))
return false;
return true;
}
else if (a is IList ail && b is IList bil)
{
if (ail.Count != bil.Count) return false;
for (int i = 0; i < ail.Count; i++)
if (!ail[i].Equals(bil[i]))
return false;
return true;
}
else if (a.GetType().GetInterface(typeof(IReadOnlyList<>).Name) != null)
{
var e1 = ((IEnumerable)a).GetEnumerator();
var e2 = ((IEnumerable)b).GetEnumerator();
while (true)
{
var e1MoveNext = e1.MoveNext();
if (e1MoveNext != e2.MoveNext()) return false;
if (!e1MoveNext) return true;
if (!Equal(e1.Current, e2.Current)) return false;
}
}
else if (a is ICollection aic && b is ICollection bic)
{
return aic.Count == bic.Count && !aic.Cast<object>().Except(bic.Cast<object>()).Any();
}
else if (a is IEnumerable aie && b is IEnumerable bie)
{
var aieo = aie.Cast<object>().ToList();
var bieo = bie.Cast<object>().ToList();
return aieo.Count == bieo.Count && !aieo.Except(bieo).Any();
}
return a.Equals(b);
}
19
Source : CheckTests.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
static double[,] MulIJK(double[,] a, double[,] b)
{
int I = a.GetLength(0), J = a.GetLength(1), K = b.GetLength(1);
var c = new double[I, K];
for (int i = 0; i < I; i++)
for (int j = 0; j < J; j++)
for (int k = 0; k < K; k++)
c[i, k] += a[i, j] * b[j, k];
return c;
}
19
Source : CheckTests.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
static double[,] MulIKJ(double[,] a, double[,] b)
{
int I = a.GetLength(0), J = a.GetLength(1), K = b.GetLength(1);
var c = new double[I, K];
for (int i = 0; i < I; i++)
for (int k = 0; k < K; k++)
{
double t = 0.0;
for (int j = 0; j < J; j++)
t += a[i, j] * b[j, k];
c[i, k] = t;
}
return c;
}
19
Source : ParserBase.cs
with MIT License
from aornelas
with MIT License
from aornelas
public T DeserializeFromFilePath<T>(string filePath) {
if (File.Exists (filePath)) {
try {
byte[] bytes = File.ReadAllBytes (filePath);
if (bytes.GetLength (0) > 0) {
string dataString = System.Text.Encoding.UTF8.GetString(bytes);
// Debug.Log("Data String: " + dataString);
return DeserializeFromString<T>(dataString);
}
} catch (Exception e) {
Debug.LogError ("Deserialization error to: " + filePath + "; " + e.Message);
}
}
return default(T);
}
19
Source : MatrixInfluenceMap.cs
with MIT License
from ApmeM
with MIT License
from ApmeM
public void AddCharge(IChargeOrigin origin, IFading fading, float value)
{
var atPosition = new Point();
for(var x = 0; x < Map.GetLength(0); x++)
for(var y = 0; y < Map.GetLength(1); y++)
{
atPosition.X = x;
atPosition.Y = y;
var vector = origin.GetVector(atPosition);
Map[atPosition.X, atPosition.Y] += fading.GetPower(Math.Abs(vector.X) + Math.Abs(vector.Y), value);
}
}
19
Source : OtherTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
[Fact]
public void CanConvertDataset2D()
{
// Arrange
var expected = new int[4, 7];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 7; j++)
{
expected[i, j] = i * j - j;
}
}
// Act
var actual = expected
.Cast<int>()
.ToArray()
.ToArray2D(4, -1);
// replacedert
replacedert.Equal(expected.Rank, actual.Rank);
for (int i = 0; i < expected.Rank; i++)
{
replacedert.Equal(expected.GetLength(i), actual.GetLength(i));
}
replacedert.True(actual.Cast<int>().SequenceEqual(expected.Cast<int>()));
}
19
Source : OtherTests.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
[Fact]
public void CanConvertDataset3D()
{
// Arrange
var expected = new int[4, 7, 2];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 7; j++)
{
for (int k = 0; k < 2; k++)
{
expected[i, j, k] = i * j - j + k;
}
}
}
// Act
var actual = expected
.Cast<int>()
.ToArray()
.ToArray3D(-1, 7, 2);
// replacedert
replacedert.Equal(expected.Rank, actual.Rank);
for (int i = 0; i < expected.Rank; i++)
{
replacedert.Equal(expected.GetLength(i), actual.GetLength(i));
}
replacedert.True(actual.Cast<int>().SequenceEqual(expected.Cast<int>()));
}
19
Source : ZlibBaseStream.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count)
{
// According to MS doreplacedentation, any implementation of the IO.Stream.Read function must:
// (a) throw an exception if offset & count reference an invalid part of the buffer,
// or if count < 0, or if buffer is null
// (b) return 0 only upon EOF, or if count = 0
// (c) if not EOF, then return at least 1 byte, up to <count> bytes
if (_streamMode == StreamMode.Undefined)
{
if (!this._stream.CanRead) throw new ZlibException("The stream is not readable.");
// for the first read, set up some controls.
_streamMode = StreamMode.Reader;
// (The first reference to _z goes through the private accessor which
// may initialize it.)
z.AvailableBytesIn = 0;
if (_flavor == ZlibStreamFlavor.GZIP)
{
_gzipHeaderByteCount = _ReadAndValidateGzipHeader();
// workitem 8501: handle edge case (decompress empty stream)
if (_gzipHeaderByteCount == 0)
return 0;
}
}
if (_streamMode != StreamMode.Reader)
throw new ZlibException("Cannot Read after Writing.");
if (count == 0) return 0;
if (nomoreinput && _wantCompress) return 0; // workitem 8557
if (buffer == null) throw new ArgumentNullException("buffer");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset");
if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count");
int rc = 0;
// set up the output of the deflate/inflate codec:
_z.OutputBuffer = buffer;
_z.NextOut = offset;
_z.AvailableBytesOut = count;
// This is necessary in case _workingBuffer has been resized. (new byte[])
// (The first reference to _workingBuffer goes through the private accessor which
// may initialize it.)
_z.InputBuffer = workingBuffer;
do
{
// need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any.
if ((_z.AvailableBytesIn == 0) && (!nomoreinput))
{
// No data available, so try to Read data from the captive stream.
_z.NextIn = 0;
_z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length);
if (_z.AvailableBytesIn == 0)
nomoreinput = true;
}
// we have data in InputBuffer; now compress or decompress as appropriate
rc = (_wantCompress)
? _z.Deflate(_flushMode)
: _z.Inflate(_flushMode);
if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR))
return 0;
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message));
if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count))
break; // nothing more to read
}
//while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK);
while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK);
// workitem 8557
// is there more room in output?
if (_z.AvailableBytesOut > 0)
{
if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0)
{
// deferred
}
// are we completely done reading?
if (nomoreinput)
{
// and in compression?
if (_wantCompress)
{
// no more input data available; therefore we flush to
// try to complete the read
rc = _z.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message));
}
}
}
rc = (count - _z.AvailableBytesOut);
// calculate CRC after reading
if (crc != null)
crc.SlurpBlock(buffer, offset, rc);
return rc;
}
19
Source : ExcelPackage.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
internal ImageInfo AddImage(byte[] image, Uri uri, string contentType)
{
#if (Core)
var hashProvider = SHA1.Create();
#else
var hashProvider = new SHA1CryptoServiceProvider();
#endif
var hash = BitConverter.ToString(hashProvider.ComputeHash(image)).Replace("-","");
lock (_images)
{
if (_images.ContainsKey(hash))
{
_images[hash].RefCount++;
}
else
{
Packaging.ZipPackagePart imagePart;
if (uri == null)
{
uri = GetNewUri(Package, "/xl/media/image{0}.jpg");
imagePart = Package.CreatePart(uri, "image/jpeg", CompressionLevel.None);
}
else
{
imagePart = Package.CreatePart(uri, contentType, CompressionLevel.None);
}
var stream = imagePart.GetStream(FileMode.Create, FileAccess.Write);
stream.Write(image, 0, image.GetLength(0));
_images.Add(hash, new ImageInfo() { Uri = uri, RefCount = 1, Hash = hash, Part = imagePart });
}
}
return _images[hash];
}
19
Source : ArrayExtensions.cs
with MIT License
from Apps72
with MIT License
from Apps72
public static int RowsCount(this object[,] twoDimensionalArray)
{
return twoDimensionalArray.GetLength(0);
}
19
Source : MockTable.cs
with MIT License
from Apps72
with MIT License
from Apps72
internal object GetFirstColRowOrNull()
{
if (Rows != null && Rows.GetLength(0) > 0 && Rows.GetLength(1) > 0)
return Rows[0, 0];
else
return null;
}
19
Source : MockDbDataReader.cs
with MIT License
from Apps72
with MIT License
from Apps72
public override bool Read()
{
_currentRowIndex++;
return _rows?.GetLength(0) > _currentRowIndex;
}
19
Source : DbMockTests.cs
with MIT License
from Apps72
with MIT License
from Apps72
[TestMethod]
public void Mock_CheckTwoDimensionalObject_Test()
{
var x = new object[,]
{
{ "Col1", "Col2" },
{ "abc" , "def" },
{ "ghi" , "jkl" }
};
var y = new object[,]
{
{ },
};
var z = new object[,]
{
};
replacedert.AreEqual(2, x.Rank);
replacedert.AreEqual(6, x.Length);
replacedert.AreEqual(3, x.GetLength(0));
replacedert.AreEqual(2, x.GetLength(1));
replacedert.AreEqual("Col1", x[0, 0]);
replacedert.AreEqual("Col2", x[0, 1]);
replacedert.AreEqual(2, y.Rank);
replacedert.AreEqual(0, y.Length);
replacedert.AreEqual(1, y.GetLength(0));
replacedert.AreEqual(0, y.GetLength(1));
replacedert.AreEqual(2, z.Rank);
replacedert.AreEqual(0, z.Length);
replacedert.AreEqual(0, z.GetLength(0));
replacedert.AreEqual(0, z.GetLength(1));
}
19
Source : ArrayExtensions.cs
with MIT License
from Apps72
with MIT License
from Apps72
public static int ColumnsCount(this object[,] twoDimensionalArray)
{
return twoDimensionalArray.GetLength(1);
}
19
Source : Object2Terrain.cs
with Apache License 2.0
from araobp
with Apache License 2.0
from araobp
void CreateTerrain()
{
//fire up the progress bar
ShowProgressBar(1, 100);
TerrainData terrain = new TerrainData();
terrain.heightmapResolution = resolution;
GameObject terrainObject = Terrain.CreateTerrainGameObject(terrain);
Undo.RegisterCreatedObjectUndo(terrainObject, "Object to Terrain");
MeshCollider collider = Selection.activeGameObject.GetComponent<MeshCollider>();
CleanUp cleanUp = null;
//Add a collider to our source object if it does not exist.
//Otherwise raycasting doesn't work.
if (!collider)
{
collider = Selection.activeGameObject.AddComponent<MeshCollider>();
cleanUp = () => DestroyImmediate(collider);
}
Bounds bounds = collider.bounds;
float sizeFactor = collider.bounds.size.y / (collider.bounds.size.y + addTerrain.y);
terrain.size = collider.bounds.size + addTerrain;
bounds.size = new Vector3(terrain.size.x, collider.bounds.size.y, terrain.size.z);
// Do raycasting samples over the object to see what terrain heights should be
float[,] heights = new float[terrain.heightmapResolution, terrain.heightmapResolution];
Ray ray = new Ray(new Vector3(bounds.min.x, bounds.max.y + bounds.size.y, bounds.min.z), -Vector3.up);
RaycastHit hit = new RaycastHit();
float meshHeightInverse = 1 / bounds.size.y;
Vector3 rayOrigin = ray.origin;
int maxHeight = heights.GetLength(0);
int maxLength = heights.GetLength(1);
Vector2 stepXZ = new Vector2(bounds.size.x / maxLength, bounds.size.z / maxHeight);
for (int zCount = 0; zCount < maxHeight; zCount++)
{
ShowProgressBar(zCount, maxHeight);
for (int xCount = 0; xCount < maxLength; xCount++)
{
float height = 0.0f;
if (collider.Raycast(ray, out hit, bounds.size.y * 3))
{
height = (hit.point.y - bounds.min.y) * meshHeightInverse;
height += shiftHeight;
//bottom up
if (bottomTopRadioSelected == 0)
{
height *= sizeFactor;
}
//clamp
if (height < 0)
{
height = 0;
}
}
heights[zCount, xCount] = height;
rayOrigin.x += stepXZ[0];
ray.origin = rayOrigin;
}
rayOrigin.z += stepXZ[1];
rayOrigin.x = bounds.min.x;
ray.origin = rayOrigin;
}
terrain.SetHeights(0, 0, heights);
EditorUtility.ClearProgressBar();
if (cleanUp != null)
{
cleanUp();
}
}
19
Source : Results.cs
with GNU General Public License v3.0
from architecture-building-systems
with GNU General Public License v3.0
from architecture-building-systems
public void SetSupplySystemsCapacity(string[] supplyTechNames, bool[,] supplyTypes, double[] supplyCapacities, string[] supplyCapUnits)
{
// should contain checks, like lengths of arrays match etc
if (supplyTechNames == null || supplyTypes == null || supplyCapacities == null || supplyCapUnits == null)
return;
var shortestLength = int.MaxValue;
if (supplyTechNames.Length < shortestLength) shortestLength = supplyTechNames.Length;
if (supplyCapacities.Length < shortestLength) shortestLength = supplyCapacities.Length;
if (supplyCapUnits.Length < shortestLength) shortestLength = supplyCapUnits.Length;
if (supplyTypes.GetLength(0) < shortestLength) shortestLength = supplyTypes.GetLength(0);
this.SupplyNames = new string[supplyTechNames.Length];
supplyTechNames.CopyTo(this.SupplyNames, 0);
this.SupplyTypes = supplyTypes.Clone() as bool[,];
/// Rows: Technologies
/// Columns: [0]: Electricity, [1]: Heating, [2]: Cooling
this.SupplyCapacities = new double[supplyCapacities.Length];
supplyCapacities.CopyTo(this.SupplyCapacities, 0);
this.SupplyCapUnits = new string[supplyCapUnits.Length];
supplyCapUnits.CopyTo(this.SupplyCapUnits, 0);
}
19
Source : PinnedArray.cs
with GNU General Public License v2.0
from ArgusMagnus
with GNU General Public License v2.0
from ArgusMagnus
public int GetLength(int dimension) => _buffer.GetLength(dimension);
19
Source : GameResources.cs
with MIT License
from ArnaudValensi
with MIT License
from ArnaudValensi
void LoadQbtModels() {
models = new Dictionary<string, Chunk>();
string qbtPath = GameConfig.Instance.GetModelsPath();
foreach (string file in Directory.GetFiles(qbtPath, "*.qbt")) {
string filename = Path.GetFileNameWithoutExtension(file);
QBTFile qbtFile = new QBTFile(file);
QBTFile.VoxelData[,,] qbtData = qbtFile.VoxelsData;
int sizeX = qbtData.GetLength(0);
int sizeY = qbtData.GetLength(1);
int sizeZ = qbtData.GetLength(2);
Chunk chunk = new Chunk(sizeX, sizeY, sizeZ);
for (int x = 0; x < sizeX; x++) {
for (int y = 0; y < sizeY; y++) {
for (int z = 0; z < sizeZ; z++) {
if (qbtData[x, y, z].m != 0) {
// The z axis is reversed in qubicle
chunk.SetVoxel(
x, y, sizeZ - 1 - z,
Voxel.Type.Solid,
qbtData[x, y, z].Color
);
}
}
}
}
models.Add(filename, chunk);
}
}
19
Source : Chunk.cs
with MIT License
from ArnaudValensi
with MIT License
from ArnaudValensi
public int SizeXBasedOnPlan(Direction direction) {
switch (direction) {
case Direction.south:
return voxels.GetLength(0);
case Direction.north:
return voxels.GetLength(0);
case Direction.west:
return voxels.GetLength(2);
case Direction.east:
return voxels.GetLength(2);
case Direction.up:
return voxels.GetLength(0);
case Direction.down:
return voxels.GetLength(0);
default:
throw new System.Exception("Bad direction");
}
}
19
Source : Chunk.cs
with MIT License
from ArnaudValensi
with MIT License
from ArnaudValensi
public int SizeYBasedOnPlan(Direction direction) {
switch (direction) {
case Direction.south:
return voxels.GetLength(1);
case Direction.north:
return voxels.GetLength(1);
case Direction.west:
return voxels.GetLength(1);
case Direction.east:
return voxels.GetLength(1);
case Direction.up:
return voxels.GetLength(2);
case Direction.down:
return voxels.GetLength(2);
default:
throw new System.Exception("Bad direction");
}
}
19
Source : Chunk.cs
with MIT License
from ArnaudValensi
with MIT License
from ArnaudValensi
public int SizeZBasedOnPlan(Direction direction) {
switch (direction) {
case Direction.south:
return voxels.GetLength(2);
case Direction.north:
return voxels.GetLength(2);
case Direction.west:
return voxels.GetLength(0);
case Direction.east:
return voxels.GetLength(0);
case Direction.up:
return voxels.GetLength(1);
case Direction.down:
return voxels.GetLength(1);
default:
throw new System.Exception("Bad direction");
}
}
19
Source : QubicleVoxelObject.cs
with MIT License
from ArnaudValensi
with MIT License
from ArnaudValensi
void Start() {
meshFilter = GetComponent<MeshFilter>();
meshCollider = GetComponent<MeshCollider>();
meshRenderer = GetComponent<MeshRenderer>();
colorTexture = GameManager.Instance.GetColorTexture();
// voxelMeshBuilder = GameManager.Instance.GetVoxelMeshBuilder();
chunkSimplifier = GameObject.Find("/Managers/ChunkSimplifier").GetComponent<ChunkSimplifier>();
QBTFile qbtFile = LoadQubicleFile();
QBTFile.VoxelData[,,] qbtData = qbtFile.VoxelsData;
colorTexture.AddColors(qbtFile.Colors.ToArray());
sizeX = qbtData.GetLength(0);
sizeY = qbtData.GetLength(1);
sizeZ = qbtData.GetLength(2);
chunk = new Chunk(sizeX, sizeY, sizeZ);
for (int x = 0; x < sizeX; x++) {
for (int y = 0; y < sizeY; y++) {
for (int z = 0; z < sizeZ; z++) {
if (qbtData[x, y, z].m != 0) {
// The z axis is reversed in qubicle
chunk.SetVoxel(
x, y, sizeZ - 1 -z,
Voxel.Type.Solid,
qbtData[x, y, z].Color
);
}
}
}
}
meshRenderer.sharedMaterial.mainTexture = colorTexture.Texture;
// MeshData meshData = voxelMeshBuilder.BuildMesh(chunk);
// voxelMeshBuilder.RenderMesh(meshData, meshFilter, meshCollider);
MeshData meshData = chunkSimplifier.BuildMesh(chunk);
chunkSimplifier.RenderMesh(meshData, meshFilter, meshCollider);
}
19
Source : Constructors.cs
with MIT License
from asc-community
with MIT License
from asc-community
private static (int height, int width) ExtractAndCheck(T[,] data)
{
var width = data.GetLength(0);
#if ALLOW_EXCEPTIONS
if (width <= 0)
throw new InvalidShapeException();
#endif
var height = data.GetLength(1);
#if ALLOW_EXCEPTIONS
if (height <= 0)
throw new InvalidShapeException();
#endif
return (width, height);
}
19
Source : Constructors.cs
with MIT License
from asc-community
with MIT License
from asc-community
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GenTensor<T, TWrapper> CreateTensor(T[] data)
{
var res = new GenTensor<T, TWrapper>(data.GetLength(0));
for (int x = 0; x < data.GetLength(0); x++)
res.SetValueNoCheck(data[x], x);
return res;
}
19
Source : Constructors.cs
with MIT License
from asc-community
with MIT License
from asc-community
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GenTensor<T, TWrapper> CreateTensor(T[,] data)
{
var res = new GenTensor<T, TWrapper>(data.GetLength(0), data.GetLength(1));
for (int x = 0; x < data.GetLength(0); x++)
for (int y = 0; y < data.GetLength(1); y++)
res.SetValueNoCheck(data[x, y], x, y);
return res;
}
19
Source : Constructors.cs
with MIT License
from asc-community
with MIT License
from asc-community
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GenTensor<T, TWrapper> CreateTensor(T[,,] data)
{
var res = new GenTensor<T, TWrapper>(data.GetLength(0),
data.GetLength(1), data.GetLength(2));
for (int x = 0; x < data.GetLength(0); x++)
for (int y = 0; y < data.GetLength(1); y++)
for (int z = 0; z < data.GetLength(2); z++)
res.SetValueNoCheck(data[x, y, z], x, y, z);
return res;
}
19
Source : Constructors.cs
with MIT License
from asc-community
with MIT License
from asc-community
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GenTensor<T, TWrapper> CreateTensor(Array data)
{
var dimensions = new int[data.Rank];
for (int i = 0; i < data.Rank; i++)
dimensions[i] = data.GetLength(i);
var res = new GenTensor<T, TWrapper>(dimensions);
dimensions = new int[data.Rank]; // Don't modify res
var normalizedIndices = new int[data.Rank];
var indices = new int[data.Rank];
for (int i = 0; i < data.Rank; i++)
{
dimensions[i] = data.GetUpperBound(i);
indices[i] = data.GetLowerBound(i);
}
var increment = indices.Length - 1;
while (true)
{
for (int i = increment; indices[i] > dimensions[i]; i--)
if (i == 0)
return res;
else
{
indices[i - 1]++;
indices[i] = data.GetLowerBound(i);
normalizedIndices[i - 1]++;
normalizedIndices[i] = 0;
}
res.SetValueNoCheck((T)data.GetValue(indices), normalizedIndices);
indices[increment]++;
normalizedIndices[increment]++;
}
}
19
Source : SharedResources.cs
with GNU General Public License v3.0
from ASCOMInitiative
with GNU General Public License v3.0
from ASCOMInitiative
public static double[,] Array2DToDouble(Array inputArray)
{
double[,] outputArray = new double[inputArray.GetLength(0), inputArray.GetLength(1)];
for (int j = 0; j <= inputArray.GetUpperBound(1); j++)
{
for (int i = 0; i <= inputArray.GetUpperBound(0); i++)
{
outputArray[i, j] = Convert.ToDouble(inputArray.GetValue(i, j));
}
}
return outputArray;
}
19
Source : SharedResources.cs
with GNU General Public License v3.0
from ASCOMInitiative
with GNU General Public License v3.0
from ASCOMInitiative
public static double[,,] Array3DToDouble(Array inputArray)
{
double[,,] outputArray = new double[inputArray.GetLength(0), inputArray.GetLength(1), inputArray.GetLength(2)];
for (int k = 0; k <= inputArray.GetUpperBound(2); k++)
{
for (int j = 0; j <= inputArray.GetUpperBound(1); j++)
{
for (int i = 0; i <= inputArray.GetUpperBound(0); i++)
{
outputArray[i, j, k] = Convert.ToDouble(inputArray.GetValue(i, j, k));
}
}
}
return outputArray;
}
19
Source : SharedResources.cs
with GNU General Public License v3.0
from ASCOMInitiative
with GNU General Public License v3.0
from ASCOMInitiative
public static int[,] Array2DToInt(Array inputArray)
{
int[,] outputArray = new int[inputArray.GetLength(0), inputArray.GetLength(1)];
for (int j = 0; j <= inputArray.GetUpperBound(1); j++)
{
for (int i = 0; i <= inputArray.GetUpperBound(0); i++)
{
outputArray[i, j] = Convert.ToInt32(inputArray.GetValue(i, j));
}
}
return outputArray;
}
19
Source : SharedResources.cs
with GNU General Public License v3.0
from ASCOMInitiative
with GNU General Public License v3.0
from ASCOMInitiative
public static int[,,] Array3DToInt(Array inputArray)
{
int[,,] outputArray = new int[inputArray.GetLength(0), inputArray.GetLength(1), inputArray.GetLength(2)];
for (int k = 0; k <= inputArray.GetUpperBound(2); k++)
{
for (int j = 0; j <= inputArray.GetUpperBound(1); j++)
{
for (int i = 0; i <= inputArray.GetUpperBound(0); i++)
{
outputArray[i, j, k] = Convert.ToInt32(inputArray.GetValue(i, j, k));
}
}
}
return outputArray;
}
19
Source : SharedResources.cs
with GNU General Public License v3.0
from ASCOMInitiative
with GNU General Public License v3.0
from ASCOMInitiative
public static short[,] Array2DToShort(Array inputArray)
{
short[,] outputArray = new short[inputArray.GetLength(0), inputArray.GetLength(1)];
for (int j = 0; j <= inputArray.GetUpperBound(1); j++)
{
for (int i = 0; i <= inputArray.GetUpperBound(0); i++)
{
outputArray[i, j] = Convert.ToInt16(inputArray.GetValue(i, j));
}
}
return outputArray;
}
19
Source : SharedResources.cs
with GNU General Public License v3.0
from ASCOMInitiative
with GNU General Public License v3.0
from ASCOMInitiative
public static short[,,] Array3DToShort(Array inputArray)
{
short[,,] outputArray = new short[inputArray.GetLength(0), inputArray.GetLength(1), inputArray.GetLength(2)];
for (int k = 0; k <= inputArray.GetUpperBound(2); k++)
{
for (int j = 0; j <= inputArray.GetUpperBound(1); j++)
{
for (int i = 0; i <= inputArray.GetUpperBound(0); i++)
{
outputArray[i, j, k] = Convert.ToInt16(inputArray.GetValue(i, j, k));
}
}
}
return outputArray;
}
19
Source : LodMesh.cs
with MIT License
from AsehesL
with MIT License
from AsehesL
public Mesh GenerateMesh(Texture2D texture)
{
if (cellSizeX <= 0 || cellSizeZ <= 0 || widthX <= 0 || widthZ <= 0 || maxLod < 0 || samples < 1)
return null;
LodMeshCell[,] cells = new LodMeshCell[cellSizeX, cellSizeZ];
//根据贴图尺寸和单元格数量,计算分配给单个单元格的像素宽高
int w = texture.width / cellSizeX;
int h = texture.height / cellSizeZ;
//计算Lod
for (int i = 0; i < cellSizeX; i++)
{
for (int j = 0; j < cellSizeZ; j++)
{
cells[i, j] = new LodMeshCell(-widthX, -widthZ, i, j, widthX*2 / cellSizeX,
widthZ*2 / cellSizeZ);
//为单元格分配指定区域的像素并计算极差和平均值
cells[i, j].Calculate(texture, i * w, j * h, w, h, maxLod);
}
}
//根据上一步计算的结果,将最大lod单元格边上的格子设置lod递减
for (int i = 0; i < cellSizeX; i++)
{
for (int j = 0; j < cellSizeZ; j++)
{
LodMeshCell cell = cells[i, j];
if (cell.lod == -1)
continue;
if (cell.lod != maxLod)
continue;
for (int lx = maxLod - 1, ly = 0; lx >= 0; lx--, ly++)
{
for (int lk = 0; lk <= ly; lk++)
{
if (lk == 0 && lx == 0)
continue;
int clod = maxLod - lx - lk;
//从最大lod处往外递减lod
SetNeighborLOD(i - lx, j - lk, cellSizeX, cellSizeZ, clod, cells);
SetNeighborLOD(i + lx, j - lk, cellSizeX, cellSizeZ, clod, cells);
SetNeighborLOD(i - lx, j + lk, cellSizeX, cellSizeZ, clod, cells);
SetNeighborLOD(i + lx, j + lk, cellSizeX, cellSizeZ, clod, cells);
}
}
}
}
//根据Lod生成Mesh
float p = Mathf.Pow(2, maxLod);
float dtx = widthX*2 / cellSizeX / p;
float dty = widthZ*2 / cellSizeZ / p;
MeshVertexData cache = new MeshVertexData(cellSizeX * (int)p, cellSizeZ * (int)p, dtx, dty, -widthX, -widthZ);
for (int i = 0; i < cellSizeX; i++)
{
for (int j = 0; j < cellSizeZ; j++)
{
LodMeshCell cell = cells[i, j];
if (cell.lod == -1)
continue;
int leftLod = i == 0 ? -1 : cells[i - 1, j].lod;
int rightLod = i == cells.GetLength(0) - 1 ? -1 : cells[i + 1, j].lod;
int downLod = j == 0 ? -1 : cells[i, j - 1].lod;
int upLod = j == cells.GetLength(1) - 1 ? -1 : cells[i, j + 1].lod;
cell.SetNeighborLOD(leftLod, rightLod, upLod, downLod);
cell.UpdateMesh(cache);
}
}
//生成网格
Mesh mesh = cache.Apply(texture, uvDir, samples);
return mesh;
}
19
Source : QuadTreeMesh.cs
with MIT License
from AsehesL
with MIT License
from AsehesL
public Mesh GenerateMesh(Texture2D texture)
{
int cellSize = (int)Mathf.Pow(2, depth);
if (widthX <= 0 || widthZ <= 0 || samples < 1)
return null;
QuadTreeMeshNode[,] cells = new QuadTreeMeshNode[cellSize, cellSize];
//根据贴图尺寸和单元格数量,计算分配给单个单元格的像素宽高
int w = texture.width / cellSize;
int h = texture.height / cellSize;
//计算Lod
for (int i = 0; i < cellSize; i++)
{
for (int j = 0; j < cellSize; j++)
{
var cell = new QuadTreeMeshLeaf(-widthX, -widthZ, i, j, widthX * 2 / cellSize,
widthZ * 2 / cellSize);
//为单元格分配指定区域的像素并计算极差和平均值
cell.Calculate(texture, i * w, j * h, w, h);
cells[i, j] = cell;
}
}
float dtx = widthX * 2 / cellSize;
float dty = widthZ * 2 / cellSize;
MeshVertexData cache = new MeshVertexData(cellSize, cellSize, dtx, dty, -widthX, -widthZ);
while (cellSize > 1)
{
cellSize = cellSize / 2;
QuadTreeMeshNode[,] nodes = new QuadTreeMeshNode[cellSize, cellSize];
for (int i = 0; i < cellSize; i++)
{
for (int j = 0; j < cellSize; j++)
{
QuadTreeMeshNode lb = cells[i * 2, j * 2];
QuadTreeMeshNode rb = cells[i * 2 + 1, j * 2];
QuadTreeMeshNode lt = cells[i * 2, j * 2 + 1];
QuadTreeMeshNode rt = cells[i * 2 + 1, j * 2 + 1];
QuadTreeMeshNode node = new QuadTreeMeshNode(lt, lb, rt, rb, -widthX, -widthZ, i, j, widthX * 2 / cellSize,
widthZ * 2 / cellSize);
nodes[i, j] = node;
}
}
for (int i = 0; i < cellSize; i++)
{
for (int j = 0; j < cellSize; j++)
{
var left = i != 0 ? nodes[i - 1, j] : null;
var right = i != nodes.GetLength(0) - 1 ? nodes[i + 1, j] : null;
var down = j != 0 ? nodes[i, j - 1] : null;
var up = j != nodes.GetLength(1) - 1 ? nodes[i, j + 1] : null;
nodes[i, j].SetNeighbor(left, right, up, down);
}
}
cells = nodes;
}
for (int i = 0; i < cellSize; i++)
{
for (int j = 0; j < cellSize; j++)
{
cells[i, j].UpdateMesh(cache);
}
}
return cache.Apply(texture, uvDir, samples);
}
19
Source : JogoDaCobra.cs
with MIT License
from atrigo
with MIT License
from atrigo
static void DesenharComida()
{
bool sobrepoe = true;
do
{
Random rnd = new Random();
posXComida = rnd.Next(1, cols - 1);
posYComida = rnd.Next(1, lins - 1);
sobrepoe = false;
for (int i = 0; i < cobra.GetLength(0); i++)
{
if (cobra[i, 0] == posXComida && cobra[i, 1] == posYComida)
{
sobrepoe = true;
}
}
}
while (sobrepoe == true);
Console.SetCursorPosition(posXComida, posYComida);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("@");
Console.ForegroundColor = ConsoleColor.White;
}
19
Source : Exercicio8.23.cs
with MIT License
from atrigo
with MIT License
from atrigo
static int[,] transposta(int[,] a)
{
int[,] r = new int[a.GetLength(1),a.GetLength(0)];// A matriz transposta terá o nº de linhas trocado com o nº de colunas
for (int i=0; i<r.GetLength(0);i++) // Linha
for (int j=0; j<r.GetLength(1);j++) // Coluna
r[i,j]+=a[j,i];
return r;
}
See More Examples