Java Code Examples for java.nio.FloatBuffer#allocate()

The following examples show how to use java.nio.FloatBuffer#allocate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OverlayLine.java    From jaamsim with Apache License 2.0 6 votes vote down vote up
public OverlayLine(  List<Vec2d> lineSegments, Color4d color,
                     boolean originTop, boolean originRight,
                     double lineWidth, VisibilityInfo visInfo,
                     long pickingID) {
	this.color = color;
	this.lineWidth = lineWidth;
	this.pickingID = pickingID;
	this.visInfo = visInfo;
	this.originTop = originTop;
	this.originRight = originRight;

	lineBuffer = FloatBuffer.allocate(2 * lineSegments.size());
	for (Vec2d vert : lineSegments) {
		RenderUtils.putPointXY(lineBuffer, vert);
	}
	lineBuffer.flip();

}
 
Example 2
Source File: BufferUtils.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new FloatBuffer with the same contents as the given FloatBuffer. The new FloatBuffer is seperate from the old one and changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the FloatBuffer to copy
 * @return the copy
 */
public static FloatBuffer clone(FloatBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	FloatBuffer copy;
	if (buf.isDirect()) {
		copy = createFloatBuffer(buf.limit());
	}
	else {
		copy = FloatBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
Example 3
Source File: BufferUtils.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Creates a new FloatBuffer with the same contents as the given
 * FloatBuffer. The new FloatBuffer is seperate from the old one and changes
 * are not reflected across. If you want to reflect changes, consider using
 * Buffer.duplicate().
 *
 * @param buf
 *            the FloatBuffer to copy
 * @return the copy
 */
public static FloatBuffer clone(FloatBuffer buf) {
    if (buf == null) {
        return null;
    }
    buf.rewind();

    FloatBuffer copy;
    if (buf.isDirect()) {
        copy = createFloatBuffer(buf.limit());
    } else {
        copy = FloatBuffer.allocate(buf.limit());
    }
    copy.put(buf);

    return copy;
}
 
Example 4
Source File: Horizon.java    From Muzesto with GNU General Public License v3.0 6 votes vote down vote up
private float[] byteToFloat(byte[] input) {
    ByteBuffer buffer = ByteBuffer.wrap(input);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    FloatBuffer floatBuffer = FloatBuffer.allocate(input.length / bytesPerSample);
    switch (bytesPerSample) {
        case 1:
            for (int i = 0; i < floatBuffer.capacity(); i++) {
                floatBuffer.put(buffer.get(i * bytesPerSample));
            }
            return floatBuffer.array();
        case 2:
            for (int i = 0; i < floatBuffer.capacity(); i++) {
                floatBuffer.put(buffer.getShort(i * bytesPerSample));
            }
            return floatBuffer.array();
        case 4:
            for (int i = 0; i < floatBuffer.capacity(); i++) {
                floatBuffer.put(buffer.getInt(i * bytesPerSample));
            }
            return floatBuffer.array();

    }
    return null;
}
 
Example 5
Source File: Noise.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public FloatBuffer getBuffer(float sx, float sy, float base, int size) {
	FloatBuffer retval = FloatBuffer.allocate(size * size);
	for (int y = 0; y < size; y++) {
		for (int x = 0; x < size; x++) {
			retval.put(this.modulate((sx + x) / size, (sy + y) / size, base));
		}
	}
	return retval;
}
 
Example 6
Source File: Polygon.java    From jaamsim with Apache License 2.0 5 votes vote down vote up
public Polygon(List<Vec4d> points, Transform trans, Vec3d scale, Color4d colour,
		Color4d hoverColour, VisibilityInfo visInfo, boolean isOutline, double lineWidth, long pickingID) {
	this.colour = colour.toFloats();
	this.hoverColour = hoverColour.toFloats();
	this.isOutline = isOutline;
	this.lineWidth = lineWidth;
	this.pickingID = pickingID;
	this.trans = trans;
	this._visInfo = visInfo;

	// Points includes the scale, but not the transform
	_points = new ArrayList<>(points.size());

	ArrayList<Vec3d> boundsPoints = new ArrayList<>(points.size());
	for (Vec4d p : points) {
		Vec3d temp = new Vec3d(p);
		temp.mul3(scale);
		_points.add(temp);

		Vec3d bTemp = new Vec3d();
		trans.multAndTrans(temp, bTemp);
		boundsPoints.add(bTemp);
	}

	_bounds = new AABB(boundsPoints);

	if (this.isOutline) {
		fb = FloatBuffer.allocate(3 * _points.size());
		for (Vec3d vert : _points) {
			RenderUtils.putPointXYZ(fb, vert);
		}
		fb.flip();
	} else {
		// Filled polygons are tesselated at render time because
		// we use the GLU tesselator which needs an active openGL context
	}
}
 
Example 7
Source File: Mat3Test.java    From jglm with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewWithBuffer() {
	FloatBuffer buffer = FloatBuffer.allocate(9);
	buffer.put(1f).put(2f).put(3f).put(4f).put(5f).put(6f).put(7f).put(8f).put(9f);
	buffer.flip();
	
	Mat3 m1 = new Mat3(buffer);
	Mat3 m2 = new Mat3(
			1f, 2f, 3f,
			4f, 5f, 6f,
			7f, 8f, 9f
	);
	
	Assert.assertEquals(m2, m1);
}
 
Example 8
Source File: MeshProto.java    From jaamsim with Apache License 2.0 5 votes vote down vote up
private void loadGPUSubLine(GL2GL3 gl, Renderer renderer, MeshData.SubLineData data) {

	Shader s = renderer.getShader(Renderer.ShaderHandle.DEBUG);

	assert (s.isGood());

	SubLine sub = new SubLine();
	sub._progHandle = s.getProgramHandle();

	int[] is = new int[1];
	gl.glGenBuffers(1, is, 0);
	sub._vertexBuffer = is[0];

	sub._numVerts = data.verts.size();

	sub._hull = data.hull;

	// Init vertices
	FloatBuffer fb = FloatBuffer.allocate(data.verts.size() * 3); //
	for (Vec3d v : data.verts) {
		RenderUtils.putPointXYZ(fb, v);
	}
	fb.flip();

	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, sub._vertexBuffer);
	gl.glBufferData(GL2GL3.GL_ARRAY_BUFFER, sub._numVerts * 3 * 4, fb, GL2GL3.GL_STATIC_DRAW);

	// Bind the shader variables
	sub._modelViewMatVar = gl.glGetUniformLocation(sub._progHandle, "modelViewMat");
	sub._projMatVar = gl.glGetUniformLocation(sub._progHandle, "projMat");

	sub._diffuseColor = new Color4d(data.diffuseColor);
	sub._colorVar = gl.glGetUniformLocation(sub._progHandle, "color");

	sub._cVar = gl.glGetUniformLocation(sub._progHandle, "C");
	sub._fcVar = gl.glGetUniformLocation(sub._progHandle, "FC");

	_subLines.add(sub);
}
 
Example 9
Source File: TessAPITest.java    From tess4j with Apache License 2.0 5 votes vote down vote up
/**
 * Test of TessBaseAPIDetectOrientationScript method, of class TessAPI.
 *
 * @throws java.lang.Exception
 */
@Test
public void testTessBaseAPIDetectOrientationScript() throws Exception {
    logger.info("TessBaseAPIDetectOrientationScript");
    File image = new File(testResourcesDataPath, "eurotext90.png");
    int expResult = TRUE;
    Leptonica leptInstance = Leptonica.INSTANCE;
    Pix pix = leptInstance.pixRead(image.getPath());
    api.TessBaseAPIInit3(handle, datapath, "osd");
    api.TessBaseAPISetImage2(handle, pix);

    IntBuffer orient_degB = IntBuffer.allocate(1);
    FloatBuffer orient_confB = FloatBuffer.allocate(1);
    PointerByReference script_nameB = new PointerByReference();
    FloatBuffer script_confB = FloatBuffer.allocate(1);

    int result = api.TessBaseAPIDetectOrientationScript(handle, orient_degB, orient_confB, script_nameB, script_confB);
    if (result == TRUE) {
        int orient_deg = orient_degB.get();
        float orient_conf = orient_confB.get();
        String script_name = script_nameB.getValue().getString(0);
        float script_conf = script_confB.get();
        logger.info(String.format("OrientationScript: orient_deg=%d, orient_conf=%f, script_name=%s, script_conf=%f", orient_deg, orient_conf, script_name, script_conf));
    }

    PointerByReference pRef = new PointerByReference();
    pRef.setValue(pix.getPointer());
    leptInstance.pixDestroy(pRef);
    assertEquals(expResult, result);
}
 
Example 10
Source File: TensorFlowModel.java    From samantha with MIT License 5 votes vote down vote up
private List<double[][]> fetch(Session.Runner runner, List<String> operations, List<Integer> outputIndices) {
    for (int i=0; i<operations.size(); i++) {
        runner.fetch(operations.get(i), outputIndices.get(i));
    }
    List<Tensor<?>> results = runner.run();
    List<double[][]> predsList = new ArrayList<>();
    for (int x=0; x<operations.size(); x++) {
        Tensor<?> tensorOutput = results.get(x);
        int dim = tensorOutput.numDimensions();
        if (dim > 2) {
            throw new BadRequestException(
                    "The TensorFlow model should always output with a one or two dimensional tensor. " +
                            "Currently it is " + Integer.valueOf(dim).toString());
        }
        long[] outputShape = tensorOutput.shape();
        long ncol = 1;
        if (outputShape.length > 1) {
            ncol = outputShape[1];
        }
        double[][] preds = new double[(int) outputShape[0]][(int) ncol];
        FloatBuffer buffer = FloatBuffer.allocate(tensorOutput.numElements());
        tensorOutput.writeTo(buffer);
        int k = 0;
        for (int i = 0; i < preds.length; i++) {
            for (int j = 0; j < preds[0].length; j++) {
                preds[i][j] = buffer.get(k++);
            }
        }
        buffer.clear();
        results.get(x).close();
        predsList.add(preds);
    }
    return predsList;
}
 
Example 11
Source File: Model.java    From Robot-Overlord-App with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Regenerate the optimized rendering buffers for the fixed function pipeline.
 * Also recalculate the bounding box.
 * @param gl2
 */
private void updateBuffers(GL2 gl2) {
	int numVertexes = vertexArray.size()/3;
	Iterator<Float> fi;
	int j=0;

	Point3d boundBottom = new Point3d(Double.MAX_VALUE,Double.MAX_VALUE,Double.MAX_VALUE);
	Point3d boundTop = new Point3d(-Double.MAX_VALUE,-Double.MAX_VALUE,-Double.MAX_VALUE);

	FloatBuffer vertices = FloatBuffer.allocate(vertexArray.size());
	fi = vertexArray.iterator();
	Point3d p = new Point3d();
	while(fi.hasNext()) {
		p.x = fi.next().floatValue();
		p.y = fi.next().floatValue();
		p.z = fi.next().floatValue();
		adjust.transform(p);
		vertices.put(j++, (float)p.x);
		vertices.put(j++, (float)p.y);
		vertices.put(j++, (float)p.z);
		
		// also recalculate the bounding limits			
		if(boundBottom.x>p.x) boundBottom.x=p.x;
		if(boundBottom.y>p.y) boundBottom.y=p.y;
		if(boundBottom.z>p.z) boundBottom.z=p.z;
		if(boundTop.x<p.x) boundTop.x=p.x;
		if(boundTop.y<p.y) boundTop.y=p.y;
		if(boundTop.z<p.z) boundTop.z=p.z;
	}
	
	cuboid.setBounds(boundTop, boundBottom);

	int s=(Float.SIZE/8);  // bits per float / bits per byte = bytes per float
	int totalBufferSize = numVertexes*3*s;
	int vboIndex=0;
	
	// bind a buffer
	vertices.rewind();
	gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[vboIndex]);
    // Write out vertex buffer to the currently bound VBO.
    gl2.glBufferData(GL2.GL_ARRAY_BUFFER, totalBufferSize, vertices, GL2.GL_STATIC_DRAW);
    vboIndex++;
    
	if(hasNormals) {
		j=0;
	    // repeat for normals
		Matrix3d pose = new Matrix3d();
		adjust.get(pose);
		FloatBuffer normals = FloatBuffer.allocate(normalArray.size());
		fi = normalArray.iterator();
		while(fi.hasNext()) {
			p.x = fi.next().floatValue();
			p.y = fi.next().floatValue();
			p.z = fi.next().floatValue();
			pose.transform(p);
			normals.put(j++, (float)p.x);
			normals.put(j++, (float)p.y);
			normals.put(j++, (float)p.z);
		}
		
		normals.rewind();
		gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[vboIndex]);
	    gl2.glBufferData(GL2.GL_ARRAY_BUFFER, totalBufferSize, normals, GL2.GL_STATIC_DRAW);
	    vboIndex++;
	}

	if(hasColors) {
	    // repeat for colors
		FloatBuffer colors = FloatBuffer.allocate(colorArray.size());
		fi = colorArray.iterator();
		while(fi.hasNext()) {
			colors.put(fi.next().floatValue());
		}
		
		colors.rewind();
		gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[vboIndex]);
	    gl2.glBufferData(GL2.GL_ARRAY_BUFFER, totalBufferSize, colors, GL2.GL_STATIC_DRAW);
	    vboIndex++;
	}
	
	if(hasUVs) {
	    // repeat for textures
		FloatBuffer texCoords = FloatBuffer.allocate(texCoordArray.size());
		fi = texCoordArray.iterator();
		while(fi.hasNext()) {
			texCoords.put(fi.next().floatValue());
		}
		
	    texCoords.rewind();
		gl2.glBindBuffer(GL2.GL_ARRAY_BUFFER, VBO[vboIndex]);
	    gl2.glBufferData(GL2.GL_ARRAY_BUFFER, numVertexes*2*s, texCoords, GL2.GL_STATIC_DRAW);
	    vboIndex++;
	}
}
 
Example 12
Source File: LeptUtils.java    From lept4j with Apache License 2.0 4 votes vote down vote up
/**
 * Removes horizontal lines from a grayscale image. The algorithm is based
 * on Leptonica <code>lineremoval.c</code> example.
 * <br>
 * To remove vertical lines, rotate the image 90 degrees first, remove the
 * horizontal lines, and rotate it back.
 *
 * @see
 * <a href="http://www.leptonica.com/line-removal.html">line-removal</a>
 *
 * @param pixs input pix
 * @return pix with lines removed
 */
public static Pix removeLines(Pix pixs) {
    float angle, conf;
    Pix pix1, pix2, pix3, pix4, pix5;
    Pix pix6, pix7, pix8, pix9;

    /* threshold to binary, extracting much of the lines */
    pix1 = Leptonica1.pixThresholdToBinary(pixs, 170);

    /* find the skew angle and deskew using an interpolated
     * rotator for anti-aliasing (to avoid jaggies) */
    FloatBuffer pangle = FloatBuffer.allocate(1);
    FloatBuffer pconf = FloatBuffer.allocate(1);
    Leptonica1.pixFindSkew(pix1, pangle, pconf);
    angle = pangle.get();
    conf = pconf.get();
    pix2 = Leptonica1.pixRotateAMGray(pixs, (float) (deg2rad * angle), (byte) 255);

    /* extract the lines to be removed */
    pix3 = Leptonica1.pixCloseGray(pix2, 51, 1);

    /* solidify the lines to be removed */
    pix4 = Leptonica1.pixErodeGray(pix3, 1, 5);

    /* clean the background of those lines */
    pix5 = Leptonica1.pixThresholdToValue(null, pix4, 210, 255);

    pix6 = Leptonica1.pixThresholdToValue(null, pix5, 200, 0);

    /* get paint-through mask for changed pixels */
    pix7 = Leptonica1.pixThresholdToBinary(pix6, 210);

    /* add the inverted, cleaned lines to orig.  Because
     * the background was cleaned, the inversion is 0,
     * so when you add, it doesn't lighten those pixels.
     * It only lightens (to white) the pixels in the lines! */
    Leptonica1.pixInvert(pix6, pix6);
    pix8 = Leptonica1.pixAddGray(null, pix2, pix6);

    pix9 = Leptonica1.pixOpenGray(pix8, 1, 9);

    Leptonica1.pixCombineMasked(pix8, pix9, pix7);

    // resource cleanup
    disposePix(pix1);
    disposePix(pix2);
    disposePix(pix3);
    disposePix(pix4);
    disposePix(pix5);
    disposePix(pix6);
    disposePix(pix7);
    disposePix(pix9);

    return pix8;
}
 
Example 13
Source File: KV.java    From uncc2014watsonsim with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Basically just does ((float[]) bytes) which is moderately complex.
 * @param bytes
 * @return
 */
public static float[] asVector(byte[] bytes) {
	FloatBuffer fb = FloatBuffer.allocate((bytes.length + 3) / 4);
	fb.put(ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer());
	return fb.array();
}
 
Example 14
Source File: Scene.java    From ParticlesDrawable with Apache License 2.0 4 votes vote down vote up
private void initSpeedFactors(final int density) {
    if (speedFactors == null || speedFactors.capacity() != density) {
        speedFactors = FloatBuffer.allocate(density);
    }
}
 
Example 15
Source File: FloatBackingBuffer.java    From jipes with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void allocate(final int size) {
    this.buffer = direct
            ? ByteBuffer.allocateDirect(size * 4).asFloatBuffer()
            : FloatBuffer.allocate(size);
}
 
Example 16
Source File: TextureView.java    From jaamsim with Apache License 2.0 4 votes vote down vote up
private static void initStaticBuffers(Renderer r) {
	GL2GL3 gl = r.getGL();

	int[] buffs = new int[3];
	gl.glGenBuffers(3, buffs, 0);
	vertBuff = buffs[0];
	texCoordBuff = buffs[1];
	normalBuff = buffs[2];

	FloatBuffer verts = FloatBuffer.allocate(6*3); // 2 triangles * 3 coordinates
	verts.put(-0.5f); verts.put(-0.5f); verts.put(0.0f);
	verts.put( 0.5f); verts.put(-0.5f); verts.put(0.0f);
	verts.put( 0.5f); verts.put( 0.5f); verts.put(0.0f);

	verts.put(-0.5f); verts.put(-0.5f); verts.put(0.0f);
	verts.put( 0.5f); verts.put( 0.5f); verts.put(0.0f);
	verts.put(-0.5f); verts.put( 0.5f); verts.put(0.0f);

	verts.flip();
	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, vertBuff);
	gl.glBufferData(GL2GL3.GL_ARRAY_BUFFER, 6*3*4, verts, GL2GL3.GL_STATIC_DRAW);

	FloatBuffer texCoords = FloatBuffer.allocate(6*2); // 2 triangles * 2 coordinates

	texCoords.put(0.0f); texCoords.put(0.0f);
	texCoords.put(1.0f); texCoords.put(0.0f);
	texCoords.put(1.0f); texCoords.put(1.0f);

	texCoords.put(0.0f); texCoords.put(0.0f);
	texCoords.put(1.0f); texCoords.put(1.0f);
	texCoords.put(0.0f); texCoords.put(1.0f);

	texCoords.flip();
	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, texCoordBuff);
	gl.glBufferData(GL2GL3.GL_ARRAY_BUFFER, 6*2*4, texCoords, GL2GL3.GL_STATIC_DRAW);

	FloatBuffer normals = FloatBuffer.allocate(6*3); // 2 triangles * 3 coordinates
	for (int i = 0; i < 6; ++i) {
		normals.put(0.0f); normals.put(0.0f); normals.put(1.0f);
	}

	normals.flip();
	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, normalBuff);
	gl.glBufferData(GL2GL3.GL_ARRAY_BUFFER, 6*3*4, normals, GL2GL3.GL_STATIC_DRAW);

	// Initialize the shader variables
	progHandle = r.getMeshShader(Renderer.DIFF_TEX_FLAG).getProgramHandle();

	modelViewMatVar = gl.glGetUniformLocation(progHandle, "modelViewMat");
	projMatVar = gl.glGetUniformLocation(progHandle, "projMat");
	normalMatVar = gl.glGetUniformLocation(progHandle, "normalMat");
	bindSpaceMatVar = gl.glGetUniformLocation(progHandle, "bindSpaceMat");
	bindSpaceNorMatVar = gl.glGetUniformLocation(progHandle, "bindSpaceNorMat");
	texVar = gl.glGetUniformLocation(progHandle, "diffuseTex");

	lightDirVar = gl.glGetUniformLocation(progHandle, "lightDir");
	lightIntVar = gl.glGetUniformLocation(progHandle, "lightIntensity");
	numLightsVar = gl.glGetUniformLocation(progHandle, "numLights");

	specColorVar = gl.glGetUniformLocation(progHandle, "specColor");
	ambientColorVar = gl.glGetUniformLocation(progHandle, "ambientColor");
	shininessVar = gl.glGetUniformLocation(progHandle, "shininess");

	cVar = gl.glGetUniformLocation(progHandle, "C");
	fcVar = gl.glGetUniformLocation(progHandle, "FC");

	lightDir[0] = 0;
	lightDir[1] = 0;
	lightDir[2] = -1;

	lightInt[0] = 1;

	staticInit = true;
}
 
Example 17
Source File: DebugUtils.java    From jaamsim with Apache License 2.0 4 votes vote down vote up
public static void renderArmature(int contextID, Renderer renderer, Mat4d modelViewMat,
                                  Armature arm, ArrayList<Mat4d> pose, Color4d color, Camera cam) {

	GL2GL3 gl = renderer.getGL();

	if (!_debugVAOMap.containsKey(contextID)) {
		setupDebugVAO(contextID, renderer);
	}

	int vao = _debugVAOMap.get(contextID);
	gl.glBindVertexArray(vao);

	gl.glUseProgram(_debugProgHandle);

	// Setup uniforms for this object
	Mat4d projMat = cam.getProjMat4d();

	gl.glUniformMatrix4fv(_modelViewMatVar, 1, false, RenderUtils.MarshalMat4d(modelViewMat), 0);
	gl.glUniformMatrix4fv(_projMatVar, 1, false, RenderUtils.MarshalMat4d(projMat), 0);

	gl.glUniform4fv(_colorVar, 1, color.toFloats(), 0);

	gl.glUniform1f(_cVar, Camera.C);
	gl.glUniform1f(_fcVar, Camera.FC);

	ArrayList<Armature.Bone> bones = arm.getAllBones();
	//Build up the list of bone vertices
	Vec4d[] vects = new Vec4d[bones.size() * 2];
	for (int i = 0; i < bones.size(); ++i) {
		Armature.Bone b = bones.get(i);

		Vec4d boneStart = new Vec4d(0, 0, 0, 1);
		boneStart.mult4(b.getMatrix(), boneStart);

		Vec4d boneEnd = new Vec4d(0, b.getLength(), 0, 1);
		boneEnd.mult4(b.getMatrix(), boneEnd);

		if (pose != null) {
			// Adjust the bone by the current pose
			Mat4d poseMat = pose.get(i);

			boneStart.mult4(poseMat, boneStart);
			boneEnd.mult4(poseMat, boneEnd);
		}

		vects[2*i + 0] = boneStart;
		vects[2*i + 1] = boneEnd;
	}

	// Now push it to the card
	FloatBuffer fb = FloatBuffer.allocate(vects.length * 3);
	for (Vec4d v : vects) {
		RenderUtils.putPointXYZ(fb, v);
	}
	fb.flip();

	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, _lineVertBuffer);
	gl.glBufferData(GL2GL3.GL_ARRAY_BUFFER, fb.limit() * 4, fb, GL2GL3.GL_STATIC_DRAW);

	gl.glVertexAttribPointer(_posVar, 3, GL2GL3.GL_FLOAT, false, 0, 0);

	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, 0);

	gl.glDisable(GL2GL3.GL_DEPTH_TEST);
	gl.glDrawArrays(GL2GL3.GL_LINES, 0, fb.limit() / 3);
	gl.glEnable(GL2GL3.GL_DEPTH_TEST);

	gl.glLineWidth(1.0f);

	gl.glBindVertexArray(0);

}
 
Example 18
Source File: Sprite.java    From tribaltrouble with GNU General Public License v2.0 4 votes vote down vote up
private final void expandAnimation(AnimationInfo[] animations, float[][][] tmp_vertices, float[][][] tmp_normals, float[] initial_pose_vertices, float[] initial_pose_normals, byte[][] skin_names, float[][] skin_weights, BoundingBox[] bounding_boxes) {
		int num_bones = animations[0].getFrames()[0].length/12;
		Matrix4f[] frame_bones = new Matrix4f[num_bones];
		for (int bone = 0; bone < frame_bones.length; bone++)
			frame_bones[bone] = new Matrix4f();
		Vector4f v = new Vector4f();
		Vector4f n = new Vector4f();
		Vector4f temp = new Vector4f();
		FloatBuffer matrix_buffer = FloatBuffer.allocate(16);
		matrix_buffer.put(15, 1f);
		for (int anim = 0; anim < animations.length; anim++) {
			BoundingBox bounding_box = bounding_boxes[anim];
			int num_frames = animations[anim].getFrames().length;
			tmp_vertices[anim] = new float[num_frames][num_vertices*3];
			tmp_normals[anim] = new float[num_frames][num_vertices*3];
			for (int frame = 0; frame < num_frames; frame++) {
				float[] frame_animation = animations[anim].getFrames()[frame];
				for (int bone = 0; bone < num_bones; bone++) {
					matrix_buffer.clear();
					matrix_buffer.put(frame_animation, bone*12, 12);
					matrix_buffer.rewind();
					frame_bones[bone].loadTranspose(matrix_buffer);
				}
				float[] frame_normals = tmp_normals[anim][frame];
				float[] frame_vertices = tmp_vertices[anim][frame];
				float bmax_x = Float.NEGATIVE_INFINITY;
				float bmax_y = Float.NEGATIVE_INFINITY;
				float bmax_z = Float.NEGATIVE_INFINITY;
				float bmin_x = Float.POSITIVE_INFINITY;
				float bmin_y = Float.POSITIVE_INFINITY;
				float bmin_z = Float.POSITIVE_INFINITY;
				for (int vertex = 0; vertex < num_vertices; vertex++) {
					float x = initial_pose_vertices[vertex*3 + 0];
					float y = initial_pose_vertices[vertex*3 + 1];
					float z = initial_pose_vertices[vertex*3 + 2];
					float nx = initial_pose_normals[vertex*3 + 0];
					float ny = initial_pose_normals[vertex*3 + 1];
					float nz = initial_pose_normals[vertex*3 + 2];
					float result_x = 0, result_y = 0, result_z = 0, result_nx = 0, result_ny = 0, result_nz = 0;
					v.set(x, y, z, 1);
					n.set(nx, ny, nz, 0);
					byte[] vertex_skin_names = skin_names[vertex];
					float[] vertex_skin_weights = skin_weights[vertex];
					for (int bone = 0; bone < vertex_skin_names.length; bone++) {
						float weight = vertex_skin_weights[bone];
						Matrix4f bone_matrix = frame_bones[vertex_skin_names[bone]];
						Matrix4f.transform(bone_matrix, v, temp);
						result_x += temp.x*weight;
						result_y += temp.y*weight;
						result_z += temp.z*weight;
						// Assume matrix is only translation and scaling
						Matrix4f.transform(bone_matrix, n, temp);
						result_nx += temp.x*weight;
						result_ny += temp.y*weight;
						result_nz += temp.z*weight;
					}
					// Use Math.sqrt here for efficiency. Only used for normals (not gamestate affecting) anyway.
					float vec_len_inv = 1f/(float)Math.sqrt(result_nx*result_nx + result_ny*result_ny + result_nz*result_nz);
					result_nx *= vec_len_inv;
					result_ny *= vec_len_inv;
					result_nz *= vec_len_inv;
					frame_normals[vertex*3 + 0] = result_nx;
					frame_normals[vertex*3 + 1] = result_ny;
					frame_normals[vertex*3 + 2] = result_nz;

//result_x = x; result_y = y; result_z = z;
					if (result_x < bmin_x)
						bmin_x = result_x;
					else if (result_x > bmax_x)
						bmax_x = result_x;
					if (result_y < bmin_y)
						bmin_y = result_y;
					else if (result_y > bmax_y)
						bmax_y = result_y;
					if (result_z < bmin_z)
						bmin_z = result_z;
					else if (result_z > bmax_z)
						bmax_z = result_z;
					frame_vertices[vertex*3 + 0] = result_x;
					frame_vertices[vertex*3 + 1] = result_y;
					frame_vertices[vertex*3 + 2] = result_z;
				}
				bounding_box.checkBounds(bmin_x, bmax_x, bmin_y, bmax_y, bmin_z, bmax_z);
			}
		}
	}
 
Example 19
Source File: FloatNioDataBufferTest.java    From java with Apache License 2.0 4 votes vote down vote up
@Override
protected FloatDataBuffer allocate(long size) {
  return new FloatNioDataBuffer(FloatBuffer.allocate((int)size));
}
 
Example 20
Source File: HullProto.java    From jaamsim with Apache License 2.0 2 votes vote down vote up
public void render(int contextID, Renderer renderer,
           Mat4d modelViewMat,
           Camera cam) {

	GL2GL3 gl = renderer.getGL();

	Shader s = renderer.getShader(Renderer.ShaderHandle.HULL);

	int progHandle = s.getProgramHandle();
	gl.glUseProgram(progHandle);

	int modelViewMatVar = gl.glGetUniformLocation(progHandle, "modelViewMat");
	int projMatVar = gl.glGetUniformLocation(progHandle, "projMat");

	int cVar = gl.glGetUniformLocation(progHandle, "C");
	int fcVar = gl.glGetUniformLocation(progHandle, "FC");

	int[] is = new int[2];
	gl.glGenBuffers(2, is, 0);
	int vertexBuffer = is[0];
	int indexBuffer = is[1];

	List<Vec3d> verts = _hull.getVertices();
	// Generate the vertex buffer
	FloatBuffer fb = FloatBuffer.allocate(verts.size() * 3); //
	for (Vec3d v : verts) {
		RenderUtils.putPointXYZ(fb, v);
	}
	fb.flip();

	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, vertexBuffer);
	gl.glBufferData(GL2GL3.GL_ARRAY_BUFFER, verts.size() * 3 * 4, fb, GL2GL3.GL_STATIC_DRAW);

	gl.glBindBuffer(GL2GL3.GL_ARRAY_BUFFER, 0);

	// Generate the index buffer
	List<ConvexHull.HullFace> faces = _hull.getFaces();

	int numIndices = faces.size() * 3;

	IntBuffer ib = IntBuffer.allocate(faces.size() * 3); //
	for (ConvexHull.HullFace f : faces) {
		ib.put(f.indices, 0 ,3);
	}

	ib.flip();

	gl.glBindBuffer(GL2GL3.GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
	gl.glBufferData(GL2GL3.GL_ELEMENT_ARRAY_BUFFER, faces.size() * 3 * 4, ib, GL2GL3.GL_STATIC_DRAW);

	gl.glBindBuffer(GL2GL3.GL_ELEMENT_ARRAY_BUFFER, 0);

	if (!_vaoMap.containsKey(contextID)) {
		setupVAO(contextID, renderer, progHandle, vertexBuffer, indexBuffer);
	}

	int vao = _vaoMap.get(contextID);
	gl.glBindVertexArray(vao);

	gl.glUseProgram(progHandle);

	// Setup uniforms for this object
	Mat4d projMat = cam.getProjMat4d();

	gl.glUniformMatrix4fv(modelViewMatVar, 1, false, RenderUtils.MarshalMat4d(modelViewMat), 0);
	gl.glUniformMatrix4fv(projMatVar, 1, false, RenderUtils.MarshalMat4d(projMat), 0);

	gl.glUniform1f(cVar, Camera.C);
	gl.glUniform1f(fcVar, Camera.FC);

	// Actually draw it

	gl.glEnable(GL2GL3.GL_BLEND);
	gl.glEnable(GL2GL3.GL_CULL_FACE);
	gl.glCullFace(GL2GL3.GL_BACK);

	gl.glBlendFunc(GL2GL3.GL_ONE, GL2GL3.GL_ONE_MINUS_SRC_ALPHA);
	gl.glBlendEquation(GL2GL3.GL_FUNC_ADD);

	gl.glDisable(GL2GL3.GL_DEPTH_TEST);

	//gl.glPolygonMode(GL2GL3.GL_FRONT_AND_BACK, GL2GL3.GL_LINE);

	gl.glDrawElements(GL2GL3.GL_TRIANGLES, numIndices, GL2GL3.GL_UNSIGNED_INT, 0);

	//gl.glPolygonMode(GL2GL3.GL_FRONT_AND_BACK, GL2GL3.GL_FILL);

	gl.glEnable(GL2GL3.GL_DEPTH_TEST);

	gl.glDisable(GL2GL3.GL_CULL_FACE);
	gl.glCullFace(GL2GL3.GL_BACK);

	gl.glDisable(GL2GL3.GL_BLEND);

	gl.glBindVertexArray(0);

	gl.glDeleteBuffers(2, is, 0);

}