Exemplo n.º 1
0
mat4
FbxParser::loadFbx(char * url)
{
	std::string err;
	bool ret_fbx = LoadFbx(fbxHandles, shapes, materials, err, url);
	shapeCount = shapes.size();
	if (ret_fbx) {
		// For Each Material
		texture = new GLuint[materials.size()];
		for (int i = 0; i < materials.size(); i++) {
			int iter;
			for (iter = strlen(materials[i].diffuse_texname.c_str()) - 1; iter >= -1; iter--)
			{
				char dick = materials[i].diffuse_texname.c_str()[iter];
				if (dick ==  '\\'|| dick == '/')
				{
					break;
				}
			}
			texture[i] = loadTexture(materials[i].diffuse_texname.c_str()+iter+1);
		}
		// For Each Shape (or Mesh, Object)
		vao = new GLuint[shapes.size()];
		positionBuffer = new GLuint[shapes.size()];
		normalBuffer = new GLuint[shapes.size()];
		textureCoordinateBuffer = new GLuint[shapes.size()];
		indexBuffer = new GLuint[shapes.size()];
		group = new std::vector<GROUP>[shapes.size()];
		for (int i = 0; i < shapes.size(); i++)
		{
			glGenVertexArrays(1, &vao[i]);
			glBindVertexArray(vao[i]);
			glGenBuffers(1, &positionBuffer[i]);
			glBindBuffer(GL_ARRAY_BUFFER, positionBuffer[i]);
			glBufferData(GL_ARRAY_BUFFER, shapes[i].mesh.positions.size() * sizeof(float), 0, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, shapes[i].mesh.positions.size() * sizeof(float), shapes[i].mesh.positions.data());
			glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
			glEnableVertexAttribArray(0);

			glGenBuffers(1, &normalBuffer[i]);
			glBindBuffer(GL_ARRAY_BUFFER, normalBuffer[i]);
			glBufferData(GL_ARRAY_BUFFER, shapes[i].mesh.normals.size() * sizeof(float), 0, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, shapes[i].mesh.normals.size() * sizeof(float), shapes[i].mesh.normals.data());
			glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
			glEnableVertexAttribArray(1);

			glGenBuffers(1, &textureCoordinateBuffer[i]);
			glBindBuffer(GL_ARRAY_BUFFER, textureCoordinateBuffer[i]);
			glBufferData(GL_ARRAY_BUFFER, shapes[i].mesh.texcoords.size() * sizeof(float), 0, GL_STATIC_DRAW);
			glBufferSubData(GL_ARRAY_BUFFER, 0, shapes[i].mesh.texcoords.size() * sizeof(float), shapes[i].mesh.texcoords.data());
			glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0);
			glEnableVertexAttribArray(2);

			glGenBuffers(1, &indexBuffer[i]);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer[i]);
			glBufferData(GL_ELEMENT_ARRAY_BUFFER, shapes[i].mesh.indices.size() * sizeof(unsigned int), 0, GL_STATIC_DRAW);
			glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, shapes[i].mesh.indices.size() * sizeof(unsigned int), shapes[i].mesh.indices.data());
			unsigned int tempMaterialIds = shapes[i].mesh.material_ids[0];
			for (int j = 0; j < shapes[i].mesh.material_ids.size(); j++) {
				if (shapes[i].mesh.material_ids[j] != tempMaterialIds) {
					group[i].push_back(GROUP{ j * 3, tempMaterialIds });
					tempMaterialIds = shapes[i].mesh.material_ids[j];
				}
			}
			group[i].push_back(GROUP{ (int)(shapes[i].mesh.material_ids.size() * 3), tempMaterialIds });
		}
	}
	normalizeMatrix = getNormalizeMatrix(shapes);
	return normalizeMatrix;
}
Exemplo n.º 2
0
bool loadMedia()
{
    bool success = true;

    // Load circle texture
    if(!gCircleTexture.loadFromFile("images/circle.png")) {
        printf("Failed to load Circle texture image\n!");
        success = false;
    }

    // Load background texture
    if(!gBackgroundTexture.loadFromFile("images/background.png")) {
        printf("Failed to load Background texture image\n!");
        success = false;
    }

    // Load default surface
    gKeyPressTextures[ KEY_PRESS_SURFACE_DEFAULT ] = loadTexture("images/press.bmp");
    if( gKeyPressTextures[ KEY_PRESS_SURFACE_DEFAULT ] == NULL )
    {
        printf( "Failed to load default image!\n" );
        success = false;
    }

    // Load up surface
    gKeyPressTextures[KEY_PRESS_SURFACE_UP] = loadTexture("images/up.bmp");
    if (gKeyPressTextures[KEY_PRESS_SURFACE_UP] == NULL )
    {
        printf("Failed to load up image!\n");
        success = false;
    }

    // Load down surface
    gKeyPressTextures[KEY_PRESS_SURFACE_DOWN] = loadTexture("images/down.bmp");
    if (gKeyPressTextures[KEY_PRESS_SURFACE_DOWN] == NULL )
    {
        printf("Failed to load down image!\n");
        success = false;
    }

    // Load left surface
    gKeyPressTextures[KEY_PRESS_SURFACE_LEFT] = loadTexture("images/left.bmp");
    if (gKeyPressTextures[KEY_PRESS_SURFACE_LEFT] == NULL )
    {
        printf("Failed to load left image!\n");
        success = false;
    }

    // Load left surface
    gKeyPressTextures[KEY_PRESS_SURFACE_RIGHT] = loadTexture("images/right.bmp");
    if (gKeyPressTextures[KEY_PRESS_SURFACE_RIGHT] == NULL )
    {
        printf("Failed to load right image!\n");
        success = false;
    }

    // Load colors surface
    gKeyPressTextures[KEY_PRESS_SURFACE_SPACE] = loadTexture("images/colors.bmp");
    if (gKeyPressTextures[KEY_PRESS_SURFACE_SPACE] == NULL )
    {
        printf("Failed to load colors (space) image!\n");
        success = false;
    }
    return success;
}
Exemplo n.º 3
0
/*!
SLAssimpImporter::loadMaterial loads the AssImp material an returns the SLMaterial.
The materials and textures are added to the SLScene material and texture 
vectors.
*/
SLMaterial* SLAssimpImporter::loadMaterial(SLint index, 
                                           aiMaterial *material,
                                           SLstring modelPath)
{
    // Get the materials name
    aiString matName;
    material->Get(AI_MATKEY_NAME, matName);
    SLstring name = matName.data;
    if (name.empty()) name = "Import Material";
   
    // Create SLMaterial instance. It is also added to the SLScene::_materials vector
    SLMaterial* mat = new SLMaterial(name.c_str());

    // set the texture types to import into our material
    const SLint		textureCount = 4;
    aiTextureType	textureTypes[textureCount];
    textureTypes[0] = aiTextureType_DIFFUSE;
    textureTypes[1] = aiTextureType_NORMALS;
    textureTypes[2] = aiTextureType_SPECULAR;
    textureTypes[3] = aiTextureType_HEIGHT;
   
    // load all the textures for this material and add it to the material vector
    for(SLint i = 0; i < textureCount; ++i) 
    {   if(material->GetTextureCount(textureTypes[i]) > 0) 
        {   aiString aipath;
            material->GetTexture(textureTypes[i], 0, &aipath, nullptr, nullptr, nullptr, nullptr, nullptr);
            SLTextureType texType = textureTypes[i]==aiTextureType_DIFFUSE  ? TT_color :
                                textureTypes[i]==aiTextureType_NORMALS  ? TT_normal :
                                textureTypes[i]==aiTextureType_SPECULAR ? TT_gloss :
                                textureTypes[i]==aiTextureType_HEIGHT   ? TT_height : 
                                TT_unknown;
            SLstring texFile = checkFilePath(modelPath, aipath.data);
            SLGLTexture* tex = loadTexture(texFile, texType);
            mat->textures().push_back(tex);
        }
    }
   
    // get color data
    aiColor3D ambient, diffuse, specular, emissive;
    SLfloat shininess, refracti, reflectivity, opacity;
    material->Get(AI_MATKEY_COLOR_AMBIENT, ambient);
    material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse);
    material->Get(AI_MATKEY_COLOR_SPECULAR, specular);
    material->Get(AI_MATKEY_COLOR_EMISSIVE, emissive);
    material->Get(AI_MATKEY_SHININESS, shininess);
    material->Get(AI_MATKEY_REFRACTI, refracti);
    material->Get(AI_MATKEY_REFLECTIVITY, reflectivity);
    material->Get(AI_MATKEY_OPACITY, opacity);

    // increase shininess if specular color is not low.
    // The material will otherwise be to bright
    if (specular.r > 0.5f &&
        specular.g > 0.5f &&
        specular.b > 0.5f &&
        shininess < 0.01f)
        shininess = 10.0f;

    // set color data
    mat->ambient(SLCol4f(ambient.r, ambient.g, ambient.b));
    mat->diffuse(SLCol4f(diffuse.r, diffuse.g, diffuse.b));
    mat->specular(SLCol4f(specular.r, specular.g, specular.b));
    mat->emission(SLCol4f(emissive.r, emissive.g, emissive.b));
    mat->shininess(shininess);
    //mat->kr(reflectivity);
    //mat->kt(1.0f-opacity);
    //mat->kn(refracti);

    return mat;
}
Exemplo n.º 4
0
int loadMTL(struct OBJ_Model * obj,char * directory,char *filename)
{
  fprintf(stderr,"loadMTL(%s , directory = %s , filename = %s ) \n",obj->filename , directory ,filename );
  FILE *file;
  char buf[128];
  char buf1[128];
  //Not Used : ? GLuint tex_id;
  GLuint mat_num;
  float   r,g,b;
 unsigned int i;


  char fname[2*MAX_MODEL_PATHS+2];
  strncpy(fname,directory,MAX_MODEL_PATHS);
  strcat(fname,"/");
  strncat(fname,filename,MAX_MODEL_PATHS);


  mat_num = 1;

  if((file=fopen(fname,"r"))==0) { printf("File %s is corrupt or does not exist.\n",fname); return 0; }

  rewind(file);
	//1st pass - count materials

	while(!feof(file))
	{
		buf[0] = 0;// ? NULL;
		fscanf(file,"%s", buf);

		if (!strcmp(buf,"newmtl")) { mat_num ++; } else
		                           { fgets(buf, sizeof(buf), file); }
	}

	if (mat_num == 0) mat_num = 1;
	obj->matList=(Material*)malloc(sizeof(Material)*(mat_num));
    if (obj->matList==0) { fprintf(stderr,"Could not make enough space for %u materials \n",mat_num); }

    obj->numMaterials = mat_num;
  /* set the default material */

  for(i = 0; i<mat_num; i++)
  {
	obj->matList[i].shine[0] = 0.0;
	obj->matList[i].diffuse[0] = 0.8;
	obj->matList[i].diffuse[1] = 0.8;
	obj->matList[i].diffuse[2] = 0.8;
	obj->matList[i].diffuse[3] = 1.0;
	obj->matList[i].ambient[0] = 0.2;
	obj->matList[i].ambient[1] = 0.2;
	obj->matList[i].ambient[2] = 0.2;
	obj->matList[i].ambient[3] = 1.0;
	obj->matList[i].specular[0] = 0.0;
	obj->matList[i].specular[1] = 0.0;
	obj->matList[i].specular[2] = 0.0;
	obj->matList[i].specular[3] = 1.0;
	obj->matList[i].ldText = 0;
	obj->matList[i].hasTex = 0;
  }//give default values
  strcpy(obj->matList[0].name,"default");
  strcpy(obj->matList[0].texture,"");

  rewind(file);

  mat_num = 0;

  while(!feof(file))
	{
		buf[0] = 0;//? NULL;
		fscanf(file,"%s", buf);

		if (!strcmp(buf,"newmtl"))
		{
			fscanf(file,"%s",buf1);
			mat_num ++;

			strcpy(obj->matList[mat_num].name, buf1);
			obj->matList[mat_num].hasTex =  0;
		} else
		if (!strcmp(buf,"Ka"))
		{
			obj->matList[mat_num].ambient[3] =  1;
			fscanf(file,"%f %f %f",&obj->matList[mat_num].ambient[0], &obj->matList[mat_num].ambient[1],&obj->matList[mat_num].ambient[2]);
		} else
		if (!strcmp(buf,"Kd"))
		{
			fscanf(file,"%f %f %f",&r,&g,&b);
			obj->matList[mat_num].diffuse[0] =  r;
			obj->matList[mat_num].diffuse[1] =  g;
			obj->matList[mat_num].diffuse[2] =  b;
			obj->matList[mat_num].diffuse[3] =  1;
		} else
		if (!strcmp(buf,"Ks"))
		{
			fscanf(file,"%f %f %f",&r,&g,&b);
			obj->matList[mat_num].specular[0] =  r;
			obj->matList[mat_num].specular[1] =  g;
			obj->matList[mat_num].specular[2] =  b;
			obj->matList[mat_num].specular[3] =  1;
		} else
		if (!strcmp(buf,"Ns"))
		{
			fscanf(file,"%f",&r);
			obj->matList[mat_num].shine[0] =  r;
		} else
		if(!strcmp(buf, "map_Kd"))
		{
			fscanf(file,"%s",obj->matList[mat_num].texture);
			obj->matList[mat_num].hasTex =  1;
		    obj->matList[mat_num].ldText = loadTexture(GL_LINEAR , obj->directory , obj->matList[mat_num].texture);
			printf("%d \t   \n\n", obj->matList[mat_num].ldText);
			printf("%s \t   \n\n", obj->matList[mat_num].texture);
		} else
		if (!strcmp(buf,"#"))
			fgets(buf,100,file);

	}

	if (file) fclose(file);
	return 1;
}
Exemplo n.º 5
0
int main() {
  // Initialize GLFW and set some hints that will create an OpenGL 3.3 context
  // using core profile.
  glfwInit();
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_SAMPLES, 4);
  glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

  // Create a fixed 800x600 window that is not resizable.
  GLFWwindow* window = glfwCreateWindow(kWindowWidth, kWindowHeight, "LearnGL", nullptr, nullptr);
  if (window == nullptr) {
    std::cerr << "Failed to created GLFW window" << std::endl;
    glfwTerminate();
    return 1;
  }

  // Create an OpenGL context and pass callbacks to GLFW.
  glfwMakeContextCurrent(window);
  glfwSetKeyCallback(window, keyCallback);
  glfwSetCursorPosCallback(window, mouseCallback);
  glfwSetScrollCallback(window, scrollCallback);

  // Lock the mouse in the window.
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

  glewExperimental = GL_TRUE;
  if (glewInit() != GLEW_OK) {
    std::cerr << "Failed to initialize GLEW" << std::endl;
    glfwTerminate();
    return 1;
  }

  // Create a viewport the same size as the window. glfwGetFramebufferSize is
  // used rather than the size constants since some windowing systems have a
  // discrepancy between window size and framebuffer size
  // (e.g HiDPi screen coordinates),
  int fbWidth, fbHeight;
  glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
  glViewport(0, 0, fbWidth, fbHeight);

  // Enable multisampling for using MSAA.
  glEnable(GL_MULTISAMPLE);

  // Enabled SRGB for gamma correction.
  glEnable(GL_FRAMEBUFFER_SRGB);

  // Enable use of the depth buffer since we're working on 3D and want to
  // prevent overlapping polygon artifacts.
  glEnable(GL_DEPTH_TEST);

  // Read and compile the vertex and fragment shaders using
  // the shader helper class.
  shader = Shader("glsl/vertex.glsl", "glsl/fragment.glsl", "glsl/geometry.glsl");
  depthShader = Shader("glsl/depth_vert.glsl", "glsl/depth_frag.glsl");
  postShader = Shader("glsl/post_vert.glsl", "glsl/post_frag.glsl");

  containerTexture  = loadTexture("assets/container2.png");
  containerSpecular = loadTexture("assets/container2_specular.png");
  containerEmission = loadTexture("assets/matrix.jpg");

  // Container mesh data.
  GLfloat vertices[] = {
    // Vertices          // Normals           // UVs
    -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
  };

  // Points for the geometry shader tutorial.
  GLfloat points[] = {
    -0.5f,  0.5f, 1.0f, 0.0f, 0.0f, // Top-left
     0.5f,  0.5f, 0.0f, 1.0f, 0.0f, // Top-right
     0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
    -0.5f, -0.5f, 1.0f, 1.0f, 0.0f  // Bottom-left
  };

  // Create and bind a framebuffer.
  GLuint FBO;
  glGenFramebuffers(1, &FBO);
  glBindFramebuffer(GL_FRAMEBUFFER, FBO);

  // Create an empty texture to be attached to the framebuffer.
  // Give a null pointer to glTexImage2D since we want an empty texture.
  GLuint frameColorBufferMultiSampled;
  glGenTextures(1, &frameColorBufferMultiSampled);
  glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, frameColorBufferMultiSampled);
  glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, kMSAASamples, GL_RGB,
      fbWidth, fbHeight, GL_TRUE);
  glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);

  // Attach the texture to the framebuffer.
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
      GL_TEXTURE_2D_MULTISAMPLE, frameColorBufferMultiSampled, 0);

  // Create a renderbuffer to hold our depth and stencil buffers with a size
  // of the window's framebuffer size.
  GLuint RBO;
  glGenRenderbuffers(1, &RBO);
  glBindRenderbuffer(GL_RENDERBUFFER, RBO);
  glRenderbufferStorageMultisample(GL_RENDERBUFFER, kMSAASamples,
      GL_DEPTH24_STENCIL8, fbWidth, fbHeight);
  glBindRenderbuffer(GL_RENDERBUFFER, 0);

  // Attach the render buffer (provides depth and stencil) to the framebuffer.
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT,
      GL_RENDERBUFFER, RBO);

  // Panic if the framebuffer is somehow incomplete at this stage. This should
  // never happen if we attached the texture but it's good practice to check.
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    std::cerr << "ERROR: Framebuffer is not complete!" << std::endl;
    glfwTerminate();
    return 1;
  }
  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  // Generate texture for intermediate stage.
  GLuint screenTexture;
  glGenTextures(1, &screenTexture);
  glBindTexture(GL_TEXTURE_2D, screenTexture);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fbWidth, fbHeight, 0, GL_RGB,
      GL_UNSIGNED_BYTE, nullptr);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glBindTexture(GL_TEXTURE_2D, 0);

  // Second framebuffer for post.
  GLuint intermediateFBO;
  glGenFramebuffers(1, &intermediateFBO);
  glBindFramebuffer(GL_FRAMEBUFFER, intermediateFBO);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
      screenTexture, 0);

  // Panic if the framebuffer is somehow incomplete at this stage. This should
  // never happen if we attached the texture but it's good practice to check.
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    std::cerr << "ERROR: Framebuffer is not complete!" << std::endl;
    glfwTerminate();
    return 1;
  }
  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  // Create a texture to hold the depth map data.
  // The depth map is used for shadow mapping.
  GLuint depthMap;
  glGenTextures(1, &depthMap);
  glBindTexture(GL_TEXTURE_2D, depthMap);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, kShadowWidth,
      kShadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
  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.0, 1.0, 1.0, 1.0 };
  glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
  glBindTexture(GL_TEXTURE_2D, 0);

  GLuint depthMapFBO;
  glGenFramebuffers(1, &depthMapFBO);
  glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthMap, 0);
  glDrawBuffer(GL_NONE);
  glReadBuffer(GL_NONE);

  // Panic if the framebuffer is somehow incomplete at this stage. This should
  // never happen if we attached the texture but it's good practice to check.
  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    std::cerr << "ERROR: Framebuffer is not complete!" << std::endl;
    glfwTerminate();
    return 1;
  }
  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  // Create a VBO to store the vertex data, an EBO to store indice data, and
  // create a VAO to retain our vertex attribute pointers.
  GLuint VBO, VAO;
  glGenVertexArrays(1, &VAO);
  glGenBuffers(1, &VBO);

  // Fill the VBO and set vertex attributes.
  glBindVertexArray(VAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
  glEnableVertexAttribArray(2);
  glBindVertexArray(0);

  // Create a lamp box thing using the existing container VBO.
  GLuint lightVAO;
  glGenVertexArrays(1, &lightVAO);

  // Use the container's VBO and set vertex attributes.
  glBindVertexArray(lightVAO);
  glBindBuffer(GL_ARRAY_BUFFER, VBO);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glBindVertexArray(0);

  // Vertex attributes for the frame quad in NDC.
  GLfloat frameVertices[] = {
    // Positions  // UVs
    -1.0f,  1.0f,  0.0f, 1.0f,
    -1.0f, -1.0f,  0.0f, 0.0f,
     1.0f, -1.0f,  1.0f, 0.0f,

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

  // Create a VBO and VAO for the post-processing step.
  GLuint frameVBO, frameVAO;
  glGenVertexArrays(1, &frameVAO);
  glGenBuffers(1, &frameVBO);

  glBindVertexArray(frameVAO);
  glBindBuffer(GL_ARRAY_BUFFER, frameVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(frameVertices), frameVertices,
      GL_STATIC_DRAW);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
      (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat),
      (GLvoid*)(2 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glBindVertexArray(0);

  // Create a VBO and VAO for the geometry shader test. The VBO will contain
  // only the position.
  GLuint pointsVBO, pointsVAO;
  glGenVertexArrays(1, &pointsVAO);
  glGenBuffers(1, &pointsVBO);

  glBindVertexArray(pointsVAO);
  glBindBuffer(GL_ARRAY_BUFFER, pointsVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat),
      (GLvoid*)0);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat),
      (GLvoid*)(2 * sizeof(GLfloat)));
  glEnableVertexAttribArray(1);
  glBindVertexArray(0);

  // Create a perspective camera to fit the viewport.
  screenWidth = (GLfloat)fbWidth;
  screenHeight = (GLfloat)fbHeight;
  camera = PerspectiveCamera(
      glm::vec3(0.0f, 0.0f, 3.0f),
      glm::vec3(0.0f, glm::radians(-90.0f), 0.0f),
      glm::radians(45.0f),
      screenWidth / screenHeight,
      0.1f,
      100.0f
  );

  GLfloat delta = 0.0f;
  GLfloat lastFrame = 0.0f;

  // Render loop.
  while (!glfwWindowShouldClose(window)) {
    GLfloat currentFrame = glfwGetTime();
    delta = currentFrame - lastFrame;
    lastFrame = currentFrame;

    // Check and call events.
    glfwPollEvents();
    move(delta);

    // Use the depth shader and set the required uniforms. The depth shader uses
    // a special lightSpaceMatrix with an orthographic projection looking at the
    // specific mesh to cast a shadow for.
    //
    // Render to the depth map for shadow mapping.
    glViewport(0, 0, kShadowWidth, kShadowHeight);
    glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
    glClear(GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    depthShader.use();
    drawContainers(VBO, depthShader, true, 0);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // Bind the off screen framebuffer (for post-processing) and clear the
    // screen to a nice blue color.
    glViewport(0, 0, fbWidth, fbHeight);
    glBindFramebuffer(GL_FRAMEBUFFER, FBO);
    glClearColor(0.1f, 0.15f, 0.15f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);

    // Update the time counter for the camera zoom.
    const GLfloat limitTime = 1.0f;
    fovTime += delta;
    if (fovTime > limitTime) {
      fovTime = limitTime;
    }

    // Update the perspective to account for changes in fov.
    // Used by the scroll to zoom feature.
    camera.fov = easeOutQuart(fovTime, startFov, (startFov - targetFov) * -1, limitTime);
    camera.update();

    shader.use();
    setupMatrices();
    drawContainers(VBO, shader, false, depthMap);

    glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, intermediateFBO);
    glBlitFramebuffer(0, 0, fbWidth, fbHeight, 0, 0, fbWidth, fbHeight,
        GL_COLOR_BUFFER_BIT, GL_NEAREST);

    // Unbind the offscreen framebuffer containing the unprocessed frame.
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisable(GL_DEPTH_TEST);

    postShader.use();
    glBindVertexArray(frameVAO);

    // Send the texture sampler to the shader.
    GLuint frameTexture = glGetUniformLocation(postShader.program, "frameTexture");
    glUniform1i(frameTexture, 0);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, screenTexture);

    // Render the color buffer in the framebuffer to the quad with post shader.
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);

    // Swap buffers used for double buffering.
    glfwSwapBuffers(window);
  }

  // Destroy the off screen framebuffer.
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glDeleteFramebuffers(1, &FBO);

  // Properly deallocate the VBO and VAO.
  glDeleteVertexArrays(1, &VAO);
  glDeleteBuffers(1, &VBO);

  // Terminate GLFW and clean any resources before exiting.
  glfwTerminate();

  return 0;
}
Exemplo n.º 6
0
int objloader::load(const char* filename)
{
	std::ifstream in(filename);
	if(!in.is_open())
	{
		std::cout << "Nor oepened" << std::endl;
		return -1;
	}
	char buf[256];
	int curmat=0;
	while(!in.eof())
	{
		in.getline(buf,256);
		coord.push_back(new std::string(buf));
	}
	for(int i=0;i<coord.size();i++)
	{
		if((*coord[i])[0]=='#')
			continue;
		else if((*coord[i])[0]=='v' && (*coord[i])[1]==' ')
		{
			float tmpx,tmpy,tmpz;
			sscanf(coord[i]->c_str(),"v %f %f %f",&tmpx,&tmpy,&tmpz);
			vertex.push_back(new coordinate(tmpx,tmpy,tmpz));
		}else if((*coord[i])[0]=='v' && (*coord[i])[1]=='n')
		{
			float tmpx,tmpy,tmpz;
			sscanf(coord[i]->c_str(),"vn %f %f %f",&tmpx,&tmpy,&tmpz);
			normals.push_back(new coordinate(tmpx,tmpy,tmpz));	
		}else if((*coord[i])[0]=='f')
		{
			int a,b,c,d,e;
			if(count(coord[i]->begin(),coord[i]->end(),' ')==4)
			{
				if(coord[i]->find("//")!=std::string::npos)
				{
					sscanf(coord[i]->c_str(),"f %d//%d %d//%d %d//%d %d//%d",&a,&b,&c,&b,&d,&b,&e,&b);
					faces.push_back(new face(b,a,c,d,e,0,0,0,0,curmat));
				}else if(coord[i]->find("/")!=std::string::npos)
				{
					int t[4];
					sscanf(coord[i]->c_str(),"f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d",&a,&t[0],&b,&c,&t[1],&b,&d,&t[2],&b,&e,&t[3],&b);
					faces.push_back(new face(b,a,c,d,e,t[0],t[1],t[2],t[3],curmat));
				}else{
					sscanf(coord[i]->c_str(),"f %d %d %d %d",&a,&b,&c,&d);
					faces.push_back(new face(-1,a,b,c,d,0,0,0,0,curmat));					
				}
			}else{
					if(coord[i]->find("//")!=std::string::npos)
					{
						sscanf(coord[i]->c_str(),"f %d//%d %d//%d %d//%d",&a,&b,&c,&b,&d,&b);
						faces.push_back(new face(b,a,c,d,0,0,0,curmat));
					}else if(coord[i]->find("/")!=std::string::npos)
					{
						int t[3];
						sscanf(coord[i]->c_str(),"f %d/%d/%d %d/%d/%d %d/%d/%d",&a,&t[0],&b,&c,&t[1],&b,&d,&t[2],&b);
						faces.push_back(new face(b,a,c,d,t[0],t[1],t[2],curmat));
					}else{
						sscanf(coord[i]->c_str(),"f %d %d %d",&a,&b,&c);
						faces.push_back(new face(-1,a,b,c,0,0,0,curmat));					
					}
			}
	}else if((*coord[i])[0]=='u' && (*coord[i])[1]=='s' && (*coord[i])[2]=='e')
	{
		char tmp[200];
		sscanf(coord[i]->c_str(),"usemtl %s",tmp);
		for(int i=0;i<materials.size();i++)
		{
			if(strcmp(materials[i]->name.c_str(),tmp)==0)
			{
				curmat=i;
				break;
			}
		}
	}else if((*coord[i])[0]=='m' && (*coord[i])[1]=='t' && (*coord[i])[2]=='l' && (*coord[i])[3]=='l')
	{
		char filen[200];
		sscanf(coord[i]->c_str(),"mtllib %s",filen);
		std::ifstream mtlin(filen);
		if(!mtlin.is_open())
		{
			std::cout << "connot open the material file" << std::endl;
			clean();
			return -1;
		}
		ismaterial=true;
		std::vector<std::string> tmp;
		char c[200];
		while(!mtlin.eof())
		{
			mtlin.getline(c,200);
			tmp.push_back(c);
		}
		char name[200];
		char filename[200];
		float amb[3],dif[3],spec[3],alpha,ns,ni;
		int illum;
		unsigned int texture;
		bool ismat=false;
		strcpy(filename,"\0");
		std::cout << tmp.size() << std::endl;
		for(int i=0;i<tmp.size();i++)
		{
			if(tmp[i][0]=='#')
				continue;
			if(tmp[i][0]=='n' && tmp[i][1]=='e' && tmp[i][2]=='w')
			{
				if(ismat)
				{
					if(strcmp(filename,"\0")!=0)
					{
						materials.push_back(new material(name,alpha,ns,ni,dif,amb,spec,illum,texture));
						strcpy(filename,"\0");
					}else{
							materials.push_back(new material(name,alpha,ns,ni,dif,amb,spec,illum,-1));				
					}
				}
				ismat=false;
				sscanf(tmp[i].c_str(),"newmtl %s",name);
			}else if(tmp[i][0]=='N' && tmp[i][1]=='s')
			{
				sscanf(tmp[i].c_str(),"Ns %f",&ns);
				ismat=true;
			}else if(tmp[i][0]=='K' && tmp[i][1]=='a')
			{
				sscanf(tmp[i].c_str(),"Ka %f %f %f",&amb[0],&amb[1],&amb[2]);
				ismat=true;
			}else if(tmp[i][0]=='K' && tmp[i][1]=='d')
			{
				sscanf(tmp[i].c_str(),"Kd %f %f %f",&dif[0],&dif[1],&dif[2]);
				ismat=true;
			}else if(tmp[i][0]=='K' && tmp[i][1]=='s')
			{
				sscanf(tmp[i].c_str(),"Ks %f %f %f",&spec[0],&spec[1],&spec[2]);
				ismat=true;
			}else if(tmp[i][0]=='N' && tmp[i][1]=='i')
			{
				sscanf(tmp[i].c_str(),"Ni %f",&ni);
				ismat=true;
			}else if(tmp[i][0]=='d' && tmp[i][1]==' ')
			{
				sscanf(tmp[i].c_str(),"d %f",&alpha);
				ismat=true;
			}else if(tmp[i][0]=='i' && tmp[i][1]=='l')
			{
				sscanf(tmp[i].c_str(),"illum %d",&illum);
				ismat=true;
			}else if(tmp[i][0]=='m' && tmp[i][1]=='a')
			{
				sscanf(tmp[i].c_str(),"map_Kd %s",filename);
				texture=loadTexture(filename);
				ismat=true;
			}
		}
				if(ismat)
				{
					if(strcmp(filename,"\0")!=0)
					{
						materials.push_back(new material(name,alpha,ns,ni,dif,amb,spec,illum,texture));
					}else{
							materials.push_back(new material(name,alpha,ns,ni,dif,amb,spec,illum,-1));				
					}
				}
	}else if((*coord[i])[0]=='v' && (*coord[i])[1]=='t')
	{
		float u,v;
		sscanf(coord[i]->c_str(),"vt %f %f",&u,&v);
		texturecoordinate.push_back(new texcoord(u,1-v));
		istexture=true;
	}
}
	if(materials.size()==0)
		ismaterial=false;
	else
		ismaterial=true;
	std::cout << vertex.size() << " " << normals.size() << " " << faces.size() << " " << materials.size() << std::endl; 
	//draw
	if(isvertexnormal)
		smoothnormals();
	int num;
	num=glGenLists(1);
	glNewList(num,GL_COMPILE);
	int last=-1;
	for(int i=0;i<faces.size();i++)
	{
		if(last!=faces[i]->mat && ismaterial)
		{
			float diffuse[]={materials[faces[i]->mat]->dif[0],materials[faces[i]->mat]->dif[1],materials[faces[i]->mat]->dif[2],1.0};
			float ambient[]={materials[faces[i]->mat]->amb[0],materials[faces[i]->mat]->amb[1],materials[faces[i]->mat]->amb[2],1.0};
			float specular[]={materials[faces[i]->mat]->spec[0],materials[faces[i]->mat]->spec[1],materials[faces[i]->mat]->spec[2],1.0};
			glMaterialfv(GL_FRONT,GL_DIFFUSE,diffuse);
			glMaterialfv(GL_FRONT,GL_AMBIENT,ambient);
			glMaterialfv(GL_FRONT,GL_SPECULAR,specular);
			glMaterialf(GL_FRONT,GL_SHININESS,materials[faces[i]->mat]->ns);
			last=faces[i]->mat;
			if(materials[faces[i]->mat]->texture==-1)
				glDisable(GL_TEXTURE_2D);
			else{
				glEnable(GL_TEXTURE_2D);
				glBindTexture(GL_TEXTURE_2D,materials[faces[i]->mat]->texture);
			}
		}
		if(faces[i]->four)
		{
			glBegin(GL_QUADS);
				glNormal3f(normals[faces[i]->facenum-1]->x,normals[faces[i]->facenum-1]->y,normals[faces[i]->facenum-1]->z);
				
				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[0]-1]->u,texturecoordinate[faces[i]->texcoord[0]-1]->v);

				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[0]-1]->x,vertexnormals[faces[i]->faces[0]-1]->y,vertexnormals[faces[i]->faces[0]-1]->z);

				
				glVertex3f(vertex[faces[i]->faces[0]-1]->x,vertex[faces[i]->faces[0]-1]->y,vertex[faces[i]->faces[0]-1]->z);
				
				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[1]-1]->u,texturecoordinate[faces[i]->texcoord[1]-1]->v);


				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[1]-1]->x,vertexnormals[faces[i]->faces[1]-1]->y,vertexnormals[faces[i]->faces[1]-1]->z);
				
				glVertex3f(vertex[faces[i]->faces[1]-1]->x,vertex[faces[i]->faces[1]-1]->y,vertex[faces[i]->faces[1]-1]->z);
				
				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[2]-1]->u,texturecoordinate[faces[i]->texcoord[2]-1]->v);

				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[2]-1]->x,vertexnormals[faces[i]->faces[2]-1]->y,vertexnormals[faces[i]->faces[2]-1]->z);

				glVertex3f(vertex[faces[i]->faces[2]-1]->x,vertex[faces[i]->faces[2]-1]->y,vertex[faces[i]->faces[2]-1]->z);
				
				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[3]-1]->u,texturecoordinate[faces[i]->texcoord[3]-1]->v);

				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[3]-1]->x,vertexnormals[faces[i]->faces[3]-1]->y,vertexnormals[faces[i]->faces[3]-1]->z);
			
				glVertex3f(vertex[faces[i]->faces[3]-1]->x,vertex[faces[i]->faces[3]-1]->y,vertex[faces[i]->faces[3]-1]->z);
			glEnd();
		}else{
			glBegin(GL_TRIANGLES);
				glNormal3f(normals[faces[i]->facenum-1]->x,normals[faces[i]->facenum-1]->y,normals[faces[i]->facenum-1]->z);

				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[0]-1]->u,texturecoordinate[faces[i]->texcoord[0]-1]->v);

				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[0]-1]->x,vertexnormals[faces[i]->faces[0]-1]->y,vertexnormals[faces[i]->faces[0]-1]->z);


				glVertex3f(vertex[faces[i]->faces[0]-1]->x,vertex[faces[i]->faces[0]-1]->y,vertex[faces[i]->faces[0]-1]->z);
				
				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[1]-1]->u,texturecoordinate[faces[i]->texcoord[1]-1]->v);
				
				
				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[1]-1]->x,vertexnormals[faces[i]->faces[1]-1]->y,vertexnormals[faces[i]->faces[1]-1]->z);
				
				glVertex3f(vertex[faces[i]->faces[1]-1]->x,vertex[faces[i]->faces[1]-1]->y,vertex[faces[i]->faces[1]-1]->z);
				
				
				if(istexture && materials[faces[i]->mat]->texture!=-1)
					glTexCoord2f(texturecoordinate[faces[i]->texcoord[2]-1]->u,texturecoordinate[faces[i]->texcoord[2]-1]->v);


				if(isvertexnormal)
					glNormal3f(vertexnormals[faces[i]->faces[2]-1]->x,vertexnormals[faces[i]->faces[2]-1]->y,vertexnormals[faces[i]->faces[2]-1]->z);
		
				glVertex3f(vertex[faces[i]->faces[2]-1]->x,vertex[faces[i]->faces[2]-1]->y,vertex[faces[i]->faces[2]-1]->z);
			glEnd();
		}
	}
	glEndList();
	clean();
	lists.push_back(num);
	return num;
}
Exemplo n.º 7
0
    //-----------------------------------------------------------------------------------
    void HlmsJsonCompute::loadJob( const rapidjson::Value &json, const HlmsJson::NamedBlocks &blocks,
                                   HlmsComputeJob *job, const String &jobName )
    {
        rapidjson::Value::ConstMemberIterator itor = json.FindMember( "threads_per_group" );
        if( itor != json.MemberEnd() && itor->value.IsArray() )
        {
            uint32 val[3];

            bool hasError = false;

            const rapidjson::Value &jsonArray = itor->value;
            if( jsonArray.Size() != 3u )
                hasError = true;
            for( rapidjson::SizeType i=0; i<3u && !hasError; ++i )
            {
                if( jsonArray[i].IsUint() )
                    val[i] = jsonArray[i].GetUint();
                else
                    hasError = true;
            }

            if( hasError )
            {
                LogManager::getSingleton().logMessage( "Error parsing JSON '" + jobName +
                                                       "': threads_per_group' expects an array "
                                                       "with three values. e.g. [16, 16, 2]" );
            }
            else
                job->setThreadsPerGroup( val[0], val[1], val[2] );
        }

        itor = json.FindMember( "thread_groups" );
        if( itor != json.MemberEnd() && itor->value.IsArray() )
        {
            uint32 val[3];

            bool hasError = false;

            const rapidjson::Value &jsonArray = itor->value;
            if( jsonArray.Size() != 3u )
                hasError = true;
            for( rapidjson::SizeType i=0; i<3u && !hasError; ++i )
            {
                if( jsonArray[i].IsUint() )
                    val[i] = jsonArray[i].GetUint();
                else
                    hasError = true;
            }

            if( hasError )
            {
                LogManager::getSingleton().logMessage( "Error parsing JSON '" + jobName +
                                                       "': thread_groups' expects an array "
                                                       "with three values. e.g. [16, 16, 2]" );
            }
            else
                job->setNumThreadGroups( val[0], val[1], val[2] );
        }

        itor = json.FindMember( "inform_shader_of_texture_data_change" );
        if( itor != json.MemberEnd() && itor->value.IsBool() )
            job->setInformHlmsOfTextureData( itor->value.GetBool() );

        itor = json.FindMember( "thread_groups_based_on_texture" );
        if( itor != json.MemberEnd() )
        {
            loadBasedOnTextureOrUav( itor->value, jobName, job,
                                     HlmsComputeJob::ThreadGroupsBasedOnTexture );
        }

        itor = json.FindMember( "thread_groups_based_on_uav" );
        if( itor != json.MemberEnd() )
        {
            loadBasedOnTextureOrUav( itor->value, jobName, job,
                                     HlmsComputeJob::ThreadGroupsBasedOnUav );
        }

        itor = json.FindMember( "properties" );
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;

            rapidjson::Value::ConstMemberIterator itSubObj = subobj.MemberBegin();
            rapidjson::Value::ConstMemberIterator enSubObj = subobj.MemberEnd();

            while( itSubObj != enSubObj )
            {
                if( itSubObj->value.IsInt() )
                {
                    job->setProperty( itSubObj->name.GetString(),
                                      static_cast<int32>(itSubObj->value.GetInt()) );
                }

                ++itSubObj;
            }
        }

        itor = json.FindMember( "params" );
        if( itor != json.MemberEnd() && itor->value.IsArray() )
            loadParams( itor->value, job->getShaderParams( "default" ), jobName );

        itor = json.FindMember( "params_glsl" );
        if( itor != json.MemberEnd() && itor->value.IsArray() )
            loadParams( itor->value, job->getShaderParams( "glsl" ), jobName );

        itor = json.FindMember( "params_hlsl" );
        if( itor != json.MemberEnd() && itor->value.IsArray() )
            loadParams( itor->value, job->getShaderParams( "hlsl" ), jobName );

        itor = json.FindMember( "textures" );
        if( itor != json.MemberEnd() && itor->value.IsArray() )
        {
            const rapidjson::Value &jsonArray = itor->value;

            assert( jsonArray.Size() < 256u && "Exceeding max limit!" );

            const uint8 arraySize = std::min( jsonArray.Size(), 255u );
            job->setNumTexUnits( arraySize );

            for( uint8 i=0; i<arraySize; ++i )
            {
                if( jsonArray[i].IsObject() )
                    loadTexture( jsonArray[i], blocks, job, i );
            }
        }

        itor = json.FindMember( "uav_units" );
        if( itor != json.MemberEnd() && itor->value.IsUint() )
        {
            assert( itor->value.GetUint() < 256u && "Exceeding max limit!" );
            job->setNumUavUnits( std::min( itor->value.GetUint(), 255u ) );
        }
    }
Exemplo n.º 8
0
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    int screenWidth, screenHeight;
    
    glfwGetFramebufferSize(window, &screenWidth, &screenHeight);
    
    // Define the viewport dimensions
    glViewport(0, 0, screenWidth, screenHeight);
    
    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("resources/bloom/bloom.vs", "resources/bloom/bloom.frag");
    Shader shaderLight("resources/bloom/bloom.vs", "resources/bloom/light_box.frag");
    Shader shaderBlur("resources/bloom/blur.vs", "resources/bloom/blur.frag");
    Shader shaderBloomFinal("resources/bloom/bloom_final.vs", "resources/bloom/bloom_final.frag");

    // Set samplers
    shaderBloomFinal.Use();
    glUniform1i(glGetUniformLocation(shaderBloomFinal.Program, "scene"), 0);
    glUniform1i(glGetUniformLocation(shaderBloomFinal.Program, "bloomBlur"), 1);

    // Light sources
    // - Positions
    std::vector<glm::vec3> lightPositions;
    lightPositions.push_back(glm::vec3(0.0f, 0.5f, 1.5f)); // back light
    lightPositions.push_back(glm::vec3(-4.0f, 0.5f, -3.0f));
    lightPositions.push_back(glm::vec3(3.0f, 0.5f, 1.0f));
    lightPositions.push_back(glm::vec3(-.8f, 2.4f, -1.0f));
    // - Colors
    std::vector<glm::vec3> lightColors;
    lightColors.push_back(glm::vec3(2.0f, 2.0f, 2.0f));
    lightColors.push_back(glm::vec3(1.5f, 0.0f, 0.0f));
    lightColors.push_back(glm::vec3(0.0f, 0.0f, 1.5f));
    lightColors.push_back(glm::vec3(0.0f, 1.5f, 0.0f));

    // Load textures
    GLuint woodTexture = loadTexture("resources/textures/wood.png");
    GLuint containerTexture = loadTexture("resources/textures/container2.png");

    // Set up floating point framebuffer to render scene to
    GLuint hdrFBO;
    glGenFramebuffers(1, &hdrFBO);
    glBindFramebuffer(GL_FRAMEBUFFER, hdrFBO);
    // - Create 2 floating point color buffers (1 for normal rendering, other for brightness treshold values)
    GLuint colorBuffers[2];
    glGenTextures(2, colorBuffers);
    for (GLuint i = 0; i < 2; i++)
    {
        glBindTexture(GL_TEXTURE_2D, colorBuffers[i]);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, SCR_WIDTH, SCR_HEIGHT, 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);  // We clamp to the edge as the blur filter would otherwise sample repeated texture values!
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        // attach texture to framebuffer
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, colorBuffers[i], 0);
    }
    // - Create and attach depth buffer (renderbuffer)
    GLuint rboDepth;
    glGenRenderbuffers(1, &rboDepth);
    glBindRenderbuffer(GL_RENDERBUFFER, rboDepth);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, SCR_WIDTH, SCR_HEIGHT);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth);
    // - Tell OpenGL which color attachments we'll use (of this framebuffer) for rendering 
    GLuint attachments[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
    glDrawBuffers(2, attachments);
    // - Finally check if framebuffer is complete
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "Framebuffer not complete!" << std::endl;
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // Ping pong framebuffer for blurring
    GLuint pingpongFBO[2];
    GLuint pingpongColorbuffers[2];
    glGenFramebuffers(2, pingpongFBO);
    glGenTextures(2, pingpongColorbuffers);
    for (GLuint i = 0; i < 2; i++)
    {
        glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[i]);
        glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[i]);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, SCR_WIDTH, SCR_HEIGHT, 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); // We clamp to the edge as the blur filter would otherwise sample repeated texture values!
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pingpongColorbuffers[i], 0);
        // Also check if framebuffers are complete (no need for depth buffer)
        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
            std::cout << "Framebuffer not complete!" << std::endl;
    }

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // 1. Render scene into floating point framebuffer
        glBindFramebuffer(GL_FRAMEBUFFER, hdrFBO);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)SCR_HEIGHT, 0.1f, 100.0f);
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 model;
        shader.Use();
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, woodTexture);
        // - set lighting uniforms
        for (GLuint i = 0; i < lightPositions.size(); i++)
        {
            glUniform3fv(glGetUniformLocation(shader.Program, ("lights[" + std::to_string(i) + "].Position").c_str()), 1, &lightPositions[i][0]);
            glUniform3fv(glGetUniformLocation(shader.Program, ("lights[" + std::to_string(i) + "].Color").c_str()), 1, &lightColors[i][0]);
        }
        glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
        // - create one large cube that acts as the floor
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0));
        model = glm::scale(model, glm::vec3(25.0f, 1.0f, 25.0f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        // - then create multiple cubes as the scenery
        glBindTexture(GL_TEXTURE_2D, containerTexture);
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(0.0f, 1.5f, 0.0));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(2.0f, 0.0f, 1.0));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(-1.0f, -1.0f, 2.0));
        model = glm::rotate(model, 60.0f, glm::normalize(glm::vec3(1.0, 0.0, 1.0)));
        model = glm::scale(model, glm::vec3(2.0));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(0.0f, 2.7f, 4.0));
        model = glm::rotate(model, 23.0f, glm::normalize(glm::vec3(1.0, 0.0, 1.0)));
        model = glm::scale(model, glm::vec3(2.5));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(-2.0f, 1.0f, -3.0));
        model = glm::rotate(model, 124.0f, glm::normalize(glm::vec3(1.0, 0.0, 1.0)));
        model = glm::scale(model, glm::vec3(2.0));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        RenderCube();
        model = glm::mat4();
        model = glm::translate(model, glm::vec3(-3.0f, 0.0f, 0.0));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        RenderCube();
        // - finally show all the light sources as bright cubes
        shaderLight.Use();
        glUniformMatrix4fv(glGetUniformLocation(shaderLight.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        glUniformMatrix4fv(glGetUniformLocation(shaderLight.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));

        for (GLuint i = 0; i < lightPositions.size(); i++)
        {
            model = glm::mat4();
            model = glm::translate(model, glm::vec3(lightPositions[i]));
            model = glm::scale(model, glm::vec3(0.5f));
            glUniformMatrix4fv(glGetUniformLocation(shaderLight.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
            glUniform3fv(glGetUniformLocation(shaderLight.Program, "lightColor"), 1, &lightColors[i][0]);
            RenderCube();
        }
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // 2. Blur bright fragments w/ two-pass Gaussian Blur 
        GLboolean horizontal = true, first_iteration = true;
        GLuint amount = 10;
        shaderBlur.Use();
        for (GLuint i = 0; i < amount; i++)
        {
            glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[horizontal]);
            glUniform1i(glGetUniformLocation(shaderBlur.Program, "horizontal"), horizontal);
            glBindTexture(GL_TEXTURE_2D, first_iteration ? colorBuffers[1] : pingpongColorbuffers[!horizontal]);  // bind texture of other framebuffer (or scene if first iteration)
            RenderQuad();
            horizontal = !horizontal;
            if (first_iteration)
                first_iteration = false;
        }
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // 2. Now render floating point color buffer to 2D quad and tonemap HDR colors to default framebuffer's (clamped) color range
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        shaderBloomFinal.Use();
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, colorBuffers[0]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[!horizontal]);
        glUniform1i(glGetUniformLocation(shaderBloomFinal.Program, "bloom"), bloom);
        glUniform1f(glGetUniformLocation(shaderBloomFinal.Program, "exposure"), exposure);
        RenderQuad();


        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Exemplo n.º 9
0
	inline
	void MyTexturedBox::makeTexture() {
		_textureDL = loadTexture("..\\..\\src\\crate.tga");
	}
Exemplo n.º 10
0
int main(int argc, char **argv) {

	// Init all SDl stuff

	SDL_Routine SDL_hdl;
	if (SDL_hdl.InitSDL()) {
		logSDLError(std::cout, "SDL Init");
		return 1;
	}

	SDL_Texture *bg = loadTexture("res/bg.png", SDL_hdl.Render);
	Character Alice;

	Alice.loadTex("res/Alice_spritesheet.png", SDL_hdl.Render);

	if (bg == nullptr || Alice.char_tex == nullptr)
			return 4;

	const Uint8 *keys = SDL_GetKeyboardState(nullptr);


	// Main Loop

	Mix_Music *bg_mus = loadBGMusic("res/bg.mp3");
	playBGMusic(bg_mus);
	bool mus_status = true;

	SDL_Event e;
	bool show_fps = true;
	bool quit = false;

	TTF_Font* fps_font = openFont("res/beau.ttf", 25);
	SDL_Color textColor = {0, 0, 0};

	std::stringstream fps_text;
	SDL_Texture* txt_image;
	//SDL_Texture* txt_image = renderText("FPS test text", fps_font, textColor, renderer);
	//if (txt_image == nullptr) {
	//	return 1;
	//}

	LTimer fpsTimer;
	int countedFrames = 0;
	std::stringstream fpsText;
	float avgFPS = 0;

	fpsTimer.start();


	while (!quit) {

		SDL_RenderClear(SDL_hdl.Render);

		int bW, bH;
		SDL_QueryTexture(bg, NULL, NULL, &bW, &bH);

		// Calculate FPS
		avgFPS = countedFrames / ( fpsTimer.getTicks() / 1000.f );
		if ( avgFPS > 2000000 )
			avgFPS = 0;
		fps_text.str("");
		fps_text << "FPS: " << avgFPS;

		// Render BG
		SDL_Rect bg_box;
		bg_box.x = 0;
		bg_box.y = 0;
		bg_box.w = SCREEN_WIDTH;
		bg_box.h = SCREEN_HEIGHT;
		renderTexture(bg, SDL_hdl.Render, bg_box, nullptr);

		// Show FPS
		if (show_fps) {
			txt_image = renderText(fps_text.str().c_str(), fps_font, textColor, SDL_hdl.Render);
			if (txt_image == nullptr) {
				return 1;
			}
		}

		//SDL_PumpEvents();
		if (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT)
				quit = true;
			if (e.type == SDL_MOUSEBUTTONDOWN)
				quit = true;
		}

		if (keys[SDL_SCANCODE_LEFT]) {
			Alice.direction_state = 6;
			Alice.anim_frame = Alice.frame / 4;
			if (Alice.char_box.x > 0)
				Alice.char_box.x -= VELOCITY;
		}
		if (keys[SDL_SCANCODE_RIGHT]) {
			Alice.direction_state = 2;
			Alice.anim_frame = Alice.frame / 4;
			if (Alice.char_box.x <= (SCREEN_WIDTH - SPRITE_SIZE * 3))
				Alice.char_box.x += VELOCITY;
		}
		if (keys[SDL_SCANCODE_UP]) {
			Alice.direction_state = 0;
			Alice.anim_frame = Alice.frame / 4;
			if (Alice.char_box.y > 0)
				Alice.char_box.y -= VELOCITY;
		}
		if (keys[SDL_SCANCODE_DOWN]) {
			Alice.direction_state = 4;
			Alice.anim_frame = Alice.frame / 4;
			if (Alice.char_box.y < (SCREEN_HEIGHT - SPRITE_SIZE * 3))
				Alice.char_box.y += VELOCITY;
		}
		if (keys[SDL_SCANCODE_UP] && keys[SDL_SCANCODE_RIGHT]) {
			Alice.direction_state = 1;
			Alice.anim_frame = Alice.frame / 4;
			if ((Alice.char_box.y > 0) && (Alice.char_box.x < (SCREEN_WIDTH - SPRITE_SIZE * 3))) {
				Alice.char_box.x += VELOCITY / 4;
				Alice.char_box.y -= VELOCITY / 4;
			}
		}
		if (keys[SDL_SCANCODE_UP] && keys[SDL_SCANCODE_LEFT]) {
			Alice.direction_state = 5;
			Alice.anim_frame = Alice.frame / 4;
			if ((Alice.char_box.y > 0) && (Alice.char_box.x > 0)) {
				Alice.char_box.x -= VELOCITY / 4;
				Alice.char_box.y -= VELOCITY / 4;
			}
		}
		if (keys[SDL_SCANCODE_DOWN] && keys[SDL_SCANCODE_RIGHT]) {
			Alice.direction_state = 3;
			Alice.anim_frame = Alice.frame / 4;
			if ((Alice.char_box.y < (SCREEN_HEIGHT - SPRITE_SIZE * 3)) &&
					(Alice.char_box.x < (SCREEN_WIDTH - SPRITE_SIZE * 3))) {
				Alice.char_box.x += VELOCITY / 4;
				Alice.char_box.y += VELOCITY / 4;
			}
		}
		if (keys[SDL_SCANCODE_DOWN] && keys[SDL_SCANCODE_LEFT]) {
			Alice.direction_state = 7;
			Alice.anim_frame = Alice.frame / 4;
			if ((Alice.char_box.y < (SCREEN_HEIGHT - SPRITE_SIZE * 3)) && (Alice.char_box.x > 0)) {
				Alice.char_box.x -= VELOCITY / 4;
				Alice.char_box.y += VELOCITY / 4;
			}
		}
		if (keys[SDL_SCANCODE_P]) {
			if (mus_status) {
				pauseBGMusic();
				mus_status = false;
			}
			else {
				resumeBGMusic();
				mus_status = true;
			}
		}
		if (keys[SDL_SCANCODE_GRAVE]) {
			if (show_fps)
				show_fps = false;
			else {
				show_fps = true;
			}
		}
		if (keys[SDL_SCANCODE_ESCAPE]) {
			quit = true;
		}

		renderTexture(Alice.char_tex, SDL_hdl.Render, Alice.char_box, &Alice.char_clips[Alice.anim_frame][Alice.direction_state]);

		if (show_fps)
			renderTexture(txt_image, SDL_hdl.Render, 20, 20, nullptr);

		SDL_RenderPresent(SDL_hdl.Render);

		++Alice.frame;
		if ( Alice.frame / 4 >= ANIMATION_FRAMES )
			Alice.frame = 0;

		++countedFrames;
	}


	// Cleanup

	unloadBGMusic(bg_mus);

	TTF_CloseFont(fps_font);

	SDL_DestroyTexture(bg);
	SDL_DestroyTexture(Alice.char_tex);

	SDL_hdl.CleanupSDL();

	return 0;
}
Exemplo n.º 11
0
    //
    // MQO
    //  このバージョンではテクスチャ、マテリアルなどを扱わない
    //
    void build_from_mqo(
        mqo_reader::document_type& doc, float scale, const Color& color) {

        // マテリアル
        for (const auto& ms: doc.materials) {
            SubModel m;
            m.vbo       = 0;
            m.ibo       = 0;
#ifdef JSTEXTURE
            m.texture   = "";
#else
            m.texture   = 0;
#endif
            m.color.rgba[0] = ms.color.red;
            m.color.rgba[1] = ms.color.green;
            m.color.rgba[2] = ms.color.blue;
            m.color.rgba[3] = ms.color.alpha;
            if (ms.texture != "") {
#ifdef JSTEXTURE
                m.texture = ms.texture;
                loadTexture(m.texture.c_str());
#else
                m.texture = build_texture(ms.texture.c_str());
#endif
            }

            submodels_.push_back(m);
        }
        {
            // default material
            SubModel m;
            m.vbo       = 0;
            m.ibo       = 0;
#ifdef JSTEXTURE
            m.texture   = "";
#else
            m.texture   = 0;
#endif
            m.color     = color;
            submodels_.push_back(m);
        }

        // 頂点, 面
        for (const auto& pair: doc.objects) {
            const mqo_reader::object_type& obj = pair.second;

            // dictionary:
            //  (source vertex index, uv ) => destination vertex index
            struct VertexKey {
                int     index;
                float   u;
                float   v;

                VertexKey(){}
                VertexKey(int aindex, float au, float av)
                    : index(aindex), u(au), v(av) {}

                bool operator<(const VertexKey& a) const {
                    if (index < a.index) { return true; }
                    if (a.index < index) { return false; }
                    if (u < a.u) { return true; }
                    if (a.u < u) { return false; }
                    return v < a.v;
                }
            };

            std::vector<std::map<VertexKey, int>> used_vertices;
            used_vertices.resize(submodels_.size());

            // マテリアルごとに使用頂点を分類
            for (const auto& face: obj.faces) {
                int material_index = face.material_index;
                if (material_index == -1) {
                    material_index = int(submodels_.size() - 1);
                }
                int i0 = face.vertex_indices[0];
                int i1 = face.vertex_indices[1];
                int i2 = face.vertex_indices[2];
                                
                std::map<VertexKey, int>& c = used_vertices[material_index];
                c[VertexKey(i0, face.uv[0].u, face.uv[0].v)] = -1; 
                c[VertexKey(i1, face.uv[1].u, face.uv[1].v)] = -1; 
                c[VertexKey(i2, face.uv[2].u, face.uv[2].v)] = -1; 
            }
                        
            // マテリアルごとに使われている頂点を追加
            size_t n = submodels_.size();
            for (size_t i = 0 ; i < n ; i++) {
                SubModel& m = submodels_[i];
                std::map<VertexKey, int>& c = used_vertices[i];

                int no = int(m.vertex_source.size());
                for (auto& j: c) {
                    const auto& src = obj.vertices[j.first.index];

                    Vertex dst;
                    dst.position = Vector(
                        src.x * scale,
                        src.y * scale,
                        src.z * -scale);
                    dst.normal = Vector(0, 0, 0);
                    dst.diffuse = m.color;
                    dst.u = j.first.u;
                    dst.v = j.first.v;
                    m.vertex_source.push_back(dst);

                    j.second = no++;
                }
            }

            // マテリアルごとに面を追加
            for (const auto& face: obj.faces) {
                int material_index = face.material_index;
                if (material_index == -1) {
                    material_index = int(submodels_.size()- 1);
                }
                                
                int i0 = face.vertex_indices[0];
                int i1 = face.vertex_indices[1];
                int i2 = face.vertex_indices[2];

                std::map<VertexKey, int>& c = used_vertices[material_index];
                int k0 = c[VertexKey(i0, face.uv[0].u, face.uv[0].v)];
                int k1 = c[VertexKey(i1, face.uv[1].u, face.uv[1].v)];
                int k2 = c[VertexKey(i2, face.uv[2].u, face.uv[2].v)];

                SubModel& m = submodels_[material_index];
                m.index_source.push_back(k0);
                m.index_source.push_back(k1);
                m.index_source.push_back(k2);

                Vertex& v0 = m.vertex_source[k0];
                Vertex& v1 = m.vertex_source[k1];
                Vertex& v2 = m.vertex_source[k2];
                Vector normal = cross(
                    v1.position - v0.position,
                    v2.position - v0.position);
                v0.normal += normal;
                v1.normal += normal;
                v2.normal += normal;
            }
        }

        // 法線後処理
        for (SubModel& m: submodels_) {
            for (auto& v: m.vertex_source) {
                normalize_f(v.normal);
            }
        }

        build_submodels();
    }        
Exemplo n.º 12
0
void Model::swapTexture(std::string fileName) {
    texture = loadTexture(fileName);
}
Exemplo n.º 13
0
Model::Model(std::string modelFileName, std::string textureFileName) {
    bound = new BoundingBox();
    texture = loadTexture(textureFileName);
    loadRawModel(modelFileName);
}
Exemplo n.º 14
0
  void RenderBackground::renderBackground()
  {
    glDisable(GL_LIGHTING);
    glDisable(GL_TEXTURE_2D);

    if (mode_ == "monochrome") {
      glPushAttrib(GL_COLOR_BUFFER_BIT);
      glClearColor(firstcolor_.r, firstcolor_.g, firstcolor_.b, firstcolor_.a);
      glClear(GL_COLOR_BUFFER_BIT);
      glPopAttrib();
      LGL_ERROR;
    }
    else if (mode_ == "gradient") {
      // linear gradient
      MatStack.pushMatrix();
      MatStack.loadIdentity();
      MatStack.rotate(static_cast<float>(angle_), 0.0f, 0.0f, 1.0f);

      // when you rotate the texture, you need to scale it.
      // otherwise the edges don't cover the complete screen
      // magic number: 0.8284271247461900976033774484194f = sqrt(8)-2;
      MatStack.scale(1.0f + (45 - abs(angle_ % 90 - 45)) / 45.0f*0.8284271247461900976033774484194f,
        1.0f + (45 - abs(angle_ % 90 - 45)) / 45.0f*0.8284271247461900976033774484194f, 1.0f);

      glBegin(GL_QUADS);
      glColor4fv(glm::value_ptr(firstcolor_));
      glVertex2f(-1.0, -1.0);
      glVertex2f(1.0, -1.0);
      glColor4fv(glm::value_ptr(secondcolor_));
      glVertex2f(1.0, 1.0);
      glVertex2f(-1.0, 1.0);
      glEnd();
      MatStack.popMatrix();
      LGL_ERROR;
    }
    else if (mode_ == "radial") {
      tgt::TextureUnit::setZeroUnit();

      if (!tex_)
        loadTexture();

      if (tex_) {
        tex_->bind();
        tex_->enable();
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
        LGL_ERROR;

        MatStack.pushMatrix();
        MatStack.scale(1.44f, 1.44f, 0.0f);

        glBegin(GL_QUADS);
        glTexCoord2f(0.0f, 0.0f);
        glVertex2f(-1.0f, -1.0f);
        glTexCoord2f(1.0f, 0.0f);
        glVertex2f(1.0f, -1.0f);
        glTexCoord2f(1.0f, 1.0f);
        glVertex2f(1.0f, 1.0f);
        glTexCoord2f(0.0f, 1.0f);
        glVertex2f(-1.0f, 1.0f);
        glEnd();

        MatStack.popMatrix();

        glDisable(GL_TEXTURE_2D);
        LGL_ERROR;
      }
      else {
        LWARNING("No texture");
      }
    }
    else if (mode_ == "none") {

      if (!tex_)
        loadTexture();

      if (tex_) {
        glActiveTexture(GL_TEXTURE0);
        tex_->bind();
        tex_->enable();
        glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
        LGL_ERROR;

        glColor4f(1.0f, 1.0f, 1.0f, 0.9f);
        glBegin(GL_QUADS);
        glTexCoord2f(0.0f, 0.0f);
        glVertex2f(-1.0f, -1.0f);
        glTexCoord2f(1.0f, 0.0f);
        glVertex2f(1.0f, -1.0f);
        glTexCoord2f(1.0f, 1.0f);
        glVertex2f(1.0f, 1.0f);
        glTexCoord2f(0.0f, 1.0f);
        glVertex2f(-1.0f, 1.0f);
        glEnd();

        tex_->disable();
        LGL_ERROR;
      }
    }
    else {
      LWARNING("Unknown background mode");
    }
  }
Exemplo n.º 15
0
	// Load material data
	MStatus Material::load(MFnDependencyNode* pShader,MStringArray& uvsets,ParamList& params)
	{
		MStatus stat;
		clear();
		//read material name, adding the requested prefix
		MString tmpStr = params.matPrefix;
		if (tmpStr != "")
			tmpStr += "/";
		tmpStr += pShader->name();
		MStringArray tmpStrArray;
		tmpStr.split(':',tmpStrArray);
		m_name = "";
		for (int i=0; i<tmpStrArray.length(); i++)
		{
			m_name += tmpStrArray[i];
			if (i < tmpStrArray.length()-1)
				m_name += "_";
		}

		//check if we want to export with lighting off option
		m_lightingOff = params.lightingOff;

		// GET MATERIAL DATA

		// Check material type
		if (pShader->object().hasFn(MFn::kPhong))
		{
			stat = loadPhong(pShader);
		}
		else if (pShader->object().hasFn(MFn::kBlinn))
		{
			stat = loadBlinn(pShader);
		}
		else if (pShader->object().hasFn(MFn::kLambert))
		{
			stat = loadLambert(pShader);
		}
		else if (pShader->object().hasFn(MFn::kPluginHwShaderNode))
		{
			stat = loadCgFxShader(pShader);
		}
		else
		{
			stat = loadSurfaceShader(pShader);
		}

		// Get textures data
		MPlugArray colorSrcPlugs;
		MPlugArray texSrcPlugs;
		MPlugArray placetexSrcPlugs;
		if (m_isTextured)
		{
			// Translate multiple textures if material is multitextured
			if (m_isMultiTextured)
			{
				// Get layered texture node
				MFnDependencyNode* pLayeredTexNode = NULL;
				if (m_type == MT_SURFACE_SHADER)
					pShader->findPlug("outColor").connectedTo(colorSrcPlugs,true,false);
				else
					pShader->findPlug("color").connectedTo(colorSrcPlugs,true,false);
				for (int i=0; i<colorSrcPlugs.length(); i++)
				{
					if (colorSrcPlugs[i].node().hasFn(MFn::kLayeredTexture))
					{
						pLayeredTexNode = new MFnDependencyNode(colorSrcPlugs[i].node());
						continue;
					}
				}

				// Get inputs to layered texture
				MPlug inputsPlug = pLayeredTexNode->findPlug("inputs");

				// Scan inputs and export textures
				for (int i=inputsPlug.numElements()-1; i>=0; i--)
				{
					MFnDependencyNode* pTextureNode = NULL;
					// Search for a connected texture
					inputsPlug[i].child(0).connectedTo(colorSrcPlugs,true,false);
					for (int j=0; j<colorSrcPlugs.length(); j++)
					{
						if (colorSrcPlugs[j].node().hasFn(MFn::kFileTexture))
						{
							pTextureNode = new MFnDependencyNode(colorSrcPlugs[j].node());
							continue;
						}
					}

					// Translate the texture if it was found
					if (pTextureNode)
					{
						// Get blend mode
						TexOpType opType;
						short bm;
						inputsPlug[i].child(2).getValue(bm);
						switch(bm)
						{				
						case 0:
							opType = TOT_REPLACE;
							break;
						case 1:
							opType = TOT_ALPHABLEND;
							break;				
						case 4:
							opType = TOT_ADD;
							break;
						case 6:
							opType = TOT_MODULATE;
							break;
						default:
							opType = TOT_MODULATE;
						}

						stat = loadTexture(pTextureNode,opType,uvsets,params);
						delete pTextureNode;
						if (MS::kSuccess != stat)
						{
							std::cout << "Error loading layered texture\n";
							std::cout.flush();
							delete pLayeredTexNode;
							return MS::kFailure;
						}
					}
				}
				if (pLayeredTexNode)
					delete pLayeredTexNode;
			}
			// Else translate the single texture
			else
			{
				// Get texture node
				MFnDependencyNode* pTextureNode = NULL;
				if (m_type == MT_SURFACE_SHADER)
					pShader->findPlug("outColor").connectedTo(colorSrcPlugs,true,false);
				else
					pShader->findPlug("color").connectedTo(colorSrcPlugs,true,false);
				for (int i=0; i<colorSrcPlugs.length(); i++)
				{
					if (colorSrcPlugs[i].node().hasFn(MFn::kFileTexture))
					{
						pTextureNode = new MFnDependencyNode(colorSrcPlugs[i].node());
						continue;
					}
				}
				if (pTextureNode)
				{
					TexOpType opType = TOT_MODULATE;
					stat = loadTexture(pTextureNode,opType,uvsets,params);
					delete pTextureNode;
					if (MS::kSuccess != stat)
					{
						std::cout << "Error loading texture\n";
						std::cout.flush();
						return MS::kFailure;
					}
				}
			}
		}

		return MS::kSuccess;
	}
Exemplo n.º 16
0
QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *)
{
    if (!window() || !m_frameSvg ||
            (!m_frameSvg->hasElementPrefix(m_frameSvg->actualPrefix()) && !m_frameSvg->hasElementPrefix(m_prefix))) {
        delete oldNode;
        return Q_NULLPTR;
    }

    if (m_fastPath) {
        if (m_textureChanged) {
            delete oldNode;
            oldNode = 0;
        }

        if (!oldNode) {
            QString prefix = m_frameSvg->actualPrefix();
            oldNode = new FrameNode(prefix, m_frameSvg);

            bool tileCenter = (m_frameSvg->hasElement(QStringLiteral("hint-tile-center"))
                               || m_frameSvg->hasElement(prefix % QLatin1String("hint-tile-center")));
            bool stretchBorders = (m_frameSvg->hasElement(QStringLiteral("hint-stretch-borders"))
                                   || m_frameSvg->hasElement(prefix % QLatin1String("hint-stretch-borders")));
            FrameItemNode::FitMode borderFitMode = stretchBorders ? FrameItemNode::Stretch : FrameItemNode::Tile;
            FrameItemNode::FitMode centerFitMode = tileCenter ? FrameItemNode::Tile: FrameItemNode::Stretch;

            new FrameItemNode(this, FrameSvg::NoBorder, centerFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::TopBorder | FrameSvg::LeftBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::TopBorder | FrameSvg::RightBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::TopBorder, borderFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::BottomBorder, borderFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::BottomBorder | FrameSvg::LeftBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::BottomBorder | FrameSvg::RightBorder, FrameItemNode::FastStretch, oldNode);
            new FrameItemNode(this, FrameSvg::LeftBorder,  borderFitMode, oldNode);
            new FrameItemNode(this, FrameSvg::RightBorder, borderFitMode, oldNode);

            m_sizeChanged = true;
            m_textureChanged = false;
        }

        if (m_sizeChanged) {
            FrameNode* frameNode = static_cast<FrameNode*>(oldNode);
            QSize frameSize(width(), height());
            QRect geometry = frameNode->contentsRect(frameSize);
            for(int i = 0; i<oldNode->childCount(); ++i) {
                FrameItemNode* it = static_cast<FrameItemNode*>(oldNode->childAtIndex(i));
                it->reposition(geometry, frameSize);
            }

            m_sizeChanged = false;
        }
    } else {
        ManagedTextureNode *textureNode = dynamic_cast<ManagedTextureNode *>(oldNode);
        if (!textureNode) {
            delete oldNode;
            textureNode = new ManagedTextureNode;
            textureNode->setFiltering(QSGTexture::Nearest);
            m_textureChanged = true; //force updating the texture on our newly created node
            oldNode = textureNode;
        }

        if ((m_textureChanged || m_sizeChanged) || textureNode->texture()->textureSize() != m_frameSvg->size()) {
            QImage image = m_frameSvg->framePixmap().toImage();
            textureNode->setTexture(s_cache->loadTexture(window(), image));
            textureNode->setRect(0, 0, width(), height());

            m_textureChanged = false;
            m_sizeChanged = false;
        }
    }

    return oldNode;
}
Exemplo n.º 17
0
int _main_(int /*_argc*/, char** /*_argv*/)
{
    uint32_t width = 1280;
    uint32_t height = 720;
    uint32_t debug = BGFX_DEBUG_TEXT;
    uint32_t reset = BGFX_RESET_VSYNC;

    bgfx::init();
    bgfx::reset(width, height, reset);

    // Enable debug text.
    bgfx::setDebug(debug);

    // Set view 0 clear state.
    bgfx::setViewClear(0
                       , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
                       , 0x303030ff
                       , 1.0f
                       , 0
                      );

    // Setup root path for binary shaders. Shader binaries are different
    // for each renderer.
    switch (bgfx::getRendererType() )
    {
    default:
    case bgfx::RendererType::Direct3D9:
        s_shaderPath = "shaders/dx9/";
        break;

    case bgfx::RendererType::Direct3D11:
        s_shaderPath = "shaders/dx11/";
        break;

    case bgfx::RendererType::OpenGL:
        s_shaderPath = "shaders/glsl/";
        s_flipV = true;
        break;

    case bgfx::RendererType::OpenGLES2:
    case bgfx::RendererType::OpenGLES3:
        s_shaderPath = "shaders/gles/";
        s_flipV = true;
        break;
    }

    bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv);
    bgfx::UniformHandle u_stipple = bgfx::createUniform("u_stipple", bgfx::UniformType::Uniform3fv);
    bgfx::UniformHandle u_texStipple = bgfx::createUniform("u_texStipple", bgfx::UniformType::Uniform1iv);

    bgfx::ProgramHandle program = loadProgram("vs_tree", "fs_tree");

    const bgfx::Memory* mem;
    mem = loadTexture("leafs1.dds");
    bgfx::TextureHandle textureLeafs = bgfx::createTexture(mem);

    mem = loadTexture("bark1.dds");
    bgfx::TextureHandle textureBark = bgfx::createTexture(mem);

    bgfx::TextureHandle textureStipple;

    const bgfx::Memory* stipple = bgfx::alloc(8*4);
    memset(stipple->data, 0, stipple->size);

    for (uint32_t ii = 0; ii < 32; ++ii)
    {
        stipple->data[knightTour[ii].m_y * 8 + knightTour[ii].m_x] = ii*4;
    }

    textureStipple = bgfx::createTexture2D(8, 4, 1, bgfx::TextureFormat::L8, BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIN_POINT, stipple);

    Mesh mesh_top[3];
    mesh_top[0].load("meshes/tree1b_lod0_1.bin");
    mesh_top[1].load("meshes/tree1b_lod1_1.bin");
    mesh_top[2].load("meshes/tree1b_lod2_1.bin");

    Mesh mesh_trunk[3];
    mesh_trunk[0].load("meshes/tree1b_lod0_2.bin");
    mesh_trunk[1].load("meshes/tree1b_lod1_2.bin");
    mesh_trunk[2].load("meshes/tree1b_lod2_2.bin");

    FILE* file = fopen("font/droidsans.ttf", "rb");
    uint32_t size = (uint32_t)fsize(file);
    void* data = malloc(size);
    size_t ignore = fread(data, 1, size, file);
    BX_UNUSED(ignore);
    fclose(file);

    imguiCreate(data, size);

    free(data);

    int32_t scrollArea = 0;

    bool transitions = true;
    int transitionFrame = 0;
    int currLOD = 0;
    int targetLOD = 0;

    float at[3] = { 0.0f, 1.0f, 0.0f };
    float eye[3] = { 0.0f, 1.0f, -2.0f };

    entry::MouseState mouseState;
    while (!entry::processEvents(width, height, debug, reset, &mouseState) )
    {
        imguiBeginFrame(mouseState.m_mx
                        , mouseState.m_my
                        , (mouseState.m_buttons[entry::MouseButton::Left  ] ? IMGUI_MBUT_LEFT  : 0)
                        | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
                        , 0
                        , width
                        , height
                       );

        imguiBeginScrollArea("Toggle transitions", width - width / 5 - 10, 10, width / 5, height / 6, &scrollArea);
        imguiSeparatorLine();

        if (imguiButton(transitions ? "ON" : "OFF") )
        {
            transitions = !transitions;
        }

        static float distance = 2.0f;
        imguiSlider("Distance", &distance, 2.0f, 6.0f, .01f);

        imguiEndScrollArea();
        imguiEndFrame();

        // Set view 0 default viewport.
        bgfx::setViewRect(0, 0, 0, width, height);

        // This dummy draw call is here to make sure that view 0 is cleared
        // if no other draw calls are submitted to view 0.
        bgfx::submit(0);

        int64_t now = bx::getHPCounter();
        static int64_t last = now;
        const int64_t frameTime = now - last;
        last = now;
        const double freq = double(bx::getHPFrequency() );
        const double toMs = 1000.0/freq;

        // Use debug font to print information about this example.
        bgfx::dbgTextClear();
        bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/12-lod");
        bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Mesh LOD transitions.");
        bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
        bgfx::dbgTextPrintf(0, 4, transitions ? 0x2f : 0x1f, transitions ? "Transitions on" : "Transitions off");

        eye[2] = -distance;

        float view[16];
        float proj[16];
        mtxLookAt(view, eye, at);
        mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);

        // Set view and projection matrix for view 0.
        bgfx::setViewTransform(0, view, proj);

        float mtx[16];
        mtxIdentity(mtx);

        float stipple[3];
        float stippleInv[3];

        const int currentLODframe = transitions ? 32-transitionFrame : 32;
        const int mainLOD = transitions ? currLOD : targetLOD;

        stipple[0] = 0.0f;
        stipple[1] = -1.0f;
        stipple[2] = (float(currentLODframe)*4.0f/255.0f) - (1.0f/255.0f);

        stippleInv[0] = (float(31)*4.0f/255.0f);
        stippleInv[1] = 1.0f;
        stippleInv[2] = (float(transitionFrame)*4.0f/255.0f) - (1.0f/255.0f);

        bgfx::setTexture(0, u_texColor, textureBark);
        bgfx::setTexture(1, u_texStipple, textureStipple);
        bgfx::setUniform(u_stipple, stipple);
        mesh_trunk[mainLOD].submit(program, mtx, false);

        bgfx::setTexture(0, u_texColor, textureLeafs);
        bgfx::setTexture(1, u_texStipple, textureStipple);
        bgfx::setUniform(u_stipple, stipple);
        mesh_top[mainLOD].submit(program, mtx, true);

        if (transitions
                && (transitionFrame != 0) )
        {
            bgfx::setTexture(0, u_texColor, textureBark);
            bgfx::setTexture(1, u_texStipple, textureStipple);
            bgfx::setUniform(u_stipple, stippleInv);
            mesh_trunk[targetLOD].submit(program, mtx, false);

            bgfx::setTexture(0, u_texColor, textureLeafs);
            bgfx::setTexture(1, u_texStipple, textureStipple);
            bgfx::setUniform(u_stipple, stippleInv);
            mesh_top[targetLOD].submit(program, mtx, true);
        }

        int lod = 0;
        if (eye[2] < -2.5f)
        {
            lod = 1;
        }

        if (eye[2] < -5.0f)
        {
            lod = 2;
        }

        if (targetLOD!=lod)
        {
            if (targetLOD==currLOD)
            {
                targetLOD = lod;
            }
        }

        if (currLOD != targetLOD)
        {
            transitionFrame++;
        }

        if (transitionFrame>32)
        {
            currLOD = targetLOD;
            transitionFrame = 0;
        }

        // Advance to next frame. Rendering thread will be kicked to
        // process submitted rendering primitives.
        bgfx::frame();
    }

    for (uint32_t ii = 0; ii < 3; ++ii)
    {
        mesh_top[ii].unload();
        mesh_trunk[ii].unload();
    }

    // Cleanup.
    bgfx::destroyProgram(program);

    bgfx::destroyUniform(u_texColor);
    bgfx::destroyUniform(u_stipple);
    bgfx::destroyUniform(u_texStipple);

    bgfx::destroyTexture(textureStipple);
    bgfx::destroyTexture(textureLeafs);
    bgfx::destroyTexture(textureBark);

    // Shutdown bgfx.
    bgfx::shutdown();

    return 0;
}
int main(int, char**) {
    // This section is the initialization for SDL2
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        logSDLError(std::cout, "SDL_Init");
        return 1;
    }
    SDL_Window *window = SDL_CreateWindow("Moving Window", 100, 100, 1440, 810, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    if (window == nullptr) {
        logSDLError(std::cout, "CreateWindow");
        SDL_Quit();
        return 1;
    }
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr) {
        logSDLError(std::cout, "CreateRenderer");
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 1;
    }

    // Initialize all the Images and Texts Pointers
    const std::string resPath = getResourcePath("FeedbackDisplay");
    SDL_Texture *instruction = loadTexture(resPath + "instruction.png", renderer);
    SDL_Texture *trial_background = loadTexture(resPath + "background.png", renderer);
    SDL_Texture *background = loadTexture(resPath + "SyncStart.png", renderer);
    SDL_Texture *background2 = loadTexture(resPath + "SyncEnd.png", renderer);
    SDL_Texture *instruction2 = loadTexture(resPath + "instruction2.png", renderer);
    SDL_Texture *sphere = loadTexture(resPath + "sphere.png", renderer);
    SDL_Texture *Target = loadTexture(resPath + "Target.png", renderer);
    SDL_Texture *sphere2 = loadTexture(resPath + "sphere2.png", renderer);
    SDL_Texture *Target2 = loadTexture(resPath + "Target2.png", renderer);
    SDL_Texture *trialStart = loadTexture(resPath + "trialStart.png", renderer);
    SDL_Texture *trialEnd = loadTexture(resPath + "trialEnd.png", renderer);
    SDL_Event event;

    if (background == nullptr || background2 == nullptr || sphere == nullptr || instruction2 == nullptr || Target == nullptr || sphere2 == nullptr || Target2 == nullptr ||
            trialStart == nullptr || trialEnd == nullptr || instruction == nullptr || trial_background == nullptr )
    {
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        SDL_Quit();
        return 1;
    }

    SDL_GetWindowSize(window, &SCREEN_WIDTH, &SCREEN_HEIGHT);
    // Wait for Synchronization between OpenBCI and Feedback Display
    SDL_RenderClear(renderer);
    renderTexture(background, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);

    // Obtain the timer as well as the logging files
    const std::string Feature1 = getResourcePath("FIFO") + "X_Direction.txt";
    const std::string Feature2 = getResourcePath("FIFO") + "Y_Direction.txt";
    const std::string Trial_Info = getResourcePath("FIFO") + "Trial_Information.txt";
    const std::string Trigger_Log = getResourcePath("FIFO") + "Trigger_Log.txt";
    const std::string Feedback = getResourcePath("FIFO") + "Feedback_Log_0.txt";
    Sync_Send(Feedback, "Timer on");
    Sync_Wait(Trigger_Log, "All Set", "ALL FINISH", event);
    SDL_RenderClear(renderer);
    renderTexture(background2, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);

    // flag used to stop the program execution
    bool Next_Trial, Finishing;
    Finishing = false;

    // Obtain Screen Size, Create position values for objects
    Position Centroid, Ball, Goal;
    const int SPHERE_SIZE = SCREEN_HEIGHT / 10;
    const int TARGET_WIDTH = SCREEN_HEIGHT / 10;
    const int TARGET_HEIGHT = TARGET_WIDTH;
    int Margin;
    Centroid.Set(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 0, 0);
    std::string Previous_X, Previous_Y, Current_X, Current_Y;
    Feature X_Direction,Y_Direction;
    X_Direction.Set(1,0);
    Y_Direction.Set(1,0);


    // Maintain the Field of movement within Square
    if (SCREEN_HEIGHT < SCREEN_WIDTH)
        Margin = (SCREEN_WIDTH - SCREEN_HEIGHT) / 2;
    else
        Margin = 0;

    // Calibration
    if (!Sync_Wait(Trigger_Log, "Calibration On", "ALL FINISH", event)) {
        Sync_Send(Feedback,"Display End");
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        return 1;
    }

    SDL_RenderClear(renderer);
    renderTexture(instruction, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);
    if (!Sync_Wait(Trigger_Log, "Calibration Stage2", "ALL FINISH", event)) {
        Sync_Send(Feedback,"Display End");
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        return 1;
    }

    SDL_RenderClear(renderer);
    renderTexture(instruction2, renderer, (SCREEN_WIDTH - SCREEN_HEIGHT) / 2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
    SDL_RenderPresent(renderer);
    if (!Sync_Wait(Trigger_Log, "Calibration End", "ALL FINISH", event)) {
        Sync_Send(Feedback,"Display End");
        SDL_DestroyWindow(window);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyTexture(background);
        SDL_DestroyTexture(instruction);
        SDL_DestroyTexture(sphere);
        SDL_DestroyTexture(background2);
        SDL_DestroyTexture(sphere2);
        SDL_DestroyTexture(trial_background);
        SDL_DestroyTexture(Target2);
        SDL_DestroyTexture(Target);
        SDL_DestroyTexture(instruction2);
        SDL_Quit();
        return 1;
    }


    /******************************
     * The Actual Experiment Part *
    ******************************/

    while(!(Sync_Check(Trigger_Log,"ALL FINISH")||Finishing)) {
        // Determine the type of Trial
        if (!Sync_Wait(Trigger_Log, "Ready", "ALL FINISH", event)) {
            Sync_Send(Feedback,"Display End");
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyTexture(background);
            SDL_DestroyTexture(instruction);
            SDL_DestroyTexture(sphere);
            SDL_DestroyTexture(trial_background);
            SDL_DestroyTexture(background2);
            SDL_DestroyTexture(sphere2);
            SDL_DestroyTexture(Target2);
            SDL_DestroyTexture(Target);
            SDL_DestroyTexture(instruction2);
            SDL_Quit();
            return 1;
        }
        switch (Read_Trial(Trial_Info)) {
        case 0:
            Goal.Set(Margin, 0, TARGET_HEIGHT, TARGET_WIDTH);
            break;
        case 1:
            Goal.Set(SCREEN_WIDTH - Margin - TARGET_WIDTH, 0, TARGET_HEIGHT, TARGET_WIDTH);
            break;
        case 2:
            Goal.Set(Margin, SCREEN_HEIGHT - TARGET_HEIGHT, TARGET_WIDTH, TARGET_HEIGHT);
            break;
        case 3:
            Goal.Set(SCREEN_WIDTH - Margin - TARGET_WIDTH, SCREEN_HEIGHT - TARGET_HEIGHT, TARGET_WIDTH, TARGET_HEIGHT);
            break;
        }

        // Signal Trial Begin
        SDL_RenderClear(renderer);
        renderTexture(trialStart, renderer, (SCREEN_WIDTH-SCREEN_HEIGHT)/2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
        SDL_RenderPresent(renderer);
        if (!Sync_Wait(Trigger_Log,"Trial Start", "ALL FINISH", event)) {
            Sync_Send(Feedback,"Display End");
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyTexture(background);
            SDL_DestroyTexture(instruction);
            SDL_DestroyTexture(sphere);
            SDL_DestroyTexture(trial_background);
            SDL_DestroyTexture(background2);
            SDL_DestroyTexture(sphere2);
            SDL_DestroyTexture(Target2);
            SDL_DestroyTexture(Target);
            SDL_DestroyTexture(instruction2);
            SDL_Quit();
            return 1;
        }

        Ball.Set(Centroid.X - SPHERE_SIZE / 2, Centroid.Y - SPHERE_SIZE / 2, SPHERE_SIZE, SPHERE_SIZE);

        Next_Trial = false;
        while (!Next_Trial) {
            // Listen to OpenBCI for Location Data
            Current_X = DirectionalReader(Feature1, Previous_X);
            Current_Y = DirectionalReader(Feature2, Previous_Y);

            if (Current_X != "No Update" && Current_Y != "No Update") {
                Y_Direction = DecodeString(Current_Y);
                X_Direction = DecodeString(Current_X);
                Previous_X = Current_X;
                Previous_Y = Current_Y;

                for (int rate = 0; rate < 10; rate++) {
                    Ball.Translocation(X_Direction.Results[0],Y_Direction.Results[0]);
                    Ball.rangeCheck(Margin, SCREEN_WIDTH - Margin, 0, SCREEN_HEIGHT);
                    SDL_RenderClear(renderer);
                    renderTexture(trial_background, renderer, Margin, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
                    renderTexture(sphere, renderer, Ball.X, Ball.Y, Ball.W, Ball.H);
                    renderTexture(Target, renderer, Goal.X, Goal.Y, Goal.W, Goal.H);
                    SDL_RenderPresent(renderer);
                    if (Determine_Location(Ball,Goal)) {
                        Next_Trial = true;
                        rate = 10;
                        SDL_RenderClear(renderer);
                        renderTexture(trial_background, renderer, Margin, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
                        renderTexture(sphere2, renderer, Ball.X, Ball.Y, Ball.W, Ball.H);
                        renderTexture(Target2, renderer, Goal.X, Goal.Y, Goal.W, Goal.H);
                        SDL_RenderPresent(renderer);
                        Sync_Send(Feedback,"Complete");
                        SDL_Delay(1000);
                    }
                    if (EventDetection(event) == SDL_SCANCODE_Q) {
                        Next_Trial = true;
                        Finishing = true;
                        Sync_Send(Feedback,"Complete");
                    }
                }
            }

            if (Sync_Check(Trigger_Log,"Trial End")) {
                Next_Trial = true;
            }
            // Check for Break or other commands
            if (EventDetection(event) == SDL_SCANCODE_Q) {
                Next_Trial = true;
                Finishing = true;
                Sync_Send(Feedback,"Complete");
            }
        }

        SDL_RenderClear(renderer);
        renderTexture(trialEnd, renderer, (SCREEN_WIDTH-SCREEN_HEIGHT)/2, 0, SCREEN_HEIGHT, SCREEN_HEIGHT);
        SDL_RenderPresent(renderer);
        if (!Sync_Wait(Trigger_Log,"Trial End", "ALL FINISH", event)) {
            Sync_Send(Feedback,"Display End");
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyTexture(background);
            SDL_DestroyTexture(instruction);
            SDL_DestroyTexture(sphere);
            SDL_DestroyTexture(trial_background);
            SDL_DestroyTexture(background2);
            SDL_DestroyTexture(sphere2);
            SDL_DestroyTexture(Target2);
            SDL_DestroyTexture(Target);
            SDL_DestroyTexture(instruction2);
            SDL_Quit();
            return 1;
        }
    }

    // Cleanning up
    Sync_Send(Feedback,"Display End");
    SDL_DestroyWindow(window);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyTexture(background);
    SDL_DestroyTexture(instruction);
    SDL_DestroyTexture(sphere);
    SDL_DestroyTexture(trial_background);
    SDL_DestroyTexture(background2);
    SDL_DestroyTexture(sphere2);
    SDL_DestroyTexture(Target2);
    SDL_DestroyTexture(Target);
    SDL_DestroyTexture(instruction2);
    SDL_Quit();
    return 0;
}
Exemplo n.º 19
0
Arquivo: hdr.cpp Projeto: Bewolf2/bgfx
int _main_(int /*_argc*/, char** /*_argv*/)
{
	PosColorTexCoord0Vertex::init();

	uint32_t width = 1280;
	uint32_t height = 720;
	uint32_t debug = BGFX_DEBUG_TEXT;
	uint32_t reset = BGFX_RESET_VSYNC;

	bgfx::init();
	bgfx::reset(width, height, reset);

	// Enable debug text.
	bgfx::setDebug(debug);

	// Set view 0 clear state.
	bgfx::setViewClear(0
		, BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
		, 0x303030ff
		, 1.0f
		, 0
		);

	// Setup root path for binary shaders. Shader binaries are different 
	// for each renderer.
	switch (bgfx::getRendererType() )
	{
	default:
	case bgfx::RendererType::Direct3D9:
		s_shaderPath = "shaders/dx9/";
		s_texelHalf = 0.5f;
		break;

	case bgfx::RendererType::Direct3D11:
		s_shaderPath = "shaders/dx11/";
		break;

	case bgfx::RendererType::OpenGL:
		s_shaderPath = "shaders/glsl/";
		s_flipV = true;
		break;

	case bgfx::RendererType::OpenGLES2:
	case bgfx::RendererType::OpenGLES3:
		s_shaderPath = "shaders/gles/";
		s_flipV = true;
		break;
	}

	const bgfx::Memory* mem;

	mem = loadTexture("uffizi.dds");
	bgfx::TextureHandle uffizi = bgfx::createTexture(mem, BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP|BGFX_TEXTURE_W_CLAMP);

	bgfx::UniformHandle u_time      = bgfx::createUniform("u_time",     bgfx::UniformType::Uniform1f);
	bgfx::UniformHandle u_texCube   = bgfx::createUniform("u_texCube",  bgfx::UniformType::Uniform1i);
	bgfx::UniformHandle u_texColor  = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1i);
	bgfx::UniformHandle u_texLum    = bgfx::createUniform("u_texLum",   bgfx::UniformType::Uniform1i);
	bgfx::UniformHandle u_texBlur   = bgfx::createUniform("u_texBlur",  bgfx::UniformType::Uniform1i);
	bgfx::UniformHandle u_mtx       = bgfx::createUniform("u_mtx",      bgfx::UniformType::Uniform4x4fv);
	bgfx::UniformHandle u_tonemap   = bgfx::createUniform("u_tonemap",  bgfx::UniformType::Uniform4fv);
	bgfx::UniformHandle u_offset    = bgfx::createUniform("u_offset",   bgfx::UniformType::Uniform4fv, 16);
	bgfx::UniformHandle u_weight    = bgfx::createUniform("u_weight",   bgfx::UniformType::Uniform4fv, 16);

	bgfx::ProgramHandle skyProgram     = loadProgram("vs_hdr_skybox",  "fs_hdr_skybox");
	bgfx::ProgramHandle lumProgram     = loadProgram("vs_hdr_lum",     "fs_hdr_lum");
	bgfx::ProgramHandle lumAvgProgram  = loadProgram("vs_hdr_lumavg",  "fs_hdr_lumavg");
	bgfx::ProgramHandle blurProgram    = loadProgram("vs_hdr_blur",    "fs_hdr_blur");
	bgfx::ProgramHandle brightProgram  = loadProgram("vs_hdr_bright",  "fs_hdr_bright");
	bgfx::ProgramHandle meshProgram    = loadProgram("vs_hdr_mesh",    "fs_hdr_mesh");
	bgfx::ProgramHandle tonemapProgram = loadProgram("vs_hdr_tonemap", "fs_hdr_tonemap");

	Mesh mesh;
	mesh.load("meshes/bunny.bin");

	bgfx::RenderTargetHandle rt = bgfx::createRenderTarget(width, height, BGFX_RENDER_TARGET_COLOR_RGBA8|BGFX_RENDER_TARGET_DEPTH);

	bgfx::RenderTargetHandle lum[5];
	lum[0] = bgfx::createRenderTarget(128, 128, BGFX_RENDER_TARGET_COLOR_RGBA8);
	lum[1] = bgfx::createRenderTarget( 64,  64, BGFX_RENDER_TARGET_COLOR_RGBA8);
	lum[2] = bgfx::createRenderTarget( 16,  16, BGFX_RENDER_TARGET_COLOR_RGBA8);
	lum[3] = bgfx::createRenderTarget(  4,   4, BGFX_RENDER_TARGET_COLOR_RGBA8);
	lum[4] = bgfx::createRenderTarget(  1,   1, BGFX_RENDER_TARGET_COLOR_RGBA8);

	bgfx::RenderTargetHandle bright;
	bright = bgfx::createRenderTarget(width/2, height/2, BGFX_RENDER_TARGET_COLOR_RGBA8);

	bgfx::RenderTargetHandle blur;
	blur = bgfx::createRenderTarget(width/8, height/8, BGFX_RENDER_TARGET_COLOR_RGBA8);

	FILE* file = fopen("font/droidsans.ttf", "rb");
	uint32_t size = (uint32_t)fsize(file);
	void* data = malloc(size);
	size_t ignore = fread(data, 1, size, file);
	BX_UNUSED(ignore);
	fclose(file);

	imguiCreate(data, size);

	free(data);

	float speed      = 0.37f;
	float middleGray = 0.18f;
	float white      = 1.1f;
	float treshold   = 1.5f;

	int32_t scrollArea = 0;

	uint32_t oldWidth = 0;
	uint32_t oldHeight = 0;

	entry::MouseState mouseState;

	float time = 0.0f;

	while (!entry::processEvents(width, height, debug, reset, &mouseState) )
	{
		if (oldWidth != width
		||  oldHeight != height)
		{
			// Recreate variable size render targets when resolution changes.
			oldWidth = width;
			oldHeight = height;
			bgfx::destroyRenderTarget(rt);
			bgfx::destroyRenderTarget(bright);
			bgfx::destroyRenderTarget(blur);

			rt = bgfx::createRenderTarget(width, height, BGFX_RENDER_TARGET_COLOR_RGBA8|BGFX_RENDER_TARGET_DEPTH);
			bright = bgfx::createRenderTarget(width/2, height/2, BGFX_RENDER_TARGET_COLOR_RGBA8);
			blur = bgfx::createRenderTarget(width/8, height/8, BGFX_RENDER_TARGET_COLOR_RGBA8);
		}

		imguiBeginFrame(mouseState.m_mx
			, mouseState.m_my
			, (mouseState.m_buttons[entry::MouseButton::Left  ] ? IMGUI_MBUT_LEFT  : 0)
			| (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
			, 0
			, width
			, height
			);

		imguiBeginScrollArea("Settings", width - width / 5 - 10, 10, width / 5, height / 3, &scrollArea);
		imguiSeparatorLine();

		imguiSlider("Speed", &speed, 0.0f, 1.0f, 0.01f);
		imguiSeparator();

		imguiSlider("Middle gray", &middleGray, 0.1f, 1.0f, 0.01f);
		imguiSlider("White point", &white, 0.1f, 2.0f, 0.01f);
		imguiSlider("Treshold", &treshold, 0.1f, 2.0f, 0.01f);

		imguiEndScrollArea();
		imguiEndFrame();

		// This dummy draw call is here to make sure that view 0 is cleared
		// if no other draw calls are submitted to view 0.
		bgfx::submit(0);

		int64_t now = bx::getHPCounter();
		static int64_t last = now;
		const int64_t frameTime = now - last;
		last = now;
		const double freq = double(bx::getHPFrequency() );
		const double toMs = 1000.0/freq;

		time += (float)(frameTime*speed/freq);

		bgfx::setUniform(u_time, &time);

		// Use debug font to print information about this example.
		bgfx::dbgTextClear();
		bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/09-hdr");
		bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Using multiple views and render targets.");
		bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);

		// Set views.
		bgfx::setViewRectMask(0x1f, 0, 0, width, height);
		bgfx::setViewRenderTargetMask(0x3, rt);

		bgfx::setViewRect(2, 0, 0, 128, 128);
		bgfx::setViewRenderTarget(2, lum[0]);

		bgfx::setViewRect(3, 0, 0, 64, 64);
		bgfx::setViewRenderTarget(3, lum[1]);

		bgfx::setViewRect(4, 0, 0, 16, 16);
		bgfx::setViewRenderTarget(4, lum[2]);

		bgfx::setViewRect(5, 0, 0, 4, 4);
		bgfx::setViewRenderTarget(5, lum[3]);

		bgfx::setViewRect(6, 0, 0, 1, 1);
		bgfx::setViewRenderTarget(6, lum[4]);

		bgfx::setViewRect(7, 0, 0, width/2, height/2);
		bgfx::setViewRenderTarget(7, bright);

		bgfx::setViewRect(8, 0, 0, width/8, height/8);
		bgfx::setViewRenderTarget(8, blur);

		bgfx::setViewRect(9, 0, 0, width, height);

		float view[16];
		float proj[16];

		mtxIdentity(view);
		mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f);

		// Set view and projection matrix for view 0.
		bgfx::setViewTransformMask(0
				|(1<<0)
				|(1<<2)
				|(1<<3)
				|(1<<4)
				|(1<<5)
				|(1<<6)
				|(1<<7)
				|(1<<8)
				|(1<<9)
				, view
				, proj
				);

		float at[3] = { 0.0f, 1.0f, 0.0f };
		float eye[3] = { 0.0f, 1.0f, -2.5f };

		float mtx[16];
		mtxRotateXY(mtx
			, 0.0f
			, time
			); 

		float temp[4];
		vec3MulMtx(temp, eye, mtx);

		mtxLookAt(view, temp, at);
		mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f);

		// Set view and projection matrix for view 1.
		bgfx::setViewTransformMask(1<<1, view, proj);

		bgfx::setUniform(u_mtx, mtx);

		// Render skybox into view 0.
		bgfx::setTexture(0, u_texCube, uffizi);
		bgfx::setProgram(skyProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad( (float)width, (float)height, true);
		bgfx::submit(0);

		// Render mesh into view 1
		bgfx::setTexture(0, u_texCube, uffizi);
		mesh.submit(1, meshProgram, NULL);

		// Calculate luminance.
		setOffsets2x2Lum(u_offset, 128, 128);
		bgfx::setTexture(0, u_texColor, rt);
		bgfx::setProgram(lumProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad(128.0f, 128.0f, s_flipV);
		bgfx::submit(2);

		// Downscale luminance 0.
		setOffsets4x4Lum(u_offset, 128, 128);
		bgfx::setTexture(0, u_texColor, lum[0]);
		bgfx::setProgram(lumAvgProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad(64.0f, 64.0f, s_flipV);
		bgfx::submit(3);

		// Downscale luminance 1.
		setOffsets4x4Lum(u_offset, 64, 64);
		bgfx::setTexture(0, u_texColor, lum[1]);
		bgfx::setProgram(lumAvgProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad(16.0f, 16.0f, s_flipV);
		bgfx::submit(4);

		// Downscale luminance 2.
		setOffsets4x4Lum(u_offset, 16, 16);
		bgfx::setTexture(0, u_texColor, lum[2]);
		bgfx::setProgram(lumAvgProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad(4.0f, 4.0f, s_flipV);
		bgfx::submit(5);

		// Downscale luminance 3.
		setOffsets4x4Lum(u_offset, 4, 4);
		bgfx::setTexture(0, u_texColor, lum[3]);
		bgfx::setProgram(lumAvgProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad(1.0f, 1.0f, s_flipV);
		bgfx::submit(6);

		float tonemap[4] = { middleGray, square(white), treshold, 0.0f };
		bgfx::setUniform(u_tonemap, tonemap);

		// Bright pass treshold is tonemap[3].
		setOffsets4x4Lum(u_offset, width/2, height/2);
		bgfx::setTexture(0, u_texColor, rt);
		bgfx::setTexture(1, u_texLum, lum[4]);
		bgfx::setProgram(brightProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad( (float)width/2.0f, (float)height/2.0f, s_flipV);
		bgfx::submit(7);

		// Blur bright pass vertically.
		bgfx::setTexture(0, u_texColor, bright);
		bgfx::setProgram(blurProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad( (float)width/8.0f, (float)height/8.0f, s_flipV);
		bgfx::submit(8);

		// Blur bright pass horizontally, do tonemaping and combine.
		bgfx::setTexture(0, u_texColor, rt);
		bgfx::setTexture(1, u_texLum, lum[4]);
		bgfx::setTexture(2, u_texBlur, blur);
		bgfx::setProgram(tonemapProgram);
		bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE);
		screenSpaceQuad( (float)width, (float)height, s_flipV);
		bgfx::submit(9);

		// Advance to next frame. Rendering thread will be kicked to 
		// process submitted rendering primitives.
		bgfx::frame();
	}

	imguiDestroy();

	// Cleanup.
	mesh.unload();

	bgfx::destroyRenderTarget(lum[0]);
	bgfx::destroyRenderTarget(lum[1]);
	bgfx::destroyRenderTarget(lum[2]);
	bgfx::destroyRenderTarget(lum[3]);
	bgfx::destroyRenderTarget(lum[4]);
	bgfx::destroyRenderTarget(bright);
	bgfx::destroyRenderTarget(blur);
	bgfx::destroyRenderTarget(rt);

	bgfx::destroyProgram(meshProgram);
	bgfx::destroyProgram(skyProgram);
	bgfx::destroyProgram(tonemapProgram);
	bgfx::destroyProgram(lumProgram);
	bgfx::destroyProgram(lumAvgProgram);
	bgfx::destroyProgram(blurProgram);
	bgfx::destroyProgram(brightProgram);
	bgfx::destroyTexture(uffizi);

	bgfx::destroyUniform(u_time);
	bgfx::destroyUniform(u_texCube);
	bgfx::destroyUniform(u_texColor);
	bgfx::destroyUniform(u_texLum);
	bgfx::destroyUniform(u_texBlur);
	bgfx::destroyUniform(u_mtx);
	bgfx::destroyUniform(u_tonemap);
	bgfx::destroyUniform(u_offset);
	bgfx::destroyUniform(u_weight);

	// Shutdown bgfx.
	bgfx::shutdown();

	return 0;
}
Exemplo n.º 20
0
int main(int argc, char* args[]) {
    // This will be the window we'll be rendering to
    SDL_Window *window = NULL;

    SDL_Renderer *renderer = NULL;

    TTF_Font *font;

    SDL_Texture *sheet = NULL;
    Text text;

    init_sprites();
    event_init();

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL_ERROR: %s\n", SDL_GetError());
    } else {
        //if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, 1)) {
        //    printf("Warning: Linear texture filtering not enabled");
        //}
        window = SDL_CreateWindow("Piggle",
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SDL_WINDOWPOS_UNDEFINED,
                                  SCREEN_WIDTH,
                                  SCREEN_HEIGHT,
                                  SDL_WINDOW_SHOWN);
        if (window == NULL) {
            printf("Window could not be created! SDL_Error: %s\n",
                   SDL_GetError());
        } else {
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == NULL) {
                printf("Renderer couldn't be created. Shit's f****d, becuase %s"
                       ", dude.\n", SDL_GetError());
            } else {
                SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);

                int imgFlags = IMG_INIT_PNG;
                if (!(IMG_Init(imgFlags) & imgFlags)) {
                    printf("SDL_image couldn't be initialized. Shit's f****d, "
                           "because %s, dude.\n", IMG_GetError());
                }

                if (TTF_Init() == -1) {
                    printf("SDL_ttf couldn't initialize. Shit's f****d, becuase"
                           " %s, dude.\n", TTF_GetError());
                }
            }
            font = TTF_OpenFont("DroidSansMono.ttf", 16);
            if (font == NULL) {
                printf("Failed to load lazy font. Shit's f****d, because %s, "
                       "dude.", TTF_GetError());
            }
                
            sheet = loadTexture("img/sprites.png", renderer);
            // When quit is set to true, we'll stop running
            bool quit = false;
            piggle_scene_over = false;
            // Event handler
            SDL_Event sdl_event;

            // Set the current scene to the start scene
            piggle_scene_update = start_scene_update;

            while (!quit) {
                timer_start();
                EventList events = EventList_new();
                while (SDL_PollEvent(&sdl_event) != 0) {
                    Event event;
                    // If the user presses that little "x"
                    if (sdl_event.type == SDL_QUIT) {
                        quit = true;
                        event.type = QUIT;
                    } else if (sdl_event.type == SDL_KEYDOWN) {
                        event.type = KEYDOWN;
                        int key = sdl_event.key.keysym.sym;
                        event.value = event_value_from_key(key);
                    } else if (sdl_event.type == SDL_KEYUP) {
                        event.type = KEYUP;
                        int key = sdl_event.key.keysym.sym;
                        event.value = event_value_from_key(key);
                    } else {
                        continue;
                    }
                    events.add_event(&events, event);
                }
                SDL_RenderClear(renderer);
                DrawActionList actions = DrawActionList_new();
                piggle_scene_update(&events, &actions);
                events.destroy(&events);
                int i;
                for (i = 0; i < actions.length; i++) {
                    DrawAction action = actions.actions[i];
                    if (action.type == SPRITE) {
                        SDL_Rect *sprite = &sprites[action.sprite];
                        SDL_Rect dest;
                        dest.x = action.x;
                        dest.y = action.y;
                        dest.w = sprite->w;
                        dest.h = sprite->h;
                        SDL_RenderCopy(renderer, sheet, sprite, &dest);
                    } else if (action.type == TEXT) {
                        SDL_Color color = {action.text.red,
                                           action.text.green,
                                           action.text.blue};
                        textureFromText(action.text.text, color, &text, font,
                                        renderer);
                        SDL_Rect textRect;
                        textRect.x = action.x;
                        textRect.y = action.y;
                        textRect.w = text.width;
                        textRect.h = text.height;
                        SDL_RenderCopy(renderer, text.texture, NULL, &textRect);
                        SDL_DestroyTexture(text.texture);
                    } else if (action.type == RECTANGLE) {
                        SDL_Rect rect = {.x = action.x,
                                         .y = action.y,
                                         .w = action.rect.width,
                                         .h = action.rect.height};
                        SDL_SetRenderDrawColor(renderer, action.rect.red,
                                               action.rect.green,
                                               action.rect.blue, 255);
                        SDL_RenderFillRect(renderer, &rect);
                    }
                }
                SDL_RenderPresent(renderer);
                actions.destroy(&actions);
                if (piggle_scene_over) {
                    piggle_scene_update = piggle_scene_next;
                    piggle_scene_over = false;
                }
                if (timer_get_ticks() < 1000 / 60) {
                    SDL_Delay((1000 / 60) - timer_get_ticks());
                }
            }
        }
    }

    SDL_DestroyTexture(sheet);
    SDL_DestroyTexture(text.texture);
    text.texture = NULL;
    sheet = NULL;
    TTF_CloseFont(font);
    font = NULL;
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    window = NULL;
    renderer = NULL;

    // Quit SDL subsystems
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

    event_uninit();

    return 0;
}
Exemplo n.º 21
0
// Entry point in the program
int main(int argc, char **argv)
{
    std::cout<<std::endl<<std::endl<<"________Template OpenGL3________"<<std::endl<<std::endl;
    //__________________________________________________________________________

    // Application creation
    std::cout<<"  Application creation"<<std::endl;
    Application * application=new Application(800, 600);
    //__________________________________________________________________________

    // Scene creation
    std::cout<<"    Scene creation"<<std::endl;
    Scene * scene=new Scene(800, 600);
    application->setScene(scene);
    GLfloat red[]= {1.0, 0.0, 0.0, 1.0};
    scene->setDefaultColor(red); // Color for the objects drawn in the scene

    //__________________________________________________________________________

    // Camera position and orientation
    std::cout<<"    Camera settings"<<std::endl;
    scene->camera->c[2]=6.0; // Position of the camera
    scene->camera->c[1]=0.0; // Position of the camera
    scene->camera->c[0]=0.0; // Position of the camera
    scene->camera->updateView();


    GLfloat c[]= {-0.2, 0.3, 0.1}; // Camera position
    GLfloat aim[]= {0.0, 0.0, 0.0}; // Where we look
    GLfloat up[]= {0.0, 1.0, 0.0}; // Vector pointing over the camera
    //scene->camera->lookAt(c, aim, up);

    //__________________________________________________________________________

    // Creation of the shaders
    std::cout<<"    Shaders reading, compiling and linking"<<std::endl;

    // Compilation and storage of the program
    std::vector<std::string> files;

    // The special shaders used for mac os are only necesary until Snow Leopard
    // From Leon on, mac os drivers version for Opengl is 3.2
    // Therefore the shaders in folder oldGLSL become out-of-date

    // One very simple shader (one color everywhere on the object)
    files.push_back("../shaders/simpleShader.glsl");
    GLuint simpleShaderID=loadProgram(files);
    files.pop_back();
    scene->setDefaultShaderID(simpleShaderID);

    // One coloring shader (colors per vertex)
    files.push_back("../shaders/colorShader.glsl");
    GLuint colorShaderID=loadProgram(files);
    files.pop_back();

    // One lighting shader
#ifdef APPLE
    files.push_back("../shaders/oldGLSL/shaderTools.glsl");
    files.push_back("../shaders/oldGLSL/lightingShader.glsl");
#else
    files.push_back("../shaders/shaderTools.glsl");
    files.push_back("../shaders/lightingShader.glsl");
#endif
    GLuint lightingShaderID=loadProgram(files);
    files.pop_back();
    scene->setDefaultShaderID(lightingShaderID);


    // Uniforms filling
    glUseProgram(lightingShaderID);
    // Material creation and to shader
    GLfloat ambient[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat ka=0.01;
    GLfloat diffuse[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat kd=1.0;
    GLfloat specular[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat ks=2.0;
    GLfloat shininess=5.0;
    setMaterialInShader(lightingShaderID, ambient, diffuse, specular, ka, kd, ks, shininess);

    files.push_back("../shaders/persoShader.glsl");
    GLuint persoShaderID=loadProgram(files);
    files.pop_back();

    // Light creation
    GLfloat lightPosition[]= {1.0, 1.0, 1.0, 1.0};
    GLfloat lightPower=2.0;
    scene->setLight(lightPosition, lightPower);

    // One texture and Phong shader
#ifdef __APPLE__
    files.push_back("../shaders/oldGLSL/lightingTexturingShader.glsl");
#else
    files.push_back("../shaders/lightingTexturingShader.glsl");
#endif
    GLuint lightingTextureShaderID=loadProgram(files);
    files.pop_back();
    glUseProgram(lightingTextureShaderID);
    setMaterialInShader(lightingTextureShaderID, ambient, diffuse, specular, ka, kd, ks, shininess);
    setTextureUnitsInShader(lightingTextureShaderID);


    //__________________________________________________________________________


    // Creation of the objects to store
    std::cout<<"    Generic objects creation and storage :"<<std::endl;

    // Définition du repère
    Object * objectAxis=new Object(GL_LINES);
    GLuint storedObjectAxisID=scene->storeObject(objectAxis);


    // Définition boundingBox
    Object * objectBB=new Object(GL_TRIANGLES);
    GLuint storedObjectBBID=scene->storeObject(objectBB);

    // Définition de la cible
    Object * objectCible=new Object(GL_LINES);
    GLuint storedObjectCibleID=scene->storeObject(objectCible);

    // Environnement
    Object * objectLaby=new Object(GL_TRIANGLES);
    GLuint storedObjectLaby=scene->storeObject(objectLaby);
    bool smoothObjectFlag=true;
    GLuint houseTextureDiffuseID=loadTexture("../textures/mur_contour.ppm");
    GLuint houseTextureSpecularID=loadTexture("../textures/mur_contour.ppm");

    //portal
    Object * objectPortal = new Object(GL_TRIANGLES);
    GLuint storedObjectPortal=scene->storeObject(objectPortal);
    //std::cout<<"IIIIIDDDDDD"<<storedObjectPortal<<std::endl;

    GLuint portalTextureDiffuseID=loadTexture("../textures/mur_contour.ppm");
    GLuint portalTextureSpecularID=loadTexture("../textures/mur_contour.ppm");

    /*Object * objectTr=new Object(GL_TRIANGLES);
    GLuint storedObjectTrID=scene->storeObject(objectTr);*/

//__________________________________________________________________________

    // Object building
    std::cout<<"    Generic objects building :"<<std::endl;


    // Construction du repère
    buildAxis(objectAxis);

    //Construction boundingBox
    //buildCube(objectBB);

    // Construction de la cible
    buildCircle(objectCible, 0.3, 20);

    //environnement
    std::string fileName="../objs/contour.obj";

    buildObjectGeometryFromOBJ(objectLaby, fileName, smoothObjectFlag, 10,10,10);

    /*std::cout << indicesObj[3] << " " << indicesObj[4] << indicesObj[5] << std::endl;

    std::cout << verticesObj[11*4] << " " << verticesObj[11*4+1] << " " << verticesObj[11*4+2] << " " << verticesObj[11*4+3] << std::endl;
    std::cout << verticesObj[10*4] << " " << verticesObj[10*4+1] << " " << verticesObj[10*4+2] << " " << verticesObj[10*4+3] << std::endl;
    std::cout << verticesObj[4] << " " << verticesObj[4+1] << " " << verticesObj[4+2] << " " << verticesObj[4+3] << std::endl << std::endl;

    std::cout << verticesObj[4] << " " << verticesObj[4+1] << " " << verticesObj[4+2] << " " << verticesObj[4+3] << std::endl;
    std::cout << verticesObj[0] << " " << verticesObj[1] << " " << verticesObj[2] << " " << verticesObj[3] << std::endl;
    std::cout << verticesObj[11*4] << " " << verticesObj[11*4+1] << " " << verticesObj[11*4+2] << " " << verticesObj[11*4+3] << std::endl << std::endl;

    for (int i=0; i<24; ++i)
    	std::cout << application->objVertices[i] << " " ;

    std::cout << std::endl;

    std::string fileNamePortal="../objs/portail.obj";
    std::vector<GLfloat> verticesObjPortal;
    std::vector<GLuint> indicesObjPortal;
    std::vector<GLfloat> normalsObjPortal;
    buildObjectGeometryFromOBJ(objectPortal, fileNamePortal, smoothObjectFlag, verticesObjPortal, indicesObjPortal, normalsObjPortal);*/


    /*std::string fileNamePortal="../objs/portail.obj";
    std::vector<GLfloat> verticesObjPortal;
    std::vector<GLuint> indicesObjPortal;
    std::vector<GLfloat> normalsObjPortal;
    buildObjectGeometryFromOBJ(objectPortal, fileNamePortal, smoothObjectFlag, verticesObjPortal, indicesObjPortal, normalsObjPortal);*/


    //__________________________________________________________________________

    // Objects we want to see
    std::cout<<"    Objects to draw setting"<<std::endl;


    //axis
    GLuint axisID=scene->addObjectToDraw(storedObjectAxisID);
    scene->setDrawnObjectShaderID(axisID, lightingShaderID);

    //BoundingBox
    GLuint BBID=scene->addObjectToDraw(storedObjectBBID);
    //scene->setDrawnObjectShaderID(BBID, lightingShaderID);

    GLfloat yellow[4]= {0.0, 0.8, 0.4, 1.0};
    scene->setDrawnObjectColor(BBID, yellow);


    //cible
    GLuint cibleID=scene->addObjectToDraw(storedObjectCibleID);
    scene->setDrawnObjectShaderID(cibleID, lightingShaderID);
    GLfloat blue[4]= {0.0, 0.3, 0.7, 1.0};
    scene->setDrawnObjectColor(cibleID, blue);

    //environnement
    GLfloat S[16];
    GLfloat s[3] = {3.0, 2.0, 3.0} ;
    setToScale(S, s);

    GLuint labyID=scene->addObjectToDraw(storedObjectLaby);
    //scene->setDrawnObjectModel(labyID, S);
    scene->setDrawnObjectColor(labyID, red);
    scene->setDrawnObjectShaderID(labyID, lightingShaderID);
    //std::cout<<"ID SHADER :"<<lightingShaderID<<std::endl;
    /*cible
    GLuint trID=scene->addObjectToDraw(storedObjectTrID);
    scene->setDrawnObjectShaderID(trID, lightingShaderID);
    GLfloat zarb[4]={0.4, 0.7, 0.2, 1.0};
    scene->setDrawnObjectColor(trID, zarb);*/

    std::cout<<scene->nbStoredObjects<<std::endl;

    //__________________________________________________________________________

    // Other informations
    // Background color creation
    GLfloat black[]= {0.0, 0.0, 0.0, 1.0};
    application->setBackgroundColor(black);

    //__________________________________________________________________________

    // Errors checking
    std::cout<<"    Errors cheking before the loop"<<std::endl;
    printGlErrors();
    std::cout<<std::endl;
    //__________________________________________________________________________

    // Loop start !
    std::cout<<"    Looping !! "<<std::endl;
    application->lastStartTime=getTime();
    application->initTimers();
    application->loop();
    printGlErrors();
    std::cout<<std::endl;
    //__________________________________________________________________________

    // Cleaning and finishing
    std::cout<<"    Cleaning before leaving"<<std::endl;
    delete application;

    return 0;
}
Exemplo n.º 22
0
bool Material::loadTexture(aiString FILEPATH)
{
	addTexture(FILEPATH);

	return loadTexture();
}
Exemplo n.º 23
0
Texture::Texture(const char *filename, GLuint shaderIndex) 
	: _filename(filename), _shaderIndex(shaderIndex)
{
	_id = loadTexture();
}
Exemplo n.º 24
0
// Set our default damage, position and velocity
Projectile::Projectile()
{
	setDamage(1);
	
	switch (rand() % 10)
	{
	case 0:
		setPos(Vector2(-10, 0));
		break;
	case 1:
		setPos(Vector2(-20, 0));
		break;
	case 2:
		setPos(Vector2(-10, -10));
		break;
	case 3:
		setPos(Vector2(10, 10));
		break;
	case 4:
		setPos(Vector2(10, -10));
		break;
	case 5:
		setPos(Vector2(10, -20));
		break;
	case 6:
		setPos(Vector2(20, -10));
		break;
	case 7:
		setPos(Vector2(-10, 20));
		break;
	case 8:
		setPos(Vector2(-20, 10));
		break;
	case 9:
		setPos(Vector2(-10, 30));
		break;
	default:
		setPos(Vector2(-30, 10));
		break;
		break;
	}

	setVel(Vector2(0, 0));
	setDim(Vector2(16, 16));

	accRate = 8;
	attackSpeed = 12;
	maxSpeed = 10;

	attackTimer = 2;
	timerSet = false;

	dest = Vector2(0, 0);
	attacking = false;

	setSpriteName("Projectile");

	if (!loaded)
	{
		loadTexture(getSpriteName(), "../textures/projectile.png", 1, 1);
		loaded = true;
	}
}
Exemplo n.º 25
0
void display(void)
{
	kuhl_limitfps(100);
	dgr_update();
	// Make sure slaves get updates ASAP
	dgr_setget("currentTex", &currentTexture, sizeof(int));


	/* If the texture has changed since we were previously in display() */
	if(alreadyDisplayedTexture != currentTexture)
	{
		// Load the new texture
		loadTexture(currentTexture);
		// Keep a record of which texture we are currently displaying
		// so we can detect when DGR changes currentTexture on a
		// slave.
		alreadyDisplayedTexture = currentTexture;
	}

	/* The view frustum is an orthographic frustum for this
	 * application. The size of the frustum doesn't matter much, but
	 * the aspect ratio of the frustum should match the aspect ratio
	 * of the screen/window. */
	float frustum[6], masterFrustum[6];
	
	/* The following two methods will get the master view frustum and
	 * the current process view frustum. If we are running in a
	 * standalone version, these two frustums will be the same. */
	projmat_get_master_frustum(masterFrustum);
	projmat_get_frustum(frustum, -1, -1); // frustum of this process (master or slave)

	/* Set this view frustum for this process. */
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(frustum[0],frustum[1],
	        frustum[2],frustum[3],
	        -1, 1);
	glMatrixMode(GL_MODELVIEW);

	// Middle of master frustum in the vertical direction. It divides the top
	// tiles from the bottom tiles.
	float masterFrustumMid = (masterFrustum[2]+masterFrustum[3])/2;
	// Dimensions of the master view frustum
	float masterFrustumWidth  = masterFrustum[1]-masterFrustum[0];
	float masterFrustumHeight = masterFrustum[3]-masterFrustum[2];

	// The width of the quad (in frustum units). Since the image will
	// be stretched to fit the screen vertically, and our units are in
	// frustum units, the width of the tile is the height of the
	// frustum times the aspect ratio divided by the number of tiles
	// in the horizontal direction.
	float quadWidth = aspectRatio * masterFrustumHeight;
	float tileWidth = quadWidth/numTiles;

// TODO: Maybe just scale the image vertically if the image almost fits in the screen horizontally?

	int msSincePictureDisplayed = glutGet(GLUT_ELAPSED_TIME)-lastAdvance;
	int scrollStatus = 0; // 0=don't need to scroll or done scrolling, 1=currently scrolling
	if(masterFrustumWidth < quadWidth)// do we need to scroll on this image
	{
		// Do we still need to scroll?
		if(scrollAmount < quadWidth-masterFrustumWidth)
			scrollStatus = 1;

		if(scrollStatus == 1)
		{
			// Wait a few seconds before scrolling. It takes a while
			// for all slaves on IVS to get the images.
			if(msSincePictureDisplayed > 5000)
				scrollAmount = ((msSincePictureDisplayed-5000) / (SCROLL_SPEED*1000.0))*masterFrustumWidth;
			else
				scrollAmount = 0;

			// If we calculated the scroll amount to be the largest
			// scrollAmount we'll need
			if(scrollAmount > quadWidth-masterFrustumWidth)
			{
				// dwell at the end of the image even if autoadvance is on.
				int now = glutGet(GLUT_ELAPSED_TIME);
				// make sure we still have a few seconds before advancing
				if(SLIDESHOW_WAIT*1000-(now-lastAdvance) < 3000)
				{
					// Go back and set lastAdvance time so we have
					// some time to dwell here.
					lastAdvance = now-SLIDESHOW_WAIT*1000+3000;
				}
			}
		}
	}

	dgr_setget("scrollAmount", &scrollAmount, sizeof(float));

	/* If autoadvance is set and we are not scrolling (or done
	 * scrolling) figure out if it is now time to advance to the next
	 * image. */
	if(autoAdvance == 1 && scrollStatus != 1)
	{
//		printf("time since last advance %d\n", glutGet(GLUT_ELAPSED_TIME)-lastAdvance);
		if(glutGet(GLUT_ELAPSED_TIME)-lastAdvance > SLIDESHOW_WAIT*1000) // time to show new image:
		{
			currentTexture = getNextTexture();
			loadTexture(currentTexture);
			return;
		}
	}

	glClear(GL_COLOR_BUFFER_BIT);
	glEnable(GL_TEXTURE_2D);
	glColor3f(1,1,1); // color of quad

	// Draw the top and bottom quad for each of the tiles going across the screen horizontally. */
	for(GLuint i=0; i<numTiles*2; i=i+2)
	{
		float tileLeft  = (i/2  )*tileWidth + masterFrustum[0];
		float tileRight = (i/2+1)*tileWidth + masterFrustum[0];
		
		// Draw bottom tile
		glBindTexture(GL_TEXTURE_2D, texNames[i]);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0); glVertex2d(tileLeft -scrollAmount, masterFrustum[2]); // lower left
		glTexCoord2f(1.0, 0.0); glVertex2d(tileRight-scrollAmount, masterFrustum[2]); // lower right
		glTexCoord2f(1.0, 1.0); glVertex2d(tileRight-scrollAmount, masterFrustumMid); // upper right
		glTexCoord2f(0.0, 1.0); glVertex2d(tileLeft -scrollAmount, masterFrustumMid); // upper left
		glEnd();

		// Draw top tile
		glBindTexture(GL_TEXTURE_2D, texNames[i+1]);
		glBegin(GL_QUADS);
		glTexCoord2f(0.0, 0.0); glVertex2d(tileLeft -scrollAmount, masterFrustumMid); // lower left
		glTexCoord2f(1.0, 0.0); glVertex2d(tileRight-scrollAmount, masterFrustumMid); // lower right
		glTexCoord2f(1.0, 1.0); glVertex2d(tileRight-scrollAmount, masterFrustum[3]); // upper right
		glTexCoord2f(0.0, 1.0); glVertex2d(tileLeft -scrollAmount, masterFrustum[3]); // upper left
		glEnd();
	}

	glDisable(GL_TEXTURE_2D);

	/* Draw filename label on top of a quad. */
	glColor4f(0,0,0,.3);
	glBegin(GL_QUADS);
	glVertex2d(-1,-1);
	glVertex2d(-.5,-1);
	glVertex2d(-.5,-.96);
	glVertex2d(-1,-.96);
	glEnd();

	glColor4f(1,1,1,.9);
	glRasterPos2f(-.98,-.98);
	void *font = GLUT_BITMAP_TIMES_ROMAN_24;
	char *str = globalargv[currentTexture];
	for(GLuint i=0; i<strlen(str); i++)
		glutBitmapCharacter(font, str[i]);

	/* Flush and swap the OpenGL buffers. */
	glFlush();
	glutSwapBuffers();
	glutPostRedisplay();
}
Exemplo n.º 26
0
int ObjLoader::Load(const char* fileName)
{
	//Open the model file
	ifstream in(fileName);

	//Temp buffer
	char buf[256];							

	if (!in.is_open())
	{
		//If it didn't load
		cout << "Not opened" << endl; 
		return -1;
	}

	while (!in.eof())
	{
		//While we are not at the end of the file, read everything as a string to the coord vector
		in.getline(buf, 256);
		coord.push_back(new string(buf));
	}

	//Go through the line and decide what kind of line it is
	for (int i = 0; i < coord.size(); i++) 
	{
		//If it's a comment
		if ((*coord[i])[0] == '#')
		{
			//We don't have to do anything with it
			continue;       
		}
		//If it's a vertex
		else if ((*coord[i])[0] == 'v' && (*coord[i])[1] == ' ')     
		{
			float tmpx, tmpy, tmpz;

			//Read the 3 floats, which makes up the vertex
			sscanf(coord[i]->c_str(), "v %f %f %f", &tmpx, &tmpy, &tmpz); 

			//And put it in the vertex vector
			vertex.push_back(new Vector3D(tmpx, tmpy, tmpz));      
		}
		//If it's a normal vector
		else if ((*coord[i])[0] == 'v' && (*coord[i])[1] == 'n')    
		{
			float tmpx, tmpy, tmpz;

			//Read the 3 floats, which makes up the normal
			sscanf(coord[i]->c_str(), "vn %f %f %f", &tmpx, &tmpy, &tmpz);
			
			//And put it in the normal vector
			normals.push_back(new Vector3D(tmpx, tmpy, tmpz));
			
			isnormals = true;
		}
		//If it's a face
		else if ((*coord[i])[0] == 'f')   
		{
			int a, b, c, d, e;
			
			//If this is a quad
			if (count(coord[i]->begin(), coord[i]->end(), ' ') == 4)     
			{
				//If it contains a normal vector, but doesn't contain a texture coorinate
				if (coord[i]->find("//") != string::npos)     
				{
					//Read in this form
					sscanf(coord[i]->c_str(), "f %d//%d %d//%d %d//%d %d//%d", &a, &b, &c, &b, &d, &b, &e, &b);      
					
					//We don't care about the texture coorinate in this case
					faces.push_back(new face(b, a, c, d, e, 0, 0, 0, 0, curmat));    
				}
				//If we have texture coorinate and normal vectors
				else if (coord[i]->find("/") != string::npos)        
				{
					//Texture Coorinates
					int t[4];       

					//Read in this form, and put to the end of the vector
					sscanf(coord[i]->c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d", &a, &t[0], &b, &c, &t[1], &b, &d, &t[2], &b, &e, &t[3], &b);
					faces.push_back(new face(b, a, c, d, e, t[0], t[1], t[2], t[3], curmat));
				}
				//Else we don't have normal vectors or texture coorinates
				else
				{
					sscanf(coord[i]->c_str(), "f %d %d %d %d", &a, &b, &c, &d);
					faces.push_back(new face(-1, a, b, c, d, 0, 0, 0, 0, curmat));
				}
			}
			//If it's a triangle
			else
			{  
				//Do the same, except we use one less vertex/texture coorinate/face number
				if (coord[i]->find("//") != string::npos)
				{
					sscanf(coord[i]->c_str(), "f %d//%d %d//%d %d//%d", &a, &b, &c, &b, &d, &b);
					
					faces.push_back(new face(b, a, c, d, 0, 0, 0, curmat));
				}
				else if (coord[i]->find("/") != string::npos)
				{
					int t[3];
					
					sscanf(coord[i]->c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d", &a, &t[0], &b, &c, &t[1], &b, &d, &t[2], &b);
					
					faces.push_back(new face(b, a, c, d, t[0], t[1], t[2], curmat));
				}
				else
				{
					sscanf(coord[i]->c_str(), "f %d %d %d", &a, &b, &c);
					
					faces.push_back(new face(-1, a, b, c, 0, 0, 0, curmat));
				}
			}
		}
		//Use material_name
		else if ((*coord[i])[0] == 'u' && (*coord[i])[1] == 's' && (*coord[i])[2] == 'e')     
		{
			char tmp[200];
			
			//Read the name of the material to tmp
			sscanf(coord[i]->c_str(), "usemtl %s", tmp);  

			//Go through all of the materials
			for (int i = 0; i<materials.size(); i++)     
			{
				//And compare the tmp with the name of the material
				if (strcmp(materials[i]->name.c_str(), tmp) == 0)   
				{
					//If it's equal then set the current material to that
					curmat = i;       
					break;
				}
			}
		}
		//Material library, a file, which contain all of the materials
		else if ((*coord[i])[0] == 'm' && (*coord[i])[1] == 't' && (*coord[i])[2] == 'l' && (*coord[i])[3] == 'l')      
		{
			char filen[200];
			
			//Read the fileName
			sscanf(coord[i]->c_str(), "mtllib %s", filen);    
			
			//Open the file
			ifstream mtlin(filen);     
			
			//If not opened, show a error message, clean all memory, then return with -1
			if (!mtlin.is_open())    
			{
				cout << "connot open the material file" << endl;
				clean();
				return -1;
			}
			
			//We use materials
			ismaterial = true;        
			
			//Contain the line of the file
			vector<string> tmp;
			
			char c[200];
			
			while (!mtlin.eof())
			{
				//Read all lines to tmp
				mtlin.getline(c, 200);   
				tmp.push_back(c);
			}
			
			//Name of the material
			char name[200]; 
			
			//fileName of the texture
			char fileName[200];     
			
			//Colors, shininess, etc
			float amb[3], dif[3], spec[3], alpha, ns, ni;        
			
			int illum;
			unsigned int texture;
			
			//Do we already have a material read in to these variables?
			bool ismat = false;       

			//Set fileName to nullbyte character
			strcpy(fileName, "\0");  
			
			//Go through all lines of the mtllib file
			for (int i = 0; i<tmp.size(); i++) 
			{
				//Ignore comments
				if (tmp[i][0] == '#')      
					continue;
				
				//New material
				if (tmp[i][0] == 'n' && tmp[i][1] == 'e' && tmp[i][2] == 'w')  
				{
					//If we have a material
					if (ismat)       
					{
						//If we have a texture
						if (strcmp(fileName, "\0") != 0)    
						{
							//Push back
							materials.push_back(new materialObj(name, alpha, ns, ni, dif, amb, spec, illum, texture)); 
							strcpy(fileName, "\0");
						}
						//Push back, but use -1 to texture
						else
						{
							materials.push_back(new materialObj(name, alpha, ns, ni, dif, amb, spec, illum, -1));                           
						}
					}
					//We start from a fresh material
					ismat = false;    
					
					//Read in the name
					sscanf(tmp[i].c_str(), "newmtl %s", name);        
				}
				//Shininess
				else if (tmp[i][0] == 'N' && tmp[i][1] == 's')      
				{
					sscanf(tmp[i].c_str(), "Ns %f", &ns);
					ismat = true;
				}
				//Ambient
				else if (tmp[i][0] == 'K' && tmp[i][1] == 'a')      
				{
					sscanf(tmp[i].c_str(), "Ka %f %f %f", &amb[0], &amb[1], &amb[2]);
					ismat = true;
				}
				//Diffuse
				else if (tmp[i][0] == 'K' && tmp[i][1] == 'd')      
				{
					sscanf(tmp[i].c_str(), "Kd %f %f %f", &dif[0], &dif[1], &dif[2]);
					ismat = true;
				}
				//Specular
				else if (tmp[i][0] == 'K' && tmp[i][1] == 's')
				{
					sscanf(tmp[i].c_str(), "Ks %f %f %f", &spec[0], &spec[1], &spec[2]);
					ismat = true;
				}
				//Others
				else if (tmp[i][0] == 'N' && tmp[i][1] == 'i')      
				{
					sscanf(tmp[i].c_str(), "Ni %f", &ni);
					ismat = true;
				}
				//Alpha
				else if (tmp[i][0] == 'd' && tmp[i][1] == ' ')      
				{
					sscanf(tmp[i].c_str(), "d %f", &alpha);
					ismat = true;
				}
				//Illum (Not Used)
				else if (tmp[i][0] == 'i' && tmp[i][1] == 'l')      
				{
					sscanf(tmp[i].c_str(), "illum %d", &illum);
					ismat = true;
				}
				//Texture
				else if (tmp[i][0] == 'm' && tmp[i][1] == 'a')      
				{
					sscanf(tmp[i].c_str(), "map_Kd %s", fileName);

					//Read the fileName, and use the loadTexture function to load it, and get the id.
					texture = loadTexture(fileName);  
					ismat = true;
				}
			}
			//There is no newmat after the last newmat, so we have to put the last material 'manually'
			if (ismat)       
			{
				if (strcmp(fileName, "\0") != 0)
				{
					materials.push_back(new materialObj(name, alpha, ns, ni, dif, amb, spec, illum, texture));
				}
				else{
					materials.push_back(new materialObj(name, alpha, ns, ni, dif, amb, spec, illum, -1));
				}
			}
		}
		//Back to the obj file, texture coorinate
		else if ((*coord[i])[0] == 'v' && (*coord[i])[1] == 't')    
		{
			float u, v;

			//Read the uv coordinate
			sscanf(coord[i]->c_str(), "vt %f %f", &u, &v);     
			
			//I push back 1-v instead of normal v, because obj file use the upper left corner as 0,0 coordinate
			texturecoordinate.push_back(new texcoordObj(u, 1 - v));       
			
			//OpenGL usesvthe bottom left corner as 0, 0, so  convert it
			istexture = true;
		}
	}
	
	//If for some reason the material file doesn't contain any material, we don't have a material
	if (materials.size() == 0) 
		ismaterial = false;
	//Else we have a material
	else    
		ismaterial = true;

	//Debug purposes
	//cout << vertex.size() << " " << normals.size() << " " << faces.size() << " " << materials.size() << endl;    
	
	//Draw
	int num;

	//I generate a unique identifier for the list
	num = glGenLists(1);
	glNewList(num, GL_COMPILE);

	//The last material (default -1, which doesn't exist, so we use the first material)
	int last = -1;  

	//Go through all faces
	for (int i = 0; i<faces.size(); i++) 
	{
		//If we have a meterial AND the last material is not the same
		if (last != faces[i]->mat && ismaterial)   
		{
			//Set all of the material property
			float diffuse[] = { materials[faces[i]->mat]->dif[0], materials[faces[i]->mat]->dif[1], materials[faces[i]->mat]->dif[2], 1.0 };
			float ambient[] = { materials[faces[i]->mat]->amb[0], materials[faces[i]->mat]->amb[1], materials[faces[i]->mat]->amb[2], 1.0 };
			float specular[] = { materials[faces[i]->mat]->spec[0], materials[faces[i]->mat]->spec[1], materials[faces[i]->mat]->spec[2], 1.0 };
			glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse);
			glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
			glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
			glMaterialf(GL_FRONT, GL_SHININESS, materials[faces[i]->mat]->ns);

			//Set the current to last
			last = faces[i]->mat;     

			//if we don't have texture, disable it, else enable it
			if (materials[faces[i]->mat]->texture == -1)       
				glDisable(GL_TEXTURE_2D);
			else
			{
				glEnable(GL_TEXTURE_2D);

				//And use it
				glBindTexture(GL_TEXTURE_2D, materials[faces[i]->mat]->texture); 
			}
		}
		//If quad
		if (faces[i]->four)      
		{
			//glBegin(GL_QUADS);
			//
			////If there are normals
			//if (isnormals)
			//{
			//	//Use them
			//	glNormal3f(normals[faces[i]->facenum - 1]->x, normals[faces[i]->facenum - 1]->y, normals[faces[i]->facenum - 1]->z);    
			//}

			//////If there are textures
			////if (istexture && materials[faces[i]->mat]->texture != -1)  
			////{
			//	////Set the texture coorinate
			//	//glTexCoord2f(texturecoordinate[faces[i]->texcoord[0] - 1]->u, texturecoordinate[faces[i]->texcoord[0] - 1]->v);      
			////}

			//glVertex3f(vertex[faces[i]->faces[0] - 1]->x, vertex[faces[i]->faces[0] - 1]->y, vertex[faces[i]->faces[0] - 1]->z);

			///*if (istexture && materials[faces[i]->mat]->texture != -1)
			//	glTexCoord2f(texturecoordinate[faces[i]->texcoord[1] - 1]->u, texturecoordinate[faces[i]->texcoord[1] - 1]->v);*/

			//glVertex3f(vertex[faces[i]->faces[1] - 1]->x, vertex[faces[i]->faces[1] - 1]->y, vertex[faces[i]->faces[1] - 1]->z);

			///*if (istexture && materials[faces[i]->mat]->texture != -1)
			//	glTexCoord2f(texturecoordinate[faces[i]->texcoord[2] - 1]->u, texturecoordinate[faces[i]->texcoord[2] - 1]->v);*/

			//glVertex3f(vertex[faces[i]->faces[2] - 1]->x, vertex[faces[i]->faces[2] - 1]->y, vertex[faces[i]->faces[2] - 1]->z);

			///*if (istexture && materials[faces[i]->mat]->texture != -1)
			//	glTexCoord2f(texturecoordinate[faces[i]->texcoord[3] - 1]->u, texturecoordinate[faces[i]->texcoord[3] - 1]->v);*/

			//glVertex3f(vertex[faces[i]->faces[3] - 1]->x, vertex[faces[i]->faces[3] - 1]->y, vertex[faces[i]->faces[3] - 1]->z);
			//glEnd();
		}
		else
		{
			glBegin(GL_TRIANGLES);
			
			//If there are normals
			if (isnormals)   
				glNormal3f(normals[faces[i]->facenum - 1]->x, normals[faces[i]->facenum - 1]->y, normals[faces[i]->facenum - 1]->z);

			//if (istexture && materials[faces[i]->mat]->texture != -1)
				//glTexCoord2f(texturecoordinate[faces[i]->texcoord[0] - 1]->u, texturecoordinate[faces[i]->texcoord[0] - 1]->v);

			glVertex3f(vertex[faces[i]->faces[0] - 1]->x, vertex[faces[i]->faces[0] - 1]->y, vertex[faces[i]->faces[0] - 1]->z);

			//if (istexture && materials[faces[i]->mat]->texture != -1)
				//glTexCoord2f(texturecoordinate[faces[i]->texcoord[1] - 1]->u, texturecoordinate[faces[i]->texcoord[1] - 1]->v);

			glVertex3f(vertex[faces[i]->faces[1] - 1]->x, vertex[faces[i]->faces[1] - 1]->y, vertex[faces[i]->faces[1] - 1]->z);

			//if (istexture && materials[faces[i]->mat]->texture != -1)
				//glTexCoord2f(texturecoordinate[faces[i]->texcoord[2] - 1]->u, texturecoordinate[faces[i]->texcoord[2] - 1]->v);

			glVertex3f(vertex[faces[i]->faces[2] - 1]->x, vertex[faces[i]->faces[2] - 1]->y, vertex[faces[i]->faces[2] - 1]->z);
			glEnd();
		}
	}
	glEndList();
	clean();
	lists.push_back(num);
	return num;
}
Exemplo n.º 27
0
int main()
{
    // glfw: initialize and configure
    // ------------------------------
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif

    // glfw window creation
    // --------------------
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
    glfwMakeContextCurrent(window);
    if (window == NULL)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // tell GLFW to capture our mouse
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // glad: load all OpenGL function pointers
    // ---------------------------------------
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
    {
        std::cout << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    // configure global opengl state
    // -----------------------------
    glEnable(GL_DEPTH_TEST);

    // build and compile shaders
    // -------------------------
    Shader shader("1.2.pbr.vs", "1.2.pbr.fs");

    shader.use();
    shader.setInt("albedoMap", 0);
    shader.setInt("normalMap", 1);
    shader.setInt("metallicMap", 2);
    shader.setInt("roughnessMap", 3);
    shader.setInt("aoMap", 4);

    // load PBR material textures
    // --------------------------
    unsigned int albedo    = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/albedo.png").c_str());
    unsigned int normal    = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/normal.png").c_str());
    unsigned int metallic  = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/metallic.png").c_str());
    unsigned int roughness = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/roughness.png").c_str());
    unsigned int ao        = loadTexture(FileSystem::getPath("resources/textures/pbr/rusted_iron/ao.png").c_str());

    // lights
    // ------
    glm::vec3 lightPositions[] = {
        glm::vec3(0.0f, 0.0f, 10.0f),
    };
    glm::vec3 lightColors[] = {
        glm::vec3(150.0f, 150.0f, 150.0f),
    };
    int nrRows = 7;
    int nrColumns = 7;
    float spacing = 2.5;

    // initialize static shader uniforms before rendering
    // --------------------------------------------------
    glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
    shader.use();
    shader.setMat4("projection", projection);

    // render loop
    // -----------
    while (!glfwWindowShouldClose(window))
    {
        // per-frame time logic
        // --------------------
        float currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // input
        // -----
        processInput(window);

        // render
        // ------
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        shader.use();
        glm::mat4 view = camera.GetViewMatrix();
        shader.setMat4("view", view);
        shader.setVec3("camPos", camera.Position);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, albedo);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, normal);
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, metallic);
        glActiveTexture(GL_TEXTURE3);
        glBindTexture(GL_TEXTURE_2D, roughness);
        glActiveTexture(GL_TEXTURE4);
        glBindTexture(GL_TEXTURE_2D, ao);

        // render rows*column number of spheres with material properties defined by textures (they all have the same material properties)
        glm::mat4 model = glm::mat4(1.0f);
        for (int row = 0; row < nrRows; ++row)
        {
            for (int col = 0; col < nrColumns; ++col)
            {
                model = glm::mat4(1.0f);
                model = glm::translate(model, glm::vec3(
                    (float)(col - (nrColumns / 2)) * spacing,
                    (float)(row - (nrRows / 2)) * spacing,
                    0.0f
                ));
                shader.setMat4("model", model);
                renderSphere();
            }
        }

        // render light source (simply re-render sphere at light positions)
        // this looks a bit off as we use the same shader, but it'll make their positions obvious and 
        // keeps the codeprint small.
        for (unsigned int i = 0; i < sizeof(lightPositions) / sizeof(lightPositions[0]); ++i)
        {
            glm::vec3 newPos = lightPositions[i] + glm::vec3(sin(glfwGetTime() * 5.0) * 5.0, 0.0, 0.0);
            newPos = lightPositions[i];
            shader.setVec3("lightPositions[" + std::to_string(i) + "]", newPos);
            shader.setVec3("lightColors[" + std::to_string(i) + "]", lightColors[i]);

            model = glm::mat4(1.0f);
            model = glm::translate(model, newPos);
            model = glm::scale(model, glm::vec3(0.5f));
            shader.setMat4("model", model);
            renderSphere();
        }

        // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        // -------------------------------------------------------------------------------
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    return 0;
}
Exemplo n.º 28
0
    //-----------------------------------------------------------------------------------
    void HlmsJsonPbs::loadMaterial( const rapidjson::Value &json, const HlmsJson::NamedBlocks &blocks,
                                    HlmsDatablock *datablock )
    {
        assert( dynamic_cast<HlmsPbsDatablock*>(datablock) );
        HlmsPbsDatablock *pbsDatablock = static_cast<HlmsPbsDatablock*>(datablock);

        rapidjson::Value::ConstMemberIterator itor = json.FindMember("workflow");
        if( itor != json.MemberEnd() && itor->value.IsString() )
            pbsDatablock->setWorkflow( parseWorkflow( itor->value.GetString() ) );

        itor = json.FindMember("brdf");
        if( itor != json.MemberEnd() && itor->value.IsString() )
            pbsDatablock->setBrdf( parseBrdf(itor->value.GetString()) );

        itor = json.FindMember("two_sided");
        if( itor != json.MemberEnd() && itor->value.IsBool() )
        {
            pbsDatablock->setTwoSidedLighting( itor->value.GetBool(), true,
                                               pbsDatablock->getMacroblock(true)->mCullMode );
        }

        itor = json.FindMember( "receive_shadows" );
        if( itor != json.MemberEnd() && itor->value.IsBool() )
            pbsDatablock->setReceiveShadows( itor->value.GetBool() );

        itor = json.FindMember("transparency");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;

            float transparencyValue = pbsDatablock->getTransparency();
            HlmsPbsDatablock::TransparencyModes transpMode = pbsDatablock->getTransparencyMode();
            bool useAlphaFromTextures = pbsDatablock->getUseAlphaFromTextures();

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsNumber() )
                transparencyValue = static_cast<float>( itor->value.GetDouble() );

            itor = subobj.FindMember( "mode" );
            if( itor != subobj.MemberEnd() && itor->value.IsString() )
                transpMode = parseTransparencyMode( itor->value.GetString() );

            itor = subobj.FindMember( "use_alpha_from_textures" );
            if( itor != subobj.MemberEnd() && itor->value.IsBool() )
                useAlphaFromTextures = itor->value.GetBool();

            const bool changeBlendblock = !json.HasMember( "blendblock" );
            pbsDatablock->setTransparency( transparencyValue, transpMode,
                                           useAlphaFromTextures, changeBlendblock );
        }

        PackedTexture packedTextures[NUM_PBSM_TEXTURE_TYPES];

        itor = json.FindMember("diffuse");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_DIFFUSE, pbsDatablock, packedTextures );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                pbsDatablock->setDiffuse( parseVector3Array( itor->value ) );

            itor = subobj.FindMember( "background" );
            if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                pbsDatablock->setBackgroundDiffuse( parseColourValueArray( itor->value ) );
        }

        itor = json.FindMember("specular");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_SPECULAR, pbsDatablock, packedTextures );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                pbsDatablock->setSpecular( parseVector3Array( itor->value ) );
        }

        itor = json.FindMember("roughness");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_ROUGHNESS, pbsDatablock, packedTextures );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsNumber() )
                pbsDatablock->setRoughness( static_cast<float>( itor->value.GetDouble() ) );
        }

        itor = json.FindMember("fresnel");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_SPECULAR, pbsDatablock, packedTextures );

            bool useIOR = false;
            bool isColoured = false;
            itor = subobj.FindMember( "mode" );
            if( itor != subobj.MemberEnd() && itor->value.IsString() )
                parseFresnelMode( itor->value.GetString(), isColoured, useIOR );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && (itor->value.IsArray() || itor->value.IsNumber()) )
            {
                Vector3 value;
                if( itor->value.IsArray() )
                    value = parseVector3Array( itor->value );
                else
                    value = static_cast<Real>( itor->value.GetDouble() );

                if( !useIOR )
                    pbsDatablock->setFresnel( value, isColoured );
                else
                    pbsDatablock->setIndexOfRefraction( value, isColoured );
            }
        }

        //There used to be a typo, so allow the wrong spelling.
        itor = json.FindMember("metalness");
        if( itor == json.MemberEnd() )
            itor = json.FindMember("metallness");

        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_METALLIC, pbsDatablock, packedTextures );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsNumber() )
                pbsDatablock->setMetalness( static_cast<float>( itor->value.GetDouble() ) );
        }

        itor = json.FindMember("normal");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_NORMAL, pbsDatablock, packedTextures );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsNumber() )
                pbsDatablock->setNormalMapWeight( static_cast<float>( itor->value.GetDouble() ) );
        }

        itor = json.FindMember("detail_weight");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_DETAIL_WEIGHT, pbsDatablock, packedTextures );
        }

        for( int i=0; i<4; ++i )
        {
            const String iAsStr = StringConverter::toString(i);
            String texTypeName = "detail_diffuse" + iAsStr;

            itor = json.FindMember(texTypeName.c_str());
            if( itor != json.MemberEnd() && itor->value.IsObject() )
            {
                const rapidjson::Value &subobj = itor->value;
                loadTexture( subobj, blocks, static_cast<PbsTextureTypes>(PBSM_DETAIL0 + i),
                             pbsDatablock, packedTextures );

                itor = subobj.FindMember( "value" );
                if( itor != subobj.MemberEnd() && itor->value.IsNumber() )
                    pbsDatablock->setDetailMapWeight( i, static_cast<float>( itor->value.GetDouble() ) );

                itor = subobj.FindMember( "mode" );
                if( itor != subobj.MemberEnd() && itor->value.IsString() )
                    pbsDatablock->setDetailMapBlendMode( i, parseBlendMode( itor->value.GetString() ) );

                Vector4 offsetScale( 0, 0, 1, 1 );

                itor = subobj.FindMember( "offset" );
                if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                    parseOffset( itor->value, offsetScale );

                itor = subobj.FindMember( "scale" );
                if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                    parseScale( itor->value, offsetScale );

                pbsDatablock->setDetailMapOffsetScale( i, offsetScale );
            }

            texTypeName = "detail_normal" + iAsStr;
            itor = json.FindMember(texTypeName.c_str());
            if( itor != json.MemberEnd() && itor->value.IsObject() )
            {
                const rapidjson::Value &subobj = itor->value;
                loadTexture( subobj, blocks, static_cast<PbsTextureTypes>(PBSM_DETAIL0_NM + i),
                             pbsDatablock, packedTextures );

                itor = subobj.FindMember( "value" );
                if( itor != subobj.MemberEnd() && itor->value.IsNumber() )
                {
                    pbsDatablock->setDetailNormalWeight( i,
                                                         static_cast<float>( itor->value.GetDouble() ) );
                }

                Vector4 offsetScale( 0, 0, 1, 1 );

                itor = subobj.FindMember( "offset" );
                if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                    parseOffset( itor->value, offsetScale );

                itor = subobj.FindMember( "scale" );
                if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                    parseScale( itor->value, offsetScale );

                pbsDatablock->setDetailMapOffsetScale( i, offsetScale );
            }
        }

        itor = json.FindMember("emissive");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_EMISSIVE, pbsDatablock, packedTextures );

            itor = subobj.FindMember( "value" );
            if( itor != subobj.MemberEnd() && itor->value.IsArray() )
                pbsDatablock->setEmissive( parseVector3Array( itor->value ) );
        }

        itor = json.FindMember("reflection");
        if( itor != json.MemberEnd() && itor->value.IsObject() )
        {
            const rapidjson::Value &subobj = itor->value;
            loadTexture( subobj, blocks, PBSM_REFLECTION, pbsDatablock, packedTextures );
        }

        pbsDatablock->_setTextures( packedTextures );
    }
Exemplo n.º 29
0
GLWidget::GLWidget(QWidget *parent)
 : QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
{
    // set default look at
    lookAt[0]=0;
    lookAt[1]=0;
    lookAt[2]=10;

    // set initial light position
    lightPos = { 0,0,0,1 };

    // load the model and move it down 100 units
    modelLocation[0] = 0;
    modelLocation[1] = -100;
    modelLocation[2] = 0;


    qtPurple = QColor::fromCmykF(0.39, 0.39, 0.0, 0.0);

    // no models loaded yet so set it to a invalid id
    modelDisplayList = -1;

    numMaterial = 0;
    // create new timer to handle animation
    t = new QTimer();

    // connect the timers timeout signal to the timer expired slot
    connect(t, SIGNAL(timeout()), this, SLOT(timerExpired()));
    // start the timer with a 30ms timout (30ms ~ 30Hz)
    t->start(30);
    // steal all keyboard inputs
    this->grabKeyboard();
    theta = 180;
    phi = 0;


    // update the GL context
    updateGL();

    // go load the terain
    loadNewModel(GL_TEXTURE0, "./models/terrain1.obj");

    this->terrainModel = getModelByName("terrain1.obj");

    // activate all the textures
    glActiveTexture(GL_TEXTURE1);
    loadTexture("./models/Grass.jpg");
    glActiveTexture(GL_TEXTURE2);
    loadTexture("./models/WoodChips.jpg");
    glActiveTexture(GL_TEXTURE3);
    loadTexture("./models/SkyBox.jpg");

    // build the skybox
    this->skyBoxModel.setDisplayID( buildSkyBox(490));

    // activate the skybox texture
    glActiveTexture(GL_TEXTURE0);

    // load all shaders
    program.removeAllShaders();
    program.addShaderFromSourceFile(QGLShader::Vertex, "./shaders/perpixelphong.vert");
    program.addShaderFromSourceFile(QGLShader::Fragment, "./shaders/perpixelphong.frag");

    // compile and bind the shader
    program.bind();
    // update all uniform values
    program.setUniformValue("heightMap",0);
    program.setUniformValue("baseMap1", 1);
    program.setUniformValue("baseMap2", 2);
    program.setUniformValue("skybox", 3);
    program.setUniformValue("mode", int(0));
    program.setUniformValue("envMap", 3);
    program.setUniformValue("numWaves", int(4));


    // set the parameter for the sum of sins equation
    waveAmp = {1.5,1.5,1,2, 10,10,10,10};
    wavelength= {50,30,50,30, 10,10,10,10};
    waveSpeed = {10,20,10,10, 10,10,10,10};
    direction[0] = QVector2D(-.2,.5);
    direction[1] = QVector2D(.5, -.3);
    direction[2] = QVector2D(0,1);
    direction[3] = QVector2D(-.1, -.8);
    program.setUniformValueArray("direction", direction, 4);
    program.setUniformValueArray("amplitude", waveAmp, 8,1);
    program.setUniformValueArray("wavelength", wavelength, 8,1);
    program.setUniformValueArray("speed", waveSpeed, 8,1);

}
Exemplo n.º 30
0
int main (void) {
	//VECTORS
	pnt A;
	pnt B;

	A.x = 150;
	A.y = 100;

	B.x = 500;
	B.y = 380;

	int speed = 10;
	int vectorA[2] = {A.x, A.y}, vectorB[2] = {B.x, B.y}, vectorP[2] = {200, 200}, vectorH[2], vectorR[2];
	//VECTORS

	int WidthBack, HeightBack, i, j;
	bool quit = 0, gotoAndStopA = 1;
	//const Uint8 *kbState = SDL_GetKeyboardState(NULL);
	char **imgFromSrc;

	SDL_Event e;
	SDL_Window *win;
	SDL_Renderer *ren;
	SDL_Texture *background;
	SDL_Texture *points;
	SDL_Texture *character;

	if (SDL_Init(SDL_INIT_VIDEO) != 0 || (IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) != IMG_INIT_PNG) {
		logSDLError("Init");
		return 1;
	}

	win = SDL_CreateWindow("Vector Movement", WINDOW_OFFSET_X, WINDOW_OFFSET_Y, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
	if (win == NULL) {
		logSDLError("CreateWindow");
		return 2;
	}

	ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (ren == NULL) {
		logSDLError("CreateRenderer");
		return 3;
	}

	imgFromSrc = bmp_xpm;
	background = loadHeader(imgFromSrc, ren);
	points = loadTexture("point.png", ren);
	character = loadTexture("char.png", ren);
	if (background == NULL || points == NULL || character == NULL) {
		logSDLError("loadTexture");
		return 4;
	}

	SDL_RenderClear(ren);

	SDL_QueryTexture(background, NULL, NULL, &WidthBack, &HeightBack);

	WidthBack /= 2;
	HeightBack /= 2;

	for (i = 0; i < WINDOW_WIDTH / WidthBack; i++) {
		for (j = 0; j <= WINDOW_HEIGHT / HeightBack; j++) {
			renderTextureS(background, ren, i * WidthBack, j * HeightBack, WidthBack, HeightBack);
		}
	}

	//WidthPoint = 50;
	//HeightPoint = 50;

	renderTexture(points, ren, A.x, A.y);
	renderTexture(points, ren, B.x, B.y);

	renderTexture(character, ren, vectorP[0], vectorP[1]);

	SDL_RenderPresent(ren);

	while (!quit) {
		while (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT) quit = 1;
			if (e.type == SDL_MOUSEBUTTONDOWN) quit = 1;
		}

		SDL_RenderClear(ren);

		for (i = 0; i < WINDOW_WIDTH / WidthBack; i++) {
			for (j = 0; j <= WINDOW_HEIGHT / HeightBack; j++) {
				renderTextureS(background, ren, i * WidthBack, j * HeightBack, WidthBack, HeightBack);
			}
		}

		renderTexture(points, ren, vectorA[0], vectorA[1]);
		renderTexture(points, ren, vectorB[0], vectorB[1]);

		if (gotoAndStopA == 1) {
			vectorA[0] = A.x; vectorA[1] = A.y; vectorB[0] = B.x; vectorB[1] = B.y;
			vectorR[0] = vectorA[0] - vectorP[0]; vectorR[1] = vectorA[1] - vectorP[1];
			vectorH[0] = speed * vectorR[0] / vectorLen(vectorR); vectorH[1] = speed * vectorR[1] / vectorLen(vectorR);
			vectorP[0] += vectorH[0]; vectorP[1] += vectorH[1];

			renderTextureR(character, ren, vectorA, vectorP[0], vectorP[1]);

			if (vectorLen(vectorR) <= speed / 2) {
				SDL_Delay(1000);

				gotoAndStopA = 0;
			}
		} else if (gotoAndStopA == 0) {
			vectorB[0] = B.x; vectorB[1] = B.y; vectorA[0] = A.x; vectorA[1] = A.y;
			vectorR[0] = vectorB[0] - vectorP[0]; vectorR[1] = vectorB[1] - vectorP[1];
			vectorH[0] = speed * vectorR[0] / vectorLen(vectorR); vectorH[1] = speed * vectorR[1] / vectorLen(vectorR);
			vectorP[0] += vectorH[0]; vectorP[1] += vectorH[1];

			renderTextureR(character, ren, vectorB, vectorP[0], vectorP[1]);

			if (vectorLen(vectorR) <= speed / 2) {
				SDL_Delay(1000);

				gotoAndStopA = 1;
			}
		}

		SDL_Delay(50);
		SDL_RenderPresent(ren);
	}

	SDL_DestroyTexture(background);
	SDL_DestroyTexture(points);
	SDL_DestroyTexture(character);

	cleanUp(win, ren);

	return 0;
}