public void Encrypt(IByteBufferAllocator allocator, EncryptMode mode, Stream src, Stream dst, bool reliable) { using (var data = new BufferWrapper(allocator.Buffer().WithOrder(ByteOrder.LittleEndian))) using (var encryptor = GetAlgorithm(mode).CreateEncryptor()) using (var cs = new CryptoStream(new NonClosingStream(dst), encryptor, CryptoStreamMode.Write)) using (var w = cs.ToBinaryWriter(false)) { var blockSize = AES.BlockSize / 8; var padding = blockSize - (src.Length + 1 + 4) % blockSize; if (reliable) { padding = blockSize - (src.Length + 1 + 4 + 2) % blockSize; } if (reliable) { var counter = (ushort)(Interlocked.Increment(ref _encryptCounter) - 1); data.Buffer.WriteShort(counter); } using (var dataStream = new WriteOnlyByteBufferStream(data.Buffer, false)) src.CopyTo(dataStream); w.Write((byte)padding); using (var dataStream = new ReadOnlyByteBufferStream(data.Buffer, false)) { w.Write(Hash.GetUInt32 <CRC32>(dataStream)); dataStream.Position = 0; dataStream.CopyTo(cs); } w.Fill((int)padding); } }
/** * Creates a sphere that completely contains a set of points. * * @param buffer the Cartesian coordinates to be enclosed by the new Sphere. * * @return a <code>Sphere</code> encompassing the given coordinates. * * @throws ArgumentException if <code>buffer</code> is null or contains fewer than three values. */ public static Sphere createBoundingSphere(BufferWrapper buffer) { if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new ArgumentException(message); } if (buffer.getBackingBuffer().position() > buffer.getBackingBuffer().limit() - 3) { String message = Logging.getMessage("Geom.Sphere.NoPointsSpecified"); Logging.logger().severe(message); throw new ArgumentException(message); } // Creates the sphere around the axis aligned bounding box of the input points. Vec4[] extrema = Vec4.computeExtrema(buffer); Vec4 center = new Vec4( (extrema[0].x() + extrema[1].x()) / 2.0, (extrema[0].y() + extrema[1].y()) / 2.0, (extrema[0].z() + extrema[1].z()) / 2.0); double radius = extrema[0].distanceTo3(extrema[1]) / 2.0; return(new Sphere(center, radius)); }
protected void loadOffsetFile() { InputStream inputStream = WWIO.openFileOrResourceStream(this.offsetsFilePath, typeof(EGM96)); if (inputStream == null) { String msg = Logging.getMessage("generic.CannotOpenFile", this.offsetsFilePath); Logging.logger().severe(msg); throw new WWRuntimeException(msg); } try { AVList bufferParams = new AVListImpl(); bufferParams.setValue(AVKey.DATA_TYPE, AVKey.INT16); bufferParams.setValue(AVKey.BYTE_ORDER, AVKey.BIG_ENDIAN); this.deltas = BufferWrapper.wrap(WWIO.readStreamToBuffer(is, true), bufferParams); } catch (IOException e) { String msg = Logging.getMessage("generic.ExceptionAttemptingToReadFile", this.offsetsFilePath); Logging.logger().log(java.util.logging.Level.SEVERE, msg, e); throw e; } finally { WWIO.closeStream(is, this.offsetsFilePath); } }
public ScalarDataBuffer(ScalarReader reader, ScalarAccessor accessor, BufferFactory bufferFactory, int numRows) { this.reader = reader; this.accessor = accessor; this.buffer = bufferFactory.newBuffer(1 + numRows); // Start with position 1 that the coordinate N cooresponds to row id N. this.position = 1; }
public override void Write(byte[] buffer, int offset, int count) { this.CheckDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "cannot be negative"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "cannot be negative"); } if ((int)buffer.Length - offset < count) { throw new ArgumentException("count is greater than the number of available bytes starting at this offset"); } if (offset >= (int)buffer.Length) { throw new ArgumentException("offset is too large for the given buffer"); } while (count > 0) { if (this.streamPosition != (long)this.totalBufferSize) { byte[] numArray = this.buffers[this.currentBufferIndex].Buffer; int length = (int)numArray.Length - this.currentBufferOffset; int num = Math.Min(length, count); Buffer.BlockCopy(buffer, offset, numArray, this.currentBufferOffset, num); this.currentBufferOffset += num; this.streamPosition += (long)num; this.streamLength = Math.Max(this.streamLength, this.streamPosition); count -= num; offset += num; if (this.currentBufferOffset != (int)this.buffers[this.currentBufferIndex].Buffer.Length) { continue; } this.currentBufferIndex++; this.currentBufferOffset = 0; } else { BufferWrapper bufferWrapper = this.bufferManager.GetBuffer(this.minBufferSize); this.buffers.Add(bufferWrapper); this.totalBufferSize += (int)bufferWrapper.Buffer.Length; if (this.totalBufferSize >= 0) { continue; } throw new IOException("too many bytes have accumulated in memory"); } } }
public VecDataBuffer(VecReader reader, int coordsPerElem, BufferFactory bufferFactory, int numRows, int elementsPerRow) { int bufferLength = Math.Max(1, elementsPerRow); BufferWrapper buffer = bufferFactory.newBuffer((1 + numRows) * coordsPerElem * bufferLength); this.reader = reader; this.buffer = new VecBufferSequence(new VecBuffer(coordsPerElem, buffer), 1 + numRows); // Insert an empty coordinate so that the coordinate N cooresponds to row id N. this.buffer.append(VecBuffer.emptyVecBuffer(coordsPerElem)); }
/** * Returns the minimum and maximum floating point values in the specified buffer. Values equivalent to * <code>Double.NaN</code> are ignored. This returns null if the buffer is empty or contains only NaN values. * * @param buffer the buffer to search for the minimum and maximum values. * * @return an array containing the minimum value in index 0 and the maximum value in index 1, or null if the buffer * is empty or contains only NaN values. * * @throws ArgumentException if the buffer is null. */ public static double[] computeExtremeValues(BufferWrapper buffer) { if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new ArgumentException(message); } return(computeExtremeValues(buffer, Double.NaN)); }
/** * Returns a copy of this VecBuffer with the specified new size. The new size must be greater than or equal to this * VecBuffer's size. If the new size is greater than this buffer's size, this returns a new buffer which is * partially filled with the contents of this buffer. The returned VecBuffer has the same number of coordinates per * tuple and the same backing buffer type, but its contents are independent from this VecBuffer. * * @param newSize the new buffer's size. * * @return the new buffer, with the specified size. */ public VecBuffer copyOf(int newSize) { if (newSize < this.getSize()) { String message = Logging.getMessage("generic.SizeOutOfRange", newSize); Logging.logger().severe(message); throw new ArgumentException(message); } BufferWrapper newBuffer = this.buffer.copyOf(this.coordsPerVec * newSize); return(new VecBuffer(this.coordsPerVec, newBuffer)); }
private void OnDataReceived(IAsyncResult asyn) { int bytesRead = _socket.EndReceive(asyn); //------------Handle Multi-byte Charactor------------- _bufferList = new List <BufferWrapper>(); //---------------------------------------------------- do { bytesRead = _socket.Receive(_buffer); SocketLogMgt.SetLog(this, _logID + "Receive succeeded. " + bytesRead.ToString() + " bytes."); //------------Handle Multi-byte Charactor------------- _bufferList.Add(BufferWrapper.Create(_buffer, bytesRead)); //foreach (BufferWrapper w in _bufferList) SocketLogMgt.SetLog(">>>>>>>>>>>> " + w.Buffer.Length.ToString()); //---------------------------------------------------- if (bytesRead > 0) { //No matter how to cut the buffer, ASCII charactor can always be decoded properly, //therefore we can use this segment to detect whether an ending sign (for example "</XMLRequestMessage>") is received. //See class XmlTest.FormCoding for unit test. string str = _entity.Encoder.GetString(_buffer, 0, bytesRead); _sb.Append(str); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, _logID + ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, str); SocketLogMgt.SetLog(this, "------------------------"); } string receiveData = _sb.ToString(); if (SocketHelper.IsEOF(receiveData, _entity.Config.ReceiveEndSign)) { string sendData = null; //------------Handle Multi-byte Charactor------------- receiveData = BufferWrapper.GetString(_entity.Encoder, _bufferList); _bufferList = null; //---------------------------------------------------- _entity.NotifyRequest(receiveData, ref sendData); ResponseData(sendData); break; } } }while (bytesRead > 0); }
private IEnumerator <IAsyncResult> WriteImpl(byte[] buffer, int offset, int count, AsyncIteratorContext <NoResults> context) { this.CheckDisposed(); if (!this.innerStream.CanWrite) { throw new NotSupportedException("writing is not supported by the inner stream"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", "cannot be negative"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "cannot be negative"); } if ((int)buffer.Length - offset < count) { throw new ArgumentException("count is greater than the number of available bytes starting at this offset"); } if (offset >= (int)buffer.Length) { throw new ArgumentException("offset is too large for the given buffer"); } while (count > 0) { if (this.bytesAccumulated == this.totalBufferSize) { BufferWrapper bufferWrapper = BufferPool.GetBuffer(this.minBufferSize); this.buffers.Add(bufferWrapper); this.totalBufferSize += (int)bufferWrapper.Buffer.Length; if (this.totalBufferSize < 0) { throw new IOException("too many bytes have accumulated in memory"); } } byte[] numArray = this.buffers[this.buffers.Count - 1].Buffer; int num = this.totalBufferSize - this.bytesAccumulated; int length = (int)numArray.Length - num; int num1 = Math.Min(num, count); Buffer.BlockCopy(buffer, offset, numArray, length, num1); count -= num1; offset += num1; this.bytesAccumulated += num1; } yield break; }
/** * Returns a new VecBuffer which is a subsequence of this buffer. The new buffer starts with the vector at the * specified position, and has the specified length. The two buffers share the same backing store, so changes to * this buffer are reflected in the new buffer, and visa versa. * * @param position the new buffer's staring position, in logical vectors. * @param size the new buffer's size, in logical vectors. * * @return a subsequence of this buffer. */ public VecBuffer getSubBuffer(int position, int size) { if (position < 0 || position >= this.getSize()) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "position < 0 or position >= size"); Logging.logger().severe(message); throw new ArgumentException(message); } int index = this.indexFromVectorPosition(position); int length = this.indexFromVectorPosition(size); BufferWrapper subBuffer = this.buffer.getSubBuffer(index, length); return(new VecBuffer(this.coordsPerVec, subBuffer)); }
public static string ReadFile(string fname, Encoding encoder) { if (!File.Exists(fname)) { return(null); } using (FileStream fs = File.OpenRead(fname)) { //StringBuilder sb = new StringBuilder(); //byte[] b = new byte[1024]; //while (fs.Read(b, 0, b.Length) > 0) //{ // string str = encoder.GetString(b); // sb.Append(str); //} //return sb.ToString().TrimEnd('\0'); bool isEOF = false; List <BufferWrapper> buffers = new List <BufferWrapper>(); while (!isEOF) { byte[] b = new byte[BufferWrapper.FixLength]; int numofBytes = fs.Read(b, 0, b.Length); if (numofBytes > 0) { BufferWrapper bw = new BufferWrapper(b, numofBytes); buffers.Add(bw); } else { isEOF = true; } } int clength = 0; byte[] totalBuffer = new byte[buffers.Count * BufferWrapper.FixLength]; foreach (BufferWrapper bw in buffers) { bw.Buffer.CopyTo(totalBuffer, clength); clength += bw.Buffer.Length; } string str = encoder.GetString(totalBuffer); return(str.TrimEnd('\0').TrimStart()); // trim utf-8 header !!! 20071218 } }
public IReadOnlyList <byte> ReadBlob(uint offset) { CheckDisposed(); if (BlobStream == null || offset > BlobStream->Size) { throw new ArgumentOutOfRangeException("offset", "Invalid blog offset."); } var pBlob = ((byte *)m_metadataRoot + BlobStream->Offset) + offset; var bufferWrapper = new BufferWrapper(pBlob, (int)(BlobStream->Size - offset)); int bytesRead; var length = SignatureParser.ParseLength(bufferWrapper, out bytesRead); if (length > checked (BlobStream->Size - offset - bytesRead.AssumeGTE(0))) { throw new InvalidOperationException("Blob has invalid size"); } return(new BufferWrapper(pBlob + bytesRead, (int)length)); }
public void Decrypt(IByteBufferAllocator allocator, EncryptMode mode, Stream src, Stream dst, bool reliable) { if (RC4 == null || AES == null) { return; } //throw new ObjectDisposedException(GetType().FullName); using (var data = new BufferWrapper(allocator.Buffer().WithOrder(ByteOrder.LittleEndian))) using (var decryptor = GetAlgorithm(mode).CreateDecryptor()) using (var cs = new CryptoStream(src, decryptor, CryptoStreamMode.Read)) { var padding = cs.ReadByte(); var checksum = cs.ReadByte() | (cs.ReadByte() << 8) | (cs.ReadByte() << 16) | (cs.ReadByte() << 24); using (var dataStream = new WriteOnlyByteBufferStream(data.Buffer, false)) { cs.CopyTo(dataStream); } if (reliable) { var counter = (ushort)(Interlocked.Increment(ref _decryptCounter) - 1); var messageCounter = data.Buffer.GetShort(data.Buffer.ReaderIndex); if (counter != messageCounter) { throw new ProudException($"Invalid decrypt counter! Remote: {messageCounter} Local: {counter}"); } } var slice = data.Buffer.ReadSlice(data.Buffer.ReadableBytes - padding); using (var dataStream = new ReadOnlyByteBufferStream(slice, false)) { if (Hash.GetUInt32 <CRC32>(dataStream) != (uint)checksum) { throw new ProudException("Invalid checksum"); } dataStream.Position = reliable ? 2 : 0; dataStream.CopyTo(dst); } } }
/** * Constructs a new VecBuffer with the specified vector size, and backing BufferWrapper. * * @param coordsPerVec the number of coordinates per logical vector. * @param buffer the backing BufferWrapper. * * @throws ArgumentException if coordsPerElem is 0 or negative, or if the buffer is null. */ public VecBuffer(int coordsPerVec, BufferWrapper buffer) { if (coordsPerVec < 1) { String message = Logging.getMessage("generic.ArgumentOutOfRange", "coordsPerVec < 1"); Logging.logger().severe(message); throw new ArgumentException(message); } if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new ArgumentException(message); } this.coordsPerVec = coordsPerVec; this.buffer = buffer; }
public void Encrypt(IByteBufferAllocator allocator, EncryptMode mode, Stream src, Stream dst, bool reliable) { if (RC4 == null || AES == null) { return; } //throw new ObjectDisposedException(GetType().FullName); using (var data = new BufferWrapper(allocator.Buffer())) using (var encryptor = GetAlgorithm(mode).CreateEncryptor()) using (var cs = new CryptoStream(new NonClosingStream(dst), encryptor, CryptoStreamMode.Write)) using (var w = cs.ToBinaryWriter(false)) { var blockSize = AES.BlockSize / 8; var padding = blockSize - ((src.Length + 1 + 4) % blockSize); if (reliable) { padding = blockSize - ((src.Length + 1 + 4 + 2) % blockSize); } if (reliable) { var counter = (ushort)(Interlocked.Increment(ref _encryptCounter) - 1); data.Buffer.WriteShortLE(counter); } using (var dataStream = new WriteOnlyByteBufferStream(data.Buffer, false)) { src.CopyTo(dataStream); } w.Write((byte)padding); using (var dataStream = new ReadOnlyByteBufferStream(data.Buffer, false)) { w.Write(Hash.GetUInt32 <CRC32>(dataStream)); dataStream.Position = 0; dataStream.CopyTo(cs); } w.Fill((int)padding); } }
public SimplePlotter(NPlot.Windows.PlotSurface2D plotSurface, int bufferSize) : base(plotSurface) { m_BufferSize = bufferSize; m_PointBuffer = CircularBuffer<Sample>.Synchronized(bufferSize); LightStoneDevice.Instance.RawOutput.Add(m_PointBuffer); m_BufferWrapper = new BufferWrapper(m_PointBuffer); this.PlotSurface.Clear(); m_LinePlot = new LinePlot(); m_LinePlot.Pen = new Pen(Color.Red, 2.0f); this.PlotSurface.Add(m_LinePlot); this.PlotSurface.Title = "Heart Signal"; this.PlotSurface.XAxis1.Label = "Time"; this.PlotSurface.YAxis1.Label = "Magnitude"; Refresh(); }
public VecBuffer read(ByteBuffer byteBuffer, int length) { VecBuffer vecBuffer = null; int prevLimit = byteBuffer.limit(); int limit = byteBuffer.position() + (this.coordsPerElem * this.bytesPerCoord * length); try { byteBuffer.limit(limit); BufferWrapper newBuffer = this.doRead(byteBuffer); vecBuffer = new VecBuffer(this.coordsPerElem, newBuffer); } finally { byteBuffer.limit(prevLimit); byteBuffer.position(limit); } return(vecBuffer); }
public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper buffer, AVList list) { base(width, height, sector, list); if (buffer == null) { String message = Logging.getMessage("nullValue.BufferNull"); Logging.logger().severe(message); throw new ArgumentException(message); } int expectedValues = width * height; if (buffer.length() < expectedValues) { String message = Logging.getMessage("generic.BufferSize", "buffer.length() < " + expectedValues); Logging.logger().severe(message); throw new ArgumentException(message); } this.buffer = buffer; }
/** * Returns the minimum and maximum floating point values in the specified buffer. Values equivalent to the specified * <code>missingDataSignal</code> are ignored. This returns null if the buffer is empty or contains only missing * values. * * @param buffer the buffer to search for the minimum and maximum values. * @param missingDataSignal the number indicating a specific floating point value to ignore. * * @return an array containing the minimum value in index 0 and the maximum value in index 1, or null if the buffer * is empty or contains only missing values. * * @throws ArgumentException if the buffer is null. */ public static double[] computeExtremeValues(BufferWrapper buffer, double missingDataSignal) { if (buffer == null) { String message = Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new ArgumentException(message); } double min = Double.MaxValue; double max = -Double.MaxValue; for (int i = 0; i < buffer.length(); i++) { double value = buffer.getDouble(i); if (Double.compare(value, missingDataSignal) == 0) { continue; } if (min > value) { min = value; } if (max < value) { max = value; } } if (Double.compare(min, Double.MaxValue) == 0 || Double.compare(max, -Double.MaxValue) == 0) { return(null); } return(new double[] { min, max }); }
public String ReadUserString(uint offset) { if (UserStringsStream == null || offset > UserStringsStream->Size) { throw new ArgumentOutOfRangeException("offset", "Invalid blog offset."); } var pBlob = ((byte *)m_metadataRoot + UserStringsStream->Offset) + offset; var bufferWrapper = new BufferWrapper(pBlob, (int)(BlobStream->Size - offset)); int bytesRead; var length = SignatureParser.ParseLength(bufferWrapper, out bytesRead); if (length > checked (UserStringsStream->Size - offset - bytesRead.AssumeGTE(0))) { throw new InvalidOperationException("String has invalid size"); } if (length == 0) { return(""); } var pStr = (char *)(pBlob + bytesRead); return(new string(pStr, 0, NativePlatform.Default.WcsLen(pStr, (int)length / 2))); }
public bool hasValue(BufferWrapper bufferWrapper, int index) { // Scalar floats are null when equal to the 32 bit floating point NaN. return(!isNoValueFloat((float)bufferWrapper.getDouble(index))); }
public PacketBufferReader(byte[] data, int length) { _buffer = new BufferWrapper <byte>(data, length); Position = 0; Length = length; }
public Object get(BufferWrapper bufferWrapper, int index) { return(bufferWrapper.getDouble(index)); }
public CrcMemoryStream(BufferWrapper bufferWrapper, int index, int count, long?crcValue, bool writable) : this(bufferWrapper.Buffer, index, count, crcValue, writable) { this.bufferWrapper = bufferWrapper; }
/** * Returns the empty VecBuffer. The returned VecBuffer has no backing buffer, and is immutable. * * @param coordsPerVec the number of coordinates per logical vector. * * @return the empty VecBuffer. */ public static VecBuffer emptyVecBuffer(int coordsPerVec) { return(new VecBuffer(coordsPerVec, BufferWrapper.emptyBufferWrapper())); }
public bool hasValue(BufferWrapper bufferWrapper, int index) { // Scalar ints are null when equal to "no value" 32 bit pattern. return(!isNoValueInt(bufferWrapper.getInt(index))); }
private void OnDataReceived(IAsyncResult asyn) { try { if (_isClosed) { SocketLogMgt.SetLog(SocketLogType.Warning, this, "Data received, but the socket is closed."); return; } int bytesRead = _socket.EndReceive(asyn); //------------Handle Multi-byte Charactor------------- //Buffer all the bytes received and then decode this bytes at one time. //in order to support multi byte charactor set (for example: utf-8) //However, ASCII or GB or BIG5 or Unicode are easy, //we can decode even bytes at each time. List <BufferWrapper> bufferList = new List <BufferWrapper>(); //---------------------------------------------------- do { bytesRead = _socket.Receive(_buffer); SocketLogMgt.SetLog(this, _strSocketID + "Receive succeeded. " + bytesRead.ToString() + " bytes."); UpdateActiveDT(); //------------Handle Multi-byte Charactor------------- bufferList.Add(BufferWrapper.Create(_buffer, bytesRead)); //foreach (BufferWrapper w in bufferList) SocketLogMgt.SetLog(">>>>>>>>>>>> " + w.Buffer.Length.ToString()); //---------------------------------------------------- if (bytesRead > 0) { //No matter how to cut the buffer, ASCII charactor can always be decoded properly, //therefore we can use this segment to detect whether an ASCII charactor ending sign (for example "</XMLRequestMessage>") is received. //See class XmlTest.FormCoding for unit test. string str = _server.Encoder.GetString(_buffer, 0, bytesRead); _sb.Append(str); if (SocketLogMgt.DumpData) { SocketLogMgt.SetLog(this, _strSocketID + ": Data received."); SocketLogMgt.SetLog(this, "------------------------"); SocketLogMgt.SetLog(this, str); SocketLogMgt.SetLog(this, "------------------------"); } string receiveData = _sb.ToString(); if (SocketHelper.FindBlockEnding(receiveData)) { string sendData = null; //------------Handle Multi-byte Charactor------------- receiveData = BufferWrapper.GetString(_server.Encoder, bufferList); bufferList.Clear(); //---------------------------------------------------- receiveData = SocketHelper.UnpackMessageBlock(receiveData); _server.NotifyRequest(receiveData, ref sendData); ResponseData(sendData); //// if allow multiple session per connection, then continue receiving till connection is closed by the client. //if (_server.Config.AllowMultipleSessionPerConnection) // continue; //else // break; continue; } } }while (bytesRead > 0); // if(bytesRead==0) which means the connection is closed by the client, we will close the worker socket. SocketLogMgt.SetLog(this, "Stop receiving data because the connection is closed by the client."); CloseWorker(); } catch (SocketException err) { //needToContinue = false; SocketLogMgt.SetLastError(err); // if client does not send data in some period of time and the connection will be expired // (controled by the lower levels, and this exception occurs when the client send message again after the connection expired) // or other network exception when receiving data, then close the server socket. CloseWorker(); } catch (Exception e) { SocketLogMgt.SetLastError(e); // if communication is ok, but process message failed, do not need to close connection. } }
public bool hasValue(BufferWrapper bufferWrapper, int index) { // Scalar doubles are null when equal to the 64 bit floating point NaN. return(!isNoValueDouble(bufferWrapper.getDouble(index))); }
/** * Computes a <code>Box</code> that bounds a specified buffer of points. Principal axes are computed for the points * and used to form a <code>Box</code>. * <p/> * The buffer must contain XYZ coordinate tuples which are either tightly packed or offset by the specified stride. * The stride specifies the number of buffer elements between the first coordinate of consecutive tuples. For * example, a stride of 3 specifies that each tuple is tightly packed as XYZXYZXYZ, whereas a stride of 5 specifies * that there are two elements between each tuple as XYZabXYZab (the elements "a" and "b" are ignored). The stride * must be at least 3. If the buffer's length is not evenly divisible into stride-sized tuples, this ignores the * remaining elements that follow the last complete tuple. * * @param coordinates the buffer containing the point coordinates for which to compute a bounding volume. * @param stride the number of elements between the first coordinate of consecutive points. If stride is 3, * this interprets the buffer has having tightly packed XYZ coordinate tuples. * * @return the bounding volume, with axes lengths consistent with the conventions described in the <code>Box</code> * class overview. * * @throws ArgumentException if the buffer is null or empty, or if the stride is less than three. */ public static Box computeBoundingBox(BufferWrapper coordinates, int stride) { if (coordinates == null) { String msg = Logging.getMessage("nullValue.CoordinatesAreNull"); Logging.logger().severe(msg); throw new ArgumentException(msg); } if (stride < 3) { String msg = Logging.getMessage("generic.StrideIsInvalid", stride); Logging.logger().severe(msg); throw new ArgumentException(msg); } Vec4[] axes = WWMath.computePrincipalAxes(coordinates, stride); if (axes == null) { String msg = Logging.getMessage("generic.ListIsEmpty"); Logging.logger().severe(msg); throw new ArgumentException(msg); } Vec4 r = axes[0]; Vec4 s = axes[1]; Vec4 t = axes[2]; // Find the extremes along each axis. double minDotR = Double.MaxValue; double maxDotR = -minDotR; double minDotS = Double.MaxValue; double maxDotS = -minDotS; double minDotT = Double.MaxValue; double maxDotT = -minDotT; for (int i = 0; i <= coordinates.length() - stride; i += stride) { double x = coordinates.getDouble(i); double y = coordinates.getDouble(i + 1); double z = coordinates.getDouble(i + 2); double pdr = x * r.x() + y * r.y() + z * r.z(); if (pdr < minDotR) { minDotR = pdr; } if (pdr > maxDotR) { maxDotR = pdr; } double pds = x * s.x() + y * s.y() + z * s.z(); if (pds < minDotS) { minDotS = pds; } if (pds > maxDotS) { maxDotS = pds; } double pdt = x * t.x() + y * t.y() + z * t.z(); if (pdt < minDotT) { minDotT = pdt; } if (pdt > maxDotT) { maxDotT = pdt; } } if (maxDotR == minDotR) { maxDotR = minDotR + 1; } if (maxDotS == minDotS) { maxDotS = minDotS + 1; } if (maxDotT == minDotT) { maxDotT = minDotT + 1; } return(new Box(axes, minDotR, maxDotR, minDotS, maxDotS, minDotT, maxDotT)); }
public BufferWrapperRaster(int width, int height, Sector sector, BufferWrapper buffer) { this(width, height, sector, buffer, null); }