void CCRenderTexture::begin() { kmGLMatrixMode(KM_GL_PROJECTION); kmGLPushMatrix(); kmGLMatrixMode(KM_GL_MODELVIEW); kmGLPushMatrix(); CCDirector *director = CCDirector::sharedDirector(); director->setProjection(director->getProjection()); #if CC_TARGET_PLATFORM == CC_PLATFORM_WP8 kmMat4 modifiedProjection; kmGLGetMatrix(KM_GL_PROJECTION, &modifiedProjection); kmMat4Multiply(&modifiedProjection, CCEGLView::sharedOpenGLView()->getReverseOrientationMatrix(), &modifiedProjection); kmGLMatrixMode(KM_GL_PROJECTION); kmGLLoadMatrix(&modifiedProjection); kmGLMatrixMode(KM_GL_MODELVIEW); #endif const CCSize& texSize = m_pTexture->getContentSizeInPixels(); // Calculate the adjustment ratios based on the old and new projections CCSize size = director->getWinSizeInPixels(); float widthRatio = size.width / texSize.width; float heightRatio = size.height / texSize.height; // Adjust the orthographic projection and viewport glViewport(0, 0, (GLsizei)texSize.width, (GLsizei)texSize.height); kmMat4 orthoMatrix; kmMat4OrthographicProjection(&orthoMatrix, (float)-1.0 / widthRatio, (float)1.0 / widthRatio, (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); kmGLMultMatrix(&orthoMatrix); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_nOldFBO); glBindFramebuffer(GL_FRAMEBUFFER, m_uFBO); /* Certain Qualcomm Andreno gpu's will retain data in memory after a frame buffer switch which corrupts the render to the texture. The solution is to clear the frame buffer before rendering to the texture. However, calling glClear has the unintended result of clearing the current texture. Create a temporary texture to overcome this. At the end of CCRenderTexture::begin(), switch the attached texture to the second one, call glClear, and then switch back to the original texture. This solution is unnecessary for other devices as they don't have the same issue with switching frame buffers. */ if (CCConfiguration::sharedConfiguration()->checkForGLExtension("GL_QCOM")) { // -- bind a temporary texture so we can clear the render buffer without losing our texture glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pTextureCopy->getName(), 0); CHECK_GL_ERROR_DEBUG(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_pTexture->getName(), 0); } }
kmMat4* hueRotation(kmMat4* m, float r) { kmMat4 mat0; kmMat4 mat1; kmMat4 temp; // Make an identity matrix. kmMat4Identity(&mat0); // Rotate the grey vector into positive Z. // Sin = 1/sqrt(2). // Cos = 1/sqrt(2). kmMat4RotationX(&temp, M_PI_4); kmMat4Multiply(&mat1, &temp, &mat0); // Sin = -1/sqrt(3). // Cos = sqrt(2/3). kmMat4RotationY(&temp, -0.615479709); kmMat4Multiply(&mat0, &temp, &mat1); // Shear the space to make the luminance plane horizontal. float lx, ly, lz; xformRGB(&mat0, rwgt, gwgt, bwgt, &lx, &ly, &lz); float zsx = lx / lz; float zsy = ly / lz; shearZMatrix(&temp, zsx, zsy); kmMat4Multiply(&mat1, &temp, &mat0); // Rotate the hue. float rad = r * M_PI / 180; kmMat4RotationZ(&temp, rad); kmMat4Multiply(&mat0, &temp, &mat1); // Unshear the space to put the luminance plane back. shearZMatrix(&temp, -zsx, -zsy); kmMat4Multiply(&mat1, &temp, &mat0); // Rotate the grey vector back into place. // Sin = 1/sqrt(3). // Cos = sqrt(2/3); kmMat4RotationY(&temp, 0.615479709); kmMat4Multiply(&mat0, &temp, &mat1); // Sin = -1/sqrt(2). // Cos = 1/sqrt(2). kmMat4RotationX(&temp, -M_PI_4); kmMat4Multiply(&mat1, &temp, &mat0); kmMat4Fill(m, mat1.mat); return m; }
void CAFlashView::draw() { CAView::draw(); ccGLBlendFunc(m_sBlendFunc.src, m_sBlendFunc.dst); kmMat4 matrixP; kmMat4 matrixMV; kmMat4 matrixMVP; kmGLGetMatrix(KM_GL_PROJECTION, &matrixP ); kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV ); matrixMV.mat[13] = this->getFrame().size.height + matrixMV.mat[13]; kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV); #if CC_ENABLE_GL_STATE_CACHE ccGLUseProgram(0);//valid program is NON_ZERO unsigned int #endif CCSize size = this->getFrame().size; float localScaleX = size.width/ m_pFlash->getWidth(); float localScaleY = -(size.height / m_pFlash->getHeight()); float localScale = localScaleX > -localScaleY ? -localScaleY : localScaleX; kmMat4 matrixs; kmMat4Scaling(&matrixs, localScale, -localScale, getZOrder()); kmMat4Multiply(&matrixMVP, &matrixMVP, &matrixs); m_pFlash->display(&matrixMVP); CHECK_GL_ERROR_DEBUG(); }
void kmGLRotatef(float angle, float x, float y, float z) { km_mat4_stack_context *current_context = (km_mat4_stack_context *)pthread_getspecific(current_context_key); kmVec3 axis; kmMat4 rotation; /*Create an axis vector*/ kmVec3Fill(&axis, x, y, z); /*Create a rotation matrix using the axis and the angle*/ kmMat4RotationAxisAngle(&rotation, &axis, kmDegreesToRadians(angle)); /*Multiply the rotation matrix by the current matrix*/ kmMat4Multiply(current_context->current_stack->top, current_context->current_stack->top, &rotation); }
/* \brief update bone structure's transformed matrices */ static void _glhckSkinBoneUpdateBones(glhckSkinBone **skinBones, unsigned int memb) { glhckBone *bone, *parent; unsigned int n; assert(skinBones); /* 1. Transform bone to 0,0,0 using offset matrix so we can transform it locally * 2. Apply all transformations from parent bones * 3. We'll end up back to bone space with the transformed matrix */ for (n = 0; n != memb; ++n) { if (!(bone = skinBones[n]->bone)) continue; memcpy(&bone->transformedMatrix, &bone->transformationMatrix, sizeof(kmMat4)); for (parent = bone->parent; parent; parent = parent->parent) kmMat4Multiply(&bone->transformedMatrix, &parent->transformationMatrix, &bone->transformedMatrix); } }
/** * Builds a translation matrix in the same way as gluLookAt() * the resulting matrix is stored in pOut. pOut is returned. */ kmMat4* const kmMat4LookAt(kmMat4* pOut, const kmVec3* pEye, const kmVec3* pCenter, const kmVec3* pUp) { kmVec3 f, up, s, u; kmMat4 translate; kmVec3Subtract(&f, pCenter, pEye); kmVec3Normalize(&f, &f); kmVec3Assign(&up, pUp); kmVec3Normalize(&up, &up); kmVec3Cross(&s, &f, &up); kmVec3Normalize(&s, &s); kmVec3Cross(&u, &s, &f); kmVec3Normalize(&s, &s); kmMat4Identity(pOut); pOut->mat[0] = s.x; pOut->mat[4] = s.y; pOut->mat[8] = s.z; pOut->mat[1] = u.x; pOut->mat[5] = u.y; pOut->mat[9] = u.z; pOut->mat[2] = -f.x; pOut->mat[6] = -f.y; pOut->mat[10] = -f.z; kmMat4Translation(&translate, -pEye->x, -pEye->y, -pEye->z); kmMat4Multiply(pOut, pOut, &translate); return pOut; }
/* Calculate view matrix */ static void dlCameraCalculateViewMatrix( dlCamera *object ) { kmVec3 tgtv, upvector; kmScalar dp; CALL("%p", object); kmVec3Subtract( &tgtv, &object->target, &object->translation ); kmVec3Normalize( &tgtv, &tgtv ); kmVec3Normalize( &upvector, &object->upVector ); dp = kmVec3Dot( &tgtv, &upvector ); if( dp == 1.f ) { upvector.x += 0.5f; } kmMat4LookAt( &object->view, &object->translation, &object->target, &upvector ); /* Frustum recalculation here */ kmMat4Multiply( &object->matrix, &object->projection, &object->view ); }
void kmGLScalef(float x, float y, float z) { kmMat4 scaling; kmMat4Scaling(&scaling, x, y, z); kmMat4Multiply(current_stack->top, current_stack->top, &scaling); }
void kmGLMultMatrix(const kmMat4* pIn) { lazyInitialize(); kmMat4Multiply(current_stack->top, current_stack->top, pIn); }
void kmGLMultMatrix(const kmMat4* pIn) { km_mat4_stack_context *current_context = lazyInitializeCurrentContext(); kmMat4Multiply(current_context->current_stack->top, current_context->current_stack->top, pIn); }
void Transform::transform(DE::Transform *v) { kmMat4Multiply(&m_matrix,&m_matrix,&v->m_matrix); }
const kmMat4& Node::getNodeToParentTransform() const { if (_transformDirty) { // Translate values float x = _position.x; float y = _position.y; float z = _positionZ; if (_ignoreAnchorPointForPosition) { x += _anchorPointInPoints.x; y += _anchorPointInPoints.y; } // Rotation values // Change rotation code to handle X and Y // If we skew with the exact same value for both x and y then we're simply just rotating float cx = 1, sx = 0, cy = 1, sy = 0; if (_rotationZ_X || _rotationZ_Y) { float radiansX = -CC_DEGREES_TO_RADIANS(_rotationZ_X); float radiansY = -CC_DEGREES_TO_RADIANS(_rotationZ_Y); cx = cosf(radiansX); sx = sinf(radiansX); cy = cosf(radiansY); sy = sinf(radiansY); } bool needsSkewMatrix = ( _skewX || _skewY ); // optimization: // inline anchor point calculation if skew is not needed // Adjusted transform calculation for rotational skew if (! needsSkewMatrix && !_anchorPointInPoints.equals(Point::ZERO)) { x += cy * -_anchorPointInPoints.x * _scaleX + -sx * -_anchorPointInPoints.y * _scaleY; y += sy * -_anchorPointInPoints.x * _scaleX + cx * -_anchorPointInPoints.y * _scaleY; } // Build Transform Matrix // Adjusted transform calculation for rotational skew kmScalar mat[] = { cy * _scaleX, sy * _scaleX, 0, 0, -sx * _scaleY, cx * _scaleY, 0, 0, 0, 0, _scaleZ, 0, x, y, z, 1 }; kmMat4Fill(&_transform, mat); // XXX // FIX ME: Expensive operation. // FIX ME: It should be done together with the rotationZ if(_rotationY) { kmMat4 rotY; kmMat4RotationY(&rotY,CC_DEGREES_TO_RADIANS(_rotationY)); kmMat4Multiply(&_transform, &_transform, &rotY); } if(_rotationX) { kmMat4 rotX; kmMat4RotationX(&rotX,CC_DEGREES_TO_RADIANS(_rotationX)); kmMat4Multiply(&_transform, &_transform, &rotX); } // XXX: Try to inline skew // If skew is needed, apply skew and then anchor point if (needsSkewMatrix) { kmMat4 skewMatrix = { 1, (float)tanf(CC_DEGREES_TO_RADIANS(_skewY)), 0, 0, (float)tanf(CC_DEGREES_TO_RADIANS(_skewX)), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; kmMat4Multiply(&_transform, &_transform, &skewMatrix); // adjust anchor point if (!_anchorPointInPoints.equals(Point::ZERO)) { // XXX: Argh, kmMat needs a "translate" method. // XXX: Although this is faster than multiplying a vec4 * mat4 _transform.mat[12] += _transform.mat[0] * -_anchorPointInPoints.x + _transform.mat[4] * -_anchorPointInPoints.y; _transform.mat[13] += _transform.mat[1] * -_anchorPointInPoints.x + _transform.mat[5] * -_anchorPointInPoints.y; } } if (_useAdditionalTransform) { kmMat4Multiply(&_transform, &_transform, &_additionalTransform); } _transformDirty = false; } return _transform; }
int process_inputs() { // Get mouse position double xpos, ypos; glfwGetCursorPos(mainWindow, &xpos, &ypos); // Reset mouse position for next frame glfwSetCursorPos(mainWindow, SCREEN_WIDTH/2, SCREEN_HEIGHT/2); // Compute new orientation horizontalAngle += mouseSpeed * (float)( SCREEN_WIDTH/2 - xpos ); verticalAngle += mouseSpeed * (float)( SCREEN_HEIGHT/2 - ypos ); /* If F1, reload */ if (glfwGetKey(mainWindow, GLFW_KEY_F1)) { Engine_Reload(); } /* If F2, reset view */ if (glfwGetKey(mainWindow, GLFW_KEY_F2)) { printf("Camera reset.\n"); Camera_Reset(); } /* If tab, change lookat to next mesh */ if (glfwGetKey(mainWindow, GLFW_KEY_TAB)) { //Camera_LookAtNext(); } /* Move closer */ //if (glfwGetKey(mainWindow, GLFW_KEY_W)) { // ypos = 100; //} /* Move further */ //if (glfwGetKey(mainWindow, GLFW_KEY_S)) { // ypos = -100; //} /* Move left */ //if (glfwGetKey(mainWindow, GLFW_KEY_A)) { // xpos = 100; //} /* Move right */ //if (glfwGetKey(mainWindow, GLFW_KEY_D)) { // xpos = -100; //} // Compute new orientation //horizontalAngle += mouseSpeed * (float)(1024/2 - xpos ); //verticalAngle += mouseSpeed * (float)( 768/2 - ypos ); horizontalAngle += mouseSpeed * xpos; verticalAngle += mouseSpeed * ypos; //printf("horizontalAngle is %f, and verticalAngle is %f.\n", horizontalAngle, verticalAngle); // Direction : Spherical coordinates to Cartesian coordinates conversion float temp1 = cos(verticalAngle) * sin(horizontalAngle); float temp2 = sin(verticalAngle); float temp3 = cos(verticalAngle) * cos(horizontalAngle); kmVec3 direction = {temp1, temp2, temp3}; // Right vector kmVec3 right = { sin(horizontalAngle - 3.14f/2.0f), 0, cos(horizontalAngle - 3.14f/2.0f) }; // Up vector kmVec3 up = *kmVec3Cross(&up, &right, &direction ); // Move forward if (glfwGetKey( mainWindow, GLFW_KEY_UP ) == GLFW_PRESS){ kmVec3Add(&position, &position, kmVec3Scale(&position, &direction, deltaTime * speed)); } // Move backward if (glfwGetKey( mainWindow, GLFW_KEY_DOWN ) == GLFW_PRESS){ kmVec3Subtract(&position, &position, kmVec3Scale(&position, &direction, deltaTime * speed)); } // Strafe right if (glfwGetKey( mainWindow, GLFW_KEY_RIGHT ) == GLFW_PRESS){ kmVec3Add(&position, &position, kmVec3Scale(&position, &right, deltaTime * speed)); } // Strafe left if (glfwGetKey( mainWindow, GLFW_KEY_LEFT ) == GLFW_PRESS){ kmVec3Subtract(&position, &position, kmVec3Scale(&position, &right, deltaTime * speed)); } float FoV = initialFoV; kmMat4PerspectiveProjection(&ProjectionMatrix, FoV, (16.0f / 8.0f), 0.1f, 100.0f); // Camera matrix //ViewMatrix = glm::lookAt( // position, // Camera is here // position+direction, // and looks here : at the same position, plus "direction" // up // Head is up (set to 0,-1,0 to look upside-down) // ); kmVec3 p_eye; p_eye = position; kmVec3 p_ctr; p_ctr = *kmVec3Add(&p_ctr, &position, &direction); kmVec3 p_up; p_up = up; kmMat4LookAt(&ViewMatrix, &p_eye, &p_ctr, &p_up); kmMat4Identity(&ModelMatrix); kmMat4 temp_mat; kmMat4Multiply(&temp_mat, &ViewMatrix, &ModelMatrix); kmMat4Multiply(&MVP, &ProjectionMatrix, &temp_mat ); //printf("Matrix contains:\n"); //printf("%f, %f, %f, %f\n", MVP.mat[0], MVP.mat[1], MVP.mat[2], MVP.mat[3]); //printf("%f, %f, %f, %f\n", MVP.mat[4], MVP.mat[5], MVP.mat[6], MVP.mat[7]); //printf("%f, %f, %f, %f\n", MVP.mat[8], MVP.mat[9], MVP.mat[10], MVP.mat[11]); //printf("%f, %f, %f, %f\n", MVP.mat[12], MVP.mat[13], MVP.mat[14], MVP.mat[15]); return 0; }
kmMat4 Camera::getProjTransformMatrix() { kmMat4 result = getTransformMatrix(); kmMat4Multiply(&result, &mCamera.projection, &result); return result; }
int main() { lightDir.x=0.5; lightDir.y=.7; lightDir.z=-0.5; kmVec3Normalize(&lightDir,&lightDir); // creates a window and GLES context if (makeContext() != 0) exit(-1); // all the shaders have at least texture unit 0 active so // activate it now and leave it active glActiveTexture(GL_TEXTURE0); // The obj shapes and their textures are loaded cubeTex = loadPNG("resources/textures/dice.png"); loadObj(&cubeObj, "resources/models/cube.gbo", "resources/shaders/textured.vert", "resources/shaders/textured.frag"); shipTex = loadPNG("resources/textures/shipv2.png"); loadObjCopyShader(&shipObj,"resources/models/ship.gbo",&cubeObj); alienTex = loadPNG("resources/textures/alien.png"); loadObjCopyShader(&alienObj, "resources/models/alien.gbo", &cubeObj); shotTex = loadPNG("resources/textures/shot.png"); loadObjCopyShader(&shotObj, "resources/models/shot.gbo", &cubeObj); expTex = loadPNG("resources/textures/explosion.png"); playerPos.x = 0; playerPos.y = 0; playerPos.z = 0; kmMat4Identity(&view); pEye.x = 0; pEye.y = 2; pEye.z = 4; pCenter.x = 0; pCenter.y = 0; pCenter.z = -5; pUp.x = 0; pUp.y = 1; pUp.z = 0; kmMat4LookAt(&view, &pEye, &pCenter, &pUp); // projection matrix, as distance increases // the way the model is drawn is effected kmMat4Identity(&projection); kmMat4PerspectiveProjection(&projection, 45, (float)getDisplayWidth() / getDisplayHeight(), 0.1, 100); glViewport(0, 0, getDisplayWidth(), getDisplayHeight()); // these two matrices are pre combined for use with each model render kmMat4Assign(&vp, &projection); kmMat4Multiply(&vp, &vp, &view); // initialises glprint's matrix shader and texture initGlPrint(getDisplayWidth(), getDisplayHeight()); font1=createFont("resources/textures/font.png",0,256,16,16,16); font2=createFont("resources/textures/bigfont.png",32,512,9.5,32,48); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); // only used by glprintf glEnable(GL_DEPTH_TEST); struct timeval t, ta, t1, t2; // fps stuff gettimeofday(&t1, NULL); int num_frames = 0; bool quit = false; mouse = getMouse(); keys = getKeys(); resetAliens(); for (int n = 0; n < MAX_PLAYER_SHOTS; n++) { playerShots[n].alive = false; } initPointClouds("resources/shaders/particle.vert", "resources/shaders/particle.frag",(float)getDisplayWidth()/24.0); for (int n = 0; n < MAX_ALIENS; n++) { aliens[n].explosion=createPointCloud(40); resetExposion(aliens[n].explosion); // sets initials positions } while (!quit) { // the main loop doEvents(); // update mouse and key arrays // mask of 4 is right mouse if (keys[KEY_ESC]) quit = true; glClearColor(0, .5, 1, 1); // render between two gettimeofday calls so // we can sleep long enough to roughly sync // to ~60fps but not on the pi! // TODO find something a tad more elegent long i; gettimeofday(&t, NULL); i = t.tv_sec * 1e6 + t.tv_usec; // render(); float rad; // radians rotation based on frame counter glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); frame++; rad = frame * (0.0175f * 2); kmMat4Identity(&model); kmMat4Translation(&model, playerPos.x, playerPos.y, playerPos.z); playerCroll += (PIDcal(playerRoll, playerCroll, &playerPre_error, &playerIntegral) / 2); kmMat4RotationPitchYawRoll(&model, 0, 3.1416, playerCroll * 3); // kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); kmMat4Assign(&mv, &view); kmMat4Multiply(&mv, &mv, &model); glBindTexture(GL_TEXTURE_2D, shipTex); drawObj(&shipObj, &mvp, &mv, lightDir, viewDir); glPrintf(50 + sinf(rad) * 16, 240 + cosf(rad) * 16, font2,"frame=%i fps=%3.2f", frame, lfps); kmVec3 tmp; playerFireCount--; if (keys[KEY_LCTRL] && playerFireCount < 0) { struct playerShot_t *freeShot; freeShot = getFreeShot(); if (freeShot != 0) { playerFireCount = 15; freeShot->alive = true; kmVec3Assign(&freeShot->pos, &playerPos); } } for (int n = 0; n < MAX_PLAYER_SHOTS; n++) { if (playerShots[n].alive) { playerShots[n].pos.z -= .08; if (playerShots[n].pos.z < -10) playerShots[n].alive = false; kmMat4Identity(&model); kmMat4Translation(&model, playerShots[n].pos.x, playerShots[n].pos.y, playerShots[n].pos.z); kmMat4RotationPitchYawRoll(&model, rad * 4, 0, -rad * 4); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); kmMat4Assign(&mv, &view); kmMat4Multiply(&mv, &mv, &model); glBindTexture(GL_TEXTURE_2D, shotTex); drawObj(&shotObj, &mvp, &mv, lightDir, viewDir); } } playerRoll = 0; if (keys[KEY_CURSL] && playerPos.x > -10) { playerPos.x -= 0.1; playerRoll = .2; } if (keys[KEY_CURSR] && playerPos.x < 10) { playerPos.x += 0.1; playerRoll = -.2; } pEye.x = playerPos.x * 1.25; pCenter.x = playerPos.x; pCenter.y = playerPos.y + 1; pCenter.z = playerPos.z; int deadAliens; deadAliens = 0; for (int n = 0; n < MAX_ALIENS; n++) { if (aliens[n].alive == true) { kmMat4Identity(&model); kmMat4Translation(&model, aliens[n].pos.x, aliens[n].pos.y, aliens[n].pos.z); kmMat4RotationPitchYawRoll(&model, -.4, 0, 0); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); kmMat4Assign(&mv, &view); kmMat4Multiply(&mv, &mv, &model); glBindTexture(GL_TEXTURE_2D, alienTex); drawObj(&alienObj, &mvp, &mv, lightDir, viewDir); kmVec3 d; for (int i = 0; i < MAX_PLAYER_SHOTS; i++) { kmVec3Subtract(&d, &aliens[n].pos, &playerShots[i].pos); if (kmVec3Length(&d) < .7 && playerShots[i].alive) { aliens[n].alive = false; playerShots[i].alive = false; aliens[n].exploding = true; resetExposion(aliens[n].explosion); } } } if (aliens[n].alive != true && aliens[n].exploding != true) { deadAliens++; } } if (deadAliens == MAX_ALIENS) { resetAliens(); } // draw explosions after ALL aliens for (int n = 0; n < MAX_ALIENS; n++) { if (aliens[n].exploding==true) { kmMat4Identity(&model); kmMat4Translation(&model, aliens[n].pos.x, aliens[n].pos.y, aliens[n].pos.z); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); glBindTexture(GL_TEXTURE_2D, expTex); drawPointCloud(aliens[n].explosion, &mvp); aliens[n].explosion->tick=aliens[n].explosion->tick+0.05; if (aliens[n].explosion->tick>1.25) { aliens[n].exploding=false; } else { // update the explosion for (int i=0; i<aliens[n].explosion->totalPoints; i++) { float t; t=aliens[n].explosion->tick; if (i>aliens[n].explosion->totalPoints/2) t=t/2.0; aliens[n].explosion->pos[i*3]=aliens[n].explosion->vel[i*3] * t; aliens[n].explosion->pos[i*3+1]=aliens[n].explosion->vel[i*3+1] * t; aliens[n].explosion->pos[i*3+2]=aliens[n].explosion->vel[i*3+2] * t; } } } } // move camera kmMat4LookAt(&view, &pEye, &pCenter, &pUp); kmMat4Assign(&vp, &projection); kmMat4Multiply(&vp, &vp, &view); kmVec3Subtract(&viewDir,&pEye,&pCenter); kmVec3Normalize(&viewDir,&viewDir); // dump values glPrintf(100, 280, font1,"eye %3.2f %3.2f %3.2f ", pEye.x, pEye.y, pEye.z); glPrintf(100, 296, font1,"centre %3.2f %3.2f %3.2f ", pCenter.x, pCenter.y, pCenter.z); glPrintf(100, 320, font1,"mouse %i,%i %i ", mouse[0], mouse[1], mouse[2]); glPrintf(100, 340, font1,"frame %i %i ", frame, frame % 20); swapBuffers(); gettimeofday(&ta, NULL); long j = (ta.tv_sec * 1e6 + ta.tv_usec); i = j - i; if (i < 0) i = 1000000; // pass through - slower that 60fps if (i < 16000) usleep(16000 - i); // every 10 frames average the time taken and store // fps value for later printing with glprintf if (++num_frames % 10 == 0) { gettimeofday(&t2, NULL); float dtf = t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) * 1e-6; lfps = num_frames / dtf; num_frames = 0; t1 = t2; } } closeContext(); return 0; }
void Sprite::updateTransform(void) { CCASSERT(_batchNode, "updateTransform is only valid when Sprite is being rendered using an SpriteBatchNode"); // recalculate matrix only if it is dirty if( isDirty() ) { // If it is not visible, or one of its ancestors is not visible, then do nothing: if( !_visible || ( _parent && _parent != _batchNode && static_cast<Sprite*>(_parent)->_shouldBeHidden) ) { _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0,0,0); _shouldBeHidden = true; } else { _shouldBeHidden = false; if( ! _parent || _parent == _batchNode ) { _transformToBatch = getNodeToParentTransform(); } else { CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite"); kmMat4 nodeToParent = getNodeToParentTransform(); kmMat4 parentTransform = static_cast<Sprite*>(_parent)->_transformToBatch; kmMat4Multiply(&_transformToBatch, &parentTransform, &nodeToParent); } // // calculate the Quad based on the Affine Matrix // Size size = _rect.size; float x1 = _offsetPosition.x; float y1 = _offsetPosition.y; float x2 = x1 + size.width; float y2 = y1 + size.height; float x = _transformToBatch.mat[12]; float y = _transformToBatch.mat[13]; float cr = _transformToBatch.mat[0]; float sr = _transformToBatch.mat[1]; float cr2 = _transformToBatch.mat[5]; float sr2 = -_transformToBatch.mat[4]; float ax = x1 * cr - y1 * sr2 + x; float ay = x1 * sr + y1 * cr2 + y; float bx = x2 * cr - y1 * sr2 + x; float by = x2 * sr + y1 * cr2 + y; float cx = x2 * cr - y2 * sr2 + x; float cy = x2 * sr + y2 * cr2 + y; float dx = x1 * cr - y2 * sr2 + x; float dy = x1 * sr + y2 * cr2 + y; _quad.bl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(ax), RENDER_IN_SUBPIXEL(ay), _positionZ ); _quad.br.vertices = Vertex3F( RENDER_IN_SUBPIXEL(bx), RENDER_IN_SUBPIXEL(by), _positionZ ); _quad.tl.vertices = Vertex3F( RENDER_IN_SUBPIXEL(dx), RENDER_IN_SUBPIXEL(dy), _positionZ ); _quad.tr.vertices = Vertex3F( RENDER_IN_SUBPIXEL(cx), RENDER_IN_SUBPIXEL(cy), _positionZ ); } // MARMALADE CHANGE: ADDED CHECK FOR nullptr, TO PERMIT SPRITES WITH NO BATCH NODE / TEXTURE ATLAS if (_textureAtlas) { _textureAtlas->updateQuad(&_quad, _atlasIndex); } _recursiveDirty = false; setDirty(false); } // MARMALADE CHANGED // recursively iterate over children /* if( _hasChildren ) { // MARMALADE: CHANGED TO USE Node* // NOTE THAT WE HAVE ALSO DEFINED virtual Node::updateTransform() arrayMakeObjectsPerformSelector(_children, updateTransform, Sprite*); }*/ Node::updateTransform(); }
/* * FIXME: Stupid argument ordering */ void GenericRenderer::set_auto_uniforms_on_shader(GPUProgram& program, CameraID camera, Renderable &subactor) { //Calculate the modelview-projection matrix Mat4 modelview_projection; Mat4 modelview; const Mat4 model = subactor.final_transformation(); const Mat4& view = window().camera(camera)->view_matrix(); const Mat4& projection = window().camera(camera)->projection_matrix(); kmMat4Multiply(&modelview, &view, &model); kmMat4Multiply(&modelview_projection, &projection, &modelview); if(program.uniforms().uses_auto(SP_AUTO_VIEW_MATRIX)) { program.uniforms().set_mat4x4( program.uniforms().auto_variable_name(SP_AUTO_VIEW_MATRIX), view ); } if(program.uniforms().uses_auto(SP_AUTO_MODELVIEW_PROJECTION_MATRIX)) { program.uniforms().set_mat4x4( program.uniforms().auto_variable_name(SP_AUTO_MODELVIEW_PROJECTION_MATRIX), modelview_projection ); } if(program.uniforms().uses_auto(SP_AUTO_MODELVIEW_MATRIX)) { program.uniforms().set_mat4x4( program.uniforms().auto_variable_name(SP_AUTO_MODELVIEW_MATRIX), modelview ); } if(program.uniforms().uses_auto(SP_AUTO_PROJECTION_MATRIX)) { program.uniforms().set_mat4x4( program.uniforms().auto_variable_name(SP_AUTO_PROJECTION_MATRIX), projection ); } if(program.uniforms().uses_auto(SP_AUTO_INVERSE_TRANSPOSE_MODELVIEW_MATRIX)) { Mat3 inverse_transpose_modelview; kmMat4ExtractRotationMat3(&modelview, &inverse_transpose_modelview); kmMat3Inverse(&inverse_transpose_modelview, &inverse_transpose_modelview); kmMat3Transpose(&inverse_transpose_modelview, &inverse_transpose_modelview); program.uniforms().set_mat3x3( program.uniforms().auto_variable_name(SP_AUTO_INVERSE_TRANSPOSE_MODELVIEW_MATRIX), inverse_transpose_modelview ); } /* if(pass.uses_auto_uniform(SP_AUTO_MATERIAL_AMBIENT)) { pass.program()->uniforms().set_colour( pass.auto_uniform_variable_name(SP_AUTO_MATERIAL_AMBIENT), pass.ambient() ); } if(pass.uses_auto_uniform(SP_AUTO_MATERIAL_DIFFUSE)) { pass.program()->uniforms().set_colour( pass.auto_uniform_variable_name(SP_AUTO_MATERIAL_DIFFUSE), pass.diffuse() ); } if(pass.uses_auto_uniform(SP_AUTO_MATERIAL_SPECULAR)) { pass.program()->uniforms().set_colour( pass.auto_uniform_variable_name(SP_AUTO_MATERIAL_SPECULAR), pass.specular() ); } if(pass.uses_auto_uniform(SP_AUTO_MATERIAL_SHININESS)) { pass.program()->uniforms().set_float( pass.auto_uniform_variable_name(SP_AUTO_MATERIAL_SHININESS), pass.shininess() ); } if(pass.uses_auto_uniform(SP_AUTO_MATERIAL_ACTIVE_TEXTURE_UNITS)) { pass.program()->uniforms().set_int( pass.auto_uniform_variable_name(SP_AUTO_MATERIAL_ACTIVE_TEXTURE_UNITS), pass.texture_unit_count() ); }*/ }
int main() { lightDir.x=0.5; lightDir.y=.7; lightDir.z=-0.5; kmVec3Normalize(&lightDir,&lightDir); // creates a window and GLES context // create a window and GLES context if (!glfwInit()) exit(EXIT_FAILURE); window = glfwCreateWindow(width, height, "I N V A D E R S ! ! !", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetWindowSizeCallback(window,window_size_callback); glfwMakeContextCurrent(window); // all the shaders have at least texture unit 0 active so // activate it now and leave it active glActiveTexture(GL_TEXTURE0); // The obj shapes and their textures are loaded cubeTex = loadPNG("resources/textures/dice.png"); loadObj(&cubeObj, "resources/models/cube.gbo", "resources/shaders/textured.vert", "resources/shaders/textured.frag"); shipTex = loadPNG("resources/textures/shipv2.png"); loadObjCopyShader(&shipObj,"resources/models/ship.gbo",&cubeObj); alienTex = loadPNG("resources/textures/alien.png"); loadObjCopyShader(&alienObj, "resources/models/alien.gbo", &cubeObj); shotTex = loadPNG("resources/textures/shot.png"); loadObjCopyShader(&shotObj, "resources/models/shot.gbo", &cubeObj); expTex = loadPNG("resources/textures/explosion.png"); playerPos.x = 0; playerPos.y = 0; playerPos.z = 0; kmMat4Identity(&view); pEye.x = 0; pEye.y = 2; pEye.z = 4; pCenter.x = 0; pCenter.y = 0; pCenter.z = -5; pUp.x = 0; pUp.y = 1; pUp.z = 0; kmMat4LookAt(&view, &pEye, &pCenter, &pUp); // projection matrix, as distance increases // the way the model is drawn is effected kmMat4Identity(&projection); kmMat4PerspectiveProjection(&projection, 45, (float)width/ height, 0.1, 1000); glViewport(0, 0, width,height); // these two matrices are pre combined for use with each model render kmMat4Assign(&vp, &projection); kmMat4Multiply(&vp, &vp, &view); // initialises glprint's matrix shader and texture initGlPrint(width,height); font1=createFont("resources/textures/font.png",0,256,16,16,16); font2=createFont("resources/textures/bigfont.png",32,512,9.5,32,48); glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); // only used by glprintf glEnable(GL_DEPTH_TEST); int num_frames = 0; bool quit = false; resetAliens(); for (int n = 0; n < MAX_PLAYER_SHOTS; n++) { playerShots[n].alive = false; } initPointClouds("resources/shaders/particle.vert", "resources/shaders/particle.frag",(float)width/24.0); for (int n = 0; n < MAX_ALIENS; n++) { aliens[n].explosion=createPointCloud(40); resetExposion(aliens[n].explosion); // sets initials positions } glClearColor(0, .5, 1, 1); while (!quit) { // the main loop clock_gettime(0,&ts); // note the time BEFORE we start to render the current frame glfwPollEvents(); if (glfwGetKey(window,GLFW_KEY_ESCAPE)==GLFW_PRESS || glfwWindowShouldClose(window)) quit = true; float rad; // radians rotation based on frame counter glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); frame++; rad = frame * (0.0175f * 2); //kmMat4Identity(&model); kmMat4Translation(&model, playerPos.x, playerPos.y, playerPos.z); playerCroll += (PIDcal(playerRoll, playerCroll, &playerPre_error, &playerIntegral) / 2); // kmMat4RotationPitchYawRoll(&model, 0, 3.1416, playerCroll * 3); // kmMat4RotationYawPitchRoll(&rot,0,3.1416,-playerCroll*3); kmMat4Multiply(&model, &model, &rot); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); kmMat4Assign(&mv, &view); kmMat4Multiply(&mv, &mv, &model); glBindTexture(GL_TEXTURE_2D, shipTex); drawObj(&shipObj, &mvp, &mv, lightDir, viewDir); glPrintf(50 + sinf(rad) * 16, 240 + cosf(rad) * 16, font2,"frame=%i", frame); kmVec3 tmp; playerFireCount--; if (glfwGetKey(window,GLFW_KEY_LEFT_CONTROL)==GLFW_PRESS && playerFireCount < 0) { struct playerShot_t *freeShot; freeShot = getFreeShot(); if (freeShot != 0) { playerFireCount = 15; freeShot->alive = true; kmVec3Assign(&freeShot->pos, &playerPos); } } for (int n = 0; n < MAX_PLAYER_SHOTS; n++) { if (playerShots[n].alive) { playerShots[n].pos.z -= .08; if (playerShots[n].pos.z < -10) playerShots[n].alive = false; //kmMat4Identity(&model); kmMat4Translation(&model, playerShots[n].pos.x, playerShots[n].pos.y, playerShots[n].pos.z); //kmMat4RotationPitchYawRoll(&model, rad * 4, 0, // -rad * 4); kmMat4RotationYawPitchRoll(&rot,rad*4,0,-rad*4); kmMat4Multiply(&model,&model,&rot); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); kmMat4Assign(&mv, &view); kmMat4Multiply(&mv, &mv, &model); glBindTexture(GL_TEXTURE_2D, shotTex); drawObj(&shotObj, &mvp, &mv, lightDir, viewDir); } } playerRoll = 0; if (glfwGetKey(window,GLFW_KEY_LEFT)==GLFW_PRESS && playerPos.x > -10) { playerPos.x -= 0.1; playerRoll = .2; } if (glfwGetKey(window,GLFW_KEY_RIGHT)==GLFW_PRESS && playerPos.x < 10) { playerPos.x += 0.1; playerRoll = -.2; } pEye.x = playerPos.x * 1.25; pCenter.x = playerPos.x; pCenter.y = playerPos.y + 1; pCenter.z = playerPos.z; int deadAliens; deadAliens = 0; for (int n = 0; n < MAX_ALIENS; n++) { if (aliens[n].alive == true) { //kmMat4Identity(&model); kmMat4Translation(&model, aliens[n].pos.x, aliens[n].pos.y, aliens[n].pos.z); //kmMat4RotationPitchYawRoll(&model, -.4, 0, 0); kmMat4RotationYawPitchRoll(&rot,.2,0,0); kmMat4Multiply(&model,&model,&rot); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); kmMat4Assign(&mv, &view); kmMat4Multiply(&mv, &mv, &model); glBindTexture(GL_TEXTURE_2D, alienTex); drawObj(&alienObj, &mvp, &mv, lightDir, viewDir); kmVec3 d; for (int i = 0; i < MAX_PLAYER_SHOTS; i++) { kmVec3Subtract(&d, &aliens[n].pos, &playerShots[i].pos); if (kmVec3Length(&d) < .7 && playerShots[i].alive) { aliens[n].alive = false; playerShots[i].alive = false; aliens[n].exploding = true; resetExposion(aliens[n].explosion); } } } if (aliens[n].alive != true && aliens[n].exploding != true) { deadAliens++; } } if (deadAliens == MAX_ALIENS) { resetAliens(); } // draw explosions after ALL aliens for (int n = 0; n < MAX_ALIENS; n++) { if (aliens[n].exploding==true) { kmMat4Identity(&model); kmMat4Translation(&model, aliens[n].pos.x, aliens[n].pos.y, aliens[n].pos.z); kmMat4Assign(&mvp, &vp); kmMat4Multiply(&mvp, &mvp, &model); glBindTexture(GL_TEXTURE_2D, expTex); drawPointCloud(aliens[n].explosion, &mvp); aliens[n].explosion->tick=aliens[n].explosion->tick+0.05; if (aliens[n].explosion->tick>1.25) { aliens[n].exploding=false; } else { // update the explosion for (int i=0; i<aliens[n].explosion->totalPoints; i++) { float t; t=aliens[n].explosion->tick; if (i>aliens[n].explosion->totalPoints/2) t=t/2.0; aliens[n].explosion->pos[i*3]=aliens[n].explosion->vel[i*3] * t; aliens[n].explosion->pos[i*3+1]=aliens[n].explosion->vel[i*3+1] * t; aliens[n].explosion->pos[i*3+2]=aliens[n].explosion->vel[i*3+2] * t; } } } } // move camera kmMat4LookAt(&view, &pEye, &pCenter, &pUp); kmMat4Assign(&vp, &projection); kmMat4Multiply(&vp, &vp, &view); kmVec3Subtract(&viewDir,&pEye,&pCenter); kmVec3Normalize(&viewDir,&viewDir); // dump values glPrintf(100, 280, font1,"eye %3.2f %3.2f %3.2f ", pEye.x, pEye.y, pEye.z); glPrintf(100, 296, font1,"centre %3.2f %3.2f %3.2f ", pCenter.x, pCenter.y, pCenter.z); glPrintf(100, 340, font1,"frame %i %i ", frame, frame % 20); glfwSwapBuffers(window); ts.tv_nsec+=20000000; // 1000000000 / 50 = 50hz less time to render the frame //thrd_sleep(&ts,NULL); // tinycthread usleep(20000); // while I work out why tinycthread that was working isnt.... :/ } glfwDestroyWindow(window); glfwTerminate(); return 0; }
void CAView::visit() { CC_RETURN_IF(!m_bVisible); kmGLPushMatrix(); this->transform(); bool isScissor = (bool)glIsEnabled(GL_SCISSOR_TEST); DRect restoreScissorRect = DRectZero; if (isScissor) { GLfloat params[4]; glGetFloatv(GL_SCISSOR_BOX, params); restoreScissorRect = DRect(params[0], params[1], params[2], params[3]); } if (!m_bDisplayRange) { kmMat4 modelview; kmGLGetMatrix(KM_GL_MODELVIEW, &modelview); kmMat4 tm; kmMat4Identity(&tm); tm.mat[12] = m_obContentSize.width; tm.mat[13] = m_obContentSize.height; kmMat4 tm2; kmMat4Multiply(&tm2, &modelview, &tm); DPoint point = DPoint(modelview.mat[12], modelview.mat[13]); static CAApplication* application = CAApplication::getApplication(); if (application->getProjection() == CAApplication::P3D) { point = ccpAdd(point, application->getWinSize() / 2); } DSize size = DSize(tm2.mat[12] - modelview.mat[12], tm2.mat[13] - modelview.mat[13]); DRect frame = DRect(point.x, point.y, size.width, size.height); if (isScissor) { float x1 = MAX(s_dip_to_px(frame.getMinX()), restoreScissorRect.getMinX()); float y1 = MAX(s_dip_to_px(frame.getMinY()), restoreScissorRect.getMinY()); float x2 = MIN(s_dip_to_px(frame.getMaxX()) + 0.5f, restoreScissorRect.getMaxX()); float y2 = MIN(s_dip_to_px(frame.getMaxY()) + 0.5f, restoreScissorRect.getMaxY()); float width = MAX(x2-x1, 0); float height = MAX(y2-y1, 0); glScissor(x1, y1, width, height); } else { glEnable(GL_SCISSOR_TEST); glScissor(s_dip_to_px(frame.origin.x), s_dip_to_px(frame.origin.y), s_dip_to_px(frame.size.width) + 0.5f, s_dip_to_px(frame.size.height) + 0.5f); } } this->sortAllSubviews(); CAVector<CAView*>::iterator itr=m_obSubviews.begin(); while (itr!=m_obSubviews.end()) { CC_BREAK_IF((*itr)->m_nZOrder >= 0); (*itr)->visit(); itr++; } this->draw(); while (itr!=m_obSubviews.end()) { (*itr)->visit(); itr++; } //m_uOrderOfArrival = 0; if (!m_bDisplayRange) { if (isScissor) { glScissor(restoreScissorRect.origin.x, restoreScissorRect.origin.y , restoreScissorRect.size.width, restoreScissorRect.size.height); } else { glDisable(GL_SCISSOR_TEST); } } kmGLPopMatrix(); }