Example #1
0
        /**
         * \brief Draw the video keyframe (in OpenGL).
         * @param mvpMatrix the model-view-projection matrix.
         */
        private void DrawKeyFrame(float[] mvpMatrix)
        {
            GLES20.GlEnable(GLES20.GlBlend);
            GLES20.GlBlendFunc(GLES20.GlSrcAlpha, GLES20.GlOneMinusSrcAlpha);

            GLES20.GlUseProgram(mKeyframe_Program_GL_ID);

            int vertexHandle       = GLES20.GlGetAttribLocation(mKeyframe_Program_GL_ID, "vertexPosition");
            int textureCoordHandle = GLES20.GlGetAttribLocation(mKeyframe_Program_GL_ID, "vertexTexCoord");
            int mvpMatrixHandle    = GLES20.GlGetUniformLocation(mKeyframe_Program_GL_ID, "modelViewProjectionMatrix");
            int texSampler2DHandle = GLES20.GlGetUniformLocation(mKeyframe_Program_GL_ID, "texSampler2D");

            GLES20.GlVertexAttribPointer(vertexHandle, 3, GLES20.GlFloat, false, 0, mVertices_Buffer);
            GLES20.GlVertexAttribPointer(textureCoordHandle, 2, GLES20.GlFloat, false, 0, mTexCoords_Buffer);

            GLES20.GlEnableVertexAttribArray(vertexHandle);
            GLES20.GlEnableVertexAttribArray(textureCoordHandle);

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mKeyframeTexture_GL_ID);
            GLES20.GlUniform1i(texSampler2DHandle, 0);

            GLES20.GlUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);


            GLES20.GlDrawElements(GLES20.GlTriangles, mIndices_Number, GLES20.GlUnsignedShort, mIndex_Buffer);

            GLES20.GlDisableVertexAttribArray(vertexHandle);
            GLES20.GlDisableVertexAttribArray(textureCoordHandle);

            GLES20.GlUseProgram(0);
            GLES20.GlDisable(GLES20.GlBlend);
        }
Example #2
0
        /**
         * \brief Draw the video (in OpenGL).
         * @param mvpMatrix the model-view-projection matrix.
         */
        private void DrawVideo(float[] mvpMatrix)
        {
            GLES20.GlUseProgram(mVideo_Program_GL_ID);

            int vertexHandle       = GLES20.GlGetAttribLocation(mKeyframe_Program_GL_ID, "vertexPosition");
            int textureCoordHandle = GLES20.GlGetAttribLocation(mKeyframe_Program_GL_ID, "vertexTexCoord");
            int mvpMatrixHandle    = GLES20.GlGetUniformLocation(mKeyframe_Program_GL_ID, "modelViewProjectionMatrix");
            int texSampler2DHandle = GLES20.GlGetUniformLocation(mKeyframe_Program_GL_ID, "texSamplerOES");

            GLES20.GlVertexAttribPointer(vertexHandle, 3, GLES20.GlFloat, false, 0, mVertices_Buffer);
            GLES20.GlVertexAttribPointer(textureCoordHandle, 2, GLES20.GlFloat, false, 0, mVideoTexCoords_Buffer);

            GLES20.GlEnableVertexAttribArray(vertexHandle);
            GLES20.GlEnableVertexAttribArray(textureCoordHandle);

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlBindTexture(GLES11Ext.GlTextureExternalOes, mVideoTexture_GL_ID);
            GLES20.GlUniform1i(texSampler2DHandle, 0);


            GLES20.GlUniformMatrix4fv(mvpMatrixHandle, 1, false, mvpMatrix, 0);

            // Render
            GLES20.GlDrawElements(GLES20.GlTriangles, mIndices_Number, GLES20.GlUnsignedShort, mIndex_Buffer);

            GLES20.GlDisableVertexAttribArray(vertexHandle);
            GLES20.GlDisableVertexAttribArray(textureCoordHandle);

            GLES20.GlUseProgram(0);
        }
        /**
         * Allocates and initializes OpenGL resources needed by the background renderer.  Must be
         * called on the OpenGL thread, typically in
         * {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}.
         *
         * @param context Needed to access shader source.
         */
        public void CreateOnGlThread(Context context)
        {
            // Generate the background texture.
            var textures = new int[1];

            //GLES20 = OpenGL ES 2.0
            //Gibt eine bestimmte Anzahl an freien Texturnamen zurück.
            GLES20.GlGenTextures(1, textures, 0);

            TextureId = textures[0];
            GLES20.GlBindTexture(mTextureTarget, TextureId);
            GLES20.GlTexParameteri(mTextureTarget, GLES20.GlTextureWrapS, GLES20.GlClampToEdge);
            GLES20.GlTexParameteri(mTextureTarget, GLES20.GlTextureWrapT, GLES20.GlClampToEdge);
            GLES20.GlTexParameteri(mTextureTarget, GLES20.GlTextureMinFilter, GLES20.GlNearest);
            GLES20.GlTexParameteri(mTextureTarget, GLES20.GlTextureMagFilter, GLES20.GlNearest);

            int numVertices = 4;

            if (numVertices != QUAD_COORDS.Length / COORDS_PER_VERTEX)
            {
                throw new Exception("Unexpected number of vertices in BackgroundRenderer.");
            }

            var bbVertices = ByteBuffer.AllocateDirect(QUAD_COORDS.Length * FLOAT_SIZE);

            bbVertices.Order(ByteOrder.NativeOrder());
            mQuadVertices = bbVertices.AsFloatBuffer();
            mQuadVertices.Put(QUAD_COORDS);
            mQuadVertices.Position(0);

            var bbTexCoords = ByteBuffer.AllocateDirect(numVertices * TEXCOORDS_PER_VERTEX * FLOAT_SIZE);

            bbTexCoords.Order(ByteOrder.NativeOrder());
            mQuadTexCoord = bbTexCoords.AsFloatBuffer();
            mQuadTexCoord.Put(QUAD_TEXCOORDS);
            mQuadTexCoord.Position(0);

            var bbTexCoordsTransformed = ByteBuffer.AllocateDirect(numVertices * TEXCOORDS_PER_VERTEX * FLOAT_SIZE);

            bbTexCoordsTransformed.Order(ByteOrder.NativeOrder());
            mQuadTexCoordTransformed = bbTexCoordsTransformed.AsFloatBuffer();

            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.screenquad_vertex);
            int fragmentShader = ShaderUtil.LoadGLShader(TAG, context,
                                                         GLES20.GlFragmentShader, Resource.Raw.screenquad_fragment_oes);

            mQuadProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mQuadProgram, vertexShader);
            GLES20.GlAttachShader(mQuadProgram, fragmentShader);
            GLES20.GlLinkProgram(mQuadProgram);
            GLES20.GlUseProgram(mQuadProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            mQuadPositionParam = GLES20.GlGetAttribLocation(mQuadProgram, "a_Position");
            mQuadTexCoordParam = GLES20.GlGetAttribLocation(mQuadProgram, "a_TexCoord");

            ShaderUtil.CheckGLError(TAG, "Program parameters");
        }
Example #4
0
        public void Draw(float[] eyeView, float[] perspective)
        {
            GLES20.GlClear(GLES20.GlColorBufferBit | GLES20.GlDepthBufferBit);

            positionParam = GLES20.GlGetAttribLocation(glProgram, "a_Position");
            normalParam   = GLES20.GlGetAttribLocation(glProgram, "a_Normal");
            colorParam    = GLES20.GlGetAttribLocation(glProgram, "a_Color");
            texCoordParam = GLES20.GlGetAttribLocation(glProgram, "a_texcoord");

            GLES20.GlEnableVertexAttribArray(positionParam);
            GLES20.GlEnableVertexAttribArray(normalParam);
            GLES20.GlEnableVertexAttribArray(texCoordParam);

            // Apply the eye transformation to the camera.
            Matrix.MultiplyMM(view, 0, eyeView, 0, camera, 0);

            // Set the position of the light
            Matrix.MultiplyMV(lightPosInEyeSpace, 0, view, 0, lightPosInWorldSpace, 0);
            GLES20.GlUniform3f(lightPosParam, lightPosInEyeSpace[0], lightPosInEyeSpace[1],
                               lightPosInEyeSpace[2]);

            // Build the ModelView and ModelViewProjection matrices
            // for calculating cube position and light.
            Matrix.MultiplyMM(modelView, 0, view, 0, modelCube, 0);
            Matrix.MultiplyMM(modelViewProjection, 0, perspective, 0, modelView, 0);
            DrawCube();

            // Set mModelView for the floor, so we draw floor in the correct location
            Matrix.MultiplyMM(modelView, 0, view, 0, modelFloor, 0);
            Matrix.MultiplyMM(modelViewProjection, 0, perspective, 0,
                              modelView, 0);
            DrawFloor(perspective);
        }
Example #5
0
        /**
         * Get id for given handle name. This method checks for both attribute and
         * uniform handles.
         *
         * @param name
         *            Name of handle.
         * @return Id for given handle or -1 if none found.
         */
        public int GetHandle(string name)
        {
            if (mShaderHandleMap.ContainsKey(name))
            {
                return(mShaderHandleMap [name]);
            }
            var handle = GLES20.GlGetAttribLocation(_program, name);

            if (handle == -1)
            {
                handle = GLES20.GlGetUniformLocation(_program, name);
            }
            if (handle == -1)
            {
                // One should never leave log messages but am not going to follow
                // this rule. This line comes handy if you see repeating 'not found'
                // messages on LogCat - usually for typos otherwise annoying to
                // spot from shader code.
                Log.Debug("GlslShader", "Could not get attrib location for " + name);
            }
            else
            {
                mShaderHandleMap.Add(name, handle);
            }
            return(handle);
        }
        public void OnSurfaceCreated(IGL10 unused, EGLConfig config)
        {
            int program = GLES20.GlCreateProgram();

            addShaderTo(GLES20.GlVertexShader, VERTEX_SHADER_STRING, program);
            addShaderTo(GLES20.GlFragmentShader, FRAGMENT_SHADER_STRING, program);

            GLES20.GlLinkProgram(program);
            int[] result = new int[] { GLES20.GlFalse };
            result[0] = GLES20.GlFalse;
            GLES20.GlGetProgramiv(program, GLES20.GlLinkStatus, result, 0);
            abortUnless(result[0] == GLES20.GlTrue, GLES20.GlGetProgramInfoLog(program));
            GLES20.GlUseProgram(program);

            GLES20.GlUniform1i(GLES20.GlGetUniformLocation(program, "y_tex"), 0);
            GLES20.GlUniform1i(GLES20.GlGetUniformLocation(program, "u_tex"), 1);
            GLES20.GlUniform1i(GLES20.GlGetUniformLocation(program, "v_tex"), 2);

            // Actually set in drawRectangle(), but queried only once here.
            posLocation = GLES20.GlGetAttribLocation(program, "in_pos");

            int tcLocation = GLES20.GlGetAttribLocation(program, "in_tc");

            GLES20.GlEnableVertexAttribArray(tcLocation);
            GLES20.GlVertexAttribPointer(tcLocation, 2, GLES20.GlFloat, false, 0, textureCoords);

            GLES20.GlClearColor(0.0f, 0.0f, 0.0f, 1.0f);
            checkNoGLES2Error();
        }
Example #7
0
        public void Draw()
        {
            // Add program to OpenGL environment
            GLES20.GlUseProgram(mProgram);

            // get handle to vertex shader's vPosition member
            mPositionHandle = GLES20.GlGetAttribLocation(mProgram, "vPosition");

            // Enable a handle to the triangle vertices
            GLES20.GlEnableVertexAttribArray(mPositionHandle);

            // Prepare the triangle coordinate data
            GLES20.GlVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                                         GLES20.GL_FLOAT, false,
                                         vertexStride, vertexBuffer);

            // get handle to fragment shader's vColor member
            mColorHandle = GLES20.GlGetUniformLocation(mProgram, "vColor");

            // Set color for drawing the triangle
            GLES20.GlUniform4fv(mColorHandle, 1, color, 0);

            // Draw the triangle
            GLES20.GlDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount);

            // Disable vertex array
            GLES20.GlDisableVertexAttribArray(mPositionHandle);
        }
Example #8
0
        public ShaderCompiller(Context context, String shaderName, String fileName)
        {
            this.context    = context;
            this.shaderName = shaderName;
            this.fileName   = fileName;

            shaderSource   = loadSource(fileName + "_shader");
            fragmentSource = loadSource(fileName + "_fragment");
            compileShader();

            mMVMatrixHandle  = GLES20.GlGetUniformLocation(program, "u_MVMatrix");
            mMVPMatrixHandle = GLES20.GlGetUniformLocation(program, "u_MVPMatrix");

            attrib_vertex = GLES20.GlGetAttribLocation(program, "coord");
            normal        = GLES20.GlGetAttribLocation(program, "a_Normal");



            mTextureCoordinateHandle = GLES20.GlGetAttribLocation(program, "a_TexCoordinate");
            mTextPosHandle           = GLES20.GlGetUniformLocation(program, "u_TextPos");
            mTextureUniformHandle    = GLES20.GlGetUniformLocation(program, "u_Texture");
            mTextureUniformHandleF   = GLES20.GlGetUniformLocation(program, "u_TextureF");
            mTextureUniformHandleS   = GLES20.GlGetUniformLocation(program, "u_TextureS");

            unif_color = GLES20.GlGetUniformLocation(program, "u_Color");
            lightPos   = GLES20.GlGetUniformLocation(program, "u_LightPos");
        }
        /// <summary>
        /// Allocates and initializes OpenGL resources needed by the plane renderer.  Must be
        /// called on the OpenGL thread, typically in
        /// {@link GLSurfaceView.Renderer#onSurfaceCreated(GL10, EGLConfig)}.
        /// </summary>
        public void CreateOnGlThread(Context context)
        {
            //ShaderHelper.CheckGLError(TAG, "before create");

            var buffers = new int[1];

            GLES20.GlGenBuffers(1, buffers, 0);
            mVbo = buffers[0];
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVbo);

            mVboSize = INITIAL_BUFFER_POINTS * BYTES_PER_POINT;
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mVboSize, null, GLES20.GlDynamicDraw);
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            var vertexShader = ShaderHelper.Load(TAG, context,
                                                 GLES20.GlVertexShader, Resource.Raw.point_cloud_vertex);
            var passthroughShader = ShaderHelper.Load(TAG, context,
                                                      GLES20.GlFragmentShader, Resource.Raw.passthrough_fragment);

            mProgramName = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mProgramName, vertexShader);
            GLES20.GlAttachShader(mProgramName, passthroughShader);
            GLES20.GlLinkProgram(mProgramName);
            GLES20.GlUseProgram(mProgramName);


            mPositionAttribute          = GLES20.GlGetAttribLocation(mProgramName, "a_Position");
            mColorUniform               = GLES20.GlGetUniformLocation(mProgramName, "u_Color");
            mModelViewProjectionUniform = GLES20.GlGetUniformLocation(
                mProgramName, "u_ModelViewProjection");
            mPointSizeUniform = GLES20.GlGetUniformLocation(mProgramName, "u_PointSize");
        }
 private void CreateProgram()
 {
     mProgram     = CreateGlProgram();
     mPosition    = GLES20.GlGetAttribLocation(mProgram, "vPosition");
     mCoord       = GLES20.GlGetAttribLocation(mProgram, "vCoord");
     mMatrix      = GLES20.GlGetUniformLocation(mProgram, "vMatrix");
     mTexture     = GLES20.GlGetUniformLocation(mProgram, "vTexture");
     mCoordMatrix = GLES20.GlGetUniformLocation(mProgram, "vCoordMatrix");
 }
Example #11
0
        public void OnDrawFrame(Javax.Microedition.Khronos.Opengles.IGL10 gl)
        {
            float[] scratch = new float[16];

            // Draw background color
            GLES20.GlClear(GLES20.GlColorBufferBit);

            //synchronized (this) {
            if (mUpdateST)
            {
                mSTexture.UpdateTexImage();
                mUpdateST = false;
            }
            //}

            GLES20.GlUseProgram(hProgram);

            int ph  = GLES20.GlGetAttribLocation(hProgram, "vPosition");
            int tch = GLES20.GlGetAttribLocation(hProgram, "vTexCoord");
            int th  = GLES20.GlGetUniformLocation(hProgram, "sTexture");

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlBindTexture(GLES11Ext.GlTextureExternalOes, hTex[0]);
            GLES20.GlUniform1i(th, 0);

            GLES20.GlVertexAttribPointer(ph, 2, GLES20.GlFloat, false, 4 * 2, pVertex);
            GLES20.GlVertexAttribPointer(tch, 2, GLES20.GlFloat, false, 4 * 2, pTexCoord);
            GLES20.GlEnableVertexAttribArray(ph);
            GLES20.GlEnableVertexAttribArray(tch);

            GLES20.GlDrawArrays(GLES20.GlTriangleStrip, 0, 4);


            // Set the camera position (View matrix)
            Android.Opengl.Matrix.SetLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

            // Calculate the projection and view transformation
            Android.Opengl.Matrix.MultiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);


            // Create a rotation for the triangle

            // Use the following code to generate constant rotation.
            // Leave this code out when using TouchEvents.
            // long time = SystemClock.uptimeMillis() % 4000L;
            // float angle = 0.090f * ((int) time);

            Android.Opengl.Matrix.SetRotateM(mRotationMatrix, 0, mAngle, 0, 0, 1.0f);

            // Combine the rotation matrix with the projection and camera view
            // Note that the mMVPMatrix factor *must be first* in order
            // for the matrix multiplication product to be correct.
            Android.Opengl.Matrix.MultiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);

            // Draw triangle
            mTriangle.draw(scratch);
        }
 private void CreateProgram()
 {
     ShaderUtil.CheckGlError(TAG, "Create program start.");
     mProgram   = HandShaderUtil.CreateGlProgram();
     mPosition  = GLES20.GlGetAttribLocation(mProgram, "inPosition");
     mColor     = GLES20.GlGetUniformLocation(mProgram, "inColor");
     mPointSize = GLES20.GlGetUniformLocation(mProgram, "inPointSize");
     mModelViewProjectionMatrix = GLES20.GlGetUniformLocation(mProgram, "inMVPMatrix");
     ShaderUtil.CheckGlError(TAG, "Create program start.");
 }
Example #13
0
            public void OnSurfaceCreated(Javax.Microedition.Khronos.Opengles.IGL10 gl, Javax.Microedition.Khronos.Egl.EGLConfig config)
            {
                _glProgram = CreateProgram(mVertexShader, mFragmentShader);

                var extensions = " " + GLES20.GlGetString(GLES20.GlExtensions) + " ";
                var ok         = extensions.IndexOf("GL_OES_framebuffer_object") >= 0;
                var ab         = extensions;

                if (_glProgram == 0)
                {
                    return;
                }

                GLES20.GlUseProgram(0);
                GLES20.GlUseProgram(_glProgram);

                _aPositionHandle     = ActOnError(GLES20.GlGetAttribLocation(_glProgram, "aPosition"), "aPosition");
                _aTextureCoord       = ActOnError(GLES20.GlGetAttribLocation(_glProgram, "aTextureCoord"), "aTextureCoord");
                _uMVPMatrixHandle    = ActOnError(GLES20.GlGetUniformLocation(_glProgram, "uMVPMatrix"), "uMVPMatrix");
                _uSTMatrixHandle     = ActOnError(GLES20.GlGetUniformLocation(_glProgram, "uSTMatrix"), "uSTMatrix");
                _OESTextureUniform   = ActOnError(GLES20.GlGetUniformLocation(_glProgram, textureName), textureName);
                _otherTextureUniform = ActOnError(GLES20.GlGetUniformLocation(_glProgram, "overlay"), "overlay");

                int[] textures = new int[1];
                GLES20.GlGenTextures(1, textures, 0);

                _OESTextureId = textures[0];
                GLES20.GlUseProgram(0);
                GLES20.GlUseProgram(_glProgram);
                GLES20.GlActiveTexture(GLES20.GlTexture1);
                GLES20.GlBindTexture(GL_TEXTURE_EXTERNAL_OES, _OESTextureId);
                GLES20.GlUniform1i(_OESTextureUniform, 1);
                GLES20.GlUseProgram(0);
                GLES20.GlUseProgram(_glProgram);

                GLES20.GlTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GlTextureMinFilter,
                                       GLES20.GlNearest);
                GLES20.GlTexParameterf(GL_TEXTURE_EXTERNAL_OES, GLES20.GlTextureMagFilter,
                                       GLES20.GlLinear);

                _surfaceTexture = new SurfaceTexture(_OESTextureId);
                _surfaceTexture.FrameAvailable += _surfaceTexture_FrameAvailable;
                Surface surface = new Surface(_surfaceTexture);

                _mediaPlayer.SetSurface(surface);
                surface.Release();

                _otherTextureId = CreateTargetTexture();
                GLES20.GlActiveTexture(GLES20.GlTexture2);
                GLES20.GlBindTexture(GLES20.GlTexture2d, _otherTextureId);
                GLES20.GlUniform1i(_otherTextureUniform, 2);

                _updateSurface = false;
                _mediaPlayer.Start();
            }
 private void CreateProgram()
 {
     ShaderUtil.CheckGlError(TAG, "program start.");
     mProgram                    = WorldShaderUtil.GetLabelProgram();
     glPositionParameter         = GLES20.GlGetAttribLocation(mProgram, "inPosXZAlpha");
     glModelViewProjectionMatrix =
         GLES20.GlGetUniformLocation(mProgram, "inMVPMatrix");
     glTexture       = GLES20.GlGetUniformLocation(mProgram, "inTexture");
     glPlaneUvMatrix = GLES20.GlGetUniformLocation(mProgram, "inPlanUVMatrix");
     ShaderUtil.CheckGlError(TAG, "program end.");
 }
Example #15
0
 private void CreateProgram()
 {
     ShaderUtil.CheckGlError(TAG, "Create gl program start.");
     mProgram          = BodyShaderUtil.CreateGlProgram();
     mColor            = GLES20.GlGetUniformLocation(mProgram, "inColor");
     mPosition         = GLES20.GlGetAttribLocation(mProgram, "inPosition");
     mPointSize        = GLES20.GlGetUniformLocation(mProgram, "inPointSize");
     mProjectionMatrix = GLES20.GlGetUniformLocation(mProgram, "inProjectionMatrix");
     mCoordinateSystem = GLES20.GlGetUniformLocation(mProgram, "inCoordinateSystem");
     ShaderUtil.CheckGlError(TAG, "Create gl program end.");
 }
 private void CreateProgram()
 {
     ShaderUtil.CheckGlError(TAG, "Create gl program start.");
     mProgram                    = CreateGlProgram();
     mPositionAttribute          = GLES20.GlGetAttribLocation(mProgram, "inPosition");
     mColorUniform               = GLES20.GlGetUniformLocation(mProgram, "inColor");
     mModelViewProjectionUniform = GLES20.GlGetUniformLocation(mProgram, "inMVPMatrix");
     mPointSizeUniform           = GLES20.GlGetUniformLocation(mProgram, "inPointSize");
     mTextureUniform             = GLES20.GlGetUniformLocation(mProgram, "inTexture");
     mTextureCoordAttribute      = GLES20.GlGetAttribLocation(mProgram, "inTexCoord");
     ShaderUtil.CheckGlError(TAG, "Create gl program end.");
 }
Example #17
0
        /**
         * \brief Draw this mesh (in OpenGL).
         * @param modelViewProjection this mesh model-view-projection matrix.
         */
        public void DrawMesh(float[] modelViewProjection)
        {
            //set up gl state
            GLES20.GlEnable(GLES20.GlDepthTest);
            //GLES20.GlDisable(GLES20.GlCullFaceMode);
            GLES20.GlCullFace(GLES20.GlBack);
            GLES20.GlFrontFace(GLES20.GlCw);

            //set shader program to use
            GLES20.GlUseProgram(mProgram_GL_ID);
            RenderUtils.CheckGLError("DrawMesh:glUseProgram");

            //find attrib and unifroms in shader program
            int vertexHandle = GLES20.GlGetAttribLocation(mProgram_GL_ID, "vertexPosition");
            //int normalHandle = GLES20.GlGetAttribLocation(Program_GL_ID, "vertexNormal");
            int textureCoordHandle = GLES20.GlGetAttribLocation(mProgram_GL_ID, "vertexTexCoord");
            int mvpMatrixHandle    = GLES20.GlGetUniformLocation(mProgram_GL_ID, "modelViewProjectionMatrix");
            int texSampler2DHandle = GLES20.GlGetUniformLocation(mProgram_GL_ID, "texSampler2D");

            RenderUtils.CheckGLError("DrawMesh:get attribs and uniforms");

            //upload mesh data to OpenGL attribs
            GLES20.GlVertexAttribPointer(vertexHandle, 3, GLES20.GlFloat, false, 0, mVertices_Buffer);
            //GLES20.GlVertexAttribPointer(normalHandle, 3, GLES20.GlFloat, false, 0, Normals_Buffer);
            GLES20.GlVertexAttribPointer(textureCoordHandle, 2, GLES20.GlFloat, false, 0, mTexCoords_Buffer);
            RenderUtils.CheckGLError("DrawMesh:put attrib pointers");

            //enable gl attribs to use
            GLES20.GlEnableVertexAttribArray(vertexHandle);
            //GLES20.GlEnableVertexAttribArray(normalHandle);
            GLES20.GlEnableVertexAttribArray(textureCoordHandle);
            RenderUtils.CheckGLError("DrawMesh:enable attrib arrays");

            // activate texture 0, bind it, and pass to shader
            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTexture_GL_ID);
            GLES20.GlUniform1i(texSampler2DHandle, 0);
            RenderUtils.CheckGLError("DrawMesh:activate texturing");

            // pass the model view matrix to the shader
            GLES20.GlUniformMatrix4fv(mvpMatrixHandle, 1, false, modelViewProjection, 0);
            RenderUtils.CheckGLError("DrawMesh:upload matrix");

            // finally draw the teapot
            GLES20.GlDrawElements(GLES20.GlTriangles, mIndices_Number, GLES20.GlUnsignedShort, mIndex_Buffer);
            RenderUtils.CheckGLError("DrawMesh:draw elements");

            // disable the enabled arrays
            GLES20.GlDisableVertexAttribArray(vertexHandle);
            //GLES20.GlDisableVertexAttribArray(normalHandle);
            GLES20.GlDisableVertexAttribArray(textureCoordHandle);
            RenderUtils.CheckGLError("DrawMesh:disable attrib arrays");
        }
 private void CreateProgram()
 {
     ShaderUtil.CheckGlError(TAG, "Create program start.");
     mGlProgram                  = WorldShaderUtil.GetObjectProgram();
     mModelViewUniform           = GLES20.GlGetUniformLocation(mGlProgram, "inViewMatrix");
     mModelViewProjectionUniform = GLES20.GlGetUniformLocation(mGlProgram, "inMVPMatrix");
     mPositionAttribute          = GLES20.GlGetAttribLocation(mGlProgram, "inObjectPosition");
     mNormalAttribute            = GLES20.GlGetAttribLocation(mGlProgram, "inObjectNormalVector");
     mTexCoordAttribute          = GLES20.GlGetAttribLocation(mGlProgram, "inTexCoordinate");
     mTextureUniform             = GLES20.GlGetUniformLocation(mGlProgram, "inObjectTexture");
     mLightingParametersUniform  = GLES20.GlGetUniformLocation(mGlProgram, "inLight");
     mColorUniform               = GLES20.GlGetUniformLocation(mGlProgram, "inObjectColor");
     Android.Opengl.Matrix.SetIdentityM(mModelMatrixs, 0);
     ShaderUtil.CheckGlError(TAG, "Create program end.");
 }
Example #19
0
	/**
	 * Initializes GL state.  Call this after the EGL surface has been created and made current.
	 */
	public SurfaceTexture createTexture() {
		mProgram = createProgram(VERTEX_SHADER, FRAGMENT_SHADER);
		if (mProgram == 0) {
			throw new Java.Lang.RuntimeException("failed creating program");
		}
		maPositionHandle = GLES20.GlGetAttribLocation(mProgram, "aPosition");
		checkGlError("glGetAttribLocation aPosition");
		if (maPositionHandle == -1) {
			throw new Java.Lang.RuntimeException("Could not get attrib location for aPosition");
		}
		maTextureHandle = GLES20.GlGetAttribLocation(mProgram, "aTextureCoord");
		checkGlError("glGetAttribLocation aTextureCoord");
		if (maTextureHandle == -1) {
			throw new Java.Lang.RuntimeException("Could not get attrib location for aTextureCoord");
		}

		muMVPMatrixHandle = GLES20.GlGetUniformLocation(mProgram, "uMVPMatrix");
		checkGlError("glGetUniformLocation uMVPMatrix");
		if (muMVPMatrixHandle == -1) {
			throw new Java.Lang.RuntimeException("Could not get attrib location for uMVPMatrix");
		}

		muSTMatrixHandle = GLES20.GlGetUniformLocation(mProgram, "uSTMatrix");
		checkGlError("glGetUniformLocation uSTMatrix");
		if (muSTMatrixHandle == -1) {
			throw new Java.Lang.RuntimeException("Could not get attrib location for uSTMatrix");
		}

		int[] textures = new int[1];
		GLES20.GlGenTextures(1, textures, 0);

		mTextureID = textures[0];
		GLES20.GlBindTexture(GLES11Ext.GlTextureExternalOes, mTextureID);
		checkGlError("glBindTexture mTextureID");

		GLES20.GlTexParameterf(GLES11Ext.GlTextureExternalOes, GLES20.GlTextureMinFilter,
				GLES20.GlNearest);
		GLES20.GlTexParameterf(GLES11Ext.GlTextureExternalOes, GLES20.GlTextureMagFilter,
				GLES20.GlLinear);
		GLES20.GlTexParameteri(GLES11Ext.GlTextureExternalOes, GLES20.GlTextureWrapS,
				GLES20.GlClampToEdge);
		GLES20.GlTexParameteri(GLES11Ext.GlTextureExternalOes, GLES20.GlTextureWrapT,
				GLES20.GlClampToEdge);
		checkGlError("glTexParameter");
		
		mSurfaceTexture = new SurfaceTexture(mTextureID);
		return mSurfaceTexture;
	}
        /// <summary>
        /// Allocates and initializes OpenGL resources needed by the plane renderer.  Must be
        /// called on the OpenGL thread, typically in
        /// <see cref="GLSurfaceView.IRenderer.OnSurfaceCreated(IGL10, Javax.Microedition.Khronos.Egl.EGLConfig)"/>
        /// </summary>
        /// <param name="context">Needed to access shader source and texture PNG.</param>
        /// <param name="gridDistanceTextureName">Name of the PNG file containing the grid texture.</param>
        public void CreateOnGlThread(Context context, String gridDistanceTextureName)
        {
            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.plane_vertex);
            int passthroughShader = ShaderUtil.LoadGLShader(TAG, context,
                                                            GLES20.GlFragmentShader, Resource.Raw.plane_fragment);

            mPlaneProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mPlaneProgram, vertexShader);
            GLES20.GlAttachShader(mPlaneProgram, passthroughShader);
            GLES20.GlLinkProgram(mPlaneProgram);
            GLES20.GlUseProgram(mPlaneProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            // Read the texture.
            var textureBitmap = Android.Graphics.BitmapFactory.DecodeStream(
                context.Assets.Open(gridDistanceTextureName));

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(mTextures.Length, mTextures, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]);

            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);

            ShaderUtil.CheckGLError(TAG, "Texture loading");

            mPlaneXZPositionAlphaAttribute = GLES20.GlGetAttribLocation(mPlaneProgram,
                                                                        "a_XZPositionAlpha");

            mPlaneModelUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_Model");
            mPlaneModelViewProjectionUniform =
                GLES20.GlGetUniformLocation(mPlaneProgram, "u_ModelViewProjection");
            mTextureUniform       = GLES20.GlGetUniformLocation(mPlaneProgram, "u_Texture");
            mLineColorUniform     = GLES20.GlGetUniformLocation(mPlaneProgram, "u_lineColor");
            mDotColorUniform      = GLES20.GlGetUniformLocation(mPlaneProgram, "u_dotColor");
            mGridControlUniform   = GLES20.GlGetUniformLocation(mPlaneProgram, "u_gridControl");
            mPlaneUvMatrixUniform = GLES20.GlGetUniformLocation(mPlaneProgram, "u_PlaneUvMatrix");

            ShaderUtil.CheckGLError(TAG, "Program parameters");
        }
        private ProgramHolder createProgramHolder()
        {
            ProgramHolder holder = new ProgramHolder();

            holder.program = createProgram("attribute vec2 aPosition;\nattribute float aVignette;\nattribute vec2 aTextureCoord;\nvarying vec2 vTextureCoord;\nvarying float vVignette;\nuniform float uTextureCoordScale;\nvoid main() {\n    gl_Position = vec4(aPosition, 0.0, 1.0);\n    vTextureCoord = aTextureCoord.xy * uTextureCoordScale;\n    vVignette = aVignette;\n}\n", "precision mediump float;\nvarying vec2 vTextureCoord;\nvarying float vVignette;\nuniform sampler2D uTextureSampler;\nvoid main() {\n    gl_FragColor = vVignette * texture2D(uTextureSampler, vTextureCoord);\n}\n");
            if (holder.program == 0)
            {
                throw new Java.Lang.RuntimeException("Could not create program");
            }

            holder.aPosition = GLES20.GlGetAttribLocation(holder.program, "aPosition");
            checkGlError("glGetAttribLocation aPosition");
            if (holder.aPosition == -1)
            {
                throw new Java.Lang.RuntimeException("Could not get attrib location for aPosition");
            }
            holder.aVignette = GLES20.GlGetAttribLocation(holder.program, "aVignette");
            checkGlError("glGetAttribLocation aVignette");
            if (holder.aVignette == -1)
            {
                throw new Java.Lang.RuntimeException("Could not get attrib location for aVignette");
            }
            holder.aTextureCoord = GLES20.GlGetAttribLocation(holder.program, "aTextureCoord");

            checkGlError("glGetAttribLocation aTextureCoord");
            if (holder.aTextureCoord == -1)
            {
                throw new Java.Lang.RuntimeException("Could not get attrib location for aTextureCoord");
            }
            holder.uTextureCoordScale = GLES20.GlGetUniformLocation(holder.program, "uTextureCoordScale");

            checkGlError("glGetUniformLocation uTextureCoordScale");
            if (holder.uTextureCoordScale == -1)
            {
                throw new Java.Lang.RuntimeException("Could not get attrib location for uTextureCoordScale");
            }
            holder.uTextureSampler = GLES20.GlGetUniformLocation(holder.program, "uTextureSampler");

            checkGlError("glGetUniformLocation uTextureSampler");
            if (holder.uTextureSampler == -1)
            {
                throw new Java.Lang.RuntimeException("Could not get attrib location for uTextureSampler");
            }

            return(holder);
        }
        private void Render(float[] matrix)
        {
            // clear Screen and Depth Buffer, we have set the clear color as black.
            GLES20.GlClear(GLES20.GlColorBufferBit | GLES20.GlDepthBufferBit);

            // get handle to vertex shader's vPosition member
            int positionHandle = GLES20.GlGetAttribLocation(ShaderHelper.SpImage, "vPosition");

            // Enable generic vertex attribute array
            GLES20.GlEnableVertexAttribArray(positionHandle);

            // Prepare the triangle coordinate data
            GLES20.GlVertexAttribPointer(positionHandle, 3,
                                         GLES20.GlFloat, false,
                                         0, vertexBuffer);

            // Get handle to texture coordinates location
            int textureCoordinatesLocation = GLES20.GlGetAttribLocation(ShaderHelper.SpImage, "a_texCoord");

            // Enable generic vertex attribute array
            GLES20.GlEnableVertexAttribArray(textureCoordinatesLocation);

            // Prepare the texturecoordinates
            GLES20.GlVertexAttribPointer(textureCoordinatesLocation, 2, GLES20.GlFloat, false, 0, uvBuffer);

            // Get handle to shape's transformation matrix
            int matrixhandle = GLES20.GlGetUniformLocation(ShaderHelper.SpImage, "uMVPMatrix");

            // Apply the projection and view transformation
            GLES20.GlUniformMatrix4fv(matrixhandle, 1, false, matrix, 0);

            // Get handle to textures locations
            int samplerLocation = GLES20.GlGetUniformLocation(ShaderHelper.SpImage, "s_texture");

            // Set the sampler texture unit to 0, where we have saved the texture.
            GLES20.GlUniform1i(samplerLocation, 0);

            // Draw the triangle
            GLES20.GlDrawElements(GLES20.GlTriangles, indices.Length,
                                  GLES20.GlUnsignedShort, drawListBuffer);

            // Disable vertex array
            GLES20.GlDisableVertexAttribArray(positionHandle);
            GLES20.GlDisableVertexAttribArray(textureCoordinatesLocation);
        }
Example #23
0
        public override void draw(float[] viewMatrix, float[] projectionMatrix)
        {
            GLES20.GlUseProgram(mProgram);
            mVertexBuffer.Position(0);

            // Compose the model, view, and projection matrices into a single m-v-p
            // matrix
            updateMvpMatrix(viewMatrix, projectionMatrix);

            // Load vertex attribute data
            mPosHandle = GLES20.GlGetAttribLocation(mProgram, "vPosition");
            GLES20.GlVertexAttribPointer(mPosHandle, COORDS_PER_VERTEX, GLES20.GlFloat, false, 0, mVertexBuffer);
            GLES20.GlEnableVertexAttribArray(mPosHandle);

            mMVPMatrixHandle = GLES20.GlGetUniformLocation(mProgram, "uMVPMatrix");
            GLES20.GlUniformMatrix4fv(mMVPMatrixHandle, 1, false, MvpMatrix, 0);

            mColorHandle = GLES20.GlGetUniformLocation(mProgram, "aColor");
            GLES20.GlUniform4f(mColorHandle, mColor[0], mColor[1], mColor[2], mColor[3]);
            GLES20.GlLineWidth(mLineWidth);
            GLES20.GlDrawArrays(GLES20.GlLineStrip, 0, mTrajectoryCount);
        }
        public void Init()
        {
            try
            {
                // Create program
                MProgram = GlToolbox.CreateProgram(VertexShader, FragmentShader);

                // Bind attributes and uniforms
                MTexSamplerHandle = GLES20.GlGetUniformLocation(MProgram, "tex_sampler");
                MTexCoordHandle   = GLES20.GlGetAttribLocation(MProgram, "a_texcoord");
                MPosCoordHandle   = GLES20.GlGetAttribLocation(MProgram, "a_position");

                // Setup coordinate buffers
                MTexVertices = ByteBuffer.AllocateDirect(TexVertices.Length * FloatSizeBytes).Order(ByteOrder.NativeOrder()).AsFloatBuffer();
                MTexVertices.Put(TexVertices).Position(0);
                MPosVertices = ByteBuffer.AllocateDirect(PosVertices.Length * FloatSizeBytes).Order(ByteOrder.NativeOrder()).AsFloatBuffer();
                MPosVertices.Put(PosVertices).Position(0);
            }
            catch (Exception e)
            {
                Methods.DisplayReportResultTrack(e);
            }
        }
Example #25
0
        /**
         * Encapsulates the OpenGL ES instructions for drawing this shape.
         *
         * @param mvpMatrix - The Model View Project matrix in which to draw
         * this shape.
         */
        public void draw(float[] mvpMatrix)
        {
            // Add program to OpenGL environment
            GLES20.GlUseProgram(mProgram);

            // get handle to vertex shader's vPosition member
            mPositionHandle = GLES20.GlGetAttribLocation(mProgram, "vPosition");

            // Enable a handle to the triangle vertices
            GLES20.GlEnableVertexAttribArray(mPositionHandle);

            // Prepare the triangle coordinate data
            GLES20.GlVertexAttribPointer(
                mPositionHandle, COORDS_PER_VERTEX,
                GLES20.GlFloat, false,
                vertexStride, vertexBuffer);

            // get handle to fragment shader's vColor member
            mColorHandle = GLES20.GlGetUniformLocation(mProgram, "vColor");

            // Set color for drawing the triangle
            GLES20.GlUniform4fv(mColorHandle, 1, color, 0);

            // get handle to shape's transformation matrix
            mMVPMatrixHandle = GLES20.GlGetUniformLocation(mProgram, "uMVPMatrix");
            MainRenderer.checkGlError("glGetUniformLocation");

            // Apply the projection and view transformation
            GLES20.GlUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
            MainRenderer.checkGlError("glUniformMatrix4fv");

            // Draw the triangle
            GLES20.GlDrawArrays(GLES20.GlTriangles, 0, vertexCount);

            // Disable vertex array
            GLES20.GlDisableVertexAttribArray(mPositionHandle);
        }
Example #26
0
        public void Init()
        {
            // Create program
            _program = GLToolbox.CreateProgram(VertexShader, FragmentShader);

            // Bind attributes and uniforms
            _texSamplerHandle = GLES20.GlGetUniformLocation(_program,
                                                            "tex_sampler");
            _texCoordHandle = GLES20.GlGetAttribLocation(_program, "a_texcoord");
            _posCoordHandle = GLES20.GlGetAttribLocation(_program, "a_position");

            // Setup coordinate buffers
            _texVertices = ByteBuffer.AllocateDirect(
                TexVertices.Length * FloatSizeBytes)
                           .Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            _texVertices.Put(TexVertices).Position(0);

            _posVertices = ByteBuffer.AllocateDirect(
                PosVertices.Length * FloatSizeBytes)
                           .Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            _posVertices.Put(PosVertices).Position(0);
        }
Example #27
0
        private int[] VBOBuffers = new int[2]; //2 buffers for vertices and colors

        public void OnSurfaceCreated(IGL10 gl, Javax.Microedition.Khronos.Egl.EGLConfig config)
        {
            const float edge = 1.0f;

            // X, Y, Z,
            float[] triangleVerticesData =
            {
                -1.5f,       -0.25f, 0.0f,
                0.5f,        -0.25f, 0.0f,
                0.0f,  0.559016994f, 0.0f
            };

            FloatBuffer mTriangleVertices = ByteBuffer.AllocateDirect(triangleVerticesData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleVertices.Put(triangleVerticesData).Flip();

            // R, G, B, A
            float[] triangleColorsData =
            {
                1.0f, 0.0f, 0.0f, 0.5f,
                0.0f, 0.5f, 1.0f, 1.0f,
                0.0f, 1.0f, 0.0f, 1.0f
            };

            FloatBuffer mTriangleColors = ByteBuffer.AllocateDirect(triangleColorsData.Length * mBytesPerFloat).Order(ByteOrder.NativeOrder()).AsFloatBuffer();

            mTriangleColors.Put(triangleColorsData).Flip();

            //Use VBO
            GLES20.GlGenBuffers(2, VBOBuffers, 0); //2 buffers for vertices and colors
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[0]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleVertices.Capacity() * mBytesPerFloat, mTriangleVertices, GLES20.GlStaticDraw);

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, VBOBuffers[1]);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, mTriangleColors.Capacity() * mBytesPerFloat, mTriangleColors, GLES20.GlStaticDraw);


            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);


            GLES20.GlClearColor(1.0f, 1.0f, 1.0f, 1.0f);

            // Position the eye behind the origin.
            float eyeX = 0.0f;
            float eyeY = 0.0f;
            float eyeZ = 4.5f;

            // We are looking toward the distance
            float lookX = 0.0f;
            float lookY = 0.0f;
            float lookZ = -5.0f;

            // Set our up vector. This is where our head would be pointing were we holding the camera.
            float upX = 0.0f;
            float upY = 1.0f;
            float upZ = 0.0f;

            // Set the view matrix. This matrix can be said to represent the camera position.
            // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and
            // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose.
            Matrix.SetLookAtM(mViewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ);

            string vertexShader =
                "uniform mat4 u_MVPMatrix;      \n"         // A constant representing the combined model/view/projection matrix.
                + "attribute vec4 a_Position;     \n"       // Per-vertex position information we will pass in.
                + "attribute vec4 a_Color;        \n"       // Per-vertex color information we will pass in.
                + "varying vec4 v_Color;          \n"       // This will be passed into the fragment shader.
                + "void main()                    \n"       // The entry point for our vertex shader.
                + "{                              \n"
                + "   v_Color = a_Color;          \n"       // Pass the color through to the fragment shader. It will be interpolated across the triangle.
                + "   gl_Position = u_MVPMatrix   \n"       // gl_Position is a special variable used to store the final position.
                + "                 * a_Position; \n"       // Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
                + "}                              \n";

            string fragmentShader =
                "precision mediump float;       \n"     // Set the default precision to medium. We don't need as high of a
                                                        // precision in the fragment shader.
                + "varying vec4 v_Color;          \n"   // This is the color from the vertex shader interpolated across the triangle per fragment.
                + "void main()                    \n"   // The entry point for our fragment shader.
                + "{                              \n"
                + "   gl_FragColor = v_Color;     \n"   // Pass the color directly through the pipeline.
                + "}                              \n";

            int vertexShaderHandle = GLES20.GlCreateShader(GLES20.GlVertexShader);

            if (vertexShaderHandle != 0)
            {
                // Pass in the shader source.
                GLES20.GlShaderSource(vertexShaderHandle, vertexShader);

                // Compile the shader.
                GLES20.GlCompileShader(vertexShaderHandle);

                // Get the compilation status.
                int[] compileStatus = new int[1];
                GLES20.GlGetShaderiv(vertexShaderHandle, GLES20.GlCompileStatus, compileStatus, 0);

                // If the compilation failed, delete the shader.
                if (compileStatus[0] == 0)
                {
                    GLES20.GlDeleteShader(vertexShaderHandle);
                    vertexShaderHandle = 0;
                }
            }

            if (vertexShaderHandle == 0)
            {
                throw new Exception("Error creating vertex shader.");
            }

            // Load in the fragment shader shader.
            int fragmentShaderHandle = GLES20.GlCreateShader(GLES20.GlFragmentShader);

            if (fragmentShaderHandle != 0)
            {
                // Pass in the shader source.
                GLES20.GlShaderSource(fragmentShaderHandle, fragmentShader);

                // Compile the shader.
                GLES20.GlCompileShader(fragmentShaderHandle);

                // Get the compilation status.
                int[] compileStatus = new int[1];
                GLES20.GlGetShaderiv(fragmentShaderHandle, GLES20.GlCompileStatus, compileStatus, 0);

                // If the compilation failed, delete the shader.
                if (compileStatus[0] == 0)
                {
                    GLES20.GlDeleteShader(fragmentShaderHandle);
                    fragmentShaderHandle = 0;
                }
            }

            if (fragmentShaderHandle == 0)
            {
                throw new Exception("Error creating fragment shader.");
            }

            // Create a program object and store the handle to it.
            int programHandle = GLES20.GlCreateProgram();

            if (programHandle != 0)
            {
                // Bind the vertex shader to the program.
                GLES20.GlAttachShader(programHandle, vertexShaderHandle);

                // Bind the fragment shader to the program.
                GLES20.GlAttachShader(programHandle, fragmentShaderHandle);

                // Bind attributes
                GLES20.GlBindAttribLocation(programHandle, 0, "a_Position");
                GLES20.GlBindAttribLocation(programHandle, 1, "a_Color");

                // Link the two shaders together into a program.
                GLES20.GlLinkProgram(programHandle);

                // Get the link status.
                int[] linkStatus = new int[1];
                GLES20.GlGetProgramiv(programHandle, GLES20.GlLinkStatus, linkStatus, 0);

                // If the link failed, delete the program.
                if (linkStatus[0] == 0)
                {
                    GLES20.GlDeleteProgram(programHandle);
                    programHandle = 0;
                }
            }

            if (programHandle == 0)
            {
                throw new Exception("Error creating program.");
            }

            // Set program handles. These will later be used to pass in values to the program.
            mMVPMatrixHandle = GLES20.GlGetUniformLocation(programHandle, "u_MVPMatrix");
            mPositionHandle  = GLES20.GlGetAttribLocation(programHandle, "a_Position");
            mColorHandle     = GLES20.GlGetAttribLocation(programHandle, "a_Color");

            // Tell OpenGL to use this program when rendering.
            GLES20.GlUseProgram(programHandle);
        }
        /**
         * Creates and initializes OpenGL resources needed for rendering the model.
         *
         * @param context Context for loading the shader and below-named model and texture assets.
         * @param objAssetName  Name of the OBJ file containing the model geometry.
         * @param diffuseTextureAssetName  Name of the PNG file containing the diffuse texture map.
         */
        public void CreateOnGlThread(Context context, string objAssetName, string diffuseTextureAssetName)
        {
            // Read the texture.
            var textureBitmap = BitmapFactory.DecodeStream(context.Assets.Open(diffuseTextureAssetName));

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(mTextures.Length, mTextures, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]);

            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);

            textureBitmap.Recycle();

            ShaderUtil.CheckGLError(TAG, "Texture loading");

            // Read the obj file.
            var objInputStream = context.Assets.Open(objAssetName);
            var obj            = ObjReader.Read(objInputStream);

            // Prepare the Obj so that its structure is suitable for
            // rendering with OpenGL:
            // 1. Triangulate it
            // 2. Make sure that texture coordinates are not ambiguous
            // 3. Make sure that normals are not ambiguous
            // 4. Convert it to single-indexed data
            obj = ObjUtils.ConvertToRenderable(obj);

            // OpenGL does not use Java arrays. ByteBuffers are used instead to provide data in a format
            // that OpenGL understands.

            // Obtain the data from the OBJ, as direct buffers:
            IntBuffer   wideIndices = ObjData.GetFaceVertexIndices(obj, 3);
            FloatBuffer vertices    = ObjData.GetVertices(obj);
            FloatBuffer texCoords   = ObjData.GetTexCoords(obj, 2);
            FloatBuffer normals     = ObjData.GetNormals(obj);

            // Convert int indices to shorts for GL ES 2.0 compatibility
            ShortBuffer indices = ByteBuffer.AllocateDirect(2 * wideIndices.Limit())
                                  .Order(ByteOrder.NativeOrder()).AsShortBuffer();

            while (wideIndices.HasRemaining)
            {
                indices.Put((short)wideIndices.Get());
            }
            indices.Rewind();

            var buffers = new int[2];

            GLES20.GlGenBuffers(2, buffers, 0);
            mVertexBufferId = buffers[0];
            mIndexBufferId  = buffers[1];

            // Load vertex buffer
            mVerticesBaseAddress  = 0;
            mTexCoordsBaseAddress = mVerticesBaseAddress + 4 * vertices.Limit();
            mNormalsBaseAddress   = mTexCoordsBaseAddress + 4 * texCoords.Limit();
            int totalBytes = mNormalsBaseAddress + 4 * normals.Limit();

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVertexBufferId);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, totalBytes, null, GLES20.GlStaticDraw);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mVerticesBaseAddress, 4 * vertices.Limit(), vertices);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mTexCoordsBaseAddress, 4 * texCoords.Limit(), texCoords);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mNormalsBaseAddress, 4 * normals.Limit(), normals);
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            // Load index buffer
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, mIndexBufferId);
            mIndexCount = indices.Limit();
            GLES20.GlBufferData(
                GLES20.GlElementArrayBuffer, 2 * mIndexCount, indices, GLES20.GlStaticDraw);
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, 0);

            ShaderUtil.CheckGLError(TAG, "OBJ buffer load");

            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.object_vertex);
            int fragmentShader = ShaderUtil.LoadGLShader(TAG, context,
                                                         GLES20.GlFragmentShader, Resource.Raw.object_fragment);

            mProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mProgram, vertexShader);
            GLES20.GlAttachShader(mProgram, fragmentShader);
            GLES20.GlLinkProgram(mProgram);
            GLES20.GlUseProgram(mProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            mModelViewUniform           = GLES20.GlGetUniformLocation(mProgram, "u_ModelView");
            mModelViewProjectionUniform =
                GLES20.GlGetUniformLocation(mProgram, "u_ModelViewProjection");

            mPositionAttribute = GLES20.GlGetAttribLocation(mProgram, "a_Position");
            mNormalAttribute   = GLES20.GlGetAttribLocation(mProgram, "a_Normal");
            mTexCoordAttribute = GLES20.GlGetAttribLocation(mProgram, "a_TexCoord");

            mTextureUniform = GLES20.GlGetUniformLocation(mProgram, "u_Texture");

            mLightingParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_LightingParameters");
            mMaterialParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_MaterialParameters");

            ShaderUtil.CheckGLError(TAG, "Program parameters");

            Android.Opengl.Matrix.SetIdentityM(mModelMatrix, 0);
        }
Example #29
0
        public void CreateOnGlThread(Context context, string objAssetName, string diffuseTextureAssetName)
        {
            // Read the texture.
            var textureBitmap = BitmapFactory.DecodeStream(context.Assets.Open(diffuseTextureAssetName));

            GLES20.GlActiveTexture(GLES20.GlTexture0);
            GLES20.GlGenTextures(mTextures.Length, mTextures, 0);
            GLES20.GlBindTexture(GLES20.GlTexture2d, mTextures[0]);

            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMinFilter, GLES20.GlLinearMipmapLinear);
            GLES20.GlTexParameteri(GLES20.GlTexture2d,
                                   GLES20.GlTextureMagFilter, GLES20.GlLinear);
            GLUtils.TexImage2D(GLES20.GlTexture2d, 0, textureBitmap, 0);
            GLES20.GlGenerateMipmap(GLES20.GlTexture2d);
            GLES20.GlBindTexture(GLES20.GlTexture2d, 0);

            textureBitmap.Recycle();

            ShaderUtil.CheckGLError(TAG, "Texture loading");

            // Read the obj file.
            var objInputStream = context.Assets.Open(objAssetName);
            var obj            = JavaGl.Obj.ObjReader.Read(objInputStream);

            obj = JavaGl.Obj.ObjUtils.ConvertToRenderable(obj);

            IntBuffer   wideIndices = JavaGl.Obj.ObjData.GetFaceVertexIndices(obj, 3);
            FloatBuffer vertices    = JavaGl.Obj.ObjData.GetVertices(obj);
            FloatBuffer texCoords   = JavaGl.Obj.ObjData.GetTexCoords(obj, 2);
            FloatBuffer normals     = JavaGl.Obj.ObjData.GetNormals(obj);

            ShortBuffer indices = ByteBuffer.AllocateDirect(2 * wideIndices.Limit())
                                  .Order(ByteOrder.NativeOrder()).AsShortBuffer();

            while (wideIndices.HasRemaining)
            {
                indices.Put((short)wideIndices.Get());
            }
            indices.Rewind();

            var buffers = new int[2];

            GLES20.GlGenBuffers(2, buffers, 0);
            mVertexBufferId = buffers[0];
            mIndexBufferId  = buffers[1];

            mVerticesBaseAddress  = 0;
            mTexCoordsBaseAddress = mVerticesBaseAddress + 4 * vertices.Limit();
            mNormalsBaseAddress   = mTexCoordsBaseAddress + 4 * texCoords.Limit();
            int totalBytes = mNormalsBaseAddress + 4 * normals.Limit();

            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, mVertexBufferId);
            GLES20.GlBufferData(GLES20.GlArrayBuffer, totalBytes, null, GLES20.GlStaticDraw);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mVerticesBaseAddress, 4 * vertices.Limit(), vertices);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mTexCoordsBaseAddress, 4 * texCoords.Limit(), texCoords);
            GLES20.GlBufferSubData(
                GLES20.GlArrayBuffer, mNormalsBaseAddress, 4 * normals.Limit(), normals);
            GLES20.GlBindBuffer(GLES20.GlArrayBuffer, 0);

            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, mIndexBufferId);
            mIndexCount = indices.Limit();
            GLES20.GlBufferData(
                GLES20.GlElementArrayBuffer, 2 * mIndexCount, indices, GLES20.GlStaticDraw);
            GLES20.GlBindBuffer(GLES20.GlElementArrayBuffer, 0);

            ShaderUtil.CheckGLError(TAG, "OBJ buffer load");

            int vertexShader = ShaderUtil.LoadGLShader(TAG, context,
                                                       GLES20.GlVertexShader, Resource.Raw.object_vertex);
            int fragmentShader = ShaderUtil.LoadGLShader(TAG, context,
                                                         GLES20.GlFragmentShader, Resource.Raw.object_fragment);

            mProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(mProgram, vertexShader);
            GLES20.GlAttachShader(mProgram, fragmentShader);
            GLES20.GlLinkProgram(mProgram);
            GLES20.GlUseProgram(mProgram);

            ShaderUtil.CheckGLError(TAG, "Program creation");

            mModelViewUniform           = GLES20.GlGetUniformLocation(mProgram, "u_ModelView");
            mModelViewProjectionUniform =
                GLES20.GlGetUniformLocation(mProgram, "u_ModelViewProjection");

            mPositionAttribute = GLES20.GlGetAttribLocation(mProgram, "a_Position");
            mNormalAttribute   = GLES20.GlGetAttribLocation(mProgram, "a_Normal");
            mTexCoordAttribute = GLES20.GlGetAttribLocation(mProgram, "a_TexCoord");

            mTextureUniform = GLES20.GlGetUniformLocation(mProgram, "u_Texture");

            mLightingParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_LightingParameters");
            mMaterialParametersUniform = GLES20.GlGetUniformLocation(mProgram, "u_MaterialParameters");

            ShaderUtil.CheckGLError(TAG, "Program parameters");

            Android.Opengl.Matrix.SetIdentityM(mModelMatrix, 0);
        }
        /**
         * Creates the buffers we use to store information about the 3D world.
         *
         * OpenGL doesn't use Java arrays, but rather needs data in a format it can understand.
         * Hence we use ByteBuffers.
         */
        public void OnSurfaceCreated(Javax.Microedition.Khronos.Egl.EGLConfig config)
        {
            Android.Util.Log.Info(TAG, "onSurfaceCreated");

            GLES20.GlClearColor(0.1f, 0.1f, 0.1f, 0.5f);  // Dark background so text shows up well.

            var bbVertices = ByteBuffer.AllocateDirect(WorldLayoutData.CUBE_COORDS.Length * 4);

            bbVertices.Order(ByteOrder.NativeOrder());
            cubeVertices = bbVertices.AsFloatBuffer();
            cubeVertices.Put(WorldLayoutData.CUBE_COORDS);
            cubeVertices.Position(0);

            var bbColors = ByteBuffer.AllocateDirect(WorldLayoutData.CUBE_COLORS.Length * 4);

            bbColors.Order(ByteOrder.NativeOrder());
            cubeColors = bbColors.AsFloatBuffer();
            cubeColors.Put(WorldLayoutData.CUBE_COLORS);
            cubeColors.Position(0);

            var bbFoundColors = ByteBuffer.AllocateDirect(WorldLayoutData.CUBE_FOUND_COLORS.Length * 4);

            bbFoundColors.Order(ByteOrder.NativeOrder());
            cubeFoundColors = bbFoundColors.AsFloatBuffer();
            cubeFoundColors.Put(WorldLayoutData.CUBE_FOUND_COLORS);
            cubeFoundColors.Position(0);

            var bbNormals = ByteBuffer.AllocateDirect(WorldLayoutData.CUBE_NORMALS.Length * 4);

            bbNormals.Order(ByteOrder.NativeOrder());
            cubeNormals = bbNormals.AsFloatBuffer();
            cubeNormals.Put(WorldLayoutData.CUBE_NORMALS);
            cubeNormals.Position(0);

            // make a floor
            var bbFloorVertices = ByteBuffer.AllocateDirect(WorldLayoutData.FLOOR_COORDS.Length * 4);

            bbFloorVertices.Order(ByteOrder.NativeOrder());
            floorVertices = bbFloorVertices.AsFloatBuffer();
            floorVertices.Put(WorldLayoutData.FLOOR_COORDS);
            floorVertices.Position(0);

            var bbFloorNormals = ByteBuffer.AllocateDirect(WorldLayoutData.FLOOR_NORMALS.Length * 4);

            bbFloorNormals.Order(ByteOrder.NativeOrder());
            floorNormals = bbFloorNormals.AsFloatBuffer();
            floorNormals.Put(WorldLayoutData.FLOOR_NORMALS);
            floorNormals.Position(0);

            var bbFloorColors = ByteBuffer.AllocateDirect(WorldLayoutData.FLOOR_COLORS.Length * 4);

            bbFloorColors.Order(ByteOrder.NativeOrder());
            floorColors = bbFloorColors.AsFloatBuffer();
            floorColors.Put(WorldLayoutData.FLOOR_COLORS);
            floorColors.Position(0);

            int vertexShader      = loadGLShader(GLES20.GlVertexShader, Resource.Raw.light_vertex);
            int gridShader        = loadGLShader(GLES20.GlFragmentShader, Resource.Raw.grid_fragment);
            int passthroughShader = loadGLShader(GLES20.GlFragmentShader, Resource.Raw.passthrough_fragment);

            cubeProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(cubeProgram, vertexShader);
            GLES20.GlAttachShader(cubeProgram, passthroughShader);
            GLES20.GlLinkProgram(cubeProgram);
            GLES20.GlUseProgram(cubeProgram);

            CheckGLError("Cube program");

            cubePositionParam = GLES20.GlGetAttribLocation(cubeProgram, "a_Position");
            cubeNormalParam   = GLES20.GlGetAttribLocation(cubeProgram, "a_Normal");
            cubeColorParam    = GLES20.GlGetAttribLocation(cubeProgram, "a_Color");

            cubeModelParam               = GLES20.GlGetUniformLocation(cubeProgram, "u_Model");
            cubeModelViewParam           = GLES20.GlGetUniformLocation(cubeProgram, "u_MVMatrix");
            cubeModelViewProjectionParam = GLES20.GlGetUniformLocation(cubeProgram, "u_MVP");
            cubeLightPosParam            = GLES20.GlGetUniformLocation(cubeProgram, "u_LightPos");

            CheckGLError("Cube program params");

            floorProgram = GLES20.GlCreateProgram();
            GLES20.GlAttachShader(floorProgram, vertexShader);
            GLES20.GlAttachShader(floorProgram, gridShader);
            GLES20.GlLinkProgram(floorProgram);
            GLES20.GlUseProgram(floorProgram);

            CheckGLError("Floor program");

            floorModelParam               = GLES20.GlGetUniformLocation(floorProgram, "u_Model");
            floorModelViewParam           = GLES20.GlGetUniformLocation(floorProgram, "u_MVMatrix");
            floorModelViewProjectionParam = GLES20.GlGetUniformLocation(floorProgram, "u_MVP");
            floorLightPosParam            = GLES20.GlGetUniformLocation(floorProgram, "u_LightPos");

            floorPositionParam = GLES20.GlGetAttribLocation(floorProgram, "a_Position");
            floorNormalParam   = GLES20.GlGetAttribLocation(floorProgram, "a_Normal");
            floorColorParam    = GLES20.GlGetAttribLocation(floorProgram, "a_Color");

            CheckGLError("Floor program params");

            Matrix.SetIdentityM(modelFloor, 0);
            Matrix.TranslateM(modelFloor, 0, 0, -floorDepth, 0);  // Floor appears below user.

            // Avoid any delays during start-up due to decoding of sound files.
            System.Threading.Tasks.Task.Run(() => {
                // Start spatial audio playback of SOUND_FILE at the model postion. The returned
                //soundId handle is stored and allows for repositioning the sound object whenever
                // the cube position changes.
                gvrAudioEngine.PreloadSoundFile(SOUND_FILE);
                soundId = gvrAudioEngine.CreateSoundObject(SOUND_FILE);
                gvrAudioEngine.SetSoundObjectPosition(
                    soundId, modelPosition [0], modelPosition [1], modelPosition [2]);
                gvrAudioEngine.PlaySound(soundId, true /* looped playback */);
            });

            UpdateModelPosition();

            CheckGLError("onSurfaceCreated");
        }