下面列出了怎么用java.nio.IntBuffer的API类实例代码及写法,或者点击链接到github查看源代码。
public void compressChunk(
IntBuffer src,
IntOutputStream dst,
IntFilter filter)
{
src.mark();
filter.saveContext();
int head = 0;
for (int i = 0; i < this.blockNum; ++i) {
int n = this.maxBits[i] = countMaxBits(src, this.blockLen, filter);
head = (head << 8) | n;
}
filter.restoreContext();
src.reset();
dst.write(head);
for (int i = 0; i < this.blockNum; ++i) {
pack(src, dst, this.maxBits[i], this.blockLen, filter);
}
}
public Texture(String fileName) throws Exception {
ByteBuffer buf;
// Load Texture file
try (MemoryStack stack = MemoryStack.stackPush()) {
IntBuffer w = stack.mallocInt(1);
IntBuffer h = stack.mallocInt(1);
IntBuffer channels = stack.mallocInt(1);
buf = stbi_load(fileName, w, h, channels, 4);
if (buf == null) {
throw new Exception("Image file [" + fileName + "] not loaded: " + stbi_failure_reason());
}
width = w.get();
height = h.get();
}
this.id = createTexture(buf);
stbi_image_free(buf);
}
@Override
public void prepareEnvironment(JsonObject environmentJson) {
final JsonObject bufferJson = environmentJson.get("buffer").getAsJsonObject();
final int bufferBinding = bufferJson.get("binding").getAsInt();
final int[] bufferInput = UniformSetter.getIntArray(bufferJson.get("input").getAsJsonArray());
final IntBuffer intBufferData = BufferUtils.createIntBuffer(bufferInput.length);
intBufferData.put(bufferInput);
intBufferData.flip();
shaderStorageBufferObject = GL15.glGenBuffers();
checkError();
GL15.glBindBuffer(GL43.GL_SHADER_STORAGE_BUFFER, shaderStorageBufferObject);
checkError();
GL15.glBufferData(GL43.GL_SHADER_STORAGE_BUFFER, intBufferData, GL15.GL_STATIC_DRAW);
checkError();
GL30.glBindBufferBase(GL43.GL_SHADER_STORAGE_BUFFER, bufferBinding, shaderStorageBufferObject);
checkError();
numGroups = UniformSetter.getIntArray(environmentJson.get("num_groups").getAsJsonArray());
}
@Override
public Set<Integer> getLe(
final IDicManager dicManager ,
final IntBuffer dicIndexIntBuffer ,
final NumberFilter numberFilter ) throws IOException {
Float target;
try {
target = Float.valueOf( numberFilter.getNumberObject().getFloat() );
} catch ( NumberFormatException ex ) {
return null;
}
Set<Integer> matchDicList = new HashSet<Integer>();
for ( int i = 0 ; i < dicManager.getDicSize() ; i++ ) {
PrimitiveObject numObj = dicManager.get( i );
if ( numObj == null ) {
continue;
}
if ( 0 <= target.compareTo( numObj.getFloat() ) ) {
matchDicList.add( Integer.valueOf( i ) );
}
}
return matchDicList;
}
public static int loadTexture(final IntBuffer data, final Size size, final int usedTexId) {
int textures[] = new int[1];
if (usedTexId == NO_TEXTURE) {
GLES20.glGenTextures(1, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, size.width, size.height,
0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, data);
} else {
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, usedTexId);
GLES20.glTexSubImage2D(GLES20.GL_TEXTURE_2D, 0, 0, 0, size.width,
size.height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, data);
textures[0] = usedTexId;
}
return textures[0];
}
@Test
public void T_long_filter_3() throws IOException{
List<PrimitiveObject> dic = new ArrayList<PrimitiveObject>();
dic.add( new LongObj( 1000 ) );
dic.add( new LongObj( 2000 ) );
dic.add( new LongObj( 3000 ) );
dic.add( new LongObj( 4000 ) );
dic.add( new LongObj( 5000 ) );
IntBuffer buffer = IntBuffer.allocate( 100 );
for( int i = 0 ; i < 100 ; i++ ){
buffer.put( i % 5 );
}
ICellIndex index = new BufferDirectSequentialNumberCellIndex( ColumnType.LONG , new TestDicManager( dic ) , buffer );
IFilter filter = new NumberFilter( NumberFilterType.LT , new LongObj( 2000 ) );
FilterdExpressionIndex result = new FilterdExpressionIndex( index.filter( filter , new boolean[100] ) );
assertEquals( result.size() , 20 );
for( int i = 0,n=0 ; n < 100 ; i++,n+=5 ){
assertEquals( result.get(i) , n );
}
}
private void create() throws IOException{
ICompressor compressor = FindCompressor.get( columnBinary.compressorClassName );
byte[] decompressBuffer = compressor.decompress( columnBinary.binary , columnBinary.binaryStart , columnBinary.binaryLength );
IntBuffer wrapBuffer = ByteBuffer.wrap( decompressBuffer ).asIntBuffer() ;
arrayColumn = new ArrayColumn( columnBinary.columnName );
Spread spread = new Spread( arrayColumn );
for( ColumnBinary childColumnBinary : columnBinary.columnBinaryList ){
IColumnBinaryMaker maker = FindColumnBinaryMaker.get( childColumnBinary.makerClassName );
IColumn column = maker.toColumn( childColumnBinary );
column.setParentsColumn( arrayColumn );
spread.addColumn( column );
}
spread.setRowCount( columnBinary.rowCount );
arrayColumn.setSpread( spread );
arrayColumn.setCellManager( new ArrayCellManager( spread , wrapBuffer ) );
isCreate = true;
}
@Test
public void T_filter_2() throws IOException{
List<PrimitiveObject> dic = new ArrayList<PrimitiveObject>();
dic.add( new StringObj( "abc" ) );
dic.add( new StringObj( "bcd" ) );
dic.add( new StringObj( "cde" ) );
dic.add( new StringObj( "def" ) );
dic.add( new StringObj( "efg" ) );
IntBuffer buffer = IntBuffer.allocate( 100 );
for( int i = 0 ; i < 100 ; i++ ){
buffer.put( i % 5 );
}
ICellIndex index = new BufferDirectSequentialStringCellIndex( new TestDicManager( dic ) , buffer );
IFilter filter = new PartialMatchStringFilter( "b" );
FilterdExpressionIndex result = new FilterdExpressionIndex( index.filter( filter , new boolean[100] ) );
assertEquals( result.size() , 40 );
for( int i = 0,n=0 ; n < 100 ; i+=2,n+=5 ){
assertEquals( result.get(i) , n );
assertEquals( result.get(i+1) , n+1 );
}
}
/**
* Determine the appropriate {@link WritablePixelFormat} type that can be
* used to transfer data into the indicated BufferedImage.
*
* @param bimg
* the BufferedImage that will be used as a destination for a
* {@code PixelReader<IntBuffer>#getPixels()} operation.
* @return
*/
private static WritablePixelFormat<IntBuffer> getAssociatedPixelFormat(BufferedImage bimg) {
switch (bimg.getType()) {
// We lie here for xRGB, but we vetted that the src data was opaque
// so we can ignore the alpha. We use ArgbPre instead of Argb
// just to get a loop that does not have divides in it if the
// PixelReader happens to not know the data is opaque.
case BufferedImage.TYPE_INT_RGB:
case BufferedImage.TYPE_INT_ARGB_PRE:
return PixelFormat.getIntArgbPreInstance();
case BufferedImage.TYPE_INT_ARGB:
return PixelFormat.getIntArgbInstance();
default:
// Should not happen...
throw new InternalError("Failed to validate BufferedImage type");
}
}
private boolean initVertexBuffer(GL4 gl4) {
FloatBuffer vertexBuffer = GLBuffers.newDirectFloatBuffer(vertexData);
IntBuffer elementBuffer = GLBuffers.newDirectIntBuffer(elementData);
gl4.glGenBuffers(Buffer.MAX, bufferName);
gl4.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(Buffer.VERTEX));
gl4.glBufferData(GL_ARRAY_BUFFER, vertexSize, vertexBuffer, GL_STATIC_DRAW);
gl4.glBindBuffer(GL_ARRAY_BUFFER, 0);
gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName.get(Buffer.ELEMENT));
gl4.glBufferData(GL_ELEMENT_ARRAY_BUFFER, elementSize, elementBuffer, GL_STATIC_DRAW);
gl4.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
BufferUtils.destroyDirectBuffer(vertexBuffer);
BufferUtils.destroyDirectBuffer(elementBuffer);
return checkError(gl4, "initArrayBuffer");
}
/**
* For debugging: Print program log info
*
* @param id program ID
*/
private void printProgramLogInfo(int id)
{
IntBuffer infoLogLength = ByteBuffer
.allocateDirect(4)
.order(ByteOrder.nativeOrder())
.asIntBuffer();
gl.glGetProgramiv(id, GL_INFO_LOG_LENGTH, infoLogLength);
if (infoLogLength.get(0) > 0)
{
infoLogLength.put(0, infoLogLength.get(0) - 1);
}
ByteBuffer infoLog = ByteBuffer
.allocateDirect(infoLogLength.get(0))
.order(ByteOrder.nativeOrder());
gl.glGetProgramInfoLog(id, infoLogLength.get(0), null, infoLog);
String infoLogString =
Charset.forName("US-ASCII").decode(infoLog).toString();
if (infoLogString.trim().length() > 0)
{
logger.warning("program log:\n"+infoLogString);
}
}
@Test
public void T_int_filter_8() throws IOException{
List<PrimitiveObject> dic = new ArrayList<PrimitiveObject>();
dic.add( new IntegerObj( 1000 ) );
dic.add( new IntegerObj( 2000 ) );
dic.add( new IntegerObj( 3000 ) );
dic.add( new IntegerObj( 4000 ) );
dic.add( new IntegerObj( 5000 ) );
IntBuffer buffer = IntBuffer.allocate( 100 );
for( int i = 0 ; i < 100 ; i++ ){
buffer.put( i % 5 );
}
ICellIndex index = new BufferDirectSequentialNumberCellIndex( ColumnType.INTEGER , new TestDicManager( dic ) , buffer );
IFilter filter = new NumberFilter( NumberFilterType.GE , new LongObj( Long.valueOf( Integer.MIN_VALUE ) - (long)1 ) );
assertEquals( null , index.filter( filter , new boolean[100] ) );
}
private boolean initBuffer(GL3 gl3) {
FloatBuffer positionBuffer = GLBuffers.newDirectFloatBuffer(positionData);
IntBuffer uniformBufferOffset = GLBuffers.newDirectIntBuffer(1);
gl3.glGenBuffers(Buffer.MAX, bufferName);
gl3.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(Buffer.VERTEX));
gl3.glBufferData(GL_ARRAY_BUFFER, positionSize, positionBuffer, GL_STATIC_DRAW);
gl3.glBindBuffer(GL_ARRAY_BUFFER, 0);
gl3.glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, uniformBufferOffset);
int uniformTransformBlockSize = Math.max(2 * Mat4.SIZE, uniformBufferOffset.get(0));
gl3.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.TRANSFORM));
gl3.glBufferData(GL_UNIFORM_BUFFER, uniformTransformBlockSize, null, GL_DYNAMIC_DRAW);
gl3.glBindBuffer(GL_UNIFORM_BUFFER, 0);
BufferUtils.destroyDirectBuffer(positionBuffer);
BufferUtils.destroyDirectBuffer(uniformBufferOffset);
return checkError(gl3, "initBuffer");
}
static public int loadShader(int type, String shaderCode)
{
int shader = GLES20.glCreateShader(type);
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
IntBuffer compile = IntBuffer.allocate(1);
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compile);
if (compile.get(0) == GLES20.GL_FALSE) {
Log.e(Config.TAG, "Error:");
Log.e(Config.TAG, shaderCode);
Log.e(Config.TAG, "Fault:");
printLog(shader);
return 0;
}
return shader;
}
@Override
public Set<Integer> getLt(
final IDicManager dicManager ,
final IntBuffer dicIndexIntBuffer ,
final NumberFilter numberFilter ) throws IOException {
byte target;
try {
target = numberFilter.getNumberObject().getByte();
} catch ( NumberFormatException ex ) {
return null;
}
Set<Integer> matchDicList = new HashSet<Integer>();
for ( int i = 0 ; i < dicManager.getDicSize() ; i++ ) {
PrimitiveObject numObj = dicManager.get( i );
if ( numObj == null ) {
continue;
}
if ( numObj.getByte() < target ) {
matchDicList.add( Integer.valueOf( i ) );
}
}
return matchDicList;
}
/**
* Writes some data to the device.
*
* @param handle
* The device handle.
* @param data
* The data to send to the device.
*/
public static void write(DeviceHandle handle, byte[] data)
{
ByteBuffer buffer = BufferUtils.allocateByteBuffer(data.length);
buffer.put(data);
IntBuffer transferred = BufferUtils.allocateIntBuffer();
int result = LibUsb.bulkTransfer(handle, OUT_ENDPOINT, buffer,
transferred, TIMEOUT);
if (result != LibUsb.SUCCESS)
{
throw new LibUsbException("Unable to send data", result);
}
System.out.println(transferred.get() + " bytes sent to device");
}
private void fillStructureArray(ArrayStructureBB sa) {
ByteBuffer bb = sa.getByteBuffer();
IntBuffer ibb = bb.asIntBuffer();
int count = 0;
for (int i = 0; i < ibb.capacity(); i++)
ibb.put(i, count++);
}
@Override
public GLRenderableUpdateTask createBatch(final VisualAccess access) {
int loopCounter = 0;
for (int i = 0; i < access.getConnectionCount(); i++) {
if (access.getConnectionLowVertex(i) == access.getConnectionHighVertex(i)) {
loopPosToBufferPos.put(i, loopCounter++);
}
}
final int numLoops = loopCounter;
FloatBuffer colorBuffer = Buffers.newDirectFloatBuffer(numLoops * COLOR_BUFFER_WIDTH);
IntBuffer dataBuffer = Buffers.newDirectIntBuffer(numLoops * LOOP_INFO_BUFFER_WIDTH);
loopPosToBufferPos.keySet().forEach(pos -> {
bufferColorInfo(pos, colorBuffer, access);
bufferLoopInfo(pos, dataBuffer, access);
});
colorBuffer.flip();
dataBuffer.flip();
return gl -> {
if (numLoops > 0) {
batch.initialise(numLoops);
batch.buffer(gl, colorTarget, colorBuffer);
batch.buffer(gl, loopInfoTarget, dataBuffer);
batch.finalise(gl);
}
};
}
private boolean initBuffer(GL4 gl4) {
ByteBuffer vertexBuffer = GLBuffers.newDirectByteBuffer(vertexSize);
IntBuffer uniformBufferOffset = GLBuffers.newDirectIntBuffer(1);
gl4.glGenBuffers(Buffer.MAX, bufferName);
gl4.glBindBuffer(GL_ARRAY_BUFFER, bufferName.get(Buffer.VERTEX));
for (int i = 0; i < vertexCount; i++) {
vertexData[i].toDbb(vertexBuffer, i * Vec2.SIZE);
}
gl4.glBufferData(GL_ARRAY_BUFFER, vertexSize, vertexBuffer, GL_STATIC_DRAW);
gl4.glBindBuffer(GL_ARRAY_BUFFER, 0);
gl4.glGetIntegerv(
GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT,
uniformBufferOffset);
int uniformBlockSize = Math.max(Transform.SIZE, uniformBufferOffset.get(0));
gl4.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(Buffer.TRANSFORM));
gl4.glBufferData(GL_UNIFORM_BUFFER, uniformBlockSize, null, GL_DYNAMIC_DRAW);
gl4.glBindBuffer(GL_UNIFORM_BUFFER, 0);
BufferUtils.destroyDirectBuffer(vertexBuffer);
BufferUtils.destroyDirectBuffer(uniformBufferOffset);
return true;
}
/**
* Create a byte buffer containing the data of the indices for the
* given OBJ. The face vertex indices of the given OBJ will be
* extracted (assuming that it contains only triangles), converted
* to the given indices component type (which is a GL constant like
* GL_SHORT), and a byte buffer containing these indices will be returned.
*
* @param obj The OBJ
* @param indicesComponentType The indices component type
* @return The byte buffer
*/
private static ByteBuffer createIndicesByteBuffer(
ReadableObj obj, int indicesComponentType)
{
int numVerticesPerFace = 3;
IntBuffer objIndices =
ObjData.getFaceVertexIndices(obj, numVerticesPerFace);
int indicesComponentSize =
Accessors.getNumBytesForAccessorComponentType(
indicesComponentType);
ByteBuffer indicesByteBuffer =
IntBuffers.convertToByteBuffer(objIndices, indicesComponentSize);
return indicesByteBuffer;
}
private boolean initQuery(GL4 gl4) {
gl4.glGenQueries(1, queryName);
IntBuffer queryBitsBuffer = GLBuffers.newDirectIntBuffer(1);
gl4.glGetQueryiv(GL_PRIMITIVES_GENERATED, GL_QUERY_COUNTER_BITS, queryBitsBuffer);
int queryBits = queryBitsBuffer.get(0);
BufferUtils.destroyDirectBuffer(queryBitsBuffer);
return queryBits >= 32;
}
@Override
public IntBuffer getIndexIntBuffer( final int size , final ByteBuffer wrapBuffer ) throws IOException{
IntBuffer result = IntBuffer.allocate( size );
for( int i = 0 ; i < size ; i++ ){
result.put( wrapBuffer.getInt() );
}
result.position( 0 );
return result;
}
/**
* Decodes a Spot from a byte representation, if the given text match the
* spot text encoded in the byte array.
*
* @see toByteArray
*
* @param text
* - the spot text to decode
* @param data
* - the binary rep for the spot
* @return A spot if the given string <code> text </code> matches the text
* of the spot encoded in data, otherwise null
*/
public static Spot fromByteArray(String text, byte[] data) {
int len = data[0];
if (text.length() != len) {
logger.warn("len {} != {} len", len, text);
return null;
}
String s = null;
try {
s = new String(Arrays.copyOfRange(data, 1, 1 + len), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!s.equals(text)) {
logger.warn(" {} != {} ", s, text);
return null;
}
IntBuffer intBuf = ByteBuffer.wrap(
Arrays.copyOfRange(data, 1 + len, data.length)).asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
// List<Entity> entities = null;
List<Entity> entities = new ArrayList<Entity>(array.length - 2);
for (int i = 2; i < array.length; i += 2) {
entities.add(new Entity(array[i], array[i + 1]));
}
Spot spot = new Spot(text, entities, array[0], array[1]);
return spot;
}
@Override
public IntBuffer getIndexIntBuffer( final byte[] buffer , final int start , final int length ) throws IOException{
int size = length / Short.BYTES;
ByteBuffer wrapBuffer = ByteBuffer.wrap( buffer , start , length );
IntBuffer result = IntBuffer.allocate( size );
for( int i = 0 ; i < size ; i++ ){
result.put( (int)( wrapBuffer.getShort() ) );
}
result.position( 0 );
return result;
}
/**
* Initialise the FBO that will be used to render to
*
* @throws SlickException
*/
private void init() throws SlickException {
IntBuffer buffer = BufferUtils.createIntBuffer(1);
EXTFramebufferObject.glGenFramebuffersEXT(buffer);
FBO = buffer.get();
// for some reason FBOs won't work on textures unless you've absolutely just
// created them.
try {
Texture tex = InternalTextureLoader.get().createTexture(image.getWidth(), image.getHeight(), image.getFilter());
EXTFramebufferObject.glBindFramebufferEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT, FBO);
EXTFramebufferObject.glFramebufferTexture2DEXT(EXTFramebufferObject.GL_FRAMEBUFFER_EXT,
EXTFramebufferObject.GL_COLOR_ATTACHMENT0_EXT,
GL11.GL_TEXTURE_2D, tex.getTextureID(), 0);
completeCheck();
unbind();
// Clear our destination area before using it
clear();
flush();
// keep hold of the original content
drawImage(image, 0, 0);
image.setTexture(tex);
} catch (Exception e) {
throw new SlickException("Failed to create new texture for FBO");
}
}
public static void decodeBlockPack(
IntBuffer src,
IntFilterFactory filterFactory,
IntBitPacking packer,
IntOutputStream dst)
{
// Fetch length of original array.
if (!src.hasRemaining()) {
return;
}
final int outLen = (int)src.get() - 1;
// Fetch and output first int, and set it as delta's initial context.
final int first = src.get();
dst.write(first);
IntFilter filter = filterFactory.newFilter(first);
// Decompress intermediate blocks.
final int chunkSize = packer.getBlockSize();
final int chunkNum = outLen / chunkSize;
if (chunkNum > 0) {
packer.decompress(src, dst, filter, chunkNum);
}
// Decompress last block.
final int chunkRemain = outLen % chunkSize;
if (chunkRemain > 0) {
int[] last = new int[chunkSize];
IntBuffer buf = IntBuffer.wrap(last);
packer.decompress(src, new IntBufferOutputStream(buf),
filter, 1);
dst.write(last, 0, chunkRemain);
}
}
@Override
public void test() throws IOException {
FileChannel fc = new RandomAccessFile(
new File("data.txt"),"rw").getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE,
0,fc.size()).asIntBuffer();
ib.put(0);
for (int i = 1; i < numOfUbuffInts; i++)
ib.put(ib.get(i-1));
fc.close();
}
public int[] decompress(byte[] src) {
IntBuffer srcBuf = ByteBuffer.wrap(src).asIntBuffer();
int len = decompressLength(srcBuf);
IntArrayOutputStream dst = (len < 0)
? new IntArrayOutputStream() : new IntArrayOutputStream(len);
decompress(srcBuf, dst);
return dst.toIntArray();
}
/**
* Manage it as an Array cell.
*/
public ArrayCellManager( final Spread spread , final IntBuffer buffer ) {
int length = buffer.capacity();
cellArray = new ICell[length];
int currentIndex = 0;
for ( int i = 0 ; i < length ; i++ ) {
int arrayLength = buffer.get();
if ( arrayLength != 0 ) {
int start = currentIndex;
int end = start + arrayLength;
cellArray[i] = new ArrayCell( new SpreadArrayLink( spread , i , start , end ) );
currentIndex += arrayLength;
}
}
}
@Test
public void testBuff() {
int[] shape = {1, 2};
int[] stride = {1, 2};
IntBuffer buff = Shape.createShapeInformation(shape, stride, 0, 1, 'c').asNioInt();
assertTrue(Shape.isVector(buff));
}