本文整理汇总了C++中Shader类的典型用法代码示例。如果您正苦于以下问题:C++ Shader类的具体用法?C++ Shader怎么用?C++ Shader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Shader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: vec3
int GLAppMain::init()
{
goon = 1;
pos = vec3(0,0.5,5);
lookat = vec3(0,0,-1);
font = new Font("../textures/font.png");
//img = new Texture( "data/papuanewguinea.png" );
img = new Texture("../textures/kiribati.png");
/* create a pbuffer and some vertex buffers */
pbuffer = new PBuffer( SIZE, SIZE, PBuffer::RGBA | PBuffer::FLOAT32 );
vertex_buffer = new Buffer( SIZE*SIZE*4*sizeof(float), GL_DYNAMIC_COPY_ARB );
normal_buffer = new Buffer( SIZE*SIZE*4*sizeof(float), GL_DYNAMIC_COPY_ARB );
/* calculate indices buffer data */
unsigned int *indices;
indices = (unsigned int*)malloc(SIZE*(SIZE-1)*2*sizeof(unsigned int));
for(unsigned int j=0;j<SIZE-1;j++)
for(unsigned int i=0;i<SIZE;i++) {
if(j&1){
indices[j*SIZE*2+2*i+1] = SIZE-1-i +j*SIZE;
indices[j*SIZE*2+2*i] = SIZE-1-i+SIZE +j*SIZE;
} else {
indices[j*SIZE*2+2*i+1] = i+SIZE +j*SIZE;
indices[j*SIZE*2+2*i] = i +j*SIZE;
}
}
index_buffer = new Buffer( SIZE*(SIZE-1)*2*sizeof(unsigned int),
GL_STATIC_DRAW_ARB, indices );
free(indices);
/* calculate texcoords buffer data */
vec2 *textures;
textures = (vec2*)malloc(SIZE*SIZE*sizeof(vec2));
for(unsigned int j=0;j<SIZE;j++)
for(unsigned int i=0;i<SIZE;i++)
textures[i+j*SIZE] = vec2((i+0.5)/SIZE,(j+0.5)/SIZE);
texcoord_buffer = new Buffer( SIZE*SIZE*sizeof(vec2),
GL_STATIC_DRAW_ARB, textures );
free(textures);
/* calculate positions texture data */
vec4 *pos;
pos = (vec4*)malloc(SIZE*SIZE*sizeof(vec4));
for(unsigned int j=0;j<SIZE;j++)
for(unsigned int i=0;i<SIZE;i++)
pos[i+j*SIZE] = vec4(4.0*i/(SIZE-1)-2.0,1.0,4.0*j/(SIZE-1)-2.0,0.0);
positions = new Texture( SIZE, SIZE, Texture::TEXTURE_2D, Texture::CLAMP |
Texture::RGBA | Texture::NEAREST | Texture::FLOAT32, pos );
/* calculate speeds texture data */
for(unsigned int j=0;j<SIZE;j++)
for(unsigned int i=0;i<SIZE;i++)
pos[i+j*SIZE] = vec4(0.0,0.0,0.0,0.0);
speeds = new Texture( SIZE, SIZE, Texture::TEXTURE_2D,
Texture::RGBA | Texture::NEAREST | Texture::FLOAT32, pos );
/* calculate normals texture data */
for(unsigned int j=0;j<SIZE;j++)
for(unsigned int i=0;i<SIZE;i++)
pos[i+j*SIZE] = vec4(0.0,1.0,0.0,0.0);
normals = new Texture( SIZE, SIZE, Texture::TEXTURE_2D,
Texture::RGBA | Texture::NEAREST | Texture::FLOAT32, pos );
free(pos);
/* load shaders */
char header[127];
sprintf(header,"#define SIZE %d\n#define LINK %d\n",
SIZE, SIZE<=64 ? 2 : (SIZE>=256 ? 4 : 3));
positions_shader = new Shader("../data/shaders/positions.vert", "../data/shaders/positions.frag",header);
positions_shader->bind();
positions_shader->setUniform("positions",0);
positions_shader->setUniform("speeds",1);
positions_shader->setUniform("normals",2);
positions_shader->unbind();
speeds_shader = new Shader("../data/shaders/speeds.vert", "../data/shaders/speeds.frag",header);
speeds_shader->bind();
speeds_shader->setUniform("speeds",0);
speeds_shader->setUniform("speeds",1);
speeds_shader->setUniform("normals",2);
speeds_shader->unbind();
normals_shader = new Shader("../data/shaders/normals.vert", "../data/shaders/normals.frag",header);
normals_shader->bind();
normals_shader->setUniform("normals",0);
normals_shader->setUniform("normals",1);
normals_shader->setUniform("normals",2);
normals_shader->unbind();
/* init the state in the pbuffer */
//.........这里部分代码省略.........
示例2: WinMain
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) {
#else
int main(int argc, char** argv) {
#endif
Window window("Sample_BurningPaper", 1024, 768, true);
RenderParameters_t renderParameters;
renderParameters.width = 1024;
renderParameters.height = 768;
renderParameters.displayFormat = DISPLAY_FORMAT_X8R8G8B8;
renderParameters.refreshRate = 0;
renderParameters.depthStencilBits = DEPTH_STENCIL_BITS_D24X8;
Renderer::GetInstance()->Initialize(RENDER_SYSTEM_OPENGL, window, renderParameters);
Renderer::GetInstance()->SetClearColor(0.2f, 0.2f, 0.2f);
// Create the paper surface
SurfaceTriangles_t surface;
surface.numVertices = 4;
surface.numTexCoords = 4;
surface.numIndices = 6;
surface.vertices = new Vector3[surface.numVertices];
surface.texCoords = new Vector2[surface.numTexCoords];
surface.indices = new unsigned short[surface.numIndices];
surface.vertices[0] = Vector3(-1.2f, -1.5f, 1.0f); surface.vertices[1] = Vector3(-1.2f, 1.5f, 1.0f); surface.vertices[2] = Vector3(1.2f, 1.5f, 1.0f); surface.vertices[3] = Vector3(1.2f, -1.5f, 1.0f);
surface.texCoords[0] = Vector2(0.0f, 0.0f); surface.texCoords[1] = Vector2(0.0f, 1.0f); surface.texCoords[2] = Vector2(1.0f, 1.0f); surface.texCoords[3] = Vector2(1.0f, 0.0f);
surface.indices[0] = 0; surface.indices[1] = 2; surface.indices[2] = 1; surface.indices[3] = 0; surface.indices[4] = 3; surface.indices[5] = 2;
Mesh paperMesh;
paperMesh.AddSurface(&surface);
VertexAttributesMap_t vertexAttributes;
vertexAttributes[VERTEX_ATTRIBUTES_POSITION] = 0;
vertexAttributes[VERTEX_ATTRIBUTES_TEX_COORDS] = 1;
paperMesh.Initialize(vertexAttributes);
// Create the paper material
Shader* shader = Renderer::GetInstance()->CreateShader();
shader->SetSourceFile("Shaders/BurningPaper/vert", "Shaders/BurningPaper/frag");
Material paperMaterial(shader);
Texture2D* paperTexture = Renderer::GetInstance()->CreateTexture2DFromFile("Media/paper.jpg");
Texture2D* noiseTexture = Renderer::GetInstance()->CreateTexture2DFromFile("Media/noise.jpg");
paperMaterial.SetUniformTexture("paper", paperTexture);
paperMaterial.SetUniformTexture("noise", noiseTexture);
// Create the paper node
Node paperNode;
paperNode.SetMaterial(&paperMaterial);
paperNode.SetMesh(&paperMesh);
Renderer::GetInstance()->GetSceneTree().AddNode(&paperNode);
Renderer::GetInstance()->CameraLookAt(Vector3(0.0f, 0.0f, 5.0f), -Vector3::LOOK, Vector3::UP);
float threshold = 0.0f;
float range = 0.075f;
float t = 0.0f;
clock_t begin, end;
#if PLATFORM == PLATFORM_WIN32
Text::GetInstance()->SetTextFont("C:/Windows/Fonts/Arial.ttf");
#elif PLATFORM == PLATFORM_LINUX
Text::GetInstance()->SetTextFont("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf");
#endif
Text::GetInstance()->SetTextSize(24, 24);
float fps = 0;
float dt = 0.0f;
size_t numFrames = 0;
while (window.IsOpen()) {
begin = clock();
WindowEvent windowEvent;
if (window.PollEvents(windowEvent)) {
}
threshold += t / 3.0f;
Renderer::GetInstance()->BindShader(shader);
shader->SetUniformVector2("thresholds", threshold, range);
Renderer::GetInstance()->Clear();
Renderer::GetInstance()->StartRender();
Renderer::GetInstance()->Render();
Text::GetInstance()->Write(to_string(fps), 5, 5);
Renderer::GetInstance()->EndRender();
Renderer::GetInstance()->PresentFrame();
end = clock();
t = float(end - begin) / CLOCKS_PER_SEC;
dt += float(end - begin) / CLOCKS_PER_SEC;
numFrames += 1;
if (dt >= 0.25f) {
fps = (float)numFrames / dt;
numFrames = 0;
//.........这里部分代码省略.........
示例3: attachShader
void Program::attachShader(Shader &shader) {
gl::AttachShader(this->ref, shader.getRef());
}
示例4: loadShader
virtual void loadShader (Shader& shader, string shader_name)
{
shader.load(shader_name, shaders_dir);
shader.initialize();
shaders_list.push_back(&shader);
}
示例5: blur
GLuint blur( Shader blur, GLuint texture, int amount)
{
static bool createAll = true;
static GLuint pingpongFBO[2];
static GLuint pingpongBuffer[2];
static GLuint vao;
static GLuint vbo[2];
if(createAll)
{
int w, h;
glBindTexture(GL_TEXTURE_2D, texture);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h);
std::cout << w << h << std::endl;
glGenFramebuffers(2, pingpongFBO);
glGenTextures(2, pingpongBuffer);
for (GLuint i = 0; i < 2; i++)
{
glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[i]);
glBindTexture(GL_TEXTURE_2D, pingpongBuffer[i]);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGB16F, w, h, 0, GL_RGB, GL_FLOAT, NULL
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pingpongBuffer[i], 0
);
}
int quad_triangleCount = 2;
int quad_triangleList[] = {0, 1, 2, 2, 1, 3};
float quad_vertices[] = {-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0};
// Quad
glBindVertexArray(vao);
// Bind indices and upload data
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quad_triangleList), quad_triangleList, GL_STATIC_DRAW);
// Bind vertices and upload data
glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices), quad_vertices, GL_STATIC_DRAW);
createAll = false;
}
GLboolean horizontal = true, first_iteration = true;
amount = amount + (amount%2);
blur.use();
for (GLuint i = 0; i < amount; i++)
{
glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[horizontal]);
glUniform1i(glGetUniformLocation(blur.getProgram(), "horizontal"), horizontal);
glBindTexture(
GL_TEXTURE_2D, first_iteration ? texture : pingpongBuffer[!horizontal]
);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, (void*)0);
horizontal = !horizontal;
if (first_iteration)
first_iteration = false;
}
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
Utils::checkGlError("blur");
return pingpongBuffer[!horizontal];
}
示例6: assert
// --[ Method ]---------------------------------------------------------------
//
// - Class : CStravaganzaMaxTools
//
// - prototype : bool BuildShaders()
//
// - Purpose : Builds the shader list from MAX's materials.
// Preview mode requires texture files to be stored with full
// path in order to load them. When we export, we only store the
// filename. Another thing is that in the export mode, we copy
// all textures into the path specified by the user if that
// option is checked.
//
// -----------------------------------------------------------------------------
bool CStravaganzaMaxTools::BuildShaders()
{
std::vector<Mtl*>::iterator it;
assert(m_vecShaders.empty());
if(!m_bPreview && m_bCopyTextures && m_strTexturePath == "")
{
CLogger::NotifyWindow("Textures won't be copied\nSpecify a valid output texture path first");
}
LOG.Write("\n\n-Building shaders: ");
for(it = m_vecMaterials.begin(); it != m_vecMaterials.end(); ++it)
{
Mtl* pMaxMaterial = *it;
assert(pMaxMaterial);
LOG.Write("\n %s", pMaxMaterial->GetName().data());
CShaderStandard* pShaderStd = new CShaderStandard;
pShaderStd->SetName(pMaxMaterial->GetName().data());
// Properties
StdMat2 *pMaxStandardMtl = NULL;
StdMat2 *pMaxBakedMtl = NULL;
float fAlpha;
if(pMaxMaterial->ClassID() == Class_ID(DMTL_CLASS_ID, 0))
{
pMaxStandardMtl = (StdMat2 *)pMaxMaterial;
}
else if(pMaxMaterial->ClassID() == Class_ID(BAKE_SHELL_CLASS_ID, 0))
{
pMaxStandardMtl = (StdMat2 *)pMaxMaterial->GetSubMtl(0);
pMaxBakedMtl = (StdMat2 *)pMaxMaterial->GetSubMtl(1);
}
if(pMaxStandardMtl)
{
// Standard material
fAlpha = pMaxStandardMtl->GetOpacity(0);
Shader* pMaxShader = pMaxStandardMtl->GetShader();
CVector4 v4Specular = ColorToVector4(pMaxStandardMtl->GetSpecular(0), 0.0f) * pMaxShader->GetSpecularLevel(0, 0);
pShaderStd->SetAmbient (ColorToVector4(pMaxStandardMtl->GetAmbient(0), 0.0f));
pShaderStd->SetDiffuse (ColorToVector4(pMaxStandardMtl->GetDiffuse(0), fAlpha));
pShaderStd->SetSpecular (v4Specular);
pShaderStd->SetShininess(pMaxShader->GetGlossiness(0, 0) * 128.0f);
if(pMaxStandardMtl->GetTwoSided() == TRUE)
{
pShaderStd->SetTwoSided(true);
}
// Need to cast to StdMat2 in order to get access to IsFaceted().
// ¿Is StdMat2 always the interface for standard materials?
if(((StdMat2*)pMaxStandardMtl)->IsFaceted())
{
pShaderStd->SetFaceted(true);
}
if(pMaxStandardMtl->GetWire() == TRUE)
{
pShaderStd->SetPostWire(true);
pShaderStd->SetWireLineThickness(pMaxStandardMtl->GetWireSize(0));
}
}
else
{
// Material != Standard
fAlpha = 1.0f; // pMaxMaterial->GetXParency();
pShaderStd->SetAmbient (ColorToVector4(pMaxMaterial->GetAmbient(), 0.0f));
pShaderStd->SetDiffuse (ColorToVector4(pMaxMaterial->GetDiffuse(), fAlpha));
pShaderStd->SetSpecular (CVector4(0.0f, 0.0f, 0.0f, 0.0f));
pShaderStd->SetShininess(0.0f);
}
// Layers
//.........这里部分代码省略.........
示例7: ShaderGraph
void BlenderSync::sync_world(bool update_all)
{
Background *background = scene->background;
Background prevbackground = *background;
BL::World b_world = b_scene.world();
if(world_recalc || update_all || b_world.ptr.data != world_map) {
Shader *shader = scene->default_background;
ShaderGraph *graph = new ShaderGraph();
/* create nodes */
if(b_world && b_world.use_nodes() && b_world.node_tree()) {
BL::ShaderNodeTree b_ntree(b_world.node_tree());
add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
/* volume */
PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
shader->volume_sampling_method = get_volume_sampling(cworld);
shader->volume_interpolation_method = get_volume_interpolation(cworld);
}
else if(b_world) {
ShaderNode *closure, *out;
closure = graph->add(new BackgroundNode());
closure->input("Color")->value = get_float3(b_world.horizon_color());
out = graph->output();
graph->connect(closure->output("Background"), out->input("Surface"));
}
if(b_world) {
/* AO */
BL::WorldLighting b_light = b_world.light_settings();
if(b_light.use_ambient_occlusion())
background->ao_factor = b_light.ao_factor();
else
background->ao_factor = 0.0f;
background->ao_distance = b_light.distance();
/* visibility */
PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
uint visibility = 0;
visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0;
background->visibility = visibility;
}
else {
background->ao_factor = 0.0f;
background->ao_distance = FLT_MAX;
}
shader->set_graph(graph);
shader->tag_update(scene);
background->tag_update(scene);
}
PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
/* when doing preview render check for BI's transparency settings,
* this is so because Blender's preview render routines are not able
* to tweak all cycles's settings depending on different circumstances
*/
if(b_engine.is_preview() == false)
background->transparent = get_boolean(cscene, "film_transparent");
else
background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
background->use_shader = render_layer.use_background_shader;
background->use_ao = render_layer.use_background_ao;
if(background->modified(prevbackground))
background->tag_update(scene);
}
示例8: TorusExample
TorusExample(void)
: make_torus(1.0, 0.5, 36, 24)
, torus_instr(make_torus.Instructions())
, torus_indices(make_torus.Indices())
, make_plane(make_plane_builders())
, plane_instr(make_plane[0].Instructions())
, plane_indices(make_plane[0].Indices())
, torus_vs(ShaderType::Vertex, ObjectDesc("Torus vertex"))
, plane_vs(ShaderType::Vertex, ObjectDesc("Plane vertex"))
, torus_fs(ShaderType::Fragment, ObjectDesc("Torus fragment"))
, plane_fs(ShaderType::Fragment, ObjectDesc("Plane fragment"))
, torus_prog(ObjectDesc("Torus"))
, plane_prog(ObjectDesc("Plane"))
, plane_normal(plane_prog, "Normal")
, plane_camera_matrix(plane_prog, "CameraMatrix")
, torus_camera_matrix(torus_prog, "CameraMatrix")
, torus_model_matrix(torus_prog, "ModelMatrix")
, plane(make_plane.size())
, plane_positions(make_plane.size())
{
std::stringstream plane_count_def;
plane_count_def <<"#define PlaneCount "<<plane.size()<<'\n';
const GLchar* torus_vs_source[3] = {
"#version 330\n",
plane_count_def.str().c_str(),
"uniform mat4 ProjectionMatrix, ModelMatrix, CameraMatrix;"
"uniform float ClipSign[PlaneCount];"
"uniform vec4 ClipPlane[PlaneCount];"
"in vec4 Position;"
"in vec2 TexCoord;"
"out vec2 vertTexCoord;"
"void main(void)"
"{"
" vertTexCoord = TexCoord;"
" gl_Position = "
" ModelMatrix *"
" Position;"
" for(int p=0; p!=PlaneCount; ++p)"
" {"
" gl_ClipDistance[p] = "
" ClipSign[p]* "
" dot(ClipPlane[p], gl_Position);"
" }"
" gl_Position = "
" ProjectionMatrix *"
" CameraMatrix *"
" gl_Position;"
"}"
};
torus_vs.Source(torus_vs_source, 3);
torus_vs.Compile();
torus_fs.Source(
"#version 330\n"
"in vec2 vertTexCoord;"
"out vec4 fragColor;"
"void main(void)"
"{"
" float i = ("
" int(vertTexCoord.x*36) % 2+"
" int(vertTexCoord.y*24) % 2"
" ) % 2;"
" fragColor = vec4(1-i/2, 1-i/2, 1-i/2, 1.0);"
"}"
);
torus_fs.Compile();
torus_prog.AttachShader(torus_vs);
torus_prog.AttachShader(torus_fs);
torus_prog.Link();
torus_prog.Use();
// bind the VAO for the torus
torus.Bind();
// bind the VBO for the torus vertices
torus_positions.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.Positions(data);
// upload the data
Buffer::Data(Buffer::Target::Array, data);
// setup the vertex attribs array for the vertices
VertexAttribArray attr(torus_prog, "Position");
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
}
// bind the VBO for the torus UV-coordinates
torus_texcoords.Bind(Buffer::Target::Array);
{
std::vector<GLfloat> data;
GLuint n_per_vertex = make_torus.TexCoordinates(data);
// upload the data
Buffer::Data(Buffer::Target::Array, data);
// setup the vertex attribs array for the vertices
VertexAttribArray attr(torus_prog, "TexCoord");
attr.Setup<GLfloat>(n_per_vertex);
attr.Enable();
//.........这里部分代码省略.........
示例9: main
//.........这里部分代码省略.........
for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) {
if (tet_mesh->get_vertex_status(i) == INTERFACE)
{
glm::detail::tvec4<REAL, glm::precision::defaultp> v(tet_mesh->vertices[i*3], tet_mesh->vertices[i*3+1], tet_mesh->vertices[i*3+2], 1);
if (tet_mesh->vertices[i*3] == 0.64f && tet_mesh->vertices[i*3+1] == 0.10f)
{
tet_mesh->vertex_targets[i*3] = tet_mesh->vertices[i*3]; // Stays the same
tet_mesh->vertex_targets[i*3+1] = -0.10f; // Moves to create C Mesh case
tet_mesh->vertex_targets[i*3+2] = tet_mesh->vertices[i*3+2]; // Stays the same
}
else
{
tet_mesh->vertex_targets[i*3] = tet_mesh->vertices[i*3];
tet_mesh->vertex_targets[i*3+1] = tet_mesh->vertices[i*3+1];
tet_mesh->vertex_targets[i*3+2] = tet_mesh->vertices[i*3+2];
}
tet_mesh->vertex_statuses[i] = MOVING;
}
}
printf("Evolving tet mesh from C mesh...\n");
tet_mesh->evolve();
} else if (meshArg == "7") { // Stretched sphere
IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj");
tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh);
for (unsigned int i = 0; i < tet_mesh->vertices.size() / 3; i++) {
if (tet_mesh->get_vertex_status(i) == INTERFACE) {
// scale x
tet_mesh->vertex_targets[i * 3] = tet_mesh->vertices[i * 3] * 1.2;
tet_mesh->vertex_targets[i * 3 + 1] = tet_mesh->vertices[i * 3 + 1];
tet_mesh->vertex_targets[i * 3 + 2] = tet_mesh->vertices[i * 3 + 2];
tet_mesh->vertex_statuses[i] = MOVING;
}
}
printf("Evolving tet mesh ...\n");
tet_mesh->evolve();
} else { // Default case (tet mesh #1)
IndexedFaceSet * mesh = IndexedFaceSet::load_from_obj("assets/models/sphere.obj");
tet_mesh = TetMeshFactory::from_indexed_face_set(*mesh);
printf("Evolving tet mesh ...\n");
tet_mesh->evolve();
delete mesh;
}
printf("Displaying tet mesh...\n");
printf("Initializing display...\n");
Shader * shader = Shader::compile_from("shaders/dsc.vsh", "shaders/dsc.gsh", "shaders/dsc.fsh");
glUseProgram(shader->get_id());
glBindVertexArray(vao);
Renderable renderable(shader, true, false, GL_TRIANGLES);
tgui::Gui gui(window);
gui.setGlobalFont("assets/fonts/DejaVuSans.ttf");
TetrahedralViewer viewer(&renderable, &gui);
viewer.init(WINDOW_WIDTH, WINDOW_HEIGHT, FOV);
viewer.bind_attributes(*tet_mesh, renderable);
check_gl_error();
delete tet_mesh;
printf("Starting display...\n");
sf::Event event;
sf::Clock clock;
tgui::Callback callback;
while (window.isOpen()) {
// float frame_length = clock.restart().asSeconds();
glUseProgram(shader->get_id());
glBindVertexArray(vao);
while (gui.pollCallback(callback)) {
viewer.handle_callback(callback);
}
viewer.update();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderable.render();
check_gl_error();
glUseProgram(0);
glBindVertexArray(0);
gui.draw();
window.display();
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
printf("Closing window...\n");
window.close();
}
viewer.handle_event(event);
}
sf::sleep(sf::seconds(1.0f / FRAME_RATE));
}
printf("Cleaning up...\n");
delete shader;
return 0;
}
示例10: render
void ModelRenderer::render(Shader& s, RenderingEngine::RenderState)
{
s.bind();
tex.bind(s);
mesh.Draw();
}
示例11: VertexShader
//----------------------------------------------------------------------------
Shader* FxCompiler::CreateShader (bool isVShader, const Program& program,
InputArray& inputs, OutputArray& outputs, ConstantArray& constants,
SamplerArray& samplers)
{
int numInputs = (int)inputs.size();
int numOutputs = (int)outputs.size();
int numConstants = (int)constants.size();
int numSamplers = (int)samplers.size();
Shader* shader;
if (isVShader)
{
shader = new0 VertexShader(program.Name, numInputs, numOutputs,
numConstants, numSamplers, true);
}
else
{
shader = new0 PixelShader(program.Name, numInputs, numOutputs,
numConstants, numSamplers, true);
}
int i;
for (i = 0; i < numInputs; ++i)
{
Input& input = inputs[i];
shader->SetInput(i, input.Name, input.Type, input.Semantic);
}
for (i = 0; i < numOutputs; ++i)
{
Output& output = outputs[i];
shader->SetOutput(i, output.Name, output.Type, output.Semantic);
}
for (i = 0; i < numConstants; ++i)
{
Constant& constant = constants[i];
shader->SetConstant(i, constant.Name, constant.NumRegistersUsed);
shader->SetBaseRegister(mActiveProfile, i, constant.BaseRegister);
}
for (i = 0; i < numSamplers; ++i)
{
Sampler& sampler = samplers[i];
shader->SetSampler(i, sampler.Name, sampler.Type);
shader->SetFilter(i, sampler.Filter);
shader->SetCoordinate(i, 0, sampler.Coordinate[0]);
shader->SetCoordinate(i, 1, sampler.Coordinate[1]);
shader->SetCoordinate(i, 2, sampler.Coordinate[2]);
shader->SetLodBias(i, sampler.LodBias);
shader->SetAnisotropy(i, sampler.Anisotropy);
shader->SetBorderColor(i, sampler.BorderColor);
shader->SetTextureUnit(mActiveProfile, i, sampler.Unit);
}
shader->SetProgram(mActiveProfile, program.Text);
return shader;
}
示例12: draw
void Model::draw(Shader & shader)
{
shader.setParameter("ModelMatrix", getMatrix());
if (m_mesh)
m_mesh->draw(shader);
}
示例13: Model
ParticleSkinnedModel::ParticleSkinnedModel(Shader& pShader, Body * body, Material ** mat, unsigned int materialCount) :
Model(body, mat, materialCount)
{
assert(body);
const std::vector<Body::sTriangle> tris = m_body->getTriangleData();
std::set<Body::sConnection> uniqueConnections;
// add unique line connections given by triangles
for(size_t i=0; i<body->getTriangleCount(); ++i)
{
uniqueConnections.insert(Body::sConnection(tris[i].index[0], tris[i].index[1]));
uniqueConnections.insert(Body::sConnection(tris[i].index[0], tris[i].index[2]));
uniqueConnections.insert(Body::sConnection(tris[i].index[1], tris[i].index[2]));
}
for(std::set<Body::sConnection>::const_iterator it = uniqueConnections.begin(); it != uniqueConnections.end(); ++it)
m_constraints.push_back(*it);
printf("Unique connections: %zu \n", m_constraints.size());
// Find vertices that share the same positions
// These must be merged after the constraints update
// Or else the seems will show
const float limit = 1.0e-9;
const std::vector<Body::sVertex> verts = m_body->getVertexData();
for(size_t i=0; i<body->getVertexCount()-1; ++i)
{
for(size_t j=i+1; j<body->getVertexCount(); ++j)
{
glm::vec3 v = verts[i].position - verts[j].position;
if(glm::dot(v,v) < limit)
m_postVertexMerge.push_back(Body::sConnection(i,j));
}
}
printf("Post vertex merge size: %u \n", m_postVertexMerge.size());
size_t particleCount = body->getVertexCount();
m_particles.resize(particleCount);
glm::vec3 boundingBoxMin(1.0e20f);
glm::vec3 boundingBoxMax(-1.0e20f);
for(size_t i=0; i<particleCount; ++i)
{
const Body::sVertex v = body->getVertexData()[i];
sParticle& p = m_particles[i];
p.position = v.position;
p.oldPosition = p.position;
p.mass_k_d = getParticleMass_K_D(i);
boundingBoxMin = glm::min(boundingBoxMin, v.position);
boundingBoxMax = glm::max(boundingBoxMax, v.position);
}
boundingBoxMin = boundingBoxMax - boundingBoxMin;
printf("%f, %f, %f\n", boundingBoxMin.x, boundingBoxMin.y, boundingBoxMin.z);
m_ps = new GPUParticleSystem(&m_particles[0], particleCount, pShader);
assert(m_ps);
m_particleBuffer.bind();
glBufferData(GL_ARRAY_BUFFER, particleCount * sizeof(sParticle), &m_particles[0], GL_STREAM_DRAW);
m_particleBuffer.unbind();
int positionAttr = pShader.getAttribLocation("in_vertexPosition");
int weightAttr = pShader.getAttribLocation("in_vertexWeight");
printf("positionAttr %i\n", positionAttr);
printf("weightAttr %i\n", weightAttr);
const char * pOffset = 0;
// Append Vertex Attribute pointers to the particle systems VAOs
glBindVertexArray(m_ps->getSourceVA());
glBindBuffer(GL_ARRAY_BUFFER, body->getVertexBuffer());
glEnableVertexAttribArray(positionAttr);
glEnableVertexAttribArray(weightAttr);
glVertexAttribPointer(positionAttr, 3, GL_FLOAT, GL_FALSE, sizeof(Body::sVertex), pOffset);
glVertexAttribPointer(weightAttr, 4, Body::VertexWeight::getGLType(), GL_FALSE, sizeof(Body::sVertex), 32 + pOffset);
glBindVertexArray(0);
glBindVertexArray(m_ps->getTargetVA());
glBindBuffer(GL_ARRAY_BUFFER, body->getVertexBuffer());
glEnableVertexAttribArray(positionAttr);
glEnableVertexAttribArray(weightAttr);
glVertexAttribPointer(positionAttr, 3, GL_FLOAT, GL_FALSE, sizeof(Body::sVertex), pOffset);
glVertexAttribPointer(weightAttr, 4, Body::VertexWeight::getGLType(), GL_FALSE, sizeof(Body::sVertex), 32 + pOffset);
glBindVertexArray(0);
}
示例14: updateFlat
void Image::encodeGpu (EncoderGpu *encoder)
{
//Prepare image data for encoding
updateFlat();
updateBounds();
updateBuffers();
glViewport( 0, 0, gridSize.x, gridSize.y );
glDisable( GL_DEPTH_TEST );
glDisable( GL_MULTISAMPLE );
/////////////////////////////////////////////////////
// Init size counters and main grid
{
Shader *shader = encoder->shaderInit;
shader->use();
Int32 uPtrInfo = shader->program->getUniform( "ptrInfo" );
glUniformui64( uPtrInfo, bufGpuInfo.getAddress() );
Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" );
glUniformui64( uPtrGrid, bufGpuGrid.getAddress() );
Int32 uGridSize = shader->program->getUniform( "gridSize" );
glUniform2i( uGridSize, gridSize.x, gridSize.y );
renderFullScreenQuad( shader );
}
/////////////////////////////////////////////////////
// Init object grids
{
Shader *shader = encoder->shaderInitObject;
shader->use();
Int32 uPtrObjects = shader->program->getUniform( "ptrObjects" );
glUniformui64( uPtrObjects, bufObjInfos.getAddress() );
Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" );
glUniformui64( uPtrGrid, bufGpuGrid.getAddress() );
Int32 uGridOrigin = shader->program->getUniform( "gridOrigin" );
glUniform2f( uGridOrigin, gridOrigin.x, gridOrigin.y );
Int32 uGridSize = shader->program->getUniform( "gridSize" );
glUniform2i( uGridSize, gridSize.x, gridSize.y );
Int32 uCellSize = shader->program->getUniform( "cellSize" );
glUniform2f( uCellSize, cellSize.x, cellSize.y );
Int32 aPos = shader->program->getAttribute( "in_pos" );
glBindBuffer( GL_ARRAY_BUFFER, bufObjs.getId() );
glVertexAttribPointer( aPos, 3, GL_FLOAT, false, sizeof(vec3), 0 );
glEnableVertexAttribArray( aPos );
glDrawArrays( GL_LINES, 0, objs.size() * 2 );
glDisableVertexAttribArray( aPos );
}
glMemoryBarrier( GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV );
checkGlError( "encodeImage init" );
/////////////////////////////////////////////////////
// Encode object lines
{
Shader *shader = encoder->shaderLines;
shader->use();
Int32 uPtrObjects = shader->program->getUniform( "ptrObjects" );
glUniformui64( uPtrObjects, bufObjInfos.getAddress() );
Int32 uPtrInfo = shader->program->getUniform( "ptrInfo" );
glUniformui64( uPtrInfo, bufGpuInfo.getAddress() );
Int32 uPtrGrid = shader->program->getUniform( "ptrGrid" );
glUniformui64( uPtrGrid, bufGpuGrid.getAddress() );
Int32 uPtrStream = shader->program->getUniform( "ptrStream" );
glUniformui64( uPtrStream, bufGpuStream.getAddress() );
Int32 uGridOrigin = shader->program->getUniform( "gridOrigin" );
glUniform2f( uGridOrigin, gridOrigin.x, gridOrigin.y );
Int32 uGridSize = shader->program->getUniform( "gridSize" );
glUniform2i( uGridSize, gridSize.x, gridSize.y );
Int32 uCellSize = shader->program->getUniform( "cellSize" );
glUniform2f( uCellSize, cellSize.x, cellSize.y );
for (int o=0; o<(int)objects.size(); ++o)
{
Object *object = objects[o];
Int32 uObjectId = shader->program->getUniform( "objectId" );
glUniform1i( uObjectId, o );
Int32 aPos = shader->program->getAttribute( "in_pos" );
glBindBuffer( GL_ARRAY_BUFFER, object->bufLines.getId() );
glVertexAttribPointer( aPos, 2, GL_FLOAT, false, sizeof( Vec2 ), 0 );
//.........这里部分代码省略.........
示例15: _renderSpriteBatch
void Renderer::_renderSpriteBatch(glm::mat4& modelMatrix, std::vector<Sprite*>& spritebatch, Camera* camera)
{
Sprite* spr = spritebatch[0];
Shader* shader = _uberShader;
// ask resourcemanager
if (shader == NULL) {
shader = _resman.getShader(spr->vertexshader().c_str(), spr->fragmentshader().c_str());
}
std::string texturename = spr->texturename();
int filter = spr->filter();
int wrap = spr->wrap();
Texture* texture = _resman.getTexture(texturename, filter, wrap);
if (spr->size.x == 0) { spr->size.x = texture->width() * spr->uvdim.x; }
if (spr->size.y == 0) { spr->size.y = texture->height() * spr->uvdim.y; }
Mesh* mesh = _resman.getSpriteMesh(spr->size.x, spr->size.y, spr->pivot.x, spr->pivot.y, spr->uvdim.x, spr->uvdim.y, spr->circlemesh(), spr->which());
if (texture != NULL) {
// Bind our texture in Texture Unit 0
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->getGLTexture());
// for every Sprite in the batch...
int s = spritebatch.size();
for (int i = 0; i < s; i++) {
Sprite* sprite = spritebatch[i]; // a Sprite handle
int culled = 0; // state that we need to draw it
if (sprite->useCulling()) { // but maybe we don't
int half_width = SWIDTH/2;
int half_height = SHEIGHT/2;
int left_edge = camera->position.x - half_width;
int right_edge = camera->position.x + half_width;
int top_edge = camera->position.y - half_height;
int bottom_edge = camera->position.y + half_height;
float posx = sprite->spriteposition.x;
float posy = sprite->spriteposition.y;
int debug = 0;
if (debug) { // cull visibly within the frame
if (posx - spr->size.x < left_edge) { culled = 1; }
if (posx + spr->size.x > right_edge) { culled = 1; }
if (posy + spr->size.y > bottom_edge) { culled = 1; }
if (posy - spr->size.y < top_edge) { culled = 1; }
} else {
if (posx + spr->size.x < left_edge) { culled = 1; }
if (posx - spr->size.x > right_edge) { culled = 1; }
if (posy - spr->size.y > bottom_edge) { culled = 1; }
if (posy + spr->size.y < top_edge) { culled = 1; }
}
}
// this Sprite isn't culled and needs to be drawn
if (!culled) {
RGBAColor blendcolor = sprite->color;
// _uvOffsetID
glUniform2f(shader->uvOffsetID(), sprite->uvoffset.x, sprite->uvoffset.y);
// use spritepos for position
glm::vec3 position = glm::vec3(sprite->spriteposition.x, sprite->spriteposition.y, 0.0f);
glm::vec3 rotation = glm::vec3(0.0f, 0.0f, sprite->spriterotation);
glm::vec3 scale = glm::vec3(sprite->spritescale.x, sprite->spritescale.y, 0.0f);
// Build the Model matrix
glm::mat4 translationMatrix = glm::translate(modelMatrix, position);
glm::mat4 rotationMatrix = glm::eulerAngleYXZ(0.0f, 0.0f, rotation.z);
glm::mat4 scalingMatrix = glm::scale(glm::mat4(1.0f), scale);
glm::mat4 mm = translationMatrix * rotationMatrix * scalingMatrix;
this->_renderMesh(mm, shader, texture, mesh, mesh->numverts(), GL_TRIANGLES, blendcolor);
}
}
}
}