Пример #1
0
void MagicView::OnRender() 
{
   if (!screen || !video) 
      return;

   double s = sin(timeGetTime() * 0.001);
   double c = cos(timeGetTime() * 0.001);

   // IF LIGHTS ANIMATED:
   if (animate_light) {
      Point light_pos(3e6*s, 5e6*c, 4e6*s);

      if (main_light) {
         main_light->SetType(Light::LIGHT_POINT);
         main_light->MoveTo(light_pos);
         main_light->SetType(Light::LIGHT_DIRECTIONAL);
      }

      if (back_light) {
         back_light->SetType(Light::LIGHT_POINT);
         back_light->MoveTo(light_pos * -1);
         back_light->SetType(Light::LIGHT_DIRECTIONAL);
      }
   }

   if (screen->Refresh()) {
      video->Present();
   }
   else {
      ::Print("ERROR: Screen refresh failed.\n");
   }
}
Пример #2
0
void AnimPositionCalibrate::keyPressed( int k )
{
	switch( k )
	{
		case OF_KEY_RIGHT:
			lights->set( current_id, 0, true );
			current_id++;
			phase = 0;
			if ( current_id >= lights->getNumLights() )
				current_id = 0;
			break;
		case OF_KEY_LEFT:
			lights->set( current_id, 0, true );
			current_id--;
			phase = 0;
			if ( current_id < 0 )
				current_id = lights->getNumLights()-1;
			break;
		case OF_KEY_RETURN:
			if ( mode == MODE_SWEEP_Y )
				lights->setLightPosition( current_id, lights->getLight( current_id ).getX(), position_pct );
			else if ( mode == MODE_SWEEP_X )
				lights->setLightPosition( current_id, position_pct, lights->getLight( current_id ).getY() );
			else
			{
				// get the nearest point on the line
				const Light& light = lights->getLight( current_id );
				ofxVec3f p( 0, position_pct );
				ofxVec3f d( sqrtf(2.0f), -sqrtf(2.0f) );
				ofxVec3f light_pos( light.getX(), light.getY() );
				ofxVec3f new_pos = NearestPointOnLineToPoint::calculateNearestPoint( p, p+d, light_pos );
				lights->setLightPosition( current_id, new_pos.x, new_pos.y );
			}
			break;
		case 'B':
			lights->toggleLightIsBig( current_id );
			break;
		case 'x':
			mode = MODE_SWEEP_X;
			break;
		case 'y':
			mode = MODE_SWEEP_Y;
			break;
		case 'z':
			mode = MODE_SWEEP_DIAG;
			break;
		case 'g':
			if ( current_group != 0 )
				lights->toggleGroupMembership( current_id, current_group );
			break;
		default:
			break;
	}			
	if ( k >= '0' && k <= '9' )
	{
		current_group = k-'0';
	}
	
	
}
Пример #3
0
boost::shared_ptr<shade::Program> setup_shading(boost::shared_ptr<shade::GLSLWrapper> state)
{
    boost::shared_ptr<shade::shaders::Surface> shader(new shade::shaders::Surface);
    boost::shared_ptr<shade::Program> program(new shade::Program(shader, state));

    boost::shared_ptr<shade::shaders::Plastic> specular(new shade::shaders::Plastic(0.4, .6));
    boost::shared_ptr<shade::shaders::ObjectSpace> object_space(new shade::shaders::ObjectSpace);
    specular->color.set_value(shade::vec4<>(1., 0.4, 0.4, 1.));
    specular->coordinate_system = object_space;
    shader->material = specular;
    {
        shade::shaders::IlluminatedMaterial::LightList::Accessor accessor(specular->lights);

        boost::shared_ptr<shade::shaders::PointLight> light(new shade::shaders::PointLight);
        boost::shared_ptr<shade::shaders::GLLightPosition> gl_light_pos(new shade::shaders::GLLightPosition);
        boost::shared_ptr<shade::shaders::Vec4ToVec3> light_pos(new shade::shaders::Vec4ToVec3);
        gl_light_pos->index.set(1);
        light_pos->value = gl_light_pos;
        light->position = light_pos;
        light->color.set_value(shade::vec3<>(1., 1., 1.));
        accessor->push_back(light);

        boost::shared_ptr<shade::shaders::DirectionalLight> light2(new shade::shaders::DirectionalLight);
        light2->direction.set_value(shade::vec3<>(0., 1., 0.));
        light2->color.set_value(shade::vec3<>(1., 0., 0.));
        accessor->push_back(light2);
    }

    return program;
}
Пример #4
0
/**
 * Returns the color based on lighting (points in world coordinates)
 *
 * Normals are scaled here, so they do not need to be unit vectors.
 */
color lighting(point *pos, point *normal, object_copy *obj,
		vector<light> *lights, camera *CAM) {
	color diffuse_sum = { 0.0, 0.0, 0.0 };
	color specular_sum = { 0.0, 0.0, 0.0 };

	Vector3d tmp(normal->x, normal->y, normal->z);
	Vector3d normal_vector = tmp / tmp.norm();

	Vector3d pos_vector(pos->x, pos->y, pos->z);

	Vector3d cam_pos(CAM->position[0], CAM->position[1], CAM->position[2]);

	Vector3d cam_direction = (cam_pos - pos_vector) / (cam_pos - pos_vector).norm();

	for (unsigned int i = 0; i < lights->size(); i++) {
		Vector3d light_pos((*lights)[i].position.x,
				(*lights)[i].position.y,
				(*lights)[i].position.z);

		Vector3d light_dir = (light_pos - pos_vector) /
				(light_pos - pos_vector).norm();


		float distance = (light_pos - pos_vector).norm();
		float attenuation = 1.0 / (1 + (*lights)[i].k * distance * distance);

		Vector3d midpoint = (cam_direction + light_dir) /
				(cam_direction + light_dir).norm();

		float tmp2 = light_dir.dot(normal_vector);
		float tmp3 = normal_vector.dot(light_dir);

		float diffuse_mult = attenuation *
				max(0.0, light_dir.dot(normal_vector));

		float tmp4 = normal_vector.dot(midpoint);
		float specular_mult = attenuation *
				pow(max(0.0, normal_vector.dot(midpoint)), obj->shininess);

		diffuse_sum += (*lights)[i].col * diffuse_mult;
		specular_sum += (*lights)[i].col * specular_mult;
	}
	color final_color = obj->ambient + (diffuse_sum * obj->diffuse) + (specular_sum * obj->specular);

	if (final_color.r > 1.0) {
		final_color.r = 1.0;
	}
	if (final_color.g > 1.0) {
		final_color.g = 1.0;
	}
	if (final_color.b > 1.0) {
		final_color.b = 1.0;
	}
	return final_color;
}
Пример #5
0
int main() {
  // msaa
  glfwWindowHint(GLFW_SAMPLES, 4);
  GLFWwindow * window = initWindow(windowWidth, windowHeight);
  if (!window) {
    glfwTerminate();
    return -1;
  }
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  glfwSetKeyCallback(window, key_callback);
  glfwSetCursorPosCallback(window, cursor_callback);
  glfwSetScrollCallback(window, scroll_callback);

  glEnable(GL_DEPTH_TEST);

  // prepare texture loading library(devil)
  init_texture_loading();

  //plane
  Shader simpleDepthShader("data/shaders/shadow_mapping_depth.vs", "data/shaders/shadow_mapping_depth.frag");

  Model ourModel("data/models/nanosuit/nanosuit.obj");

  GLfloat planeVertices[] = {
    // Positions          // Normals         // Texture Coords
    2.0f, 0.0f, 2.0f, 0.0f, 1.0f, 0.0f, 2.0f, 0.0f,
    -2.0f, 0.0f, -2.0f, 0.0f, 1.0f, 0.0f, 0.0f, 2.0f,
    -2.0f, 0.0f, 2.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,

    2.0f, 0.0f, 2.0f, 0.0f, 1.0f, 0.0f, 2.0f, 0.0f,
    2.0f, 0.0f, -2.0f, 0.0f, 1.0f, 0.0f, 2.0f, 2.0f,
    -2.0f, 0.0f, -2.0f, 0.0f, 1.0f, 0.0f, 0.0f, 2.0f
  };

  // Setup plane VAO xzhs
  GLuint planeVBO;
  GLuint woodTexture;
  GLuint rockTexture;
  glGenVertexArrays(1, &planeVAO);
  glGenBuffers(1, &planeVBO);
  glBindVertexArray(planeVAO);
  glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), &planeVertices, GL_STATIC_DRAW);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(2);
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
  glBindVertexArray(0);

  // Load textures
  woodTexture = load_texture("data/textures/wood.png");
  rockTexture = load_texture("data/textures/rock.jpg");

  // Configure depth map FBO
  const GLuint SHADOW_WIDTH = 1024, SHADOW_HEIGHT = 1024;
  GLuint depthMapFBO;
  glGenFramebuffers(1, &depthMapFBO);
  // - Create depth texture
  GLuint depthMap;
  glGenTextures(1, &depthMap);
  glBindTexture(GL_TEXTURE_2D, depthMap);

  glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
  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_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  GLfloat borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
  glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);

  glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
  glDrawBuffer(GL_NONE);
  glReadBuffer(GL_NONE);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

  //xzhe

  Shader shaders("data/shaders/shader.vert", "data/shaders/shader.frag");
  Shader colorShaders("data/shaders/shaderColorUniform.vert",
                      "data/shaders/shaderColorUniform.frag");
  Shader domeShaders("data/shaders/dome.vert", "data/shaders/dome.frag");
  Shader lightShaders("data/shaders/lightShader.vert", "data/shaders/lightShader.frag");
  Shader spriteShaders("data/shaders/spriteShader.vert", "data/shaders/spriteShader.frag");
  Shader starShaders("data/shaders/spriteShader.vert", "data/shaders/stars.frag");

  std::cout << "Loading models..." << std::endl;
  Model dome("data/models/geodesic_dome.obj");
  Model landscape("data/models/landscape.obj");
  std::cout << "Models loaded!" << std::endl;

  std::cout << "Loading extra textures..." << std::endl;
  GLuint domeColor = load_texture("data/textures/sky.png", true, GL_MIRRORED_REPEAT, GL_MIRRORED_REPEAT);
  GLuint domeGlow = load_texture("data/textures/glow.png", true, GL_MIRRORED_REPEAT, GL_MIRRORED_REPEAT);

  Sprite sun("data/textures/sun.png");
  Sprite moon("data/textures/moon.png");
  Sprite star("data/textures/star.png");

  // enable blending!
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  // enable msaa(multisample anti-aliasing)
  glEnable(GL_MULTISAMPLE);

  std::vector<glm::mat4> starModels(256);
  for (auto& m : starModels) {
    m = glm::rotate(m, glm::radians(rand_rotate()), glm::vec3(1.0f, 0.0f, 0.0f));
    m = glm::rotate(m, glm::radians(rand_rotate()), glm::vec3(0.0f, 1.0f, 0.0f));
    m = glm::rotate(m, glm::radians(rand_rotate()), glm::vec3(0.0f, 0.0f, 1.0f));
    m = glm::translate(m, glm::vec3(5.0f, 0.0f, 0.0f));
    m = glm::rotate(m, glm::radians(rand_rotate()), glm::vec3(1.0f, 0.0f, 0.0f));
    m = glm::rotate(m, glm::radians(rand_rotate()), glm::vec3(0.0f, 1.0f, 0.0f));
  }

  double last_frame = glfwGetTime();
  while (!glfwWindowShouldClose(window)) {
    double current_frame = glfwGetTime();
    double delta_time = current_frame - last_frame;
    last_frame = current_frame;

    glfwPollEvents();

    do_movement(delta_time);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, windowWidth, windowHeight);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)windowWidth / (float)windowHeight, 0.1f, 100.0f);
    glm::mat4 view = camera.GetViewMatrix();

    // sun
    float sunAngle = current_frame * 30.0f;
    glm::mat4 sunModel;
    sunModel = glm::rotate(sunModel, glm::radians(sunAngle), glm::vec3(0.0f, 0.0f, 1.0f));
    sunModel = glm::translate(sunModel, glm::vec3(3.5f, 0.0f, 0.0f));
    glm::vec3 sunPos = glm::vec3(sunModel * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f));

    // moon
    float moonAngle = sunAngle + 180.0f;
    glm::mat4 moonModel;
    moonModel = glm::rotate(moonModel, glm::radians(moonAngle), glm::vec3(0.0f, 0.0f, 1.0f));
    moonModel = glm::translate(moonModel, glm::vec3(3.5f, 0.0f, 0.0f));

    // directional light
    DirLight dirLight(-sunPos, glm::vec3(0.8f, 0.8f, 0.8f));

    // point light
    GLfloat light_pos_angle = glm::radians(60.0f * current_frame);
    glm::vec3 light_pos(1.2f + sin(light_pos_angle), 0.0f, 2.0f + cos(light_pos_angle));
    glm::vec3 lightColor(1.0f, 1.0f, 1.0f);
    lightColor.r = sin(current_frame * 2.0f);
    lightColor.g = sin(current_frame * 0.7f);
    lightColor.b = sin(current_frame * 1.3f);
    PointLight pointLight(light_pos, lightColor * 0.5f);

    // spot light
    SpotLight spotLight(camera.Position, camera.Front,
                        glm::vec3((GLfloat)flash_light_on));

    shaders.Use();
    shaders.SetUniform("view", view);
    shaders.SetUniform("projection", projection);
    shaders.SetUniform("ViewPos", camera.Position);
    dirLight.SetUniforms(shaders, "dirLight");
    pointLight.SetUniforms(shaders, "pointLights[0]");
    shaders.SetUniform("pointLightCount", 0);
    spotLight.SetUniforms(shaders, "spotLight");
    shaders.SetUniform("material.shininess", 16.0f);

    colorShaders.Use();
    colorShaders.SetUniform("view", view);
    colorShaders.SetUniform("projection", projection);
    colorShaders.SetUniform("ViewPos", camera.Position);
    dirLight.SetUniforms(colorShaders, "dirLight");
    //pointLight.SetUniforms(colorShaders, "pointLights[0]");
    colorShaders.SetUniform("pointLightCount", 0);
    spotLight.SetUniforms(colorShaders, "spotLight");
    colorShaders.SetUniform("material.shininess", 1.8f);

    // make the dome and landscape pinned
    glm::mat4 pinnedView = glm::lookAt(glm::vec3(0.0f, 1.0f, 0.0f),
                                       glm::vec3(0.0f, 1.0f, 0.0f) + camera.Front,
                                       glm::vec3(0.0f, 1.0f, 0.0f));

    if (enable_stars) {
      // stars
      starShaders.Use();
      starShaders.SetUniform("view", view);
      starShaders.SetUniform("projection", projection);
      starShaders.SetUniform("groundBases[0]", 1.0f, 0.0f, 0.0f);
      starShaders.SetUniform("groundBases[1]", 0.0f, 0.0f, 1.0f);
      starShaders.SetUniform("groundUp", 0.0f, 1.0f, 0.0f);
      starShaders.SetUniform("sunPos", sunPos);
      for (const auto& m : starModels) {
        glm::mat4 model = glm::rotate(glm::mat4(), glm::radians(sunAngle), glm::vec3(0.0f, 0.0f, 1.0f)) * m;
        starShaders.SetUniform("model", model);
        star.Draw(starShaders);
      }
    }

    colorShaders.Use();
    glm::mat4 lmodel;
    lmodel = glm::scale(lmodel, glm::vec3(3.0f, 3.0f, 3.0f));
    lmodel = glm::translate(lmodel, glm::vec3(0.0f, 0.1f, 0.0f));
    lmodel = glm::rotate(lmodel, glm::radians(30.0f), glm::vec3(0.0f, 1.0f, 0.0f));
    glm::mat3 normalMatrix = glm::mat3(glm::transpose(glm::inverse(lmodel)));
    colorShaders.SetUniform("view", view);
    colorShaders.SetUniform("model", lmodel);
    colorShaders.SetUniform("normalMatrix", normalMatrix);
    colorShaders.SetUniform("Color", glm::vec4(0.93f, 0.79f, 0.69f, 1.0f));
    landscape.Draw(colorShaders, false);

    domeShaders.Use();
    domeShaders.SetUniform("view", view);
    domeShaders.SetUniform("projection", projection);
    glActiveTexture(GL_TEXTURE7);
    glBindTexture(GL_TEXTURE_2D, domeColor);
    glActiveTexture(GL_TEXTURE8);
    glBindTexture(GL_TEXTURE_2D, domeGlow);
    domeShaders.SetUniform("domeColor", 7);
    domeShaders.SetUniform("glow", 8);
    glm::mat4 dmodel;
    dmodel = glm::scale(dmodel, glm::vec3(4.0f, 4.0f, 4.0f));
    domeShaders.SetUniform("model", dmodel);
    domeShaders.SetUniform("sunPos", sunPos);
    dome.Draw(domeShaders, false);

    // cheating billboarding to make the sun and moon always face the camera
    glm::mat4 sunModelView = view * sunModel;
    for (int i = 0; i < 3; ++i)
      for (int j = 0; j < 3; ++j)
        sunModelView[i][j] = (GLfloat)(i == j);
    sunModelView = glm::scale(sunModelView, glm::vec3(0.5f, 0.5f, 0.5f));
    glm::mat4 moonModelView = view * moonModel;
    for (int i = 0; i < 3; ++i)
      for (int j = 0; j < 3; ++j)
        moonModelView[i][j] = (GLfloat)(i == j);
    moonModelView = glm::scale(moonModelView, glm::vec3(0.5f, 0.5f, 0.5f));

    spriteShaders.Use();
    spriteShaders.SetUniform("view", glm::mat4());
    spriteShaders.SetUniform("projection", projection);
    spriteShaders.SetUniform("model", sunModelView);
    sun.Draw(spriteShaders);
    spriteShaders.SetUniform("model", moonModelView);
    moon.Draw(spriteShaders);

    //xzhs
    // Set texture samples
    shaders.Use();
    glActiveTexture(GL_TEXTURE13);
    glBindTexture(GL_TEXTURE_2D, woodTexture);
    glActiveTexture(GL_TEXTURE14);
    glBindTexture(GL_TEXTURE_2D, rockTexture);
    glActiveTexture(GL_TEXTURE15);
    glBindTexture(GL_TEXTURE_2D, depthMap);
    shaders.SetUniform("material.texture_diffuse1", 14);
    shaders.SetUniform("material.texture_specular1", 14);
    shaders.SetUniform("shadowMap", 15);

    // 1. Render depth of scene to texture (from light's perspective)
    // - Get light projection/view matrix.
    glm::mat4 lightProjection, lightView;
    glm::mat4 lightSpaceMatrix;
    GLfloat near_plane = 1.0f, far_plane = 7.5f;

    lightProjection = glm::ortho(-10.0f, 10.0f, -10.0f, 10.0f, near_plane, far_plane);
    lightView = glm::lookAt(sunPos, glm::vec3(0.0f), glm::vec3(1.0));
    lightSpaceMatrix = lightProjection * lightView;
    // - now render scene from light's point of view
    simpleDepthShader.Use();
    simpleDepthShader.SetUniform("lightSpaceMatrix", lightSpaceMatrix);

    glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT);
    glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
    glClear(GL_DEPTH_BUFFER_BIT);
    RenderFloor(simpleDepthShader);
    RenderCubes(simpleDepthShader);

    glm::mat4 nmodel;
    nmodel = glm::translate(nmodel, glm::vec3(0.1f, 0.3f, -0.5f));
    nmodel = glm::rotate(nmodel, glm::radians(70.0f), glm::vec3(0.0f, 1.0f, 0.0f));
    nmodel = glm::scale(nmodel, glm::vec3(0.05f, 0.05f, 0.05f));
    simpleDepthShader.SetUniform("model", nmodel);
    ourModel.Draw(simpleDepthShader);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // 2. Render scene as normal
    glViewport(0, 0, windowWidth, windowHeight);
    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    shaders.Use();
    shaders.SetUniform("projection", projection);
    shaders.SetUniform("view", view);
    shaders.SetUniform("ViewPos", camera.Position);
    // Set light uniforms
    // PointLight sunPointLight(sunPos, glm::vec3(0.02f, 0.02f, 0.02f), glm::vec3(1.0f, 1.0f, 1.0f), glm::vec3(0.5f, 0.5f, 0.5f));
    // sunPointLight.SetUniforms(shaders, "pointLights[0]");
    // shaders.SetUniform("pointLightCount", 0);
    dirLight.SetUniforms(shaders, "dirLight");
    shaders.SetUniform("pointLightCount", 0);

    shaders.SetUniform("lightSpaceMatrix", lightSpaceMatrix);

    shaders.SetUniform("material.texture_diffuse1", 14);
    shaders.SetUniform("material.texture_specular1", 14);
    shaders.SetUniform("shadowMap", 15);
    RenderFloor(shaders);
    shaders.SetUniform("material.texture_diffuse1", 13);
    shaders.SetUniform("material.texture_specular1", 13);
    RenderCubes(shaders);
    shaders.SetUniform("model", nmodel);
    ourModel.Draw(shaders);
    //xzhe

    glfwSwapBuffers(window);
  }

  glfwTerminate();
  return 0;
}
Пример #6
0
int main(int argc,char** args) {

    srand(time(NULL));

    try {

        if (SDL_Init(SDL_INIT_VIDEO)) {
            fprintf(stderr,"Unable to initialize SDL: %s\n",SDL_GetError());
            return EXIT_FAILURE;
        }
        atexit(SDL_Quit);

        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
#if 0
        screen = SDL_SetVideoMode(1440,900,32,SDL_OPENGL|SDL_FULLSCREEN);
#else
        screen = SDL_SetVideoMode(1024,768,32,SDL_OPENGL/*|SDL_FULLSCREEN*/);
#endif
        if(!screen) {
            fprintf(stderr,"Unable to create SDL screen: %s\n",SDL_GetError());
            return EXIT_FAILURE;
        }
        SDL_WM_SetCaption("GlestNG","GlestNG");

        GLenum err = glewInit();
        if(GLEW_OK != err) {
            fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
            return EXIT_FAILURE;
        }
        fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

        // we have a GL context so we can go ahead and init all the singletons
        std::auto_ptr<fs_t> fs_settings(fs_t::create("data/"));
        fs_t::settings = fs_settings.get(); // set it globally
        std::auto_ptr<xml_parser_t> xml_settings(new xml_parser_t("UI Settings",fs_settings->get_body("ui_settings.xml")));
        xml_settings->set_as_settings();
        std::auto_ptr<graphics_t::mgr_t> graphics_mgr(graphics_t::create());
        std::auto_ptr<fonts_t> fonts(fonts_t::create());
        std::auto_ptr<fs_t> fs;
        try {
            fs.reset(fs_t::create("data/Glest"));
            if(false) {
                fs_file_t::ptr_t logo_file(fs_settings->get("logo.g3d"));
                istream_t::ptr_t logostream(logo_file->reader());
                logo = std::auto_ptr<model_g3d_t>(new model_g3d_t(*logostream));
            }
            load(*fs);
        } catch(glest_exception_t* e) {
            std::cerr << "cannot load glest data: " << e << std::endl;
            delete e;
        }
        std::auto_ptr<ui_mgr_t> ui_(ui_mgr());
        std::auto_ptr<mod_ui_t> mod_ui(mod_ui_t::create());

        std::auto_ptr<terrain_t> terrain(terrain_t::gen_planet(5,500,3));
        //world()->dump(std::cout);

        v4_t light_amb(0,0,0,1), light_dif(1.,1.,1.,1.), light_spec(1.,1.,1.,1.), light_pos(1.,1.,-1.,0.),
             mat_amb(.7,.7,.7,1.), mat_dif(.8,.8,.8,1.), mat_spec(1.,1.,1.,1.);
        glLightfv(GL_LIGHT0,GL_AMBIENT,light_amb.v);
        glLightfv(GL_LIGHT0,GL_DIFFUSE,light_dif.v);
        glLightfv(GL_LIGHT0,GL_SPECULAR,light_spec.v);
        glLightfv(GL_LIGHT0,GL_POSITION,light_pos.v);
        glLightfv(GL_LIGHT1,GL_AMBIENT,light_amb.v);
        glLightfv(GL_LIGHT1,GL_DIFFUSE,light_dif.v);
        glLightfv(GL_LIGHT1,GL_SPECULAR,light_spec.v);
        glMaterialfv(GL_FRONT,GL_AMBIENT,mat_amb.v);
        glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_dif.v);
        glMaterialfv(GL_FRONT,GL_SPECULAR,mat_spec.v);
        glMaterialf(GL_FRONT,GL_SHININESS,100.0);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        glEnable(GL_LIGHT1);
        glDepthFunc(GL_LEQUAL);
        glEnable(GL_DEPTH_TEST);
        glAlphaFunc(GL_GREATER,0.4);
        glEnable(GL_COLOR_MATERIAL);
        glEnable(GL_RESCALE_NORMAL);
        glEnable(GL_BLEND);
        glEnable(GL_TEXTURE_2D);
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
        glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
        glEnable(GL_COLOR_MATERIAL);
        glEnable(GL_NORMALIZE);
        glFrontFace(GL_CW);
        camera();
        bool quit = false;
        SDL_Event event;
        SDL_EnableKeyRepeat(200,20);
        SDL_EnableUNICODE(true);
        const unsigned start = SDL_GetTicks();
        framerate.reset();
        while(!quit) {
            set_now(SDL_GetTicks()-start);
            while(!quit && SDL_PollEvent(&event)) {
                if(ui_mgr()->offer(event))
                    continue;
                switch (event.type) {
                case SDL_MOUSEMOTION:
                    if(selection)
                        std::cout << "drag" << std::endl;
                    /*printf("Mouse moved by %d,%d to (%d,%d)\n",
                    event.motion.xrel, event.motion.yrel,
                    event.motion.x, event.motion.y);*/
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    click(event.button.x,event.button.y);
                    if(selection)
                        std::cout << "selection: "<<selected_point<<std::endl;
                    break;
                case SDL_MOUSEBUTTONUP:
                    if(selection)
                        std::cout << "selection stopped" << std::endl;
                    selection = false;
                    break;
                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym) {
                    case SDLK_PLUS:
                        zoom += 1;
                        camera();
                        break;
                    case SDLK_MINUS:
                        zoom -= 1;
                        camera();
                        break;
                    case SDLK_ESCAPE:
                        quit = true;
                        break;
                    case SDLK_m: // MODDING MODE
                        if(!fs.get()) {
                            std::cerr << "(modding menu triggered but mod not loaded)" << std::endl;
                            break;
                        }
                        if(mod_ui->is_shown())
                            mod_ui->hide();
                        else
                            mod_ui->show(ref_t(*techtree,TECHTREE,techtree->name));
                        break;
                    default:
                        std::cout << "Ignoring key " <<
                                  (int)event.key.keysym.scancode << "," <<
                                  event.key.keysym.sym << "," <<
                                  event.key.keysym.mod << "," <<
                                  event.key.keysym.unicode << std::endl;
                    }
                    break;
                case SDL_QUIT:
                    quit = true;
                    break;
                }
            }
            framerate.tick(now());
            tick();
        }
        for(tests_t::iterator i=objs.begin(); i!=objs.end(); i++)
            delete *i;
        return EXIT_SUCCESS;
    } catch(data_error_t* de) {
        std::cerr << "Oh! " << de << std::endl;
    } catch(graphics_error_t* ge) {
        std::cerr << "Oh! " << ge << std::endl;
    } catch(panic_t* panic) {
        std::cerr << "Oh! " << panic << std::endl;
    }
    return EXIT_FAILURE;
}
Пример #7
0
// 使用DirectX 9來繪圖
void RenderFrameDX9(void)
{
	LPDIRECT3DDEVICE9 device = GutGetGraphicsDeviceDX9();
	Matrix4x4 view_matrix = g_Control.GetViewMatrix();
	Matrix4x4 world_matrix = g_Control.GetObjectMatrix();
	Matrix4x4 ident_matrix; ident_matrix.Identity();
	device->BeginScene(); 
	// 消除畫面
	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_RGBA(30, 30, 30, 255), 1.0f, 0);
	// light position & orientation
	Vector4 light_pos(5.0f, 0.0f, 5.0f);
	Vector4 light_lookat(0.0f, 0.0f, 0.0f);
	Vector4 light_up(0.0f, 1.0f, 0.0f);
	// light matrix
	Matrix4x4 light_view = GutMatrixLookAtRH(light_pos, light_lookat, light_up);
	Matrix4x4 light_world_view = world_matrix * light_view;
	Matrix4x4 shadow_matrix;
	// 建立shadow volume
	if ( g_bDirectionalLight )
	{
		g_ShadowVolume.BuildShadowVolume_DirectionalLight(light_world_view, 20.0f, true);
		shadow_matrix = light_view;
		shadow_matrix.FastInvert();
	}
	else
	{
		g_ShadowVolume.BuildShadowVolume_PointLight(light_pos, world_matrix, 20.0f, true);
		shadow_matrix.Identity();
	}
	// 畫出空間中的茶壼
	{
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &world_matrix);

		g_Model_DX9.Render();
	}
	// 畫出墻壁
	{
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &ident_matrix);

		sModelMaterial_DX9 material;

		material.m_Material.Diffuse.r = 0.0f;
		material.m_Material.Diffuse.g = 0.0f;
		material.m_Material.Diffuse.b = 1.0f;
		material.m_Material.Diffuse.a = 1.0f;

		material.Submit();

		device->SetFVF(D3DFVF_XYZ);
		device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_Quad, sizeof(Vertex_VT));
	}
	device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
	device->SetRenderState(D3DRS_STENCILENABLE, TRUE);
	device->SetRenderState(D3DRS_STENCILREF, 0x01);
	device->SetRenderState(D3DRS_STENCILMASK, 0xff);
	// 在Stencil Buffer上標示出陰影區域
	{
		sModelMaterial_DX9 material;
		material.m_bCullFace = false;
		material.Submit();
		// 套用矩陣
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &shadow_matrix);
		// 設定頂點資料格式
		device->SetFVF(D3DFVF_XYZ);

		device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
		// cw stencil setting
		device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
		device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_INCR);
		// ccw stencil setting
		device->SetRenderState(D3DRS_CCW_STENCILFUNC, D3DCMP_ALWAYS);
		device->SetRenderState(D3DRS_CCW_STENCILZFAIL, D3DSTENCILOP_DECR);
		// disable color write
		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
		// 畫出Shadow Volume
		device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, g_ShadowVolume.m_iNumShadowVolumeFaces, g_ShadowVolume.m_pShadowVolume, sizeof(Vector4));
		// 恢復更新framebuffer
		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0xff);
		device->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
		device->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_KEEP);
		device->SetRenderState(D3DRS_CCW_STENCILZFAIL, D3DSTENCILOP_KEEP);
	}
	// 畫出陰影
	{
		sModelMaterial_DX9 material;
		material.m_bCullFace = false;
		material.Submit();

		device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TFACTOR);
		device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG2);
		// 套用矩陣
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &ident_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &ident_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &ident_matrix);
		// 只更新stencil buffer上值為1的像素
		device->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_EQUAL);
		device->SetRenderState(D3DRS_STENCILREF, 0x01);
		// 使用黑色再畫一次墻壁
		device->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_RGBA(0, 0, 0,255) );
		device->SetFVF(D3DFVF_XYZ);
		device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, g_FullScreenQuad, sizeof(Vertex_VT));
	}
	device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
	// 觀察shadow volume, 除錯用.
	if ( g_bDrawShadowVolume )
	{
		device->SetTransform(D3DTS_PROJECTION, (D3DMATRIX *) &g_projection_matrix);
		device->SetTransform(D3DTS_VIEW, (D3DMATRIX *) &view_matrix);
		device->SetTransform(D3DTS_WORLD, (D3DMATRIX *) &shadow_matrix);

		sModelMaterial_DX9 material;
		material.m_bCullFace = false;
		material.Submit();

		device->SetRenderState(D3DRS_TEXTUREFACTOR, D3DCOLOR_RGBA(255, 255, 255, 255) );
		device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
		device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, g_ShadowVolume.m_iNumShadowVolumeFaces, g_ShadowVolume.m_pShadowVolume, sizeof(Vector4));
		device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
	}
	// 恢復更新zbuffer
	device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
	// 把顏色來源還原為 diffuse * texture
	device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
	device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
	device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
	// 宣告所有的繪圖指令都下完了
	device->EndScene(); 
	// 把背景backbuffer的畫面呈現出來
	device->Present( NULL, NULL, NULL, NULL );
}
Пример #8
0
void Lighting::Draw()
{
	//sample mesh
	//haruna::SolidCubeFactory cube_factory(1, 1, 1);
	//auto data = cube_factory.CreateNormalMesh();
	haruna::SolidSphereFactory sphere_factory(1, 16, 16);
	auto data = sphere_factory.CreateNormalMesh();


	prog_->Use();
	haruna::gl::ShaderLocation pos_loc = prog_->GetAttribLocation("a_position");
	haruna::gl::ShaderLocation normal_loc = prog_->GetAttribLocation("a_normal");
	
	haruna::gl::ShaderLocation light_pos_loc = prog_->GetUniformLocation("u_modelLightPos");
	haruna::gl::ShaderLocation cam_pos_loc = prog_->GetUniformLocation("u_modelCameraPos");
	haruna::gl::ShaderLocation model_loc = prog_->GetUniformLocation("u_model");
	haruna::gl::ShaderLocation view_loc = prog_->GetUniformLocation("u_view");
	haruna::gl::ShaderLocation proj_loc = prog_->GetUniformLocation("u_proj");

	//projection
	float aspect = width() / height();
	glm::mat4 proj_mat = glm::perspective(60.0f, aspect, 0.1f, 100.0f);

	float radius = 2;
	glm::vec3 eye(cos(y_rot_) * radius, 0, sin(y_rot_) * radius);
	glm::vec3 center(0, 0, 0);
	glm::vec3 up(0, 1, 0);
	glm::mat4 view_mat = glm::lookAt(eye, center, up);
		
	//model
	glm::mat4 model_mat = glm::mat4();

	//draw
	glViewport(0, 0, (int)width(), (int)height());
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glEnable(GL_CULL_FACE);

	//glUniformMatrix4fv(mvp_loc.handle(), 1, GL_FALSE, glm::value_ptr(mvp));
	glUniformMatrix4fv(model_loc.handle(), 1, GL_FALSE, glm::value_ptr(model_mat));
	glUniformMatrix4fv(view_loc.handle(), 1, GL_FALSE, glm::value_ptr(view_mat));
	glUniformMatrix4fv(proj_loc.handle(), 1, GL_FALSE, glm::value_ptr(proj_mat));


	glEnableVertexAttribArray(pos_loc.handle());
	glEnableVertexAttribArray(normal_loc.handle());

	glm::vec3 light_pos(10, 10, 10);
	glUniform3fv(light_pos_loc.handle(), 1, glm::value_ptr(light_pos));

	glUniform3fv(cam_pos_loc.handle(), 1, glm::value_ptr(eye));

	for(auto cmd : data) {
		std::vector<haruna::Vertex_1P1N1UV> &vert_list = cmd.vertex_list;
		std::vector<unsigned short> &index_list = cmd.index_list;

		int stride = sizeof(haruna::Vertex_1P1N1UV);
		glVertexAttribPointer(pos_loc.handle(), 3, GL_FLOAT, GL_FALSE, stride, &vert_list[0].p);
		glVertexAttribPointer(normal_loc.handle(), 3, GL_FLOAT, GL_FALSE, stride, &vert_list[0].n);

		GLenum draw_mode = ToDrawMode(cmd.draw_mode);
		glDrawElements(draw_mode, index_list.size(), GL_UNSIGNED_SHORT, &index_list[0]);
	}

	haruna::gl::GLEnv::CheckError("End Frame");
}
Пример #9
0
int main() {
  GLFWwindow * window = initWindow(windowWidth, windowHeight);
  if (!window) {
    glfwTerminate();
    return -1;
  }
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  glfwSetKeyCallback(window, key_callback);
  glfwSetCursorPosCallback(window, cursor_callback);
  glfwSetScrollCallback(window, scroll_callback);

  glEnable(GL_DEPTH_TEST);

  // prepare texture loading library(devil)
  ilInit();

  // prepare an array of vertices
  GLfloat vertices[] = {
    // Positions           // Normals           // Texture Coords
    -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,
     0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 0.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f, 1.0f,
    -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 1.0f,
    -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f, 0.0f,

    -0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   0.0f, 0.0f,
     0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   1.0f, 0.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   1.0f, 1.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   1.0f, 1.0f,
    -0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   0.0f, 1.0f,
    -0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,   0.0f, 0.0f,

    -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f, 0.0f,
    -0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  1.0f, 1.0f,
    -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f, 1.0f,
    -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f, 1.0f,
    -0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  0.0f, 0.0f,
    -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f, 0.0f,

     0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f, 0.0f,
     0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f, 1.0f,
     0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f, 1.0f,
     0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f, 1.0f,
     0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  0.0f, 0.0f,
     0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f, 0.0f,

    -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f, 1.0f,
     0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  1.0f, 1.0f,
     0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f, 0.0f,
     0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f, 0.0f,
    -0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  0.0f, 0.0f,
    -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f, 1.0f,

    -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f, 1.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  1.0f, 1.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f, 0.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f, 0.0f,
    -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  0.0f, 0.0f,
    -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f, 1.0f
  };
  glm::vec3 cubePositions[] = {
    glm::vec3( 0.0f,  0.0f,  0.0f),
    glm::vec3( 2.0f,  5.0f, -15.0f),
    glm::vec3(-1.5f, -2.2f, -2.5f),
    glm::vec3(-3.8f, -2.0f, -12.3f),
    glm::vec3( 2.4f, -0.4f, -3.5f),
    glm::vec3(-1.7f,  3.0f, -7.5f),
    glm::vec3( 1.3f, -2.0f, -2.5f),
    glm::vec3( 1.5f,  2.0f, -2.5f),
    glm::vec3( 1.5f,  0.2f, -1.5f),
    glm::vec3(-1.3f,  1.0f, -1.5f)
  };

  GLuint lightVAO;
  glGenVertexArrays(1, &lightVAO);
  glBindVertexArray(lightVAO);

  GLuint lightVBO;
  glGenBuffers(1, &lightVBO);
  glBindBuffer(GL_ARRAY_BUFFER, lightVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat),
                       (void*)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat),
                        (void*)(6 * sizeof(GLfloat)));
  glEnableVertexAttribArray(2);

  glBindVertexArray(0);

  Shader shaders("shader.vert", "shader.frag");
  Shader lightShaders("lightShader.vert", "lightShader.frag");

  std::cout << "Input path: ";
  std::string path;
  std::getline(std::cin, path);
  std::cout << "path is: " << path << std::endl;

  std::cout << "Loading model..." << std::endl;
  Model themodel(path.c_str());
  std::cout << "Model loaded!" << std::endl;

  double last_frame = glfwGetTime();
  while (!glfwWindowShouldClose(window)) {
    double current_frame = glfwGetTime();
    double delta_time = current_frame - last_frame;
    last_frame = current_frame;

    glfwPollEvents();

    do_movement(delta_time);

    glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    GLfloat light_pos_angle = glm::radians(60.0f * current_frame);
    glm::vec3 light_pos(1.2f + sin(light_pos_angle), 0.0f, 2.0f + cos(light_pos_angle));
    glm::vec3 light_dir(-0.2f, -1.0f, -0.3f);

    // draw common container
    shaders.Use();

    glm::mat4 view = camera.GetViewMatrix();
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom),
                                (GLfloat)windowWidth / (GLfloat)windowHeight,
                                0.01f, 1000.0f);
    shaders.SetUniform("view", view);
    shaders.SetUniform("projection", projection);

    glm::vec3 lightColor(1.0f, 1.0f, 1.0f);
    //lightColor.r = sin(current_frame * 2.0f);
    //lightColor.g = sin(current_frame * 0.7f);
    //lightColor.b = sin(current_frame * 1.3f);
    shaders.SetUniform("ViewPos", camera.Position);

    // directional light
    shaders.SetUniform("dirLight.direction", light_dir);
    shaders.SetUniform("dirLight.ambient", 0.1f, 0.1f, 0.1f);
    shaders.SetUniform("dirLight.diffuse", 0.5f, 0.5f, 0.5f);
    shaders.SetUniform("dirLight.specular", 1.0f, 1.0f, 1.0f);

    // point light
    shaders.SetUniform("pointLights[0].position", light_pos);
    shaders.SetUniform("pointLights[0].ambient", lightColor * 0.1f);
    shaders.SetUniform("pointLights[0].diffuse", lightColor * 0.5f);
    shaders.SetUniform("pointLights[0].specular", 1.0f, 1.0f, 1.0f);
    shaders.SetUniform("pointLights[0].constant", 1.0f);
    shaders.SetUniform("pointLights[0].linear", 0.09f);
    shaders.SetUniform("pointLights[0].quadratic", 0.032f);

    shaders.SetUniform("pointLightCount", 1);

    glm::vec3 spotLight((GLfloat)flash_light_on);
    // spot light
    shaders.SetUniform("spotLight.ambient", spotLight * 0.1f);
    shaders.SetUniform("spotLight.diffuse", spotLight * 0.5f);
    shaders.SetUniform("spotLight.specular", spotLight);
    shaders.SetUniform("spotLight.position", camera.Position);
    shaders.SetUniform("spotLight.direction", camera.Front);
    shaders.SetUniform("spotLight.cutoff", glm::cos(glm::radians(12.5f)));
    shaders.SetUniform("spotLight.outerCutoff", glm::cos(glm::radians(17.5f)));

    shaders.SetUniform("material.shininess", 10000.0f);

    glm::mat4 model = glm::translate(glm::mat4(), glm::vec3(0.2f, -1.0f, 1.0f));
    model = glm::scale(model, glm::vec3(0.1f, 0.1f, 0.1f));
    shaders.SetUniform("model", model);
    glm::mat3 normalMatrix = glm::mat3(glm::transpose(glm::inverse(model)));
    shaders.SetUniform("normalMatrix", normalMatrix);

    themodel.Draw(shaders);

    // draw lamp
    lightShaders.Use();

    glm::mat4 lightModel = glm::scale(glm::translate(glm::mat4(), light_pos), glm::vec3(0.2f));

    lightShaders.SetUniform("view", view);
    lightShaders.SetUniform("projection", projection);
    lightShaders.SetUniform("model", lightModel);
    lightShaders.SetUniform("lightColor", lightColor);

    glBindVertexArray(lightVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);

    glfwSwapBuffers(window);
  }

  glfwTerminate();
  return 0;
}
Пример #10
0
int main(int argc, char *argv[])
{
	GLFWwindow* window;
	glfwSetErrorCallback(error_callback);
	if (!glfwInit())
		exit(EXIT_FAILURE);
	// OpenGL 3.3, Mac OS X is reported to have some problem. However I don't have Mac to test
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	// For Mac OS X
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	window = glfwCreateWindow(1280, 960, "Mesh Smoothing Demo", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return EXIT_FAILURE;
	}

	glfwMakeContextCurrent(window);

	// This line MUST put below glfwMakeContextCurrent
	glewExperimental = GL_TRUE;
	glewInit();

	// Enable vsync
	glfwSwapInterval(1);

	// Setup input callback
	glfwSetKeyCallback(window, key_callback);
	glfwSetMouseButtonCallback(window, mouse_callback);

	setup_gui_texture();
	setup_gui_render_obj();

	filenames[0] = "smoothing";
	filenames[1] = "/ori/";
	filenames[2] = "/lap/";
	filenames[3] = "/tau/";

	// load shader program
	shaders[0] = setup_shader(readfile("shaders/vs.txt").c_str(), readfile("shaders/fs.txt").c_str());
	gui_shader = setup_shader(readfile("shaders/guivs.txt").c_str(), readfile("shaders/guifs.txt").c_str());
	shaders[1] = setup_shader(readfile("shaders/nvs.txt").c_str(), readfile("shaders/nfs.txt").c_str());
	shaders[2] = setup_shader(readfile("shaders/fvs.txt").c_str(), readfile("shaders/ffs.txt").c_str());
	printf("we have:%d, %d, %d\n", shaders[0], shaders[1], shaders[2]);
	program1 = shaders[0];

	show_obj = add_obj("smoothing/ori/bunny.obj");
	glm::vec3 light_pos(0.0f, 0.0f, 0.0f);
	camera_location = glm::vec4(0.0f, 0.0f, 2.0f, 1.0f);
	up_direction = glm::vec4(0.0f, 1.0f, 0.0f, 1.0f);

	glEnable(GL_DEPTH_TEST);
	glCullFace(GL_BACK);

	glm::vec3 camera_location_xyz = glm::vec3(camera_location.x, camera_location.y, camera_location.z);
	glm::vec3 up_direction_xyz = glm::vec3(up_direction.x, up_direction.y, up_direction.z);
	setUniformMat4(shaders[0], "p", glm::perspective(glm::radians(45.0f), 640.0f/480, 0.1f, 100.f) *glm::mat4(1.0f));
	setUniformMat4(shaders[0], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), glm::vec3(0, 1, 0))*glm::mat4(1.0f));

	setUniformMat4(shaders[1], "p", glm::perspective(glm::radians(45.0f), 640.0f/480, 0.1f, 100.f) *glm::mat4(1.0f));
	setUniformMat4(shaders[1], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), glm::vec3(0, 1, 0))*glm::mat4(1.0f));

	setUniformMat4(shaders[2], "p", glm::perspective(glm::radians(45.0f), 640.0f/480, 0.1f, 100.f) *glm::mat4(1.0f));
	setUniformMat4(shaders[2], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), glm::vec3(0, 1, 0))*glm::mat4(1.0f));



	glm::mat4 rot;
	glm::mat4 rev;

	float last, start;
	last = start = glfwGetTime();
	float fps = 0;
	while (!glfwWindowShouldClose(window))
	{
		rotate();
		zoom();

		camera_location_xyz = glm::vec3(camera_location.x, camera_location.y, camera_location.z);
		up_direction_xyz = glm::vec3(up_direction.x, up_direction.y, up_direction.z);
		setUniformMat4(shaders[0], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), up_direction_xyz)*glm::mat4(1.0f));
		setUniformMat4(shaders[1], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), up_direction_xyz)*glm::mat4(1.0f));
		setUniformMat4(shaders[2], "v", glm::lookAt(camera_location_xyz, glm::vec3(0.0f), up_direction_xyz)*glm::mat4(1.0f));

		render();

		glfwSwapBuffers(window);
		glfwPollEvents();
		fps++;
		if(glfwGetTime() - last > 1.0)
		{
			std::cout<<(double)fps/(glfwGetTime()-last)<<std::endl;
			fps = 0;
			last = glfwGetTime();
		}
	}

	releaseObjects();
	glfwDestroyWindow(window);
	glfwTerminate();
	return EXIT_SUCCESS;
}
Пример #11
0
    void start() {



        float x1 = -10;
        float y1 = -10;




//      glBindTexture(GL_TEXTURE_2D, texName);
//         float roty = -45;
        int light_x = 0;
        int light_xd = 1;

        vec3i light_pos( 0, 40, 0 );

        //int steps = 1;

        //light_scene ls( planes_, solid_ );


        auto t_old = CL_System::get_microseconds();
        bool light_on = true;
        bool light_button_down = false;
        double delta_t = 0.01;
        player p1;

        //rad_core_ = make_unique<rad_core_threaded>( scene_static_, light_static_ );
        
//         rad_core_ = make_rad_core_threaded(scene_static_, light_static_);
        
        
//         auto rad_core2 = make_unique<rad_core_opencl>( cl_context_, cl_cqueue_, scene_static_, light_static_ );
//         rad_core2->load_kernel( cl_context_, cl_used_devices_ );
        
        
//      float min_ff = 5e-5;

        
//         vab.render(planes_.begin(), planes_.end() );
        
//         vbo_builder vbob(scene_static_.planes().size());
//         vbob.update_index_buffer(scene_static_.planes().size());
//         vbob.update_vertices( scene_static_.planes().begin(), scene_static_.planes().end());
        
     //    std::ifstream is( "cryistal-castle-hidden-ramp.txt" );
        std::ifstream is( "house1.txt" );
        render_unit runit(is, vec3f( -40.0, -20.0, -40.0 ));
        
//         std::ifstream is2( "cryistal-castle-tree-wave.txt" );
//         std::ifstream is2( "cryistal-castle-hidden-ramp.txt" );
//         std::ifstream is2( "house1.txt" );
//         render_unit runit2(is2, vec3f( 60.0, -20.0, 0.0 ));
        
#if 0
        cl::BufferGL buf;
        //cl::Buffer buf;
        try {
            
            //cl_int cl_err;
            //buf = cl::Buffer( clCreateFromGLBuffer( cl_context_(), CL_MEM_WRITE_ONLY, vbob.buffers_[1], &cl_err ));
            //assert( cl_err == CL_SUCCESS );
            buf = cl::BufferGL( cl_context_, CL_MEM_WRITE_ONLY, vbob.buffers_[1] );
        
        
        
            cl_fcolor_ = cl::Buffer( cl_context_, CL_MEM_READ_ONLY, scene_static_.planes().size() * 3 * sizeof(float) );
            
            cl_kernel_.setArg(0, buf() );
            //cl_kernel_.setArg(1, cl_fcolor_ );
            cl_kernel_.setArg(1, rad_core2->f_rad() );
            cl_uint cl_color_size = scene_static_.planes().size();
            cl_kernel_.setArg(2, cl_color_size );
            
            
            
        } catch( cl::Error x ) {
            std::cerr << "cl error during gl buffer setup\ncall: " << x.what() << "\nerror code: " << cl_str_error( x.err() ) << "\n";            
            throw;
        }
#endif
        bool light_changed = true;
        
        //rad_core_ = make_unique<rad_core_lockfree>( scene_static_, light_static_ );
        
        bool do_quit = false;
        
        while ( !do_quit ) {

            //cube c(x1, 0, y1);

            CL_GraphicContext gc = wnd_.get_gc();
            CL_InputDevice &keyboard = wnd_.get_ic().get_keyboard();
            CL_InputDevice &mouse = wnd_.get_ic().get_mouse();

//          if( keyboard.get_keycode(CL_KEY_I) ) {
//          //  roty += 1;
//
//              min_ff += 5e-6;
//          }
//          if(  keyboard.get_keycode(CL_KEY_K) ) {
//              //roty -= 1;
//              min_ff -= 5e-6;
//          }
//
//          std::cout << "min ff: " << min_ff << "\n";

            p1.input(keyboard, mouse);
            p1.frame(t_old * 1.0e-3, delta_t);

            int light_speed = 1;
            
            do_quit = keyboard.get_keycode(CL_KEY_Q);
            
            if ( keyboard.get_keycode(CL_KEY_LEFT) ) {
                light_pos.x += light_speed;
                light_changed = true;
            }
            if (  keyboard.get_keycode(CL_KEY_RIGHT) ) {
                light_pos.x -= light_speed;
                light_changed = true;
            }
            if ( keyboard.get_keycode(CL_KEY_UP) ) {
                light_pos.z += light_speed;
                light_changed = true;
            }
            if (  keyboard.get_keycode(CL_KEY_DOWN) ) {
                light_pos.z -= light_speed;
                light_changed = true;
            }
            if ( keyboard.get_keycode(CL_KEY_L )) {
                if ( !light_button_down ) {
                    light_on = !light_on;
                    light_changed = true;
                }
                light_button_down = true;
            } else {
                light_button_down = false;
            }



            glEnable(GL_CULL_FACE);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


//          glTranslatef(0,0,-100);
//          glRotatef(45,1,0,0);
//          glRotatef(roty,0,1,0);


            if ( light_x > 60 || light_x < -60 ) {
                light_xd = -light_xd;
//              light_x = -20;
            }

            //          light_planes(vec3i(light_x, 10, 10 ));
            
            if( light_changed ) {
                //ls.reset_emit();
//                 light_dynamic_.clear_emit();
                runit.clear_emit();
//                 runit2.clear_emit();
                //ls.render_light(vec3f( 40, 50.0, light_x ), vec3f(1.0, 1.0, 1.0 ));
                if ( light_on ) {
                    //ls.render_light(light_pos, vec3f(1.0, 0.8, 0.6 ));
                    
                    //vec3f light_pos( p1.pos)
                    
                    //              vec3f light_pos = (p1.pos()* pump_factor_) - base_pos_;
                    vec3f light_weird = (light_pos * pump_factor_) - base_pos_;
//                     light_utils::render_light( light_dynamic_.emit(), scene_static_, light_weird, vec3f(1.0, 0.8, 0.6 ));
                    runit.render_light(light_weird, vec3f(1.0, 0.8, 0.6 ));
//                     runit2.render_light(light_weird, vec3f(1.0, 0.8, 0.6 ));
                }
                //ls.post();
                light_changed = false;
            }
            runit.update();
//             runit2.update();
//             rad_core2->set_emit( *light_dynamic_.emit() );
//             rad_core_->set_emit( *light_dynamic_.emit() );
            //ls.render_emit_patches();

            //steps = 1;
            //ls.do_radiosity( steps );

            //rad_core2->run();
//             rad_core_->copy( light_dynamic_.rad() );
             // stupid: transfer rgb energy fomr light scene to planes
//             for ( size_t i = 0; i < scene_static_.planes().size(); ++i ) {
//                 plane &p = const_cast<plane &>(scene_static_.planes()[i]); // FIXME: HACK!!! is the energy_rgp stored in the planes actually used? remove it!
//                 p.energy_rgb((*light_dynamic_.rad())[i]);
//             }
//             
            light_x += light_xd;


//          glPushMatrix();
            
            //CL_Mat4f proj = CL_Mat4f::look_at( 20, 20, 20, 0, 0, 0, 0.0, 1.0, 0.0 );

            //vab.update_color( planes_.begin(), planes_.end() );
//             vab.update_color( ls.rad_rgb().begin(), ls.rad_rgb().end() );
            
//             vab.setup_gl_pointers();
//             vbob.update_color(light_dynamic_.rad()->begin(), light_dynamic_.rad()->end());
#if 0
            try
            {
                cl_int err;
//                 glFinish();
                const auto &rad_colors = *light_dynamic_.rad();
//                 
                cl_cqueue_.enqueueWriteBuffer( cl_fcolor_, false, 0, rad_colors.size() * sizeof(vec3f), rad_colors.data() );
//                 
                

                err = clEnqueueAcquireGLObjects( cl_cqueue_(), 1, &(buf()), 0, 0, 0 );
                assert( err == CL_SUCCESS );


                
                //cl_kernel_.setArg(1, rad_core2->f_rad() );
                cl_kernel_.setArg(1, cl_fcolor_ );
                cl_cqueue_.enqueueNDRangeKernel( cl_kernel_, 0, cl::NDRange(scene_static_.planes().size()) );
                
                               

                // unmap buffer object
                err = clEnqueueReleaseGLObjects( cl_cqueue_(), 1, &(buf()), 0,0,0);
                assert( err == CL_SUCCESS );
                
                cl_cqueue_.finish();
                
                
                
            } catch( cl::Error x ) {
                std::cerr << "cl error during kernel execution\ncall: " << x.what() << "\nerror code: " << cl_str_error( x.err() ) << "\n";               
                throw;
            }
#endif       
            
            //setup_perspective( p1 );
            setup_ortho();

            int ortho_width = 320;
            int ortho_heigth = 200;
            glViewport( gc.get_width() - ortho_width, gc.get_height() - ortho_heigth, ortho_width, ortho_heigth );
       //     vab.draw_arrays();
            //  render_quads();
//          glPopMatrix();
            setup_perspective(p1);
            glViewport( 0, 0, gc.get_width(), gc.get_height());
//             render_quads();
//            vab.setup_gl_pointers();
//             vab.draw_arrays();
//             vbob.draw_arrays();
            runit.draw();
//             runit2.draw();
            wnd_.flip(1);



            auto t = CL_System::get_microseconds();

//             std::cout << "fps: " << 1e6 / (t - t_old) << "\n";
            delta_t = (t - t_old) * 1.0e-6;
            t_old = t;



//           std::cout << "delta: " << delta_t << "\n";

//             CL_System::sleep( 1000 / 60. );
//          getchar();
            CL_KeepAlive::process();


            x1 += 1;
            if ( x1 > 10 ) {
                x1 = -10;
                y1 += 1;
            }
            if ( y1 > 10 ) {
                y1 = -10;
            }

        }

    }
Пример #12
0
	TorusExample(void)
	 : make_torus()
	 , torus_instr(make_torus.Instructions())
	 , torus_indices(make_torus.Indices())
	{
		// Set the vertex shader source
		vs.Source(
			"#version 150\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"in vec3 Color;"
			"out vec3 vertColor;"
			"out vec3 vertNormal;"
			"out vec3 vertViewDir;"
			"void main(void)"
			"{"
			"	vertColor = normalize(vec3(1,1,1)-Color);"
			"	vertNormal = Normal;"
			"	vertViewDir = ("
			"		vec4(0.0, 0.0, 1.0, 1.0)*"
			"		CameraMatrix"
			"	).xyz;"
			"	gl_Position = "
			"		ProjectionMatrix *"
			"		CameraMatrix *"
			"		Position;"
			"}"
		);
		// compile it
		vs.Compile();

		// set the fragment shader source
		fs.Source(
			"#version 150\n"
			"in vec3 vertColor;"
			"in vec3 vertNormal;"
			"in vec3 vertViewDir;"
			"out vec4 fragColor;"
			"uniform vec3 LightPos[3];"
			"void main(void)"
			"{"
			"	float amb = 0.2;"
			"	float diff = 0.0;"
			"	float spec = 0.0;"
			"	for(int i=0;i!=3;++i)"
			"	{"
			"		diff += max("
			"			dot(vertNormal,  LightPos[i])/"
			"			dot(LightPos[i], LightPos[i]),"
			"			0.0"
			"		);"
			"		float k = dot(vertNormal, LightPos[i]);"
			"		vec3 r = 2.0*k*vertNormal - LightPos[i];"
			"		spec += pow(max("
			"			dot(normalize(r), vertViewDir),"
			"			0.0"
			"		), 32.0 * dot(r, r));"
			"	}"
			"	fragColor = "
			"		vec4(vertColor, 1.0)*(amb+diff)+"
			"		vec4(1.0, 1.0, 1.0, 1.0)*spec;"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the torus
		torus.Bind();

		// bind the VBO for the torus vertex positions
		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
			VertexArrayAttrib attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the torus normals
		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Normals(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// bind the VBO for the torus colors
		colors.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_torus.Tangents(data);
			// upload the data
			Buffer::Data(Buffer::Target::Array, data);
			// setup the vertex attribs array for the vertices
			VertexArrayAttrib attr(prog, "Color");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// set the light positions
		Uniform<Vec3f> light_pos(prog, "LightPos");
		light_pos[0].Set(Vec3f(2.0f,-1.0f, 0.0f));
		light_pos[1].Set(Vec3f(0.0f, 3.0f,-1.0f));
		light_pos[2].Set(Vec3f(0.0f,-1.0f, 4.0f));
		//
		gl.ClearColor(0.8f, 0.8f, 0.7f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);
		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_torus.FaceWinding());
		gl.CullFace(Face::Back);
	}
Пример #13
0
void
TacRefDlg::RegisterControls()
{
    btn_close         = (Button*)       FindControl(1);
    btn_ships         = (Button*)       FindControl(101);
    btn_weaps         = (Button*)       FindControl(102);
    lst_designs       = (ListBox*)      FindControl(200);
    txt_caption       =                 FindControl(301);
    beauty            =                 FindControl(401);
    txt_stats         = (RichTextBox*)  FindControl(402);
    txt_description   = (RichTextBox*)  FindControl(403);

    if (btn_close) {
        REGISTER_CLIENT(EID_CLICK,          btn_close,   TacRefDlg, OnClose);
    }

    if (btn_ships) {
        btn_ships->SetButtonState(mode == MODE_SHIPS);
        REGISTER_CLIENT(EID_CLICK,          btn_ships,   TacRefDlg, OnMode);
    }

    if (btn_weaps) {
        btn_weaps->SetButtonState(mode == MODE_WEAPONS);
        REGISTER_CLIENT(EID_CLICK,          btn_weaps,   TacRefDlg, OnMode);
    }

    if (lst_designs) {
        REGISTER_CLIENT(EID_SELECT,         lst_designs, TacRefDlg, OnSelect);
    }

    if (beauty) {
        REGISTER_CLIENT(EID_RBUTTON_DOWN,   beauty,     TacRefDlg, OnCamRButtonDown);
        REGISTER_CLIENT(EID_RBUTTON_UP,     beauty,     TacRefDlg, OnCamRButtonUp);
        REGISTER_CLIENT(EID_MOUSE_MOVE,     beauty,     TacRefDlg, OnCamMove);
        REGISTER_CLIENT(EID_MOUSE_WHEEL,    beauty,     TacRefDlg, OnCamZoom);

        scene.SetAmbient(Color(60,60,60));

        Point light_pos(3e6, 5e6, 4e6);

        Light* main_light = new Light(1.0f); //1.25f);
        main_light->MoveTo(light_pos);
        main_light->SetType(Light::LIGHT_DIRECTIONAL);
        main_light->SetColor(Color::White);
        main_light->SetShadow(true);

        scene.AddLight(main_light);

        Light* back_light = new Light(0.5f);
        back_light->MoveTo(light_pos * -1);
        back_light->SetType(Light::LIGHT_DIRECTIONAL);
        back_light->SetColor(Color::White);
        back_light->SetShadow(false);

        scene.AddLight(back_light);

        camview = new(__FILE__,__LINE__) CameraView(beauty, &cam, &scene);
        camview->SetProjectionType(Video::PROJECTION_PERSPECTIVE);
        camview->SetFieldOfView(2);

        beauty->AddView(camview);

        imgview = new(__FILE__,__LINE__) ImgView(beauty, 0);
        imgview->SetBlend(Video::BLEND_ALPHA);
    }
}
Пример #14
0
void MagicView::OnInitialUpdate() 
{
	CView::OnInitialUpdate();
   Color::SetPalette(standard_palette, 256, inverse_palette);

   if (!video_settings)
      video_settings = new VideoSettings;

   GetClientRect(&client_rect);

   // Use client area to set video window size
   int w = client_rect.right - client_rect.left;
   int h = client_rect.bottom - client_rect.top;

   video_settings->is_windowed   = true;
   video_settings->window_width  = w;
   video_settings->window_height = h;

   if (!video) {
      video = new VideoDX9(GetSafeHwnd(), video_settings);
      *video_settings = *video->GetVideoSettings();

      if (video) {
         Color::UseVideo(video);
         video->UseXFont("System", 12, false, false);

         screen = new Screen(video);
         if (!screen) {
            ::Print("ERROR: Could not create Screen object.\n");
            return;
         }

         ::Print("  Created screen object (%d x %d).\n", w, h);
   
         if (!screen->SetBackgroundColor(Color::Black))
            ::Print("  WARNING: could not set video background color to Black\n");

         screen->ClearAllFrames(true);

         ::Print("  Established requested video parameters.\n");
         ::Print("  ---------------------------------------\n\n");

         if (!scene) {
            scene = new Scene;

            scene->SetAmbient(Color(60,60,60));

            Point light_pos(3e6, 5e6, 4e6);

            main_light = new Light(1.0f); //1.25f);
            main_light->MoveTo(light_pos);
            main_light->SetType(Light::LIGHT_DIRECTIONAL);
            main_light->SetColor(Color::White);
            main_light->SetShadow(true);

            scene->AddLight(main_light);

            back_light = new Light(0.5f);
            back_light->MoveTo(light_pos * -1);
            back_light->SetType(Light::LIGHT_DIRECTIONAL);
            back_light->SetColor(Color::White);

            scene->AddLight(back_light);

            Selection*  seln     = GetDocument()->GetSelection();
            Selector*   selector = GetDocument()->GetSelector();

            if (seln && selector) {
               scene->Graphics().clear();
               scene->AddGraphic(seln);
               scene->AddGraphic(selector);

               selector->UseModel(0);
            }
         }

         int   mins[2]     = { 0, 0 };
         float weights[2]  = { 1, 1 };

         main_win = new ActiveWindow(screen, 0, 0, w, h, 100, 0);
         main_win->UseLayout(2, 2, mins, mins, weights, weights);
         main_win->SetBackColor(Color::Gray);

         screen->AddWindow(main_win);

         DWORD view_types[] = { 
            ModelView::VIEW_PLAN,
            ModelView::VIEW_PROJECT,
            ModelView::VIEW_SIDE,
            ModelView::VIEW_FRONT
         };

         for (int row = 0; row < 2; row++) {
            for (int col = 0; col < 2; col++) {
               int index = 2*row + col;

               ActiveWindow* win = new ActiveWindow(screen, 
                                                    col*w/2, 
                                                    row*h/2, 
                                                    w/2, 
                                                    h/2, 
                                                    101+index, 
                                                    WIN_BLACK_FRAME, 
                                                    main_win);

               win->SetCells(col, row, 1, 1);
               win->SetCellInsets(Insets(1,1,1,1));
               win->SetBackColor(Color(160,160,160));

               ModelView* mv = new ModelView(win, scene, view_types[index]);

               if (view_types[index] == ModelView::VIEW_PROJECT)
                  mv->SetFillMode(ModelView::FILL_TEXTURE);

               mv->UseGrid(grid);
               win->AddView(mv);

               view_win[index]   = win;
               model_view[index] = mv;
            }
         }

         view_win[0]->SetStyle(WIN_WHITE_FRAME);

         uvmap_win  = new ActiveWindow(screen, 0, 0, w, h, 110, WIN_BLACK_FRAME, main_win);
         uvmap_view = new UVMapView(uvmap_win);
         uvmap_win->AddView(uvmap_view);

         main_win->DoLayout();
      }

      else {
         ::Print("  Could not establish requested video parameters.\n");
         ::Print("  -----------------------------------------------\n\n");
      }
   }
}
Пример #15
0
int main() {
  GLFWwindow * window = initWindow(windowWidth, windowHeight);
  if (!window) {
    glfwTerminate();
    return -1;
  }
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  glfwSetKeyCallback(window, key_callback);
  glfwSetCursorPosCallback(window, cursor_callback);
  glfwSetScrollCallback(window, scroll_callback);
  glEnable(GL_DEPTH_TEST);

  // prepare an array of vertices
  GLfloat vertices[] = {
    // Positions          // normal vectors
    -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
     0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
    -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
    -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,

    -0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
     0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
    -0.5f,  0.5f,  0.5f,  0.0f,  0.0f, 1.0f,
    -0.5f, -0.5f,  0.5f,  0.0f,  0.0f, 1.0f,

    -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
    -0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
    -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
    -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
    -0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
    -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,

     0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
     0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
     0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
     0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
     0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
     0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,

    -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
     0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
     0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
     0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
    -0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
    -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,

    -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
     0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
     0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
    -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
    -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f
};
  glm::vec3 cubePositions[] = {
    glm::vec3( 0.0f,  0.0f,  0.0f),
    glm::vec3( 2.0f,  5.0f, -15.0f),
    glm::vec3(-1.5f, -2.2f, -2.5f),
    glm::vec3(-3.8f, -2.0f, -12.3f),
    glm::vec3( 2.4f, -0.4f, -3.5f),
    glm::vec3(-1.7f,  3.0f, -7.5f),
    glm::vec3( 1.3f, -2.0f, -2.5f),
    glm::vec3( 1.5f,  2.0f, -2.5f),
    glm::vec3( 1.5f,  0.2f, -1.5f),
    glm::vec3(-1.3f,  1.0f, -1.5f)
  };

  GLuint lightVAO;
  glGenVertexArrays(1, &lightVAO);
  glBindVertexArray(lightVAO);

  GLuint lightVBO;
  glGenBuffers(1, &lightVBO);
  glBindBuffer(GL_ARRAY_BUFFER, lightVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),
                       (void*)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);

  glBindVertexArray(0);

  Shader shaders("shader.vert", "shader.frag");
  Shader lightShaders("lightShader.vert", "lightShader.frag");

  double last_frame = glfwGetTime();
  while (!glfwWindowShouldClose(window)) {
    double current_frame = glfwGetTime();
    double delta_time = current_frame - last_frame;
    last_frame = current_frame;

    glfwPollEvents();

    do_movement(delta_time);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    GLfloat light_pos_angle = glm::radians(60.0f * current_frame);
    glm::vec3 light_pos(1.2f + sin(light_pos_angle), 1.0f, 2.0f + cos(light_pos_angle));

    // draw common container
    shaders.Use();

    glm::mat4 view = camera.GetViewMatrix();
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom),
                                (GLfloat)windowWidth / (GLfloat)windowHeight,
                                0.01f, 1000.0f);
    shaders.SetUniform("view", view);
    shaders.SetUniform("projection", projection);
    shaders.SetUniform("objectColor", glm::vec3(1.0f, 0.5f, 0.31f));
    shaders.SetUniform("lightColor", glm::vec3(1.0f, 1.0f, 1.0f));
    shaders.SetUniform("lightPos", light_pos);

    glm::mat4 model = glm::translate(glm::mat4(), cubePositions[0]);
    model = glm::rotate(model, (GLfloat)glm::radians(60.0f * current_frame),
                        glm::vec3(1.0f, 1.0f, 1.0f));
    glm::mat3 normalMatrix = glm::mat3(view *glm::transpose(glm::inverse(model)));
    shaders.SetUniform("model", model);
    shaders.SetUniform("normalMatrix", normalMatrix);
    glBindVertexArray(lightVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);

    // draw lamp
    lightShaders.Use();

    model = glm::scale(glm::translate(glm::mat4(), light_pos), glm::vec3(0.2f));

    lightShaders.SetUniform("view", view);
    lightShaders.SetUniform("projection", projection);
    lightShaders.SetUniform("model", model);

    glBindVertexArray(lightVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);

    glfwSwapBuffers(window);
  }

  glfwTerminate();
  return 0;
}