void RenderBatchTriangle::fill(const CanvasPtr &canvas, float x1, float y1, float x2, float y2, const Colorf &color) { int texindex = set_batcher_active(canvas); vertices[position + 0].position = to_position(x1, y1); vertices[position + 1].position = to_position(x2, y1); vertices[position + 2].position = to_position(x1, y2); vertices[position + 3].position = to_position(x2, y1); vertices[position + 4].position = to_position(x2, y2); vertices[position + 5].position = to_position(x1, y2); for (int i = 0; i < 6; i++) { vertices[position + i].color = Vec4f(color.x, color.y, color.z, color.w); vertices[position + i].texcoord = Vec2f(0.0f, 0.0f); vertices[position + i].texindex = texindex; } position += 6; }
void Frustum::buildViewFrustum( const Matrix4f &viewMat, const Matrix4f &projMat ) { // This routine works with the OpenGL projection matrix // The view matrix is the inverse camera transformation matrix // Note: Frustum corners are not updated! Matrix4f m = projMat * viewMat; _planes[0] = Plane( -(m.c[0][3] + m.c[0][0]), -(m.c[1][3] + m.c[1][0]), -(m.c[2][3] + m.c[2][0]), -(m.c[3][3] + m.c[3][0]) ); // Left _planes[1] = Plane( -(m.c[0][3] - m.c[0][0]), -(m.c[1][3] - m.c[1][0]), -(m.c[2][3] - m.c[2][0]), -(m.c[3][3] - m.c[3][0]) ); // Right _planes[2] = Plane( -(m.c[0][3] + m.c[0][1]), -(m.c[1][3] + m.c[1][1]), -(m.c[2][3] + m.c[2][1]), -(m.c[3][3] + m.c[3][1]) ); // Bottom _planes[3] = Plane( -(m.c[0][3] - m.c[0][1]), -(m.c[1][3] - m.c[1][1]), -(m.c[2][3] - m.c[2][1]), -(m.c[3][3] - m.c[3][1]) ); // Top _planes[4] = Plane( -(m.c[0][3] + m.c[0][2]), -(m.c[1][3] + m.c[1][2]), -(m.c[2][3] + m.c[2][2]), -(m.c[3][3] + m.c[3][2]) ); // Near _planes[5] = Plane( -(m.c[0][3] - m.c[0][2]), -(m.c[1][3] - m.c[1][2]), -(m.c[2][3] - m.c[2][2]), -(m.c[3][3] - m.c[3][2]) ); // Far _origin = viewMat.inverted() * Vec3f( 0, 0, 0 ); // Calculate corners Matrix4f mm = m.inverted(); Vec4f corner = mm * Vec4f( -1, -1, 1, 1 ); _corners[0] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( 1, -1, 1, 1 ); _corners[1] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( 1, 1, 1, 1 ); _corners[2] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( -1, 1, 1, 1 ); _corners[3] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( -1, -1, -1, 1 ); _corners[4] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( 1, -1, -1, 1 ); _corners[5] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( 1, 1, -1, 1 ); _corners[6] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); corner = mm * Vec4f( -1, 1, -1, 1 ); _corners[7] = Vec3f( corner.x / corner.w, corner.y / corner.w, corner.z / corner.w ); }
Vec3f Matrix4::TransformNormal(const Vec3f &Normal) const { Vec4f UnprojectedResult = Vec4f(Normal, 0.0f) * (*this); if(UnprojectedResult.w == 0.0f) { UnprojectedResult.w = 1.0f; } Vec3f Result(UnprojectedResult.x / UnprojectedResult.w, UnprojectedResult.y / UnprojectedResult.w, UnprojectedResult.z / UnprojectedResult.w); if(UnprojectedResult.w < 0.0f) { Result = -Result; } return Result; }
/*! * Transform object vertices */ static void Cedric_TransformVerts(EERIE_3DOBJ * eobj, const Vec3f & pos) { Skeleton & rig = *eobj->m_skeleton; // Transform & project all vertices for(size_t i = 0; i != rig.bones.size(); i++) { Bone & bone = rig.bones[i]; glm::mat4x4 matrix = glm::toMat4(bone.anim.quat); // Apply Scale matrix[0][0] *= bone.anim.scale.x; matrix[0][1] *= bone.anim.scale.x; matrix[0][2] *= bone.anim.scale.x; matrix[1][0] *= bone.anim.scale.y; matrix[1][1] *= bone.anim.scale.y; matrix[1][2] *= bone.anim.scale.y; matrix[2][0] *= bone.anim.scale.z; matrix[2][1] *= bone.anim.scale.z; matrix[2][2] *= bone.anim.scale.z; Vec3f vector = bone.anim.trans; for(size_t v = 0; v != bone.idxvertices.size(); v++) { size_t index = bone.idxvertices[v]; Vec3f & inVert = eobj->vertexlocal[index]; EERIE_VERTEX & outVert = eobj->vertexlist3[index]; outVert.v = Vec3f(matrix * Vec4f(inVert, 1.f)); outVert.v += vector; outVert.vert.p = outVert.v; } } if(eobj->sdata) { for(size_t i = 0; i < eobj->vertexlist.size(); i++) { eobj->vertexlist[i].vert.p = eobj->vertexlist3[i].v - pos; } } }
void PointLight::setupLight(unsigned int glLightId) { Transform & transform = *(object.getComponent<Transform>()); Mat4x4f localToWorld = Mat4x4f(transform.getLocalToWorld()); Vec4f position = localToWorld * Vec4f(0,0,0,1); GLfloat pos[] = { position[0], position[1], position[2], 1 }; glLightfv(glLightId, GL_POSITION, pos); GLfloat ambientLight[] = { 0.0f, 0.0f, 0.0f, 1.0f }; GLfloat diffuseLight[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat specularLight[] = { 1.0f, 1.0f, 1.0f, 1.0f }; // Assign created components to GL_LIGHT_? glLightfv(glLightId, GL_AMBIENT, ambientLight); glLightfv(glLightId, GL_DIFFUSE, diffuseLight); glLightfv(glLightId, GL_SPECULAR, specularLight); }
Vec4f Meteor::getColorFromName(QString colorName) { int R, G, B; // 0-255 if (colorName == "violet") { // Calcium R = 176; G = 67; B = 172; } else if (colorName == "blueGreen") { // Magnesium R = 0; G = 255; B = 152; } else if (colorName == "yellow") { // Iron R = 255; G = 255; B = 0; } else if (colorName == "orangeYellow") { // Sodium R = 255; G = 160; B = 0; } else if (colorName == "red") { // atmospheric nitrogen and oxygen R = 255; G = 30; B = 0; } else { // white R = 255; G = 255; B = 255; } return Vec4f(R/255.f, G/255.f, B/255.f, 1); }
void LSystem::updateList() { mPerlin = Perlin( 8, Rand::randInt( 0, 100000 ) ); mSteps = mProduction.length(); if( mSteps > mProduction.length() ) { mSteps = mProduction.length(); } gl::pushModelView(); gl::translate( mLoc ); gl::pushModelView(); int countFood = 0; for( int i = 0; i < mSteps; i++ ) { char step = mProduction.at(i); if( step == 'F' || step == '|' ) { Vec2f current_loc = (gl::getModelView() * Vec4f( 0.0f, 0.0f, 0.0f, 1.0f )).xy(); current_loc -= mStartLength; current_loc += mLoc; boost::shared_ptr<Food> add_food( new Food( current_loc, ColorA( ColorA::black() ) ) ); mFood.push_back( add_food ); if( countFood > 0 ) { boost::weak_ptr<Food> weakFood(add_food); mFood[countFood-1]->setNext( weakFood ); } countFood++; gl::translate( 0, -mDrawLength + mPerlin.fBm( app::getElapsedFrames()*1.0f, i, 0.001f )*20000.0f ); } else if( step == '+' ) { gl::rotate( mTheta + mPerlin.fBm( app::getElapsedFrames()*1.0f, i, 0.001f )*(2000.0f * i/30.0f)); } else if( step == '-' ) { gl::rotate( -1*(mTheta + mPerlin.fBm( app::getElapsedFrames()*1.0f, i, 0.001f )*(2000.0f * i/30.0f))); } else if( step == '[' ) { gl::pushModelView(); } else if( step == ']' ) { gl::popModelView(); } } gl::popModelView(); gl::popModelView(); }
static void gaussianBlurV(const T * __srcp, float * dstp, const float * weights, const int width, const int height, const int srcStride, const int dstStride, const int radius, const float offset) noexcept { const int diameter = radius * 2 + 1; const T ** _srcp = new const T *[diameter]; _srcp[radius] = __srcp; for (int i = 1; i <= radius; i++) { _srcp[radius - i] = _srcp[radius - 1 + i]; _srcp[radius + i] = _srcp[radius] + srcStride * i; } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x += 4) { Vec4f sum = zero_4f(); for (int i = 0; i < diameter; i++) { if (std::is_same<T, uint8_t>::value) { const Vec4f srcp = to_float(Vec4i().load_4uc(_srcp[i] + x)); sum = mul_add(srcp, weights[i], sum); } else if (std::is_same<T, uint16_t>::value) { const Vec4f srcp = to_float(Vec4i().load_4us(_srcp[i] + x)); sum = mul_add(srcp, weights[i], sum); } else { const Vec4f srcp = Vec4f().load_a(_srcp[i] + x); sum = mul_add(srcp + offset, weights[i], sum); } } sum.stream(dstp + x); } for (int i = 0; i < diameter - 1; i++) _srcp[i] = _srcp[i + 1]; if (y < height - 1 - radius) _srcp[diameter - 1] += srcStride; else if (y > height - 1 - radius) _srcp[diameter - 1] -= srcStride; dstp += dstStride; } delete[] _srcp; }
void UniformResamplingRecursiveMISBPTRenderer::processTile(uint32_t threadID, uint32_t tileID, const Vec4u& viewport) const { auto spp = getSppCount(); TileProcessingRenderer::processTilePixels(viewport, [&](uint32_t x, uint32_t y) { auto pixelID = getPixelIndex(x, y); // Add a new sample to the pixel for(auto i = 0u; i <= getFramebuffer().getChannelCount(); ++i) { accumulate(i, pixelID, Vec4f(0, 0, 0, 1)); } // Process each sample for(auto sampleID = 0u; sampleID < spp; ++sampleID) { processSample(threadID, tileID, pixelID, sampleID, x, y); } }); // Compute contributions for 1-length eye paths (connection to sensor) connectLightVerticesToSensor(threadID, tileID, viewport); }
void StelQGLRenderer::drawWindow(StelViewportEffect* const effect) { // At this point, FBOs have been released (if using FBOs), so we're drawing // directly to the screen. The StelViewportEffect::drawToViewport call // actually draws puts the rendered result onto the viewport. invariant(); //Warn about any GL errors. checkGLErrors("drawWindow() start"); //Effects are ignored when FBO is not supported. //That might be changed for some GPUs, but it might not be worth the effort. viewport.prepareToDrawViewport(); if(NULL == effect) { // If using FBO, we still need to put it on the screen. if(viewport.useFBO()) { StelTextureNew* screenTexture = getViewportTexture(); const QSize size = screenTexture->getDimensions(); glDisable(GL_BLEND); setGlobalColor(Vec4f(1.0f, 1.0f, 1.0f, 1.0f)); screenTexture->bind(); drawTexturedRect(0, 0, size.width(), size.height()); delete screenTexture; } // If not using FBO, the result is already drawn to the screen. } else { effect->drawToViewport(this); } viewport.disablePainting(); checkGLErrors("drawWindow() end"); invariant(); }
void MenuBackground::createRainParticleSystem() { //printf("In MenuBackground::createRainParticleSystem() rps = %p\n",rps); if(rps == NULL) { rps= new RainParticleSystem(); rps->setSpeed(12.f/GameConstants::updateFps); rps->setEmissionRate(25); rps->setWind(-90.f, 4.f/GameConstants::updateFps); rps->setPos(Vec3f(0.f, 25.f, 0.f)); rps->setColor(Vec4f(1.f, 1.f, 1.f, 0.2f)); rps->setRadius(30.f); Renderer &renderer= Renderer::getInstance(); renderer.manageParticleSystem(rps, rsMenu); for(int i=0; i<raindropCount; ++i){ raindropStates[i]= random.randRange(0.f, 1.f); raindropPos[i]= computeRaindropPos(); } } }
render::Mesh MorphableModel::drawSample(vector<float> shapeCoefficients, vector<float> colorCoefficients) { render::Mesh mean; mean.tvi = shapeModel.getTriangleList(); mean.tci = colorModel.getTriangleList(); Mat shapeSample; Mat colorSample; if (shapeCoefficients.empty()) { shapeSample = shapeModel.getMean(); } else { shapeSample = shapeModel.drawSample(shapeCoefficients); } if (colorCoefficients.empty()) { colorSample = colorModel.getMean(); } else { colorSample = colorModel.drawSample(colorCoefficients); } unsigned int numVertices = shapeModel.getDataDimension() / 3; unsigned int numVerticesColor = colorModel.getDataDimension() / 3; if (numVertices != numVerticesColor) { string msg("MorphableModel: The number of vertices of the shape and color models are not the same: " + lexical_cast<string>(numVertices) + " != " + lexical_cast<string>(numVerticesColor)); Loggers->getLogger("shapemodels").debug(msg); throw std::runtime_error(msg); } mean.vertex.resize(numVertices); for (unsigned int i = 0; i < numVertices; ++i) { mean.vertex[i].position = Vec4f(shapeSample.at<float>(i*3 + 0), shapeSample.at<float>(i*3 + 1), shapeSample.at<float>(i*3 + 2), 1.0f); mean.vertex[i].color = Vec3f(colorSample.at<float>(i*3 + 0), colorSample.at<float>(i*3 + 1), colorSample.at<float>(i*3 + 2)); // order in hdf5: RGB. Order in OCV: BGR. But order in vertex.color: RGB } mean.hasTexture = false; return mean; }
void UniTransform3fDirection(const UniTransform3f& transf,const Direction3f& direction, Direction3f* outDirection) { //reference: pag. 200 Essential Mathematics for Games and Interactive Applications A Programmer’s Guide Second Edition //outDirection = quat * (scale * direction) * inverseQuaternion + translate Vec4f scaleD = Vec4f(transf.scale * direction.dir.x, transf.scale * direction.dir.y, transf.scale * direction.dir.z, 0.f); Quatf quatD; QuatfInitWithValues(scaleD.x, scaleD.y, scaleD.z, 0.f, &quatD); Quatf ris; QuatfMult(transf.rotation, quatD, &ris); Quatf invquat; QuatfInverse(transf.rotation, &invquat); Quatf ris1; QuatfMult(ris, invquat, &ris1); //traslation don't change direction outDirection->dir.x = ris1.qX; //+ transf.translation.x; outDirection->dir.y = ris1.qY; //+ transf.translation.y; outDirection->dir.z = ris1.qZ; //+ transf.translation.z; }
void UniTransform3fPoint(const UniTransform3f& transf,const Point3f& point, Point3f* outPoint) { //reference: pag. 200 Essential Mathematics for Games and Interactive Applications A Programmer’s Guide Second Edition //outPoint = quat * (scale * point) * inverseQuaternion + translate //scaleP = scale * point Vec4f scaleP = Vec4f(transf.scale * point.point.x, transf.scale * point.point.y, transf.scale * point.point.z, 1.f); Quatf quatP; QuatfInitWithValues(scaleP.x, scaleP.y, scaleP.z, 0.f, &quatP); Quatf ris; QuatfMult(transf.rotation, quatP, &ris); Quatf invquat; QuatfInverse(transf.rotation, &invquat); Quatf ris1; QuatfMult(ris, invquat, &ris1); outPoint->point.x = ris1.qX + transf.translation.x; outPoint->point.y = ris1.qY + transf.translation.y; outPoint->point.z = ris1.qZ + transf.translation.z; }
bool Program::update() { GraphicContext gc = window.get_gc(); InputDevice mouse = window.get_ic().get_mouse(); float time = System::get_time() / 1000.0f; uniforms.time = time; auto pos = mouse.get_position(); uniforms.mouse = Vec4f(pos.x / 800.0f, pos.y / 600.0f, 0, 0); for(int i=0; i< uniforms.particle_count; ++i) { uniforms.positions[i].x += sinf(time + i * 2.0f) / 40.0f; uniforms.positions[i].y += cosf(time + i * 2.0f) / 40.0f; } uniformVector.upload_data(gc, &uniforms, 1); effect.draw(gc); window.flip(1); return !exit; }
CubeExample(void) : cube( List("Position")("Normal")("TexCoord").Get(), shapes::Cube(), cube_prog ) { // setup the texture { GLuint tex_side = 512; auto image = images::NewtonFractal( tex_side, tex_side, Vec3f(0.2f, 0.1f, 0.4f), Vec3f(0.8f, 0.8f, 1.0f), Vec2f(-1.0f, -1.0f), Vec2f( 1.0f, 1.0f), images::NewtonFractal::X4Minus1(), images::NewtonFractal::DefaultMixer() ); gl.Bound(Texture::Target::_2D, cube_tex) .Image2D(image) .GenerateMipmap() .BorderColor(Vec4f(0.8f, 0.8f, 1.0f, 1.0f)) .MinFilter(TextureMinFilter::LinearMipmapLinear) .MagFilter(TextureMagFilter::Linear) .WrapS(TextureWrap::Repeat) .WrapT(TextureWrap::Repeat); } cube_prog.cube_tex = 0; cube_prog.light_position.Set(4.0f, 4.0f, -8.0f); gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f); gl.ClearDepth(1.0f); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); gl.CullFace(Face::Back); }
void processSample(uint32_t threadID, uint32_t pixelID, uint32_t sampleID, uint32_t x, uint32_t y) const { PixelSensor sensor(getSensor(), Vec2u(x, y), getFramebufferSize()); auto pixelSample = getPixelSample(threadID, sampleID); auto lensSample = getFloat2(threadID); RaySample raySample; Intersection I; sampleExitantRay( sensor, getScene(), lensSample, pixelSample, raySample, I); auto ray = raySample.value; accumulate(0, pixelID, Vec4f(ray.dir, 1.f)); }
void Render(double time) { gl.Clear().ColorBuffer().DepthBuffer(); // auto camera = CamMatrixf::Orbiting( Vec3f(), 14.0 - SineWave(time / 13)*8.0, Degrees(time * 33), Degrees(SineWave(time / 21.0) * 31) ); camera_matrix = camera; const Vec3f offsets[6] = { Vec3f( 2, 0, 0), Vec3f(-2, 0, 0), Vec3f( 0, 2, 0), Vec3f( 0,-2, 0), Vec3f( 0, 0, 2), Vec3f( 0, 0,-2) }; for(int i=0; i!=6; ++i) { auto model = ModelMatrixf::RotationX(Degrees(time * 11))* ModelMatrixf::Translation(offsets[i])* ModelMatrixf::RotationZ(Degrees(time * (37+9*i))); model_matrix = model; offset = offsets[i]; view_position = ( Inverse(model)* Vec4f(camera.Position(), 1) ).xyz(); shape_instr.Draw(shape_indices); } }
void Render(double time) { gl.Clear().ColorBuffer().DepthBuffer(); // auto camera = CamMatrixf::Orbiting( Vec3f(), 15.0 - SineWave(time / 13)*8.0, Degrees(time * 33), Degrees(SineWave(time / 21.0) * 31) ); camera_matrix = camera; const Vec3f offsets[4] = { Vec3f( 2, 0, 0), Vec3f(-2, 0, 0), Vec3f( 0, 0, 2), Vec3f( 0, 0,-2) }; for(int i=0; i!=4; ++i) { auto model = ModelMatrixf::RotationX(Degrees(time * 11))* ModelMatrixf::Translation(offsets[i])* ModelMatrixf::RotationZ(Degrees(time * (37+3*i))); GLint level = GLint(17.0 / (Length(( Inverse(model)* Vec4f(camera.Position(), 1) ).xyz())+0.1)); model_matrix = model; tess_level = level; shape_instr.Draw(shape_indices); } }
int OutputLocations( int locationCount, Dll_Interface::TopologyResult* locationData, Vec3fDA& outPos, Vec3f normal, float width = 0.0f, float length = 0.0f) { // If they didn't provide any data, just report the size if ((locationCount == 0) || (locationData == NULL)) { locationCount = outPos.GetSize(); return locationCount; } UnderstandingMgr_W &UnderstandingMgr = UnderstandingMgr_W::GetUnderstandingMgr(); // Transform out of dll Quat quatDLLToWorld = UnderstandingMgr.GetFrameTransfoForOutput(); Mat4x4 matDLLToWorld; quatDLLToWorld.GetMatrix(matDLLToWorld); // Transform the normal normal = VecFloat4x4Transform3(matDLLToWorld, Vec4f(normal)); // Copy the data out (and transform it back) locationCount = min(outPos.GetSize(), locationCount); for (int i = 0; i < locationCount; ++i) { Util_L::Transform_Vec3f_to_XMFLOAT3(outPos[i], locationData[i].position, matDLLToWorld); Util_L::Convert_Vec3f_to_XMFLOAT3(normal, locationData[i].normal); locationData[i].width = width; locationData[i].length = length; } return locationCount; }
int clusterDetections(vector<Vec4f> &obj) { vector<int> a(obj.size(),0); int ncc = findConnectedComponents(a, obj); if (! ncc) return 0; int idx = 0; for (int cc=1; cc<=ncc; ++cc) { Vec4f sum(0,0,0,0); int k = 0; for (size_t i=0; i<obj.size(); ++i) { if (a[i] == cc) { sum += obj[i]; k++; } } obj[idx++] = Vec4f(sum[0], sum[1]/k, sum[2]/k, sum[3]/k); // sum[0] is accumulated confidence measure } obj.resize(idx); return idx; }
void GTranformation::Projection(const Camera& cur_camera, PolyModel& Model){ //build matrix if (false){ //float Mat2[4][4] = { // (2*cur_camera.d() / (cur_camera.R()-cur_camera.L())), 0.0f, ((cur_camera.R()+cur_camera.L()) / (cur_camera.R()-cur_camera.L())), 0.0f, // 0.0f, (2*cur_camera.d() / (cur_camera.T()-cur_camera.B())), ((cur_camera.T()+cur_camera.B()) / (cur_camera.T()-cur_camera.B())), 0.0f, // 0.0f, 0.0f, (cur_camera.f() / (cur_camera.f() - cur_camera.d())), -((cur_camera.d()* cur_camera.f()) / (cur_camera.f() - cur_camera.d())), // 0.0f, 0.0f, -1.0f, 0.0f //}; } //float Mat1[4][4] = { // 1.0f, 0.0f, 0.0f, 0.0f, // 0.0f, 1.0f, 0.0f, 0.0f, // 0.0f, 0.0f, 1.0f, 0.0f, // 0.0f, 0.0f, 1 / cur_camera.d(), 0.0f //}; float Mat2[4][4] = { (cur_camera.d() / cur_camera.H()), 0.0f, 0.0f, 0.0f, 0.0f, (cur_camera.d() / cur_camera.H()), 0.0f, 0.0f, 0.0f, 0.0f, (cur_camera.f() / (cur_camera.f() - cur_camera.d())), -((cur_camera.d()* cur_camera.f()) / (cur_camera.f() - cur_camera.d())), 0.0f, 0.0f, 1.0f, 0.0f }; Mat4f Projectionmatrix = Mat4f(Mat2); //Mat4f Prespectivematrix = Mat4f(Mat1); for (int i = 0; i < Model.m_verts.size(); i++){ float x = Model.m_verts[i].x(); float y = Model.m_verts[i].y(); float z = Model.m_verts[i].z(); float w = 1.0f; Vec4f up_point = Vec4f(x, y, z, w); //up_point = Prespectivematrix*up_point; up_point = Projectionmatrix*up_point; Model.m_verts[i] = Vec3f(up_point.x() / up_point.w(), up_point.y() / up_point.w(), up_point.z() / up_point.w()); } }
void StateManager::LoadVertexColor(RGBColor &C, UINT Index) { for(UINT i = 0; i < VertexDeclaration.Length(); i++) { const D3D9Base::D3DVERTEXELEMENT9 &Decl = VertexDeclaration[i]; if(Decl.Usage == D3DDECLUSAGE_COLOR && Decl.UsageIndex == 0) { StreamInfo &Stream = VBufferStreams[Decl.Stream]; Assert(Stream.StreamData != NULL, "Reference to unbound stream"); BYTE *ByteStream = (BYTE *)(Stream.StreamData->Buffer.CArray() + Stream.OffsetInBytes + Index * Stream.Stride + Decl.Offset); float *FloatStream = (float *)ByteStream; Vec4f Result = Vec4f(0.0f, 0.0f, 0.0f, 0.0f); if(Decl.Type == D3DDECLTYPE_D3DCOLOR) { C = RGBColor(ByteStream[0], ByteStream[1], ByteStream[2], ByteStream[3]); return; } else { SignalError(String("Unsupported type: ") + String(UINT(Decl.Type))); } } } }
Vec4f DepthMapJudge::Measure(Mat xyz) { float density = 0; float emptines = 0; float outliers = 0; float stdev = 0; int amount = 0; const double max_z = 10000; for(int y = 0; y < xyz.rows; y++) { for(int x = 0; x < xyz.cols; x++) { Vec3f point = xyz.at<Vec3f>(y, x); if(fabs(point[2] - max_z) < FLT_EPSILON || fabs(point[2]) > max_z || point[2]<=0 ){ emptines++; continue; } if(point[2]<=minZ||point[2]>=maxZ){ outliers++; } Vec2f aux = CalculateNeighbours(point,x,y,xyz); density+= aux[0]/pow((float)2*ws+1,2); stdev+=aux[1]; amount++; } } return Vec4f(density/amount,emptines/(xyz.cols*xyz.rows),outliers/(xyz.cols*xyz.rows),stdev/(amount*radius)); }
BloomPass::BloomPass(GraphicContext &gc, const std::string &shader_path, ResourceContainer &inout) { viewport = inout.get<Rect>("Viewport"); final_color = inout.get<Texture2D>("FinalColor"); bloom_contribution = inout.get<Texture2D>("BloomContribution"); if (gc.get_shader_language() == shader_glsl) { bloom_shader = ShaderSetup::compile(gc, "", PathHelp::combine(shader_path, "Final/vertex_present.glsl"), PathHelp::combine(shader_path, "Bloom/fragment_bloom_extract.glsl"), ""); bloom_shader.bind_frag_data_location(0, "FragColor"); } else { bloom_shader = ShaderSetup::compile(gc, "", PathHelp::combine(shader_path, "Final/vertex_present.hlsl"), PathHelp::combine(shader_path, "Bloom/fragment_bloom_extract.hlsl"), ""); } ShaderSetup::link(bloom_shader, "bloom extract program"); bloom_shader.bind_attribute_location(0, "PositionInProjection"); bloom_shader.set_uniform1i("FinalColors", 0); bloom_shader.set_uniform1i("FinalColorsSampler", 0); bloom_shader.set_uniform1i("LogAverageLight", 1); Vec4f positions[6] = { Vec4f(-1.0f, -1.0f, 1.0f, 1.0f), Vec4f( 1.0f, -1.0f, 1.0f, 1.0f), Vec4f(-1.0f, 1.0f, 1.0f, 1.0f), Vec4f( 1.0f, -1.0f, 1.0f, 1.0f), Vec4f(-1.0f, 1.0f, 1.0f, 1.0f), Vec4f( 1.0f, 1.0f, 1.0f, 1.0f) }; rect_positions = VertexArrayVector<Vec4f>(gc, positions, 6); rect_primarray = PrimitivesArray(gc); rect_primarray.set_attributes(0, rect_positions); bloom_blur.input = bloom_contribution; BlendStateDescription blend_desc; blend_desc.enable_blending(false); blend_state = BlendState(gc, blend_desc); }
Vec4f Vec4fCounterDesc::getOneElement(void) { return Vec4f(1.f, 1.f, 1.f); }
Vec4f Vec4fCounterDesc::getZeroElement(void) { return Vec4f(0.f, 0.f, 0.f); }
int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindow = createNativeWindow(); TutorialWindow->initWindow(); TutorialWindow->setDisplayCallback(display); TutorialWindow->setReshapeCallback(reshape); //Add Window Listener TutorialKeyListener TheKeyListener; TutorialWindow->addKeyListener(&TheKeyListener); TutorialMouseListener TheTutorialMouseListener; TutorialMouseMotionListener TheTutorialMouseMotionListener; TutorialWindow->addMouseListener(&TheTutorialMouseListener); TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindow); //Shader Material BlendChunkUnrecPtr ExampleBlendChunk = BlendChunk::create(); ExampleBlendChunk->setSrcFactor(GL_SRC_ALPHA); ExampleBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); //Material Chunk MaterialChunkUnrecPtr ShaderMaterialChunk = MaterialChunk::create(); ShaderMaterialChunk->setAmbient(Color4f(0.4f,0.4f,0.4f,1.0f)); ShaderMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f)); ShaderMaterialChunk->setSpecular(Color4f(1.0f,1.0f,1.0f,1.0f)); //Shader Chunk SimpleSHLChunkUnrecPtr TheSHLChunk = SimpleSHLChunk::create(); TheSHLChunk->setVertexProgram(createSHLVertexProg()); TheSHLChunk->setFragmentProgram(createSHLFragProg()); //Color Parameter ShaderVariableVec4fUnrecPtr Color1Parameter = ShaderVariableVec4f::create(); Color1Parameter->setName("Color1"); Color1Parameter->setValue(Vec4f(0.0f,1.0f,0.0f,1.0f)); ShaderVariableVec4fUnrecPtr Color2Parameter = ShaderVariableVec4f::create(); Color2Parameter->setName("Color2"); Color2Parameter->setValue(Vec4f(1.0f,1.0f,1.0f,1.0f)); //Shader Parameter Chunk SHLParameterChunkUnrecPtr SHLParameters = SHLParameterChunk::create(); SHLParameters->getParameters().push_back(Color1Parameter); SHLParameters->getParameters().push_back(Color2Parameter); SHLParameters->setSHLChunk(TheSHLChunk); ChunkMaterialUnrecPtr ShaderMaterial = ChunkMaterial::create(); ShaderMaterial->addChunk(ShaderMaterialChunk); ShaderMaterial->addChunk(TheSHLChunk); ShaderMaterial->addChunk(SHLParameters); //Torus Node GeometryUnrecPtr TorusGeometry = makeTorusGeo(5.0f,20.0f, 32,32); TorusGeometry->setMaterial(ShaderMaterial); NodeUnrecPtr TorusNode = Node::create(); TorusNode->setCore(TorusGeometry); // Make Main Scene Node NodeUnrecPtr scene = Node::create(); scene->setCore(Group::create()); scene->addChild(TorusNode); mgr->setRoot(scene); // Show the whole Scene mgr->showAll(); //Create the Animations initAnimations(Color1Parameter, "value"); //Open Window Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5); TutorialWindow->openWindow(WinPos, WinSize, "04ShaderAnimation"); //Main Loop TutorialWindow->mainLoop(); osgExit(); return 0; }
void VulkanReplay::RenderMesh(uint32_t eventId, const vector<MeshFormat> &secondaryDraws, const MeshDisplay &cfg) { if(cfg.position.vertexResourceId == ResourceId() || cfg.position.numIndices == 0) return; auto it = m_OutputWindows.find(m_ActiveWinID); if(m_ActiveWinID == 0 || it == m_OutputWindows.end()) return; OutputWindow &outw = it->second; // if the swapchain failed to create, do nothing. We will try to recreate it // again in CheckResizeOutputWindow (once per render 'frame') if(outw.swap == VK_NULL_HANDLE) return; VkDevice dev = m_pDriver->GetDev(); VkCommandBuffer cmd = m_pDriver->GetNextCmd(); const VkLayerDispatchTable *vt = ObjDisp(dev); VkResult vkr = VK_SUCCESS; VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; vkr = vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo); RDCASSERTEQUAL(vkr, VK_SUCCESS); VkRenderPassBeginInfo rpbegin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, NULL, Unwrap(outw.rpdepth), Unwrap(outw.fbdepth), {{ 0, 0, }, {m_DebugWidth, m_DebugHeight}}, 0, NULL, }; vt->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = {0.0f, 0.0f, (float)m_DebugWidth, (float)m_DebugHeight, 0.0f, 1.0f}; vt->CmdSetViewport(Unwrap(cmd), 0, 1, &viewport); Matrix4f projMat = Matrix4f::Perspective(90.0f, 0.1f, 100000.0f, float(m_DebugWidth) / float(m_DebugHeight)); Matrix4f InvProj = projMat.Inverse(); Matrix4f camMat = cfg.cam ? ((Camera *)cfg.cam)->GetMatrix() : Matrix4f::Identity(); Matrix4f ModelViewProj = projMat.Mul(camMat); Matrix4f guessProjInv; if(cfg.position.unproject) { // the derivation of the projection matrix might not be right (hell, it could be an // orthographic projection). But it'll be close enough likely. Matrix4f guessProj = cfg.position.farPlane != FLT_MAX ? Matrix4f::Perspective(cfg.fov, cfg.position.nearPlane, cfg.position.farPlane, cfg.aspect) : Matrix4f::ReversePerspective(cfg.fov, cfg.position.nearPlane, cfg.aspect); if(cfg.ortho) { guessProj = Matrix4f::Orthographic(cfg.position.nearPlane, cfg.position.farPlane); } guessProjInv = guessProj.Inverse(); ModelViewProj = projMat.Mul(camMat.Mul(guessProjInv)); } if(!secondaryDraws.empty()) { size_t mapsUsed = 0; for(size_t i = 0; i < secondaryDraws.size(); i++) { const MeshFormat &fmt = secondaryDraws[i]; if(fmt.vertexResourceId != ResourceId()) { // TODO should move the color to a push constant so we don't have to map all the time uint32_t uboOffs = 0; MeshUBOData *data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = Vec4f(fmt.meshColor.x, fmt.meshColor.y, fmt.meshColor.z, fmt.meshColor.w); data->homogenousInput = cfg.position.unproject; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->displayFormat = MESHDISPLAY_SOLID; data->rawoutput = 0; m_MeshRender.UBO.Unmap(); mapsUsed++; if(mapsUsed + 1 >= m_MeshRender.UBO.GetRingCount()) { // flush and sync so we can use more maps vt->CmdEndRenderPass(Unwrap(cmd)); vkr = vt->EndCommandBuffer(Unwrap(cmd)); RDCASSERTEQUAL(vkr, VK_SUCCESS); m_pDriver->SubmitCmds(); m_pDriver->FlushQ(); mapsUsed = 0; cmd = m_pDriver->GetNextCmd(); vkr = vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo); RDCASSERTEQUAL(vkr, VK_SUCCESS); vt->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); vt->CmdSetViewport(Unwrap(cmd), 0, 1, &viewport); } MeshDisplayPipelines secondaryCache = GetDebugManager()->CacheMeshDisplayPipelines( m_MeshRender.PipeLayout, secondaryDraws[i], secondaryDraws[i]); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(secondaryCache.pipes[MeshDisplayPipelines::ePipe_WireDepth])); VkBuffer vb = m_pDriver->GetResourceManager()->GetCurrentHandle<VkBuffer>(fmt.vertexResourceId); VkDeviceSize offs = fmt.vertexByteOffset; vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(vb), &offs); if(fmt.indexByteStride) { VkIndexType idxtype = VK_INDEX_TYPE_UINT16; if(fmt.indexByteStride == 4) idxtype = VK_INDEX_TYPE_UINT32; if(fmt.indexResourceId != ResourceId()) { VkBuffer ib = m_pDriver->GetResourceManager()->GetLiveHandle<VkBuffer>(fmt.indexResourceId); vt->CmdBindIndexBuffer(Unwrap(cmd), Unwrap(ib), fmt.indexByteOffset, idxtype); } vt->CmdDrawIndexed(Unwrap(cmd), fmt.numIndices, 1, 0, fmt.baseVertex, 0); } else { vt->CmdDraw(Unwrap(cmd), fmt.numIndices, 1, 0, 0); } } } { // flush and sync so we can use more maps vt->CmdEndRenderPass(Unwrap(cmd)); vkr = vt->EndCommandBuffer(Unwrap(cmd)); RDCASSERTEQUAL(vkr, VK_SUCCESS); m_pDriver->SubmitCmds(); m_pDriver->FlushQ(); cmd = m_pDriver->GetNextCmd(); vkr = vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo); RDCASSERTEQUAL(vkr, VK_SUCCESS); vt->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); vt->CmdSetViewport(Unwrap(cmd), 0, 1, &viewport); } } MeshDisplayPipelines cache = GetDebugManager()->CacheMeshDisplayPipelines( m_MeshRender.PipeLayout, cfg.position, cfg.second); if(cfg.position.vertexResourceId != ResourceId()) { VkBuffer vb = m_pDriver->GetResourceManager()->GetCurrentHandle<VkBuffer>(cfg.position.vertexResourceId); VkDeviceSize offs = cfg.position.vertexByteOffset; // we source all data from the first instanced value in the instanced case, so make sure we // offset correctly here. if(cfg.position.instanced) offs += cfg.position.vertexByteStride * (cfg.curInstance / cfg.position.instStepRate); vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(vb), &offs); } SolidShade solidShadeMode = cfg.solidShadeMode; // can't support secondary shading without a buffer - no pipeline will have been created if(solidShadeMode == SolidShade::Secondary && cfg.second.vertexResourceId == ResourceId()) solidShadeMode = SolidShade::NoSolid; if(solidShadeMode == SolidShade::Secondary) { VkBuffer vb = m_pDriver->GetResourceManager()->GetCurrentHandle<VkBuffer>(cfg.second.vertexResourceId); VkDeviceSize offs = cfg.second.vertexByteOffset; // we source all data from the first instanced value in the instanced case, so make sure we // offset correctly here. if(cfg.second.instanced) offs += cfg.second.vertexByteStride * (cfg.curInstance / cfg.second.instStepRate); vt->CmdBindVertexBuffers(Unwrap(cmd), 1, 1, UnwrapPtr(vb), &offs); } // solid render if(solidShadeMode != SolidShade::NoSolid && cfg.position.topology < Topology::PatchList) { VkPipeline pipe = VK_NULL_HANDLE; switch(solidShadeMode) { default: case SolidShade::Solid: pipe = cache.pipes[MeshDisplayPipelines::ePipe_SolidDepth]; break; case SolidShade::Lit: pipe = cache.pipes[MeshDisplayPipelines::ePipe_Lit]; break; case SolidShade::Secondary: pipe = cache.pipes[MeshDisplayPipelines::ePipe_Secondary]; break; } // can't support lit rendering without the pipeline - maybe geometry shader wasn't supported. if(solidShadeMode == SolidShade::Lit && pipe == VK_NULL_HANDLE) pipe = cache.pipes[MeshDisplayPipelines::ePipe_SolidDepth]; uint32_t uboOffs = 0; MeshUBOData *data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); if(solidShadeMode == SolidShade::Lit) data->invProj = projMat.Inverse(); data->mvp = ModelViewProj; data->color = Vec4f(0.8f, 0.8f, 0.0f, 1.0f); data->homogenousInput = cfg.position.unproject; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->displayFormat = (uint32_t)solidShadeMode; data->rawoutput = 0; if(solidShadeMode == SolidShade::Secondary && cfg.second.showAlpha) data->displayFormat = MESHDISPLAY_SECONDARY_ALPHA; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(pipe)); if(cfg.position.indexByteStride) { VkIndexType idxtype = VK_INDEX_TYPE_UINT16; if(cfg.position.indexByteStride == 4) idxtype = VK_INDEX_TYPE_UINT32; if(cfg.position.indexResourceId != ResourceId()) { VkBuffer ib = m_pDriver->GetResourceManager()->GetCurrentHandle<VkBuffer>(cfg.position.indexResourceId); vt->CmdBindIndexBuffer(Unwrap(cmd), Unwrap(ib), cfg.position.indexByteOffset, idxtype); } vt->CmdDrawIndexed(Unwrap(cmd), cfg.position.numIndices, 1, 0, cfg.position.baseVertex, 0); } else { vt->CmdDraw(Unwrap(cmd), cfg.position.numIndices, 1, 0, 0); } } // wireframe render if(solidShadeMode == SolidShade::NoSolid || cfg.wireframeDraw || cfg.position.topology >= Topology::PatchList) { Vec4f wireCol = Vec4f(cfg.position.meshColor.x, cfg.position.meshColor.y, cfg.position.meshColor.z, 1.0f); uint32_t uboOffs = 0; MeshUBOData *data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = wireCol; data->displayFormat = (uint32_t)SolidShade::Solid; data->homogenousInput = cfg.position.unproject; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->rawoutput = 0; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(cache.pipes[MeshDisplayPipelines::ePipe_WireDepth])); if(cfg.position.indexByteStride) { VkIndexType idxtype = VK_INDEX_TYPE_UINT16; if(cfg.position.indexByteStride == 4) idxtype = VK_INDEX_TYPE_UINT32; if(cfg.position.indexResourceId != ResourceId()) { VkBuffer ib = m_pDriver->GetResourceManager()->GetCurrentHandle<VkBuffer>(cfg.position.indexResourceId); vt->CmdBindIndexBuffer(Unwrap(cmd), Unwrap(ib), cfg.position.indexByteOffset, idxtype); } vt->CmdDrawIndexed(Unwrap(cmd), cfg.position.numIndices, 1, 0, cfg.position.baseVertex, 0); } else { vt->CmdDraw(Unwrap(cmd), cfg.position.numIndices, 1, 0, 0); } } MeshFormat helper; helper.indexByteStride = 2; helper.topology = Topology::LineList; helper.format.type = ResourceFormatType::Regular; helper.format.compByteWidth = 4; helper.format.compCount = 4; helper.format.compType = CompType::Float; helper.vertexByteStride = sizeof(Vec4f); // cache pipelines for use in drawing wireframe helpers cache = GetDebugManager()->CacheMeshDisplayPipelines(m_MeshRender.PipeLayout, helper, helper); if(cfg.showBBox) { Vec4f a = Vec4f(cfg.minBounds.x, cfg.minBounds.y, cfg.minBounds.z, cfg.minBounds.w); Vec4f b = Vec4f(cfg.maxBounds.x, cfg.maxBounds.y, cfg.maxBounds.z, cfg.maxBounds.w); Vec4f TLN = Vec4f(a.x, b.y, a.z, 1.0f); // TopLeftNear, etc... Vec4f TRN = Vec4f(b.x, b.y, a.z, 1.0f); Vec4f BLN = Vec4f(a.x, a.y, a.z, 1.0f); Vec4f BRN = Vec4f(b.x, a.y, a.z, 1.0f); Vec4f TLF = Vec4f(a.x, b.y, b.z, 1.0f); Vec4f TRF = Vec4f(b.x, b.y, b.z, 1.0f); Vec4f BLF = Vec4f(a.x, a.y, b.z, 1.0f); Vec4f BRF = Vec4f(b.x, a.y, b.z, 1.0f); // 12 frustum lines => 24 verts Vec4f bbox[24] = { TLN, TRN, TRN, BRN, BRN, BLN, BLN, TLN, TLN, TLF, TRN, TRF, BLN, BLF, BRN, BRF, TLF, TRF, TRF, BRF, BRF, BLF, BLF, TLF, }; VkDeviceSize vboffs = 0; Vec4f *ptr = (Vec4f *)m_MeshRender.BBoxVB.Map(vboffs); memcpy(ptr, bbox, sizeof(bbox)); m_MeshRender.BBoxVB.Unmap(); vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.BBoxVB.buf), &vboffs); uint32_t uboOffs = 0; MeshUBOData *data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = Vec4f(0.2f, 0.2f, 1.0f, 1.0f); data->displayFormat = (uint32_t)SolidShade::Solid; data->homogenousInput = 0; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->rawoutput = 0; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(cache.pipes[MeshDisplayPipelines::ePipe_WireDepth])); vt->CmdDraw(Unwrap(cmd), 24, 1, 0, 0); } // draw axis helpers if(!cfg.position.unproject) { VkDeviceSize vboffs = 0; vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.AxisFrustumVB.buf), &vboffs); uint32_t uboOffs = 0; MeshUBOData *data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = Vec4f(1.0f, 0.0f, 0.0f, 1.0f); data->displayFormat = (uint32_t)SolidShade::Solid; data->homogenousInput = 0; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->rawoutput = 0; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(cache.pipes[MeshDisplayPipelines::ePipe_Wire])); vt->CmdDraw(Unwrap(cmd), 2, 1, 0, 0); // poke the color (this would be a good candidate for a push constant) data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = Vec4f(0.0f, 1.0f, 0.0f, 1.0f); data->displayFormat = (uint32_t)SolidShade::Solid; data->homogenousInput = 0; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->rawoutput = 0; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdDraw(Unwrap(cmd), 2, 1, 2, 0); data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = Vec4f(0.0f, 0.0f, 1.0f, 1.0f); data->displayFormat = (uint32_t)SolidShade::Solid; data->homogenousInput = 0; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->rawoutput = 0; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdDraw(Unwrap(cmd), 2, 1, 4, 0); } // 'fake' helper frustum if(cfg.position.unproject) { VkDeviceSize vboffs = sizeof(Vec4f) * 6; // skim the axis helpers vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.AxisFrustumVB.buf), &vboffs); uint32_t uboOffs = 0; MeshUBOData *data = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); data->mvp = ModelViewProj; data->color = Vec4f(1.0f, 1.0f, 1.0f, 1.0f); data->displayFormat = (uint32_t)SolidShade::Solid; data->homogenousInput = 0; data->pointSpriteSize = Vec2f(0.0f, 0.0f); data->rawoutput = 0; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(cache.pipes[MeshDisplayPipelines::ePipe_Wire])); vt->CmdDraw(Unwrap(cmd), 24, 1, 0, 0); } // show highlighted vertex if(cfg.highlightVert != ~0U) { { // need to end our cmd buffer, it might be submitted in GetBufferData when caching highlight // data vt->CmdEndRenderPass(Unwrap(cmd)); vkr = vt->EndCommandBuffer(Unwrap(cmd)); RDCASSERTEQUAL(vkr, VK_SUCCESS); #if ENABLED(SINGLE_FLUSH_VALIDATE) m_pDriver->SubmitCmds(); #endif } m_HighlightCache.CacheHighlightingData(eventId, cfg); { // get a new cmdbuffer and begin it cmd = m_pDriver->GetNextCmd(); vkr = vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo); RDCASSERTEQUAL(vkr, VK_SUCCESS); vt->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); vt->CmdSetViewport(Unwrap(cmd), 0, 1, &viewport); } Topology meshtopo = cfg.position.topology; /////////////////////////////////////////////////////////////// // vectors to be set from buffers, depending on topology // this vert (blue dot, required) FloatVector activeVertex; // primitive this vert is a part of (red prim, optional) vector<FloatVector> activePrim; // for patch lists, to show other verts in patch (green dots, optional) // for non-patch lists, we use the activePrim and adjacentPrimVertices // to show what other verts are related vector<FloatVector> inactiveVertices; // adjacency (line or tri, strips or lists) (green prims, optional) // will be N*M long, N adjacent prims of M verts each. M = primSize below vector<FloatVector> adjacentPrimVertices; helper.topology = Topology::TriangleList; uint32_t primSize = 3; // number of verts per primitive if(meshtopo == Topology::LineList || meshtopo == Topology::LineStrip || meshtopo == Topology::LineList_Adj || meshtopo == Topology::LineStrip_Adj) { primSize = 2; helper.topology = Topology::LineList; } else { // update the cache, as it's currently linelist helper.topology = Topology::TriangleList; cache = GetDebugManager()->CacheMeshDisplayPipelines(m_MeshRender.PipeLayout, helper, helper); } bool valid = m_HighlightCache.FetchHighlightPositions(cfg, activeVertex, activePrim, adjacentPrimVertices, inactiveVertices); if(valid) { //////////////////////////////////////////////////////////////// // prepare rendering (for both vertices & primitives) // if data is from post transform, it will be in clipspace if(cfg.position.unproject) ModelViewProj = projMat.Mul(camMat.Mul(guessProjInv)); else ModelViewProj = projMat.Mul(camMat); MeshUBOData uniforms = {}; uniforms.mvp = ModelViewProj; uniforms.color = Vec4f(1.0f, 1.0f, 1.0f, 1.0f); uniforms.displayFormat = (uint32_t)SolidShade::Solid; uniforms.homogenousInput = cfg.position.unproject; uniforms.pointSpriteSize = Vec2f(0.0f, 0.0f); uint32_t uboOffs = 0; MeshUBOData *ubodata = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); *ubodata = uniforms; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(cache.pipes[MeshDisplayPipelines::ePipe_Solid])); //////////////////////////////////////////////////////////////// // render primitives // Draw active primitive (red) uniforms.color = Vec4f(1.0f, 0.0f, 0.0f, 1.0f); // poke the color (this would be a good candidate for a push constant) ubodata = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); *ubodata = uniforms; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); if(activePrim.size() >= primSize) { VkDeviceSize vboffs = 0; Vec4f *ptr = (Vec4f *)m_MeshRender.BBoxVB.Map(vboffs, sizeof(Vec4f) * primSize); memcpy(ptr, &activePrim[0], sizeof(Vec4f) * primSize); m_MeshRender.BBoxVB.Unmap(); vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.BBoxVB.buf), &vboffs); vt->CmdDraw(Unwrap(cmd), primSize, 1, 0, 0); } // Draw adjacent primitives (green) uniforms.color = Vec4f(0.0f, 1.0f, 0.0f, 1.0f); // poke the color (this would be a good candidate for a push constant) ubodata = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); *ubodata = uniforms; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); if(adjacentPrimVertices.size() >= primSize && (adjacentPrimVertices.size() % primSize) == 0) { VkDeviceSize vboffs = 0; Vec4f *ptr = (Vec4f *)m_MeshRender.BBoxVB.Map(vboffs, sizeof(Vec4f) * adjacentPrimVertices.size()); memcpy(ptr, &adjacentPrimVertices[0], sizeof(Vec4f) * adjacentPrimVertices.size()); m_MeshRender.BBoxVB.Unmap(); vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.BBoxVB.buf), &vboffs); vt->CmdDraw(Unwrap(cmd), (uint32_t)adjacentPrimVertices.size(), 1, 0, 0); } //////////////////////////////////////////////////////////////// // prepare to render dots float scale = 800.0f / float(m_DebugHeight); float asp = float(m_DebugWidth) / float(m_DebugHeight); uniforms.pointSpriteSize = Vec2f(scale / asp, scale); // Draw active vertex (blue) uniforms.color = Vec4f(0.0f, 0.0f, 1.0f, 1.0f); // poke the color (this would be a good candidate for a push constant) ubodata = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); *ubodata = uniforms; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); // vertices are drawn with tri strips helper.topology = Topology::TriangleStrip; cache = GetDebugManager()->CacheMeshDisplayPipelines(m_MeshRender.PipeLayout, helper, helper); FloatVector vertSprite[4] = { activeVertex, activeVertex, activeVertex, activeVertex, }; vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(cache.pipes[MeshDisplayPipelines::ePipe_Solid])); { VkDeviceSize vboffs = 0; Vec4f *ptr = (Vec4f *)m_MeshRender.BBoxVB.Map(vboffs, sizeof(vertSprite)); memcpy(ptr, &vertSprite[0], sizeof(vertSprite)); m_MeshRender.BBoxVB.Unmap(); vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.BBoxVB.buf), &vboffs); vt->CmdDraw(Unwrap(cmd), 4, 1, 0, 0); } // Draw inactive vertices (green) uniforms.color = Vec4f(0.0f, 1.0f, 0.0f, 1.0f); // poke the color (this would be a good candidate for a push constant) ubodata = (MeshUBOData *)m_MeshRender.UBO.Map(&uboOffs); *ubodata = uniforms; m_MeshRender.UBO.Unmap(); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_MeshRender.PipeLayout), 0, 1, UnwrapPtr(m_MeshRender.DescSet), 1, &uboOffs); if(!inactiveVertices.empty()) { VkDeviceSize vboffs = 0; FloatVector *ptr = (FloatVector *)m_MeshRender.BBoxVB.Map(vboffs, sizeof(vertSprite)); for(size_t i = 0; i < inactiveVertices.size(); i++) { *ptr++ = inactiveVertices[i]; *ptr++ = inactiveVertices[i]; *ptr++ = inactiveVertices[i]; *ptr++ = inactiveVertices[i]; } m_MeshRender.BBoxVB.Unmap(); for(size_t i = 0; i < inactiveVertices.size(); i++) { vt->CmdBindVertexBuffers(Unwrap(cmd), 0, 1, UnwrapPtr(m_MeshRender.BBoxVB.buf), &vboffs); vt->CmdDraw(Unwrap(cmd), 4, 1, 0, 0); vboffs += sizeof(FloatVector) * 4; } } } } vt->CmdEndRenderPass(Unwrap(cmd)); vkr = vt->EndCommandBuffer(Unwrap(cmd)); RDCASSERTEQUAL(vkr, VK_SUCCESS); #if ENABLED(SINGLE_FLUSH_VALIDATE) m_pDriver->SubmitCmds(); #endif }
__device__ __inline__ Vec4f dFdy (const Vec4f& v) const { return Vec4f(dFdy(v.x), dFdy(v.y), dFdy(v.z), dFdy(v.w)); }