uint32_t SDLScreen::CompileShader(std::string vertexShader, std::string fragmentShader ) { return loadShader(vertexShader.c_str(), fragmentShader.c_str()); }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateCI = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationStateCI = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendStateCI = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilStateCI = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportStateCI = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleStateCI = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicStateCI = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), dynamicStateEnables.size(), 0); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCI = vks::initializers::pipelineCreateInfo(pipelineLayouts.radialBlur, renderPass, 0); pipelineCI.pInputAssemblyState = &inputAssemblyStateCI; pipelineCI.pRasterizationState = &rasterizationStateCI; pipelineCI.pColorBlendState = &colorBlendStateCI; pipelineCI.pMultisampleState = &multisampleStateCI; pipelineCI.pViewportState = &viewportStateCI; pipelineCI.pDepthStencilState = &depthStencilStateCI; pipelineCI.pDynamicState = &dynamicStateCI; pipelineCI.stageCount = shaderStages.size(); pipelineCI.pStages = shaderStages.data(); // Radial blur pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/radialblur/radialblur.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/radialblur/radialblur.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); // Empty vertex input state VkPipelineVertexInputStateCreateInfo emptyInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); pipelineCI.pVertexInputState = &emptyInputState; pipelineCI.layout = pipelineLayouts.radialBlur; // Additive blending blendAttachmentState.colorWriteMask = 0xF; blendAttachmentState.blendEnable = VK_TRUE; blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE; blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.radialBlur)); // No blending (for debug display) blendAttachmentState.blendEnable = VK_FALSE; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.offscreenDisplay)); // Phong pass pipelineCI.layout = pipelineLayouts.scene; shaderStages[0] = loadShader(getAssetPath() + "shaders/radialblur/phongpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/radialblur/phongpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); blendAttachmentState.blendEnable = VK_FALSE; depthStencilStateCI.depthWriteEnable = VK_TRUE; // Vertex bindings and attributes std::vector<VkVertexInputBindingDescription> vertexInputBindings = { vks::initializers::vertexInputBindingDescription(0, vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX), }; std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = { vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Position vks::initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 3), // Texture coordinates vks::initializers::vertexInputAttributeDescription(0, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 5), // Color vks::initializers::vertexInputAttributeDescription(0, 3, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Normal }; VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexInputBindings.size()); vertexInputState.pVertexBindingDescriptions = vertexInputBindings.data(); vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size()); vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes.data(); pipelineCI.pVertexInputState = &vertexInputState; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.phongPass)); // Color only pass (offscreen blur base) shaderStages[0] = loadShader(getAssetPath() + "shaders/radialblur/colorpass.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/radialblur/colorpass.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); pipelineCI.renderPass = offscreenPass.renderPass; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.colorPass)); }
DeferredShader::DeferredShader() { /*} void SpriteShader::loadFromFiles(const char* vertexShader, const char* fragmentShader) {*/ GLuint vertexShaderId = loadShader("Calamity/Shader/pointLight.vert", GL_VERTEX_SHADER); GLuint fragmentShaderId = loadShader("Calamity/Shader/pointLight.frag", GL_FRAGMENT_SHADER); /*GLuint vertexShaderId = loadShader(vertexShader, GL_VERTEX_SHADER); GLuint fragmentShaderId = loadShader(fragmentShader, GL_FRAGMENT_SHADER);*/ programId = glCreateProgram(); glAttachShader(programId, vertexShaderId); glAttachShader(programId, fragmentShaderId); glLinkProgram(programId); // Check for errors GLint programSuccess = GL_TRUE; glGetProgramiv(programId, GL_LINK_STATUS, &programSuccess); if (programSuccess != GL_TRUE) { printf("Error linking program %d!\n", programId); printProgramLog(programId); glDeleteProgram(programId); programId = 0; glDetachShader(programId, vertexShaderId); glDetachShader(programId, fragmentShaderId); glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); return; } glDetachShader(programId, vertexShaderId); glDetachShader(programId, fragmentShaderId); glDeleteShader(vertexShaderId); glDeleteShader(fragmentShaderId); positionLocation = getAttribLocation("in_Position"); projectionMatrixLocation = getUniformLocation("projectionMatrix"); modelViewMatrixLocation = getUniformLocation("modelViewMatrix"); /*dirLightColorLocation = getUniformLocation("directionalLight.color"); dirLightDirectionLocation = getUniformLocation("directionalLight.direction"); dirLightAmbientIntensityLocation = getUniformLocation("directionalLight.ambientIntensity"); dirLightDiffuseIntensityLocation = getUniformLocation("directionalLight.diffuseIntensity");*/ /*dirLightLocation.color = getUniformLocation("directionalLight.base.color"); dirLightLocation.ambientIntensity = getUniformLocation("directionalLight.base.ambientIntensity"); dirLightLocation.diffuseIntensity = getUniformLocation("directionalLight.base.diffuseIntensity"); dirLightLocation.direction = getUniformLocation("directionalLight.direction");*/ pointLightLocation.color = getUniformLocation("pointLight.base.color"); pointLightLocation.ambientIntensity = getUniformLocation("pointLight.base.ambientIntensity"); pointLightLocation.diffuseIntensity = getUniformLocation("pointLight.base.diffuseIntensity"); pointLightLocation.position = getUniformLocation("pointLight.position"); pointLightLocation.attConstant = getUniformLocation("pointLight.attConstant"); pointLightLocation.attLinear = getUniformLocation("pointLight.attLinear"); pointLightLocation.attExponential = getUniformLocation("pointLight.attExponential"); eyeWorldPosLocation = getUniformLocation("eyeWorldPos"); matSpecularIntensityLocation = getUniformLocation("matSpecularIntensity"); matSpecularPowerLocation = getUniformLocation("matSpecularPower"); screenSizeLocation = getUniformLocation("screenSize"); GLint positionTextureLocation = getUniformLocation("positionTexture"); GLint colorTextureLocation = getUniformLocation("colorTexture"); GLint normalTextureLocation = getUniformLocation("normalTexture"); bind(); glUniform1i(positionTextureLocation, 0); glUniform1i(colorTextureLocation, 1); glUniform1i(normalTextureLocation, 2); unbind(); }
ResourceId CResourceManager::loadMaterial(const std::string& file) { auto entry = m_materialFiles.find(file); if (entry != m_materialFiles.end()) { return entry->second; } LOG_DEBUG("Loading material from file %s.", file.c_str()); CIniFile ini; if (!ini.load(file)) { LOG_ERROR("Failed to load material file %s as ini file.", file.c_str()); return -1; } ResourceId diffuseId = -1; if (ini.hasKey("diffuse", "file")) { // Diffuse texture is RGB format, ignore alpha diffuseId = loadImage(ini.getValue("diffuse", "file", "error"), EColorFormat::RGB24); if (diffuseId == -1) { LOG_ERROR("Failed to load diffuse texture specified in material file %s.", file.c_str()); return -1; } } ResourceId normalId = -1; if (ini.hasKey("normal", "file")) { // Normal texture is RGB format normalId = loadImage(ini.getValue("normal", "file", "error"), EColorFormat::RGB24); if (normalId == -1) { LOG_ERROR("Failed to load normal texture specified in material file %s.", file.c_str()); return -1; } } ResourceId specularId = -1; if (ini.hasKey("specular", "file")) { // Specular texture is grey-scale format specularId = loadImage(ini.getValue("specular", "file", "error"), EColorFormat::GreyScale8); if (specularId == -1) { LOG_ERROR("Failed to load specular texture specified in material file %s.", file.c_str()); return -1; } } ResourceId glowId = -1; if (ini.hasKey("glow", "file")) { // Glow texture is grey-scale format glowId = loadImage(ini.getValue("glow", "file", "error"), EColorFormat::GreyScale8); if (glowId == -1) { LOG_ERROR("Failed to load glow texture specified in material file %s.", file.c_str()); return -1; } } ResourceId alphaId = -1; if (ini.hasKey("alpha", "file")) { // Alpha texture is grey-scale format alphaId = loadImage(ini.getValue("alpha", "file", "error"), EColorFormat::GreyScale8); if (alphaId == -1) { LOG_ERROR("Failed to load alpha texture specified in material file %s.", file.c_str()); return -1; } } ResourceId customShaderId = -1; if (ini.hasKey("shader", "file")) { // Has custom shader file specified customShaderId = loadShader(ini.getValue("shader", "file", "error")); if (customShaderId == -1) { LOG_ERROR("Failed to load custom shader file specified in material file %s.", file.c_str()); return -1; } } ResourceId materialId = createMaterial(diffuseId, normalId, specularId, glowId, alphaId, customShaderId); if (materialId == -1) { LOG_ERROR("Failed to create material resource id for material file %s.", file.c_str()); return -1; } m_materialFiles[file] = materialId; return materialId; }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vkTools::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vkTools::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vkTools::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vkTools::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vkTools::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vkTools::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH, }; VkPipelineDynamicStateCreateInfo dynamicState = vkTools::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), static_cast<uint32_t>(dynamicStateEnables.size()), 0); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCreateInfo = vkTools::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); // Prepare specialization data // Host data to take specialization constants from struct SpecializationData { // Sets the lighting model used in the fragment "uber" shader uint32_t lightingModel; // Parameter for the toon shading part of the fragment shader float toonDesaturationFactor = 0.5f; } specializationData; // Each shader constant of a shader stage corresponds to one map entry std::array<VkSpecializationMapEntry, 2> specializationMapEntries; // Shader bindings based on specialization constants are marked by the new "constant_id" layout qualifier: // layout (constant_id = 0) const int LIGHTING_MODEL = 0; // layout (constant_id = 1) const float PARAM_TOON_DESATURATION = 0.0f; // Map entry for the lighting model to be used by the fragment shader specializationMapEntries[0].constantID = 0; specializationMapEntries[0].size = sizeof(specializationData.lightingModel); specializationMapEntries[0].offset = 0; // Map entry for the toon shader parameter specializationMapEntries[1].constantID = 1; specializationMapEntries[1].size = sizeof(specializationData.toonDesaturationFactor); specializationMapEntries[1].offset = offsetof(SpecializationData, toonDesaturationFactor); // Prepare specialization info block for the shader stage VkSpecializationInfo specializationInfo{}; specializationInfo.dataSize = sizeof(specializationData); specializationInfo.mapEntryCount = static_cast<uint32_t>(specializationMapEntries.size()); specializationInfo.pMapEntries = specializationMapEntries.data(); specializationInfo.pData = &specializationData; // Create pipelines // All pipelines will use the same "uber" shader and specialization constants to change branching and parameters of that shader shaderStages[0] = loadShader(getAssetPath() + "shaders/specializationconstants/uber.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/specializationconstants/uber.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); // Specialization info is assigned is part of the shader stage (modul) and must be set after creating the module and before creating the pipeline shaderStages[1].pSpecializationInfo = &specializationInfo; // Solid phong shading specializationData.lightingModel = 0; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.phong)); // Phong and textured specializationData.lightingModel = 1; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.toon)); // Textured discard specializationData.lightingModel = 2; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.textured)); }
void FilterOutputOpticalFlowPlugin::setupShader( GPU::Shader &shader ) { std::string logs; if( !loadShader(shader,"reproj",&logs) ) qWarning( (__FUNCTION__": "+logs).c_str() ); }
void preparePipelines() { VkResult err; VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vkTools::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_POINT_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vkTools::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vkTools::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vkTools::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vkTools::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vkTools::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vkTools::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), dynamicStateEnables.size(), 0); // Rendering pipeline // Load shaders std::array<VkPipelineShaderStageCreateInfo,2> shaderStages; shaderStages[0] = loadShader(getAssetPath() + "shaders/computeparticles/particle.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/computeparticles/particle.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vkTools::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.renderPass = renderPass; // Additive blending blendAttachmentState.colorWriteMask = 0xF; blendAttachmentState.blendEnable = VK_TRUE; blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE; blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_DST_ALPHA; err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.postCompute); assert(!err); }
void ShaderLoader::load( const std::string& _path, const SHADER_TYPE _shaderType ) { // argument checks if ( _path.empty() ) GEM_ERROR( "Path argument is empty." ); // always create new if ( isLoaded_ ) clear(); // local variables SHADER_TYPE shaderType = _shaderType; std::string path = _path; // split path std::string dir, name, ext; splitPath( path, &dir, &name, &ext ); // Tell the user that we are trying to load the file GEM_CONSOLE( "Loading shader " + name + (ext.empty() ? "" : ".") + ext ); // Determine file format from extension if ( shaderType == SHADER_TYPE_NONE ) { if ( ext == "vert" ) { shaderType = SHADER_TYPE_VERTEX; } else if ( ext == "frag" ) { shaderType = SHADER_TYPE_FRAGMENT; } else if ( ext == "geom" ) { shaderType = SHADER_TYPE_GEOMETRY; } else if ( ext == "tesc" ) { shaderType = SHADER_TYPE_TESSELATION_CONTROL; } else if ( ext == "tese" ) { shaderType = SHADER_TYPE_TESSELATION_EVALUATION; } } // activate the right file loader depending on file type try { switch( shaderType ) { case SHADER_TYPE_VERTEX: case SHADER_TYPE_FRAGMENT: case SHADER_TYPE_GEOMETRY: case SHADER_TYPE_TESSELATION_CONTROL: case SHADER_TYPE_TESSELATION_EVALUATION: loadShader( path ); break; default: GEM_THROW( "Unsupported file type ." + ext ); break; } } catch( const std::exception& e ) { clear(); GEM_ERROR( e.what() ); } // we got this far, so we are ok to setup member variables path_ = path; shaderType_ = shaderType; isLoaded_ = true; }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), static_cast<uint32_t>(dynamicStateEnables.size()), 0); // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; shaderStages[0] = loadShader(getAssetPath() + "shaders/dynamicuniformbuffer/base.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/dynamicuniformbuffer/base.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipeline)); }
bool Application::Init() { glClearColor(0.100f, 0.200f, 0.250f, 1.0f); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glCullFace(GL_BACK); // ================================================================= // ================== Generate the Cylinder ======================== // ================================================================= Vertex cylinder_vertices[( N + 1 )*( M + 1 )]; compute_cylinders(cylinder_vertices); GLushort cylinder_indices[3 * 2 * ( N )*( M )]; for( size_t i = 0; i < N; ++i ) { for( size_t j = 0; j < M; ++j ) { cylinder_indices[6 * i + j * 3 * 2 * N + 0] = i + j *( N + 1 ); cylinder_indices[6 * i + j * 3 * 2 * N + 1] = i + 1 + j *( N + 1 ); cylinder_indices[6 * i + j * 3 * 2 * N + 2] = i + ( j + 1 )*( N + 1 ); cylinder_indices[6 * i + j * 3 * 2 * N + 3] = i + 1 + j *( N + 1 ); cylinder_indices[6 * i + j * 3 * 2 * N + 4] = i + 1 + ( j + 1 )*( N + 1 ); cylinder_indices[6 * i + j * 3 * 2 * N + 5] = i + ( j + 1 )*( N + 1 ); } } // ================================================================= // ================== Initialize buffers for Cylinder ============== // ================================================================= glGenVertexArrays(1, &m_VAO_ID[0]); glBindVertexArray(m_VAO_ID[0]); glGenBuffers(1, &m_VBO_ID[0]); glBindBuffer(GL_ARRAY_BUFFER, m_VBO_ID[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(cylinder_vertices), cylinder_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(glm::vec3))); glGenBuffers(1, &m_IB_ID[0]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IB_ID[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cylinder_indices), cylinder_indices, GL_STATIC_DRAW); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // ================================================================= // ================== Generate the Circle ========================== // ================================================================= Vertex circle_vertices[N+1]; compute_circles(circle_vertices); GLushort circle_indices[3*2*N]; /*for( size_t i = 0; i < N; i++ ) { circle_indices[6 * i + 0] = i; circle_indices[6 * i + 1] = i+1; circle_indices[6 * i + 2] = i; circle_indices[6 * i + 3] = i; circle_indices[6 * i + 4] = i; circle_indices[6 * i + 5] = i; }*/ for( size_t i = 0; i < N; ++i ) { for( size_t j = 0; j < M; ++j ) { circle_indices[6 * i + j * 3 * 2 * N + 0] = i + j *( N + 1 ); circle_indices[6 * i + j * 3 * 2 * N + 1] = i + 1 + j *( N + 1 ); circle_indices[6 * i + j * 3 * 2 * N + 2] = i + ( j + 1 )*( N + 1 ); circle_indices[6 * i + j * 3 * 2 * N + 3] = i + 1 + j *( N + 1 ); circle_indices[6 * i + j * 3 * 2 * N + 4] = i + 1 + ( j + 1 )*( N + 1 ); circle_indices[6 * i + j * 3 * 2 * N + 5] = i + ( j + 1 )*( N + 1 ); } } // ================================================================= // ================== Initialize buffers for Circle ================ // ================================================================= glGenVertexArrays(1, &m_VAO_ID[1]); glBindVertexArray(m_VAO_ID[1]); glGenBuffers(1, &m_VBO_ID[1]); glBindBuffer(GL_ARRAY_BUFFER, m_VBO_ID[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(circle_vertices), circle_vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)( sizeof(glm::vec3) )); glGenBuffers(1, &m_IB_ID[1]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IB_ID[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(circle_indices), circle_indices, GL_STATIC_DRAW); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // ================================================================= // ================== Create the shader program ==================== // ================================================================= GLuint vertex_shader = loadShader(GL_VERTEX_SHADER, "myVert.vert"); GLuint fragment_shader = loadShader(GL_FRAGMENT_SHADER, "myFrag.frag"); m_program_ID = glCreateProgram(); glAttachShader(m_program_ID, vertex_shader); glAttachShader(m_program_ID, fragment_shader); glBindAttribLocation(m_program_ID, 0, "vs_in_pos"); glBindAttribLocation(m_program_ID, 1, "vs_in_col"); glLinkProgram(m_program_ID); // 'uniform' variables of the shader: m_loc_MVP = glGetUniformLocation(m_program_ID, "MVP"); // TODO: Hiba ellenörzés glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); // ================================================================= // =========== Create the projection and view matrices ============= // ================================================================= return true; }
SuperShader::Cache::Pair SuperShader::getShader(const Material& material) { // First check the cache Cache::Pair p = cache.getSimilar(material); if (p.shadowMappedShader.isNull()) { // Not found in cache; load from disk static const std::string shadowName = "ShadowMappedLightPass"; static const std::string nonShadowName = "NonShadowedPass"; std::string defines; if (material.diffuse.constant != Color3::black()) { if (material.diffuse.map.notNull()) { defines += "#define DIFFUSEMAP\n"; // If the color is white, don't multiply by it if (material.diffuse.constant != Color3::white()) { defines += "#define DIFFUSECONSTANT\n"; } } else { defines += "#define DIFFUSECONSTANT\n"; } } if (material.specular.constant != Color3::black()) { if (material.specular.map.notNull()) { defines += "#define SPECULARMAP\n"; // If the color is white, don't multiply by it if (material.specular.constant != Color3::white()) { defines += "#define SPECULARCONSTANT\n"; } } else { defines += "#define SPECULARCONSTANT\n"; } if (material.specularExponent.constant != Color3::black()) { if (material.specularExponent.map.notNull()) { defines += "#define SPECULAREXPONENTMAP\n"; // If the color is white, don't multiply by it if (material.specularExponent.constant != Color3::white()) { defines += "#define SPECULAREXPONENTCONSTANT\n"; } } else { defines += "#define SPECULAREXPONENTCONSTANT\n"; } } } if (material.emit.constant != Color3::black()) { if (material.emit.map.notNull()) { defines += "#define EMITMAP\n"; // If the color is white, don't multiply by it if (material.emit.constant != Color3::white()) { defines += "#define EMITCONSTANT\n"; } } else { defines += "#define EMITCONSTANT\n"; } } if (material.reflect.constant != Color3::black()) { if (material.reflect.map.notNull()) { defines += "#define REFLECTMAP\n"; // If the color is white, don't multiply by it if (material.reflect.constant != Color3::white()) { defines += "#define REFLECTCONSTANT\n"; } } else { defines += "#define REFLECTCONSTANT\n"; if (material.reflect.constant == Color3::white()) { defines += "#define REFLECTWHITE\n"; } } } if ((material.bumpMapScale != 0) && material.normalBumpMap.notNull()) { defines += "#define NORMALBUMPMAP\n"; } p.nonShadowedShader = loadShader(nonShadowName, defines); p.shadowMappedShader = loadShader(shadowName, defines); p.nonShadowedShader->args.set("backside", 1.0); p.shadowMappedShader->args.set("backside", 1.0); cache.add(material, p); } return p; }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo( VK_FALSE, VK_FALSE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), dynamicStateEnables.size(), 0); // Vertex bindings and attributes VkVertexInputBindingDescription vertexInputBinding = vks::initializers::vertexInputBindingDescription(0, vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX); std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = { vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 0: Position vks::initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3), // Location 1: Normal }; VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = 1; vertexInputState.pVertexBindingDescriptions = &vertexInputBinding; vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size()); vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes.data(); std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass, 0); pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.pVertexInputState = &vertexInputState; // Skybox pipeline (background cube) shaderStages[0] = loadShader(getAssetPath() + "shaders/texturecubemap/skybox.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/texturecubemap/skybox.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.skybox)); // Cube map reflect pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/texturecubemap/reflect.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/texturecubemap/reflect.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); // Enable depth test and write depthStencilState.depthWriteEnable = VK_TRUE; depthStencilState.depthTestEnable = VK_TRUE; // Flip cull mode rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.reflect)); }
/** * @brief Load and initialize shaders */ virtual void initialize (void) { // searches in default shader directory (/shaders) for shader files phongShader.(vert,frag,geom,comp) loadShader(depthmap_shader, "depthmap") ; }
void grass_tech::loadShaders() { shaders[0] = loadShader("../shaders/grassVS.glsl", GL_VERTEX_SHADER); shaders[1] = loadShader("../shaders/grassGS.glsl", GL_GEOMETRY_SHADER); shaders[2] = loadShader("../shaders/grassFS.glsl", GL_FRAGMENT_SHADER); }
bool initialize() { // Initialize geometry and shaders for this example //this defines a cube, this is why a model loader is nice //you can also do this with a draw elements and indices, try to get that working std::cout << "Obj file is loading this might take a moment. Please wait." << std::endl; if(!loadObj("sphere.obj", geometry, vertexCount)) { std::cerr << "[F] The obj file did not load correctly." << std::endl; return false; } // Create a Vertex Buffer object to store this vertex info on the GPU glGenBuffers(1, &vbo_geometry); glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry); glBufferData(GL_ARRAY_BUFFER, vertexCount*sizeof(Vertex), geometry, GL_STATIC_DRAW); //--Geometry done GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); //Shader Sources // Put these into files and write a loader in the future // Note the added uniform! std::string vs = loadShader("VertexShader.txt"); std::string fs = loadShader("FragShader.txt"); //compile the shaders GLint shader_status; const char* _vs = vs.c_str(); const char* _fs = fs.c_str(); // Vertex shader first glShaderSource(vertex_shader, 1, &_vs, NULL); glCompileShader(vertex_shader); //check the compile status glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &shader_status); if(!shader_status) { std::cerr << "[F] FAILED TO COMPILE VERTEX SHADER!" << std::endl; return false; } // Now the Fragment shader glShaderSource(fragment_shader, 1, &_fs, NULL); glCompileShader(fragment_shader); //check the compile status glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &shader_status); if(!shader_status) { std::cerr << "[F] FAILED TO COMPILE FRAGMENT SHADER!" << std::endl; return false; } //Now we link the 2 shader objects into a program //This program is what is run on the GPU program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); //check if everything linked ok glGetProgramiv(program, GL_LINK_STATUS, &shader_status); if(!shader_status) { std::cerr << "[F] THE SHADER PROGRAM FAILED TO LINK" << std::endl; return false; } //Now we set the locations of the attributes and uniforms //this allows us to access them easily while rendering loc_position = glGetAttribLocation(program, const_cast<const char*>("v_position")); if(loc_position == -1) { std::cerr << "[F] POSITION NOT FOUND" << std::endl; return false; } loc_color = glGetAttribLocation(program, const_cast<const char*>("v_color")); if(loc_color == -1) { std::cerr << "[F] V_COLOR NOT FOUND" << std::endl; return false; } //loc_norm = glGetAttribLocation(program, //commented out just so it can compile // const_cast<const char*>("v_norm")); //commented out just so it can compile //if(loc_norm == -1) //commented out just so it can compile //{ //commented out just so it can compile // std::cerr << "[F] V_NORM NOT FOUND" << std::endl; //commented out just so it can compile // return false; //commented out just so it can compile //} //commented out just so it can compile loc_modelView = glGetUniformLocation(program, const_cast<const char*>("ModelView")); if(loc_modelView == -1) { std::cerr << "[F] MODELVIEW NOT FOUND" << std::endl; return false; } loc_projection = glGetUniformLocation(program, const_cast<const char*>("Projection")); if(loc_projection == -1) { std::cerr << "[F] PROJECTION NOT FOUND" << std::endl; return false; } //--Init the view and projection matrices // if you will be having a moving camera the view matrix will need to more dynamic // ...Like you should update it before you render more dynamic // for this project having them static will be fine view = glm::lookAt( glm::vec3(0.0, 8.0, -16.0), //Eye Position glm::vec3(0.0, 0.0, 0.0), //Focus point glm::vec3(0.0, 1.0, 0.0)); //Positive Y is up projection = glm::perspective( 45.0f, //the FoV typically 90 degrees is good which is what this is set to float(w)/float(h), //Aspect Ratio, so Circles stay Circular 0.01f, //Distance to the near plane, normally a small value like this 100.0f); //Distance to the far plane, //enable depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); //and its done return true; }
int main(void) { GLFWwindow* window; /* Initialize the library */ if(!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if(!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); GLFWmousebuttonfun pFun = mouseCallback; // init GLEW glewExperimental = GL_TRUE; GLenum err = glewInit(); if(GLEW_OK != err) return -1; GLuint m_shaderProgramId; { // shaders GLuint m_vertexShaderId = loadShader("C:\\Projects\\DI\\testGL\\VertexShader.glsl", GL_VERTEX_SHADER); GLuint m_fragmentShaderId = loadShader("C:\\Projects\\DI\\testGL\\FragmentShader.glsl", GL_FRAGMENT_SHADER); m_shaderProgramId = glCreateProgram(); glAttachShader(m_shaderProgramId, m_vertexShaderId); glAttachShader(m_shaderProgramId, m_fragmentShaderId); glLinkProgram(m_shaderProgramId); } CModel model; kt::readObj(&model, "C:\\Projects\\Resources\\Models\\obj\\african_head.obj"); GLuint vertexbuffer = model.vbId(); //glEnable(GL_DEPTH_TEST); //glClearDepth(1.0f); //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // ???? // Camera and matrices float radius = 1.0f; static float orbitX = 0; static float orbitY = 0; // GLFWAPI void glfwSetCursorPos(GLFWwindow* window, double xpos, double ypos); // glfwSetMouseButtonCallback(GLFWwindow* window, GLFWmousebuttonfun cbfun); // glfwSetCursorPosCallback(GLFWwindow* window, GLFWcursorposfun cbfun); // GLFWAPI void glfwGetCursorPos(GLFWwindow* window, double* xpos, double* ypos); /* Loop until the user closes the window */ while(!glfwWindowShouldClose(window)) { GLFWmousebuttonfun ptr = glfwSetMouseButtonCallback(window, pFun); /* Render here */ { glEnable(GL_DEPTH_TEST); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(pRotation) { D1 x, y; glfwGetCursorPos(window, &x, &y); orbitX += (pRotation->x - x) / 100; orbitY += (pRotation->y - y) / 100; pRotation->x = x; pRotation->y = y; } // orbit += 0.0001f; // Инициализация орбитальных данных координат камеры // glm::vec3 Eye(sin(orbitX)*radius, 1.0f, -0.5f + cos(orbitX)*radius*1.5f); glm::vec3 Eye(-radius*sin(orbitY)*cos(orbitX), radius*cos(orbitY), radius*sin(orbitY)*sin(orbitX)); glm::mat4 mWorld; glm::mat4 mView; glm::mat4 mProjection; mWorld = glm::mat4(1.0f, 0, 0, 0, 0, 1.0f, 0, 0, 0, 0, 1.0f, 0, 0, 0, 0, 1.0f); mView = glm::lookAt(Eye, glm::vec3(0, 0, 0), glm::vec3(0.0f, 1.0f, 0.0f)); mProjection = glm::perspectiveFov(90.0f, 533.0f, 400.0f, 0.001f, 1000.0f); // Clear the screen glClear(GL_COLOR_BUFFER_BIT); // Use our shader glUseProgram(m_shaderProgramId); //Установка констант шейдера матриц int iWorld = glGetUniformLocation(m_shaderProgramId, "mWorld"); int iView = glGetUniformLocation(m_shaderProgramId, "mView"); int iProjection = glGetUniformLocation(m_shaderProgramId, "mProjection"); glUniformMatrix4fv(iWorld, 1, GL_FALSE, glm::value_ptr(mWorld)); glUniformMatrix4fv(iView, 1, GL_FALSE, glm::value_ptr(mView)); glUniformMatrix4fv(iProjection, 1, GL_FALSE, glm::value_ptr(mProjection)); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, model.nTrng()*3); // 3 indices starting at 0 -> 1 triangle glDisableVertexAttribArray(0); } /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables); // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass); pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); // Vertex bindings an attributes std::vector<VkVertexInputBindingDescription> vertexInputBindings = { vks::initializers::vertexInputBindingDescription(0, vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX), }; std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = { vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 0: Position vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 3), // Location 1: Texture coordinates vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 5), // Location 2: Normal vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 3, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 8), // Location 3: Tangent vks::initializers::vertexInputAttributeDescription(VERTEX_BUFFER_BIND_ID, 4, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 11), // Location 4: Bitangent }; VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexInputBindings.size()); vertexInputState.pVertexBindingDescriptions = vertexInputBindings.data(); vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size()); vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes.data(); pipelineCreateInfo.pVertexInputState = &vertexInputState; // Parallax mapping modes pipeline shaderStages[0] = loadShader(getAssetPath() + "shaders/parallaxmapping/parallax.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/parallaxmapping/parallax.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipeline)); }
bool SkyBox::load(GLfloat scale) { GLfloat cube_vertices[] = { // front -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, // top -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, // back 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, // bottom -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, // left -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, // right 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, }; for(int i=0;i<72;i++) cube_vertices[i]*=scale; glGenBuffers(1, &vbo_cube_vertices); glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_vertices); glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW); GLushort cube_elements[] = { /* // front 0, 1, 2, 2, 3, 0, // top 4, 5, 6, 6, 7, 4, // back 8, 9, 10, 10, 11, 8, // bottom 12, 13, 14, 14, 15, 12, // left 16, 17, 18, 18, 19, 16, // right 20, 21, 22, 22, 23, 20*/ // front 2, 1, 0, 0, 3, 2, // top 6, 5, 4, 4, 7, 6, // back 10, 9, 8, 8, 11, 10, // bottom 14, 13, 12, 12, 15, 14, // left 18, 17, 16, 16, 19, 18, // right 22, 21, 20, 20, 23, 22 }; glGenBuffers(1, &ibo_cube_elements); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_cube_elements); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_elements), cube_elements, GL_STATIC_DRAW); return loadShader(); }
Object *SceneParser::loadObject(KeyValues *data) { const char *format = data->getString("format"); if(!format) { fprintf(stderr, "Key 'format' not found on Object\n"); return NULL; } Mesh *mesh; if(strcmp("OFF", format) == 0 || strcmp("PLY", format) == 0) { const char *file = data->getString("file"); if(!file) { fprintf(stderr, "Key 'file' not found on Object\n"); return NULL; } char *filename = resolvePath(file); MeshData *meshData; if(strcmp("OFF", format) == 0) { meshData = MeshLoaderOFF::load(filename); } else if(strcmp("PLY", format) == 0) { meshData = MeshLoaderPLY::load(filename); } if(!meshData) { fprintf(stderr, "Failed to load MeshData of %s\n", filename); delete[] filename; return NULL; } if(data->getInt("normalize", 1)) { meshData->normalize(); } if(data->getInt("normals", 0)) { meshData->computeNormals(); } const char *texcoords = data->getString("texcoords"); if(texcoords) { MeshData::TexCoordsMethod method; if(strcmp(texcoords, "sphere") == 0) { method = MeshData::TexCoordsSphere; } else if(strcmp(texcoords, "cylinder") == 0) { method = MeshData::TexCoordsCylinder; } meshData->genTexCoords(method); } if(data->getInt("tangents", 0)) { meshData->genTangents(); } mesh = new Mesh(meshData); delete meshData; delete[] filename; } else { fprintf(stderr, "Invalid object format: %s\n", format); return NULL; } Material *material = NULL; QGLShaderProgram *shaderProgram = new QGLShaderProgram(); KeyValues *key; bool error = false; key = data->firstSubKey(); while(key) { if(strcmp(key->name(), "shader") == 0) { QGLShader *shader = loadShader(key); if(shader) { shaderProgram->addShader(shader); } else { fprintf(stderr, "Failed to load shader\n"); error = true; break; } } else if (strcmp(key->name(), "material") == 0) { if(material) { fprintf(stderr, "Duplicated material definition\n"); } else { material = loadMaterial(key); } } key = key->nextKey(); } if(!shaderProgram->link()) { fprintf(stderr, "Failed to link shader program\n"); error = true; } if(error) { if(material) { delete material; } delete shaderProgram; delete mesh; return NULL; } Object *object = new Object(mesh, shaderProgram, material); object->scale(data->getFloat("scale", 1.0)); float pitch = data->getFloat("pitch", 0.0); float yaw = data->getFloat("yaw", 0.0); object->rotation(pitch, yaw); const char *position = data->getString("position"); if(position) { object->position(strtoV3D(position)); } key = data->firstSubKey(); while(key) { if (strcmp(key->name(), "texture") == 0) { Texture *texture = loadTexture(key); if(texture) { object->addTexture(texture); } else { fprintf(stderr, "Failed to load texture\n"); error = true; break; } } key = key->nextKey(); } if(error) { return object; } return object; }
void preparePipelines() { if (pipeline != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipeline, nullptr); } VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, cullMode, VK_FRONT_FACE_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo(VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo(VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo(dynamicStateEnables.data(), static_cast<uint32_t>(dynamicStateEnables.size()), 0); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass, 0); VkPipelineTessellationStateCreateInfo tessellationState = vks::initializers::pipelineTessellationStateCreateInfo(3); pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; // Vertex bindings and attributes std::vector<VkVertexInputBindingDescription> vertexInputBindings = { vks::initializers::vertexInputBindingDescription(0, vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX) }; std::vector<VkVertexInputAttributeDescription> vertexInputAttributes = { vks::initializers::vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0), // Location 0 : Position vks::initializers::vertexInputAttributeDescription(0, 1, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3), // Location 1 : Normal vks::initializers::vertexInputAttributeDescription(0, 2, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 6) // Location 3 : Color }; VkPipelineVertexInputStateCreateInfo vertexInputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertexInputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertexInputBindings.size()); vertexInputState.pVertexBindingDescriptions = vertexInputBindings.data(); vertexInputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertexInputAttributes.size()); vertexInputState.pVertexAttributeDescriptions = vertexInputAttributes.data(); pipelineCreateInfo.pVertexInputState = &vertexInputState; if (blending) { blendAttachmentState.blendEnable = VK_TRUE; blendAttachmentState.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; blendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; blendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; blendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; blendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; blendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; depthStencilState.depthWriteEnable = VK_FALSE; } if (discard) { rasterizationState.rasterizerDiscardEnable = VK_TRUE; } if (wireframe) { rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; } std::vector<VkPipelineShaderStageCreateInfo> shaderStages; shaderStages.resize(tessellation ? 4 : 2); shaderStages[0] = loadShader(getAssetPath() + "shaders/pipelinestatistics/scene.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/pipelinestatistics/scene.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); if (tessellation) { inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; pipelineCreateInfo.pTessellationState = &tessellationState; shaderStages[2] = loadShader(getAssetPath() + "shaders/pipelinestatistics/scene.tesc.spv", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT); shaderStages[3] = loadShader(getAssetPath() + "shaders/pipelinestatistics/scene.tese.spv", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); } pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipeline)); }
void prepareCompute() { // Create compute pipeline // Compute pipelines are created separate from graphics pipelines // even if they use the same queue std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Particle position storage buffer vkTools::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 0), // Binding 1 : Uniform buffer vkTools::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 1), }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vkTools::initializers::descriptorSetLayoutCreateInfo( setLayoutBindings.data(), setLayoutBindings.size()); VkResult err = vkCreateDescriptorSetLayout( device, &descriptorLayout, nullptr, &computeDescriptorSetLayout); assert(!err); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vkTools::initializers::pipelineLayoutCreateInfo( &computeDescriptorSetLayout, 1); err = vkCreatePipelineLayout( device, &pPipelineLayoutCreateInfo, nullptr, &computePipelineLayout); assert(!err); VkDescriptorSetAllocateInfo allocInfo = vkTools::initializers::descriptorSetAllocateInfo( descriptorPool, &computeDescriptorSetLayout, 1); err = vkAllocateDescriptorSets(device, &allocInfo, &computeDescriptorSet); assert(!err); std::vector<VkWriteDescriptorSet> computeWriteDescriptorSets = { // Binding 0 : Particle position storage buffer vkTools::initializers::writeDescriptorSet( computeDescriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 0, &computeStorageBuffer.descriptor), // Binding 1 : Uniform buffer vkTools::initializers::writeDescriptorSet( computeDescriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &uniformData.computeShader.ubo.descriptor) }; vkUpdateDescriptorSets(device, computeWriteDescriptorSets.size(), computeWriteDescriptorSets.data(), 0, NULL); // Create pipeline VkComputePipelineCreateInfo computePipelineCreateInfo = vkTools::initializers::computePipelineCreateInfo( computePipelineLayout, 0); computePipelineCreateInfo.stage = loadShader(getAssetPath() + "shaders/computeparticles/particle.comp.spv", VK_SHADER_STAGE_COMPUTE_BIT); err = vkCreateComputePipelines(device, pipelineCache, 1, &computePipelineCreateInfo, nullptr, &pipelines.compute); assert(!err); }
void App::reloadShader() { loadShader(shader_filepath, /*reload*/true); }
void setupShaders( char* vertexfile, char* fragmentfile, GLuint *Program, GLuint *vertexShaderObject, GLuint *fragmentShaderObject) { glewInit(); *vertexShaderObject = glCreateShader(GL_VERTEX_SHADER); *fragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER); GLchar *vertexShaderSource = 0, *fragmentShaderSource = 0; GLint vlength = 0, flength = 0; loadShader((char*)vertexfile, &vertexShaderSource, &vlength); loadShader((char*)fragmentfile, &fragmentShaderSource, &flength); glShaderSource(*vertexShaderObject, 1, (const GLchar**) &vertexShaderSource, &vlength); glShaderSource(*fragmentShaderObject, 1, (const GLchar**) &fragmentShaderSource, &flength); glCompileShader(*vertexShaderObject); glCompileShader(*fragmentShaderObject); GLint compiled=0; glGetShaderiv(*vertexShaderObject, GL_COMPILE_STATUS, &compiled); if(!compiled) { GLint len; GLchar *log; glGetShaderiv(*vertexShaderObject, GL_INFO_LOG_LENGTH, &len); log =(GLchar*) malloc(len); glGetShaderInfoLog(*vertexShaderObject, len, &len, log); fprintf(stderr, "vertex shader error log: %s\n", log); free(log); } glGetShaderiv(*fragmentShaderObject, GL_COMPILE_STATUS, &compiled); if(!compiled) { GLint len; GLchar *log; glGetShaderiv(*fragmentShaderObject, GL_INFO_LOG_LENGTH, &len); log =(GLchar*) malloc(len); glGetShaderInfoLog(*fragmentShaderObject, len, &len, log); fprintf(stderr, "fragment shader error log: %s\n", log); free(log); } *Program = glCreateProgram(); glAttachShader(*Program, *vertexShaderObject); glAttachShader(*Program, *fragmentShaderObject); glLinkProgram(*Program); GLint linked = 0; glGetProgramiv(*Program, GL_LINK_STATUS, &linked); if(!linked) { GLint len; GLchar *log; glGetProgramiv(*Program, GL_INFO_LOG_LENGTH, &len); log =(GLchar*) malloc(len); glGetProgramInfoLog(*Program, len, &len, log); fprintf(stderr, "liner error log: %s\n", log); free(log); } }
void App::gui() { ImGuiIO& io = ImGui::GetIO(); if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New", io.OSXBehaviors ? "Cmd+N" : "Ctrl+N")) { newShader(); } ImGui::Separator(); if (ImGui::MenuItem("Open...", io.OSXBehaviors ? "Cmd+O" : "Ctrl+O")) { openShaderDialog(); } if (ImGui::BeginMenu("Open Recent", !!recently_used_filepaths[most_recently_used_index])) { for (int i = 0; i < (int)ARRAY_COUNT(recently_used_filepaths); i++) { int index = (most_recently_used_index+i) % ARRAY_COUNT(recently_used_filepaths); if (recently_used_filepaths[index]) { char *menuitem_label = recently_used_filepaths[index]; // we might include libgen.h and use basename(3) but there is no windows support... // TODO: test this on windows char *basename = strrchr(menuitem_label, '/'); if (basename) menuitem_label = basename+1; if (ImGui::MenuItem(menuitem_label)) { loadShader(recently_used_filepaths[index]); } if (basename && ImGui::IsItemHovered()) { ImGui::SetTooltip("%s", recently_used_filepaths[index]); } } else break; } ImGui::Separator(); if (ImGui::MenuItem("Clear Items")) { clearRecentlyUsedFilepaths(); } ImGui::EndMenu(); } // TODO: move this to settings pane eventually if (ImGui::MenuItem("Autoreload", nullptr, shader_file_autoreload)) { shader_file_autoreload = !shader_file_autoreload; writePreferences(); } if (ImGui::MenuItem("Save", io.OSXBehaviors ? "Cmd+S" : "Ctrl+S", false, !!shader_filepath)) { saveShader(); } if (ImGui::IsItemHovered() && shader_filepath) { ImGui::SetTooltip("%s", shader_filepath); } if (ImGui::MenuItem("Save As...", io.OSXBehaviors ? "Cmd+Shift+S" : "Ctrl+Shift+S", false, !!src_edit_buffer[0])) { saveShaderDialog(); } ImGui::Separator(); if (ImGui::MenuItem("Quit", io.OSXBehaviors ? "Cmd+Q" : "Ctrl+Q")) { quit = true; } ImGui::EndMenu(); } if (ImGui::BeginMenu("View")) { if (ImGui::MenuItem("Fullscreen", io.OSXBehaviors ? "Cmd+F" : "Ctrl+F", windowIsFullscreen())) { windowToggleFullscreen(); } if (ImGui::MenuItem("Hide Controls", io.OSXBehaviors ? "Cmd+Shift+H" : "Ctrl+H", hide_gui)) { hide_gui = !hide_gui; } ImGui::Separator(); if (ImGui::MenuItem(anim_play ? "Pause Animation" : "Play Animation", "Space")) { toggleAnimation(); } if (ImGui::MenuItem("Reset Animation")) { frame_count = 0; } if (ImGui::MenuItem("Reset Camera")) { resetCamera(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Tools")) { if (ImGui::MenuItem("Recompile Shader", io.OSXBehaviors ? "Cmd+B" : "Ctrl+B", false, !!src_edit_buffer[0])) { recompileShader(); } ImGui::EndMenu(); } if (ImGui::BeginMenu("Window")) { if (ImGui::MenuItem("Uniforms", io.OSXBehaviors ? "Cmd+1" : "Ctrl+1", show_uniforms_window)) { show_uniforms_window = !show_uniforms_window; } if (ImGui::MenuItem("Textures", io.OSXBehaviors ? "Cmd+2" : "Ctrl+2", show_textures_window)) { show_textures_window = !show_textures_window; } ImGui::Separator(); if (ImGui::MenuItem("Camera", io.OSXBehaviors ? "Cmd+3" : "Ctrl+3", show_textures_window)) { show_camera_window = !show_camera_window; } ImGui::Separator(); if (ImGui::MenuItem("Source editor", io.OSXBehaviors ? "Cmd+4" : "Ctrl+4", show_src_edit_window)) { show_src_edit_window = !show_src_edit_window; } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } if (show_uniforms_window) { if (ImGui::Begin("Uniforms", &show_uniforms_window)) { if (ImGui::CollapsingHeader("Built-in uniform names")) { ImGui::InputText("Time", u_time_name, sizeof(u_time_name)); ImGui::InputText("Resolution", u_resolution_name, sizeof(u_resolution_name)); ImGui::InputText("View to World Matrix", u_view_to_world_name, sizeof(u_view_to_world_name)); ImGui::InputText("World to View Matrix", u_world_to_view_name, sizeof(u_world_to_view_name)); } ImGui::Separator(); if (!compile_error_log) { ImGui::AlignFirstTextHeightToWidgets(); ImGui::Text("Data"); ImGui::SameLine(); if (ImGui::Button("Clear")) { if (uniform_data) { memset(uniform_data, 0, uniform_data_size); } } ImGui::SameLine(); if (ImGui::Button("Save")) { writeUniformData(); } ImGui::SameLine(); if (ImGui::Button("Load")) { readUniformData(); } for (int i = 0; i < uniform_count; i++) { // skip builtin uniforms if (!strcmp(u_time_name, uniforms[i].name)) continue; if (!strcmp(u_resolution_name, uniforms[i].name)) continue; if (!strcmp(u_view_to_world_name, uniforms[i].name)) continue; if (!strcmp(u_world_to_view_name, uniforms[i].name)) continue; uniforms[i].gui(); } } } ImGui::End(); } if (show_textures_window) { if (ImGui::Begin("Textures", &show_textures_window)) { ImGui::Columns(2); for (int tsi = 0; tsi < (int)ARRAY_COUNT(texture_slots); tsi++) { TextureSlot *texture_slot = texture_slots + tsi; ImGui::BeginGroup(); ImGui::PushID(tsi); ImGui::Text("%d:", tsi); ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(0.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(0.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(0.0f, 0.8f, 0.8f)); if (ImGui::SmallButton("x")) texture_slot->clear(); ImGui::PopStyleColor(3); if (ImGui::Button(" 2D ")) openImageDialog(texture_slot); if (ImGui::Button("Cube")) openImageDialog(texture_slot, /*load_cube_cross*/true); ImGui::PopID(); ImGui::EndGroup(); ImGui::SameLine(); //ImTextureID im_tex_id = (ImTextureID)(intptr_t)texture_slot->texture; ImGui::Image((void*)texture_slot, ImVec2(64, 64)); if (ImGui::IsItemHovered() && texture_slot->image_filepath) { ImGui::SetTooltip("%s\n%dx%d", texture_slot->image_filepath, texture_slot->image_width, texture_slot->image_height); } if ((tsi & 1) && tsi + 1 != ARRAY_COUNT(texture_slots)) { ImGui::Separator(); } else { ImGui::SameLine(); ImGui::Spacing(); } ImGui::NextColumn(); } ImGui::Columns(1); } ImGui::End(); } if (show_camera_window) { if (ImGui::Begin("Camera", &show_camera_window)) { ImGui::DragFloat3("Location", camera_location.e); ImGui::SliderAngle("Pitch", &camera_euler_angles.x); ImGui::SliderAngle("Yaw", &camera_euler_angles.y); ImGui::SliderAngle("Roll", &camera_euler_angles.z); if (ImGui::Button("Reset")) resetCamera(); ImGui::End(); } } if (show_src_edit_window) { if (ImGui::Begin("Source editor", &show_src_edit_window)) { // TODO: add horizontal scrollbar ImGui::InputTextMultiline("##Text buffer", src_edit_buffer, sizeof(src_edit_buffer)-1, /*fullwidth, fullheight*/ImVec2(-1.0f, -1.0f), ImGuiInputTextFlags_AllowTabInput); } ImGui::End(); } // overlay messages int overlay_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings; if (!shader_filepath && !src_edit_buffer[0]) { ImGui::SetNextWindowPosCenter(); ImGui::Begin("Overlay", nullptr, ImVec2(0, 0), 0.3f, overlay_flags); ImGui::AlignFirstTextHeightToWidgets(); // valign text to button ImGui::Text("No fragment shader"); ImGui::SameLine(); if (ImGui::Button("Open")) openShaderDialog(); ImGui::SameLine(); if (ImGui::Button("New")) newShader(); ImGui::End(); } else if (compile_error_log) { ImGui::SetNextWindowPosCenter(); ImGui::Begin("Overlay", nullptr, ImVec2(0, 0), 0.3f, overlay_flags); ImGui::TextUnformatted(compile_error_log); ImGui::End(); } }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vkTools::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vkTools::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vkTools::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vkTools::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vkTools::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vkTools::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vkTools::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), dynamicStateEnables.size(), 0); // Parallax mapping pipeline // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; shaderStages[0] = loadShader("./../data/shaders/parallax/parallax.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader("./../data/shaders/parallax/parallax.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vkTools::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.parallaxMapping); assert(!err); // Normal mapping (no parallax effect) shaderStages[0] = loadShader("./../data/shaders/parallax/normalmap.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader("./../data/shaders/parallax/normalmap.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.normalMapping); assert(!err); }
void preparePipelines() { VkResult err; VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vkTools::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vkTools::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vkTools::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vkTools::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vkTools::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vkTools::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH }; VkPipelineDynamicStateCreateInfo dynamicState = vkTools::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), dynamicStateEnables.size(), 0); // Tessellation pipeline // Load shaders std::array<VkPipelineShaderStageCreateInfo, 3> shaderStages; shaderStages[0] = loadShader(getAssetPath() + "shaders/geometryshader/base.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/geometryshader/base.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); shaderStages[2] = loadShader(getAssetPath() + "shaders/geometryshader/normaldebug.geom.spv", VK_SHADER_STAGE_GEOMETRY_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vkTools::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.renderPass = renderPass; // Normal debugging pipeline err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.normals); assert(!err); // Solid rendering pipeline // Shader shaderStages[0] = loadShader(getAssetPath() + "shaders/geometryshader/mesh.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/geometryshader/mesh.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); pipelineCreateInfo.stageCount = 2; err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.solid); assert(!err); }
GPGPU::GPGPU(int w, int h) : _initialized(0), _width(w), _height(h) { // Create a texture to store the framebuffer glGenTextures(1, &_textureId); glBindTexture(GL_TEXTURE_2D, _textureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, _width, _height, 0, GL_RGB, GL_FLOAT, 0); _programId = glCreateProgram(); // Load fragment shader which will be used as computational kernel std::string edgeFragSource2; loadShader("fragment.glsl", edgeFragSource2); // Create the fragment program _fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); const char* source = edgeFragSource2.c_str(); glShaderSource(_fragmentShader, 1, &source, NULL); glCompileShader(_fragmentShader); glAttachShader(_programId, _fragmentShader); // Link the shader into a complete GLSL program. glLinkProgram(_programId); // Check program { int infologLength = 0; glGetProgramiv(_programId, GL_INFO_LOG_LENGTH, &infologLength); if (infologLength > 0) { char *infoLog = (char *)malloc(infologLength); glGetProgramInfoLog(_programId, infologLength, NULL, infoLog); printf("%s\n",infoLog); free(infoLog); } } // Get location of the uniform variables _texUnitLoc = glGetUniformLocation(_programId, "texUnit"); _initializedLoc = glGetUniformLocation(_programId, "initialized"); // gpu _timeLoc = glGetUniformLocation(_programId, "time"); _ck_start = std::clock(); _wSizeLoc = glGetUniformLocation(_programId, "wSize"); _wTypeLoc = glGetUniformLocation(_programId, "wType"); // gpu: sine params _sinParamALoc = glGetUniformLocation(_programId, "gAi"); _sinParamDxLoc = glGetUniformLocation(_programId, "gDx"); _sinParamDyLoc = glGetUniformLocation(_programId, "gDy"); _sinParamWlLoc = glGetUniformLocation(_programId, "gwl"); _sinParamSpLoc = glGetUniformLocation(_programId, "gSp"); _sinParamCxLoc = glGetUniformLocation(_programId, "gCx"); _sinParamCyLoc = glGetUniformLocation(_programId, "gCy"); // gpu: config islands setupIsland(); }
int main () { // start GL context and O/S window using the GLFW helper library if (!glfwInit ()) { fprintf (stderr, "ERROR: could not start GLFW3\n"); return 1; } // uncomment these lines if on Apple OS X glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow (640, 480, "Cube to Sphere", NULL, NULL); if (!window) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } GLFWwindow* window2 = glfwCreateWindow (640, 480, "Just checking", NULL, NULL); if (!window2) { fprintf (stderr, "ERROR: could not open window with GLFW3\n"); glfwTerminate(); return 1; } glfwMakeContextCurrent (window); //start GLEW extension handler glewExperimental = GL_TRUE; glewInit (); // get version info const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string const GLubyte* version = glGetString (GL_VERSION); // version as a string printf ("Renderer: %s\n", renderer); printf ("OpenGL version supported %s\n", version); //CLGLUtils::init(); boost::compute::context context; try { context = boost::compute::opengl_create_shared_context(); } catch (std::exception e) { std::cerr<<"Failed to initialize a CLGL context"<<e.what()<<std::endl; exit(0); } // tell GL to only draw onto a pixel if the shape is closer to the viewer glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" // OTHER STUFF GOES HERE NEXT float points[] = { -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; GLuint vbo; glGenBuffers (1, &vbo); glBindBuffer (GL_ARRAY_BUFFER, vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 36 * sizeof (float), &points, GL_STATIC_DRAW); GLuint vao; glGenVertexArrays (1, &vao); glBindVertexArray (vao); glEnableVertexAttribArray (0); glBindBuffer (GL_ARRAY_BUFFER, vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); //Create Cube map GLuint cube_map_texture; create_cube_map ((resource_dir+"negz.jpg").c_str(), (resource_dir+"posz.jpg").c_str(), (resource_dir+"posy.jpg").c_str(), (resource_dir+"negy.jpg").c_str(), (resource_dir+"negx.jpg").c_str(), (resource_dir+"posx.jpg").c_str(), &cube_map_texture); boost::shared_ptr<boost::compute::opengl_texture> cl_cube_map_texture; try { cl_cube_map_texture = boost::shared_ptr<boost::compute::opengl_texture>(new boost::compute::opengl_texture(context,GL_TEXTURE_2D_ARRAY,0,cube_map_texture,boost::compute::memory_object::mem_flags::read_only)); } catch ( const std::exception& e ) { std::cerr << e.what() << std::endl; } const char* vertex_shader = "#version 400\n" "in vec3 vp;" "uniform mat4 P, V;" // "uniform vec3 vertOut;" "out vec3 texcoords;" "vec3 newP;" "void main () {" " texcoords = vp;" // " vertOut = vp;" " gl_Position = P * V * vec4 (vp, 1.0);" "}"; const char* fragment_shader = loadShader(resource_dir+"fragmentShader.frag").c_str(); /*"#version 400\n" "in vec3 texcoords;" "uniform samplerCube cube_texture;" "out vec4 frag_colour;" "vec4 cubeToLatLon(samplerCube cubemap, vec3 inUV) {" "vec3 cubmapTexCoords;" //"cubmapTexCoords.x = inUV.x*sqrt(1 - ( (inUV.y * inUV.y)/2 ) - ( (inUV.z * inUV.z)/2 ) + ( ( (inUV.y * inUV.y) * (inUV.z * inUV.z))/3));" "cubmapTexCoords.x = inUV.x;" //"cubmapTexCoords.y= inUV.y*sqrt(1 - ( (inUV.z * inUV.z)/2 ) - ( (inUV.x * inUV.x)/2 ) + ( ( (inUV.z * inUV.z) * (inUV.x * inUV.x))/3));" "cubmapTexCoords.y = inUV.y;" "cubmapTexCoords.z = inUV.z*sqrt(1 - ( (inUV.x * inUV.x)/2 ) - ( (inUV.y * inUV.y)/2 ) + ( ( (inUV.x * inUV.x) * (inUV.y * inUV.y))/3));" //"cubmapTexCoords.z = inUV.z;" "return texture(cubemap, cubmapTexCoords);" "}" "void main () {" //" frag_colour = texture (cube_texture, texcoords);" " frag_colour = cubeToLatLon (cube_texture, texcoords);" "}";*/ GLuint vs = glCreateShader (GL_VERTEX_SHADER); glShaderSource (vs, 1, &vertex_shader, NULL); glCompileShader (vs); GLuint fs = glCreateShader (GL_FRAGMENT_SHADER); glShaderSource (fs, 1, &fragment_shader, NULL); glCompileShader (fs); GLuint cube_sp = glCreateProgram (); glAttachShader (cube_sp, fs); glAttachShader (cube_sp, vs); glLinkProgram (cube_sp); //*-----------------------------Compile Shaders for second window - square --------*/ glfwMakeContextCurrent(window2); //start GLEW extension handler glewExperimental = GL_TRUE; glewInit (); glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" float squarePoints[] = { -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f }; GLfloat texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f }; GLuint vbo_square; glGenBuffers (1, &vbo_square); glBindBuffer (GL_ARRAY_BUFFER, vbo_square); glBufferData (GL_ARRAY_BUFFER, 3 * 6 * sizeof (float), &squarePoints, GL_STATIC_DRAW); GLuint texcoords_vbo; glGenBuffers (1, &texcoords_vbo); glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo); glBufferData (GL_ARRAY_BUFFER, 12 * sizeof (GLfloat), texcoords, GL_STATIC_DRAW); GLuint vao_square; glGenVertexArrays (1, &vao_square); glBindVertexArray (vao_square); glBindBuffer (GL_ARRAY_BUFFER, vbo_square); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); // normalise! glEnableVertexAttribArray (0); glEnableVertexAttribArray (1); GLuint square_sp = create_programme_from_files((resource_dir+"square.vert").c_str(), (resource_dir+"square.frag").c_str()); GLuint tex; assert (load_texture ((resource_dir+"negz.jpg").c_str(), &tex)); //*----------------------------------------------------------------------------------*/ glfwMakeContextCurrent (window); int cube_V_location = glGetUniformLocation (cube_sp, "V"); int cube_P_location = glGetUniformLocation (cube_sp, "P"); //int cube_vertOut = glGetUniformLocation (cube_sp, "vertOut"); /*-------------------------------CREATE GLOBAL CAMERA--------------------------------*/ #define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444 // input variables float near = 0.1f; // clipping plane float far = 100.0f; // clipping plane float fovy = 80.0f; // 67 degrees float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio proj_mat = perspective (fovy, aspect, near, far); float cam_speed = 3.0f; // 1 unit per second float cam_heading_speed = 50.0f; // 30 degrees per second float cam_heading = 0.0f; // y-rotation in degrees mat4 T = translate (identity_mat4 (), vec3 (-cam_pos.v[0], -cam_pos.v[1], -cam_pos.v[2])); mat4 R = rotate_y_deg (identity_mat4 (), -cam_heading); versor q = quat_from_axis_deg (-cam_heading, 0.0f, 1.0f, 0.0f); view_mat = R * T; // keep track of some useful vectors that can be used for keyboard movement vec4 fwd (0.0f, 0.0f, -1.0f, 0.0f); vec4 rgt (1.0f, 0.0f, 0.0f, 0.0f); vec4 up (0.0f, 1.0f, 0.0f, 0.0f); /*---------------------------SET RENDERING DEFAULTS---------------------------*/ glUseProgram (cube_sp); glUniformMatrix4fv (cube_V_location, 1, GL_FALSE, R.m); glUniformMatrix4fv (cube_P_location, 1, GL_FALSE, proj_mat.m); // unique model matrix for each sphere mat4 model_mat = identity_mat4 (); glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" glEnable (GL_CULL_FACE); // cull face glCullFace (GL_BACK); // cull back face glFrontFace (GL_CCW); // set counter-clock-wise vertex order to mean the front glClearColor (0.2, 0.2, 0.2, 1.0); // grey background to help spot mistakes glViewport (0, 0, g_gl_width, g_gl_height); while (!glfwWindowShouldClose (window) && !glfwWindowShouldClose (window2)) { // update timers static double previous_seconds = glfwGetTime (); double current_seconds = glfwGetTime (); double elapsed_seconds = current_seconds - previous_seconds; previous_seconds = current_seconds; //_update_fps_counter (window); // wipe the drawing surface clear glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // render a sky-box using the cube-map texture glDepthMask (GL_FALSE); glUseProgram (cube_sp); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_CUBE_MAP, cube_map_texture); glBindVertexArray (vao); glDrawArrays (GL_TRIANGLES, 0, 36); glDepthMask (GL_TRUE); //*---------------------------------Display for second window-------------------*/ glfwMakeContextCurrent (window2); glUseProgram (square_sp); int cubemap_vert = glGetUniformLocation (square_sp, "cubeMap_texcoords"); glEnable (GL_DEPTH_TEST); // enable depth-testing glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer" glEnable (GL_CULL_FACE); // cull face glCullFace (GL_BACK); // cull back face glFrontFace (GL_CCW); // set counter-clock-wise vertex order to mean the front glClearColor (0.3, 0.2, 0.3, 1.0); // grey background to help spot mistakes glViewport (0, 0, g_gl_width, g_gl_height); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDepthMask (GL_FALSE); glUseProgram (square_sp); glBindVertexArray (vao_square); glDrawArrays (GL_TRIANGLES, 0, 6); glDepthMask (GL_TRUE); //*------------------------------GO back to cubemap window--------------------*/ glfwMakeContextCurrent (window); // update other events like input handling glfwPollEvents (); // control keys bool cam_moved = false; vec3 move (0.0, 0.0, 0.0); float cam_yaw = 0.0f; // y-rotation in degrees float cam_pitch = 0.0f; float cam_roll = 0.0; if (glfwGetKey (window, GLFW_KEY_A)) { move.v[0] -= cam_speed * elapsed_seconds; cam_moved = true; print(move); } if (glfwGetKey (window, GLFW_KEY_D)) { move.v[0] += cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (window, GLFW_KEY_Q)) { move.v[1] += cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (window, GLFW_KEY_E)) { move.v[1] -= cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (window, GLFW_KEY_W)) { move.v[2] -= cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (window, GLFW_KEY_S)) { move.v[2] += cam_speed * elapsed_seconds; cam_moved = true; } if (glfwGetKey (window, GLFW_KEY_LEFT)) { cam_yaw += cam_heading_speed * elapsed_seconds; cam_moved = true; versor q_yaw = quat_from_axis_deg ( cam_yaw, up.v[0], up.v[1], up.v[2] ); q = q_yaw * q; } if (glfwGetKey (window, GLFW_KEY_RIGHT)) { cam_yaw -= cam_heading_speed * elapsed_seconds; cam_moved = true; versor q_yaw = quat_from_axis_deg ( cam_yaw, up.v[0], up.v[1], up.v[2] ); q = q_yaw * q; } if (glfwGetKey (window, GLFW_KEY_UP)) { cam_pitch += cam_heading_speed * elapsed_seconds; cam_moved = true; versor q_pitch = quat_from_axis_deg ( cam_pitch, rgt.v[0], rgt.v[1], rgt.v[2] ); q = q_pitch * q; } if (glfwGetKey (window, GLFW_KEY_DOWN)) { cam_pitch -= cam_heading_speed * elapsed_seconds; cam_moved = true; versor q_pitch = quat_from_axis_deg ( cam_pitch, rgt.v[0], rgt.v[1], rgt.v[2] ); q = q_pitch * q; } if (glfwGetKey (window, GLFW_KEY_Z)) { cam_roll -= cam_heading_speed * elapsed_seconds; cam_moved = true; versor q_roll = quat_from_axis_deg ( cam_roll, fwd.v[0], fwd.v[1], fwd.v[2] ); q = q_roll * q; } if (glfwGetKey (window, GLFW_KEY_C)) { cam_roll += cam_heading_speed * elapsed_seconds; cam_moved = true; versor q_roll = quat_from_axis_deg ( cam_roll, fwd.v[0], fwd.v[1], fwd.v[2] ); q = q_roll * q; } // update view matrix if (cam_moved) { cam_heading += cam_yaw; // re-calculate local axes so can move fwd in dir cam is pointing R = quat_to_mat4 (q); fwd = R * vec4 (0.0, 0.0, -1.0, 0.0); rgt = R * vec4 (1.0, 0.0, 0.0, 0.0); up = R * vec4 (0.0, 1.0, 0.0, 0.0); cam_pos = cam_pos + vec3 (fwd) * -move.v[2]; cam_pos = cam_pos + vec3 (up) * move.v[1]; cam_pos = cam_pos + vec3 (rgt) * move.v[0]; mat4 T = translate (identity_mat4 (), vec3 (cam_pos)); view_mat = inverse (R) * inverse (T); //std::cout<<inverse(R).m<<std::endl; // cube-map view matrix has rotation, but not translation glUseProgram (cube_sp); glUniformMatrix4fv (cube_V_location, 1, GL_FALSE, inverse (R).m); } if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (window, 1); } if (GLFW_PRESS == glfwGetKey (window2, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose (window2, 1); } // put the stuff we've been drawing onto the display glfwSwapBuffers (window); glfwMakeContextCurrent (window2); glfwSwapBuffers (window2); glfwMakeContextCurrent (window); } // close GL context and any other GLFW resources glfwTerminate(); return 0; }
void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vkTools::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vkTools::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vkTools::initializers::pipelineColorBlendAttachmentState( 0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vkTools::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vkTools::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vkTools::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamicState = vkTools::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), dynamicStateEnables.size(), 0); // Pipeline for the meshes (armadillo, bunny, etc.) // Load shaders std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages; shaderStages[0] = loadShader(getAssetPath() + "shaders/vulkanscene/mesh.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/vulkanscene/mesh.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vkTools::initializers::pipelineCreateInfo( pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &demoMeshes.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.stageCount = shaderStages.size(); pipelineCreateInfo.pStages = shaderStages.data(); VkResult err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.models); assert(!err); // Pipeline for the logos shaderStages[0] = loadShader(getAssetPath() + "shaders/vulkanscene/logo.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/vulkanscene/logo.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.logos); assert(!err); // Pipeline for the sky sphere (todo) rasterizationState.cullMode = VK_CULL_MODE_FRONT_BIT; // Inverted culling depthStencilState.depthWriteEnable = VK_FALSE; // No depth writes shaderStages[0] = loadShader(getAssetPath() + "shaders/vulkanscene/skybox.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/vulkanscene/skybox.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); err = vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.skybox); assert(!err); // Assign pipelines demoMeshes.logos->pipeline = pipelines.logos; demoMeshes.models->pipeline = pipelines.models; demoMeshes.background->pipeline = pipelines.models; demoMeshes.skybox->pipeline = pipelines.skybox; }
int startOGLRendering() { if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error while initializing scene\n"); } glEnable(GL_DEPTH_TEST); /* enable depth buffering */ glDepthFunc(GL_LESS); /* pedantic, GL_LESS is the default */ glDepthMask(GL_TRUE); glClearDepth(1.0); /* pedantic, 1.0 is the default */ //HQ settings glEnable(GL_NORMALIZE); glShadeModel(GL_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error while initializing HQ settings\n"); } /* frame buffer clears should be to black */ glClearColor(0.0, 0.0, 0.0, 0.0); /* set up projection transform */ glMatrixMode(GL_PROJECTION); updateProjectionMatrix(); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after updating projection matrix\n"); } /* establish initial viewport */ /* pedantic, full window size is default viewport */ #warning "GL_COLOR does not even exist" //glEnable(GL_COLOR); //if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after enabling color \n"); } glEnable(GL_COLOR_MATERIAL); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after enabling color material\n"); } #if USE_LIGHTS glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after enabling lighting\n"); } glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after setting up lights\n"); } GLenum faces=GL_FRONT;//GL_FRONT_AND_BACK; glMaterialfv(faces, GL_AMBIENT, mat_ambient); glMaterialfv(faces, GL_DIFFUSE, mat_diffuse); glMaterialfv(faces, GL_SPECULAR, mat_specular); glMaterialfv(faces, GL_SHININESS, mat_shininess); // <- this was glMateriali if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error after setting up Front/Back lights\n"); } #else fprintf(stderr,"Please note that lighting is disabled via the USE_LIGHTS precompiler define\n"); #endif // USE_LIGHTS if ( ( selectedFragmentShader != 0) || ( selectedVertexShader != 0 ) ) { loadedShader = loadShader(selectedVertexShader,selectedFragmentShader); } //This is not needed -> :P glCullFace(GL_FRONT_AND_BACK); //Enable Culling if (doCulling) { glFrontFace(GL_CCW); //GL_CW / GL_CCW if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error glFrontFace(GL_CCW); \n"); } glCullFace(GL_BACK); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error glCullFace(GL_BACK); \n"); } glEnable(GL_CULL_FACE); if (checkOpenGLError(__FILE__, __LINE__)) { fprintf(stderr,"OpenGL error glEnable(GL_CULL_FACE); \n"); } } }