Ejemplo n.º 1
0
Archivo: texture.c Proyecto: Tastyep/rt
int	init_texture(t_param *param)
{
  if ((param->tab_texture_menu =
       malloc(sizeof(t_texture) * 24)) == NULL ||
      load_texture(param) == 0 ||
      (param->panel_control.img =
       mlx_xpm_file_to_image(param->window.p,
			     "texture/panel_config.xpm",
			     &(param->panel_control.y),
			     &(param->panel_control.x))) == NULL ||
      (param->textbox.img =
       mlx_xpm_file_to_image(param->window.p,
			     "texture/textbox.xpm",
			     &(param->textbox.y),
			     &(param->textbox.x))) == NULL ||
      load_write_and_chack(param) == 0 ||
      load_texture_form(param) == 0)
    return (0);
  return (1);
}
Ejemplo n.º 2
0
void init_gpu_stuff() {
	// Load the vertex shader, create a shader program and bind it
	vshader_dvlb = DVLB_ParseFile((u32*) vshader_shbin, vshader_shbin_size);
	shaderProgramInit(&program);
	shaderProgramSetVsh(&program, &vshader_dvlb->DVLE[0]);
	C3D_BindProgram(&program);

	// Get the location of the uniforms
	proj_uloc = shaderInstanceGetUniformLocation(program.vertexShader, "projection");

	// Configure attributes for use with the vertex shader
	// Attribute format and element count are ignored in immediate mode
	C3D_AttrInfo* attrInfo = C3D_GetAttrInfo();
	AttrInfo_Init(attrInfo);
	AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); // v0=position
	AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 2); // v1=texcoord
	AttrInfo_AddLoader(attrInfo, 2, GPU_FLOAT, 4); // v2=color

	// Compute the projection matrix
	// Note: we're setting top to 240 here so origin is at top left.
	Mtx_OrthoTilt(&proj_mat, 0.0, 400.0, 240.0, 0.0, 0.0, 1.0, true);

	// Configure buffers
	C3D_BufInfo* bufInfo = C3D_GetBufInfo();
	BufInfo_Init(bufInfo);

	// Load textures
	load_texture(&background_tex, background_png, background_png_size);
	load_texture(&empty_tex, empty_png, empty_png_size);
	load_texture(&frame_tex, frame_png, frame_png_size);
	load_texture(&text_tex, ui_font_png, ui_font_png_size);
	load_texture(&tileset_tex, tileset_png, tileset_png_size);
	load_texture(&outline_tex, outline_png, outline_png_size);

	// Configure the first fragment shading substage to just pass through the texture color
	// See https://www.opengl.org/sdk/docs/man2/xhtml/glTexEnv.xml for more insight
	C3D_TexEnv* env = C3D_GetTexEnv(0);
	C3D_TexEnvSrc(env, C3D_Both, GPU_TEXTURE0, GPU_PRIMARY_COLOR, GPU_PRIMARY_COLOR);
	//C3D_TexEnvSrc(env, C3D_Both, GPU_TEXTURE0, 0, 0);

	//C3D_TexEnvOp(env, C3D_Both, 0, 0, 0);
	C3D_TexEnvFunc(env, C3D_Both, GPU_MODULATE);
	//C3D_TexEnvFunc(env, C3D_Both, GPU_REPLACE);

	// Configure depth test to overwrite pixels with the same depth (needed to draw overlapping sprites)
	C3D_DepthTest(true, GPU_GEQUAL, GPU_WRITE_ALL);

	C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, proj_uloc, &proj_mat);
}
Ejemplo n.º 3
0
Chip74192::Chip74192()
{
    set(0,0,4.54,2.25,"Synchronous up/down decade counter");
    float xpos = 0.15 + 0.54;
    mPin.push_back(&mInputPin[0]);
    mInputPin[0].set(xpos , 0, this, "Pin 15:INPUT DATA A"); xpos += 0.54;
    mPin.push_back(&mClear);
    mClear.set(xpos , 0, this, "Pin 14:CLEAR"); xpos += 0.54;
    mPin.push_back(&mBorrow);
    mBorrow.set(xpos , 0, this, "Pin 13:BORROW"); xpos += 0.54;
    mPin.push_back(&mCarry);
    mCarry.set(xpos , 0, this, "Pin 12:CARRY"); xpos += 0.54;
    mPin.push_back(&mLoad);
    mLoad.set(xpos , 0, this, "Pin 11:LOAD"); xpos += 0.54;
    mPin.push_back(&mInputPin[2]);
    mInputPin[2].set(xpos , 0, this, "Pin 10:INPUT DATA C"); xpos += 0.54;
    mPin.push_back(&mInputPin[3]);
    mInputPin[3].set(xpos , 0, this, "Pin 9:INPUT DATA D"); xpos += 0.54;
    
    xpos = 0.15;
    mPin.push_back(&mInputPin[1]);
    mInputPin[1].set(xpos, 1.75, this, "Pin 1:INPUT DATA B"); xpos += 0.54;
    mPin.push_back(&mOutputPin[1]);
    mOutputPin[1].set(xpos, 1.75, this, "Pin 2:QB"); xpos += 0.54;
    mPin.push_back(&mOutputPin[0]);
    mOutputPin[0].set(xpos, 1.75, this, "Pin 3:QA"); xpos += 0.54;
    mPin.push_back(&mCountDown);
    mCountDown.set(xpos, 1.75, this, "Pin 4:COUNT DOWN"); xpos += 0.54;
    mPin.push_back(&mCountUp);
    mCountUp.set(xpos, 1.75, this, "Pin 5:COUNT UP"); xpos += 0.54;
    mPin.push_back(&mOutputPin[2]);
    mOutputPin[2].set(xpos, 1.75, this, "Pin 6:QC"); xpos += 0.54;
    mPin.push_back(&mOutputPin[3]);
    mOutputPin[3].set(xpos, 1.75, this, "Pin 7:QD"); xpos += 0.54;

    mTexture = load_texture("data/chip_16pin.png");

    mValue = 0;
    mCountDownLastState = 0;
    mCountUpLastState = 0;
}
Ejemplo n.º 4
0
static void mtllib(char *dirname, char *filename)
{
	char path[1024];
	char *line, *next;
	unsigned char *data;
	int len;
	char *s;

	data = load_file(abspath(path, dirname, filename, sizeof path), &len);
	if (!data) {
		warn("cannot load material library: '%s'", filename);
		return;
	}

	data[len-1] = 0; /* over-write final newline to zero-terminate */

	for (line = (char*)data; line; line = next) {
		next = strchr(line, '\n');
		if (next)
			*next++ = 0;

		s = strtok(line, SEP);
		if (!s) {
			continue;
		} else if (!strcmp(s, "newmtl")) {
			s = strtok(NULL, SEP);
			if (s) {
				strlcpy(mtl_map[mtl_count].name, s, sizeof mtl_map[0].name);
				mtl_map[mtl_count].material = 0;
				mtl_count++;
			}
		} else if (!strcmp(s, "map_Kd")) {
			s = strtok(NULL, SEP);
			if (s && mtl_count > 0) {
				mtl_map[mtl_count-1].material = load_texture(abspath(path, dirname, s, sizeof path), 1);
			}
		}
	}

	free(data);
}
Ejemplo n.º 5
0
void fs_emu_set_texture(fs_emu_texture *texture) {
    fs_gl_texturing(1);
    /*
    if (texture && texture->opengl_context_stamp && \
            g_fs_ml_opengl_context_stamp != texture->opengl_context_stamp) {
        // OpenGL context has been recreated. load_texture also binds
        load_texture(texture);
    }
    */
    if (!texture) {
        fs_gl_bind_texture(0);
        return;
    }
    if (texture->texture) {
        fs_gl_bind_texture(texture->texture);
    }
    else {
        // texture was not loaded, perhaps due to context recreation
        load_texture(texture);
    }
}
Ejemplo n.º 6
0
Chip7485::Chip7485()
{
    set(0,0,4.54,2.25,"4-bit Magnitude Comparator");
    float xpos = 0.15 + 0.54;
    mPin.push_back(&mInputPinA[3]);
    mInputPinA[3].set(xpos , 0, this, "Pin 15:A3"); xpos += 0.54;
    mPin.push_back(&mInputPinB[2]);
    mInputPinB[2].set(xpos , 0, this, "Pin 14:B3"); xpos += 0.54;
    mPin.push_back(&mInputPinA[2]);
    mInputPinA[2].set(xpos , 0, this, "Pin 13:A2"); xpos += 0.54;
    mPin.push_back(&mInputPinA[1]);
    mInputPinA[1].set(xpos , 0, this, "Pin 12:A1"); xpos += 0.54;
    mPin.push_back(&mInputPinB[1]);
    mInputPinB[1].set(xpos , 0, this, "Pin 11:B1"); xpos += 0.54;
    mPin.push_back(&mInputPinA[0]);
    mInputPinA[0].set(xpos , 0, this, "Pin 10:A0"); xpos += 0.54;
    mPin.push_back(&mInputPinB[0]);
    mInputPinB[0].set(xpos , 0, this, "Pin 9:B0"); xpos += 0.54;
    
    xpos = 0.15;

    mPin.push_back(&mInputPinB[3]);
    mInputPinB[3].set(xpos , 1.75, this, "Pin 1:B3"); xpos += 0.54;
    mPin.push_back(&mCascadingInputPin[0]);
    mCascadingInputPin[0].set(xpos , 1.75, this, "Pin 2:A<B cascading input"); xpos += 0.54;
    mPin.push_back(&mCascadingInputPin[1]);
    mCascadingInputPin[1].set(xpos , 1.75, this, "Pin 3:A=B cascading input"); xpos += 0.54;
    mPin.push_back(&mCascadingInputPin[2]);
    mCascadingInputPin[2].set(xpos , 1.75, this, "Pin 4:A>B cascading input"); xpos += 0.54;
    mPin.push_back(&mOutputPin[0]);
    mOutputPin[0].set(xpos , 1.75, this, "Pin 5:A>B output"); xpos += 0.54;
    mPin.push_back(&mOutputPin[1]);
    mOutputPin[1].set(xpos , 1.75, this, "Pin 1:A=B output"); xpos += 0.54;
    mPin.push_back(&mOutputPin[2]);
    mOutputPin[2].set(xpos , 1.75, this, "Pin 1:A<B output"); xpos += 0.54;


    mTexture = load_texture("data/chip_16pin.png");
}
Ejemplo n.º 7
0
projectile *make_projectile(char *name, double x, double y, double rotation, item *spawned_by)
{
	projectile *proto = (projectile *) get_hash(PROJECTILE_PROTOTYPES, name);
	if (proto == NULL) {
		log_err("Projectile prototype \"%s\" does not exist", name);
		exit(1);
	}
	projectile *p = malloc(sizeof(projectile));
	memcpy(p, proto, sizeof(projectile));
	char buf[256] = "textures/projectiles/";
	strncat(buf, name, sizeof(buf) - strlen(buf) - 5);
	strcat(buf, ".png");
	p->t = load_texture(buf, p->w, p->h);
	p->x = x;
	p->y = y;
	p->rotation = rotation;
	p->xv = p->speed * cos(rotation);
	p->yv = p->speed * sin(rotation);
	p->spawned_by = spawned_by;

	return p;
}
Ejemplo n.º 8
0
void load_all_tiles()
{
	int i;
	int cur_text;
	char str[80];
	for(i=0;i<255;i++)
	{
		sprintf(str,"./3dobjects/tile%i.dds",i);
		if(is_water_tile(i) && is_reflecting(i)) cur_text=load_texture_cache(str,70);
		else cur_text=load_texture_cache(str,255);
		if(cur_text==-1)return;
		tile_list[i]=cur_text;
		tiles_no=i;
#ifdef	OLD_TEXTURE_LOADER
		//map_tiles[i].img=load_bmp8_color_key_no_texture_img(str,map_tiles+i,255);
		load_bmp8_texture(str,map_tiles+i,255);
#else	//OLD_TEXTURE_LOADER
		load_texture(str,map_tiles+i,255);
#endif	//OLD_TEXTURE_LOADER
	}
	map_tiles[255].texture=NULL;
}
Ejemplo n.º 9
0
Animation *init_animation(char *filename) {
	Animation *buf = create_element((void **)&resources.animations, sizeof(Animation));
	
	char *beg = strstr(filename, "gfx/") + 4;
	char *end = strrchr(filename, '.');
		
	char *name = malloc(end - beg + 1);
	memset(name, 0, end - beg + 1);
	strncpy(name, beg, end-beg);
	
	char* tok;
	strtok(name, "_");
	
	if((tok = strtok(NULL, "_")) == NULL)
		errx(-1, "init_animation():\n!- bad 'rows' in filename '%s'", name);
	buf->rows = atoi(tok);
	if((tok = strtok(NULL, "_")) == NULL)
		errx(-1, "init_animation():\n!- bad 'cols' in filename '%s'", name);
	buf->cols = atoi(tok);
	if((tok = strtok(NULL, "_")) == NULL)
		errx(-1, "init_animation():\n!- bad 'speed' in filename '%s'", name);
	buf->speed = atoi(tok);
	
	if((tok = strtok(NULL, "_")) == NULL)
		errx(-1, "init_animation():\n!- bad 'name' in filename '%s'", name);
	
	
	buf->name = malloc(strlen(tok)+1);
	memset(buf->name, 0, strlen(tok)+1);
	strcpy(buf->name, tok);
	
	buf->tex = load_texture(filename);
	buf->w = buf->tex->w/buf->cols;
	buf->h = buf->tex->h/buf->rows;
	
	printf("-- initialized animation '%s'\n", buf->name);
	return buf;
}
Ejemplo n.º 10
0
PluginChip::PluginChip(DLLHANDLETYPE aDllHandle, const char *aChipname)
{
    memset(&mChipInfo,0,sizeof(mChipInfo));

    dllcreate = (createproc)getdllproc(aDllHandle, "create");
    dllupdate = (updateproc)getdllproc(aDllHandle, "update");
    dllrender = (renderproc)getdllproc(aDllHandle, "render");
    dllcleanup = (cleanupproc)getdllproc(aDllHandle, "cleanup");
    if (dllcreate == NULL ||
        dllupdate == NULL ||
        dllrender == NULL ||
        dllcleanup == NULL ||
        dllcreate(&mChipInfo, aChipname) == 0)
    {
        dllcreate = NULL;
        return;
    }
    
    set(0, 0, mChipInfo.mWidth, mChipInfo.mHeight, mChipInfo.mTooltip);

    int i;
    for (i = 0; i < mChipInfo.mPinCount; i++)
    {
        const char *tt = NULL;
        Pin *p = new Pin;
        mPin.push_back(p);
        if (mChipInfo.mPinTooltips)
            tt = mChipInfo.mPinTooltips[i];
        if (tt == NULL) 
            tt = "-";
        p->set(mChipInfo.mPinCoordinates[i*2+0], mChipInfo.mPinCoordinates[i*2+1], this, tt);
    }
    
    mTexture = 0;
    if (mChipInfo.mTextureFilename)
        mTexture = load_texture((char*)mChipInfo.mTextureFilename);

}
Ejemplo n.º 11
0
texture2d::texture2d(SDL_Surface * data)
{
	init();
	if (data == NULL)
		return;
	GLfloat texcoord[4];
//	GLenum gl_error;

	w = data->w;
	h = data->h;

	//Convert the data into an OpenGL texture
	texture = load_texture(data, texcoord);

	//Make texture coordinates easy to understand
	minX = texcoord[0];
	minY = texcoord[1];
	maxX = texcoord[2];
	maxY = texcoord[3];

	//We don't need the original data surface anymore 
	SDL_FreeSurface(data);
}
Ejemplo n.º 12
0
void tcapplication::init()
{
    std::vector<std::string> const textureNameContainer{
        "opengl.bmp",
        "gamedev.bmp",
        "goblet.bmp",
        "box.bmp",
        "fire.bmp",
        "stone.bmp",
        "steel.bmp"
    };

    std::string const textureFile(PARENT_DIRECTORY + std::string("data/"));

    for(size_t i = 0; i < textureNameContainer.size(); i++) {
        if(!load_texture(textureFile + textureNameContainer[i], i)) {
            std::cerr << "Error loading texture" << std::endl;
            exit(1);
        }
    }

    glClearColor(0.0, 0.0, 0.0, 0.5);
    glShadeModel(GL_SMOOTH);

    glEnable(GL_DEPTH_TEST);

    glEnable(GL_TEXTURE_2D);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

    glColor4d(1.0, 1.0, 1.0, 0.5);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE);

    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
Ejemplo n.º 13
0
Chip74283::Chip74283()
{
    set(0,0,4.54,2.25,"4-bit Binary Full Adder");
    float xpos = 0.15 + 0.54;
    mPin.push_back(&mInputPinB[2]);
    mInputPinB[2].set(xpos , 0, this, "Pin 15:B3"); xpos += 0.54;
    mPin.push_back(&mInputPinA[2]);
    mInputPinA[2].set(xpos , 0, this, "Pin 14:A3"); xpos += 0.54;
    mPin.push_back(&mOutputPin[2]);
    mOutputPin[2].set(xpos , 0, this, "Pin 13:S3"); xpos += 0.54;
    mPin.push_back(&mInputPinB[3]);
    mInputPinB[3].set(xpos , 0, this, "Pin 12:A4"); xpos += 0.54;
    mPin.push_back(&mInputPinA[3]);
    mInputPinA[3].set(xpos , 0, this, "Pin 11:B4"); xpos += 0.54;
    mPin.push_back(&mOutputPin[3]);
    mOutputPin[3].set(xpos , 0, this, "Pin 10:S4"); xpos += 0.54;
    mPin.push_back(&mOutputPinC);
    mOutputPinC.set(xpos , 0, this, "Pin 9:C4"); xpos += 0.54;

    xpos = 0.15;
    mPin.push_back(&mOutputPin[1]);
    mOutputPin[1].set(xpos, 1.75, this, "Pin 1:S2"); xpos += 0.54;
    mPin.push_back(&mInputPinB[1]);
    mInputPinB[1].set(xpos, 1.75, this, "Pin 2:B2"); xpos += 0.54;
    mPin.push_back(&mInputPinA[1]);
    mInputPinA[1].set(xpos, 1.75, this, "Pin 3:A2"); xpos += 0.54;
    mPin.push_back(&mOutputPin[0]);
    mOutputPin[0].set(xpos, 1.75, this, "Pin 4:S1"); xpos += 0.54;
    mPin.push_back(&mInputPinA[0]);
    mInputPinA[0].set(xpos, 1.75, this, "Pin 5:A1"); xpos += 0.54;
    mPin.push_back(&mInputPinB[0]);
    mInputPinB[0].set(xpos, 1.75, this, "Pin 6:B1"); xpos += 0.54;
    mPin.push_back(&mInputPinC);
    mInputPinC.set(xpos, 1.75, this, "Pin 7:C0"); xpos += 0.54;

    mTexture = load_texture("data/chip_16pin.png");
}
Ejemplo n.º 14
0
void House::init(GLuint shader)
{
	if (initialised) return; // init once

	shader_programme = shader;

	// Load objects
	std::vector<glm::vec3> vertices;
	std::vector<glm::vec2> uvs;
	std::vector<glm::vec3> normals;
	bool res;

	// body
	res = loadOBJ("assets/house.obj", vertices, uvs, normals);
	point_count = vertices.size();
	assert(res);
	std::cout << "loaded assets/house.obj. point count: " << point_count << std::endl;
	vao = create_vao(vertices, uvs, normals);


	// Get uniforms locations
	M_loc = glGetUniformLocation (shader_programme, "M");
	assert (M_loc > -1);
	V_loc = glGetUniformLocation (shader_programme, "V");
	assert (V_loc > -1);
	P_loc = glGetUniformLocation (shader_programme, "P");
	assert (P_loc > -1);
	light_pos_loc = glGetUniformLocation (shader_programme, "light_pos");
	assert (light_pos_loc > -1);


	// Load textures
	texture = load_texture("assets/house_texture.png");

	initialised = true;
}
Ejemplo n.º 15
0
int load_material(char *dirname, char *material)
{
	char filename[1024], *s;
	int texture;
	s = strrchr(material, ';');
	if (s) s++; else s = material;
	if (dirname[0]) {
		strlcpy(filename, dirname, sizeof filename);
		strlcat(filename, "/textures/", sizeof filename);
		strlcat(filename, s, sizeof filename);
		strlcat(filename, ".png", sizeof filename);
	} else {
		strlcpy(filename, "textures/", sizeof filename);
		strlcat(filename, s, sizeof filename);
		strlcat(filename, ".png", sizeof filename);
	}
	texture = load_texture(filename, 1);
	if (strstr(material, "clamp;")) {
		glBindTexture(GL_TEXTURE_2D, texture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	}
	return texture;
}
Ejemplo n.º 16
0
void CALLBACK load_texture_cb(ID3D11Device* device, char* texture_file, ID3D11ShaderResourceView** srv, void* context)
{
    tstring* base_path = reinterpret_cast<tstring*>(context);

	load_texture(device, (*base_path + to_tstring(texture_file)), srv);
}
Ejemplo n.º 17
0
int main() {
  // msaa
  glfwWindowHint(GLFW_SAMPLES, 4);
  GLFWwindow * window = initWindow(windowWidth, windowHeight);
  if (!window) {
    glfwTerminate();
    return -1;
  }
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  glfwSetKeyCallback(window, key_callback);
  glfwSetCursorPosCallback(window, cursor_callback);
  glfwSetScrollCallback(window, scroll_callback);

  glEnable(GL_DEPTH_TEST);

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

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

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

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

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

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

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

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

  glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  GLfloat borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
  glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);

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

  //xzhe

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

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

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

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

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

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

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

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

    glfwPollEvents();

    do_movement(delta_time);

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    shaders.SetUniform("lightSpaceMatrix", lightSpaceMatrix);

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

    glfwSwapBuffers(window);
  }

  glfwTerminate();
  return 0;
}
Ejemplo n.º 18
0
 texture_t::texture_t(std::string const& _name, std::string const& filepath)
 : name(_name)
 {
     load_texture(filepath);
 }
Ejemplo n.º 19
0
 texture_t::texture_t(std::string const& filepath, int force_channels)
 {
     load_texture(filepath, force_channels);
 }
Ejemplo n.º 20
0
void md5_read_mesh(FILE *f, Md5_mesh *m)
{
  char s[200];
  while (fgets(s, 200, f) != NULL) {
    if (s[0] == '}') {
      int i;
      m->max_joints_per_vert = 0;
      /*Calculate max joints per vertex*/
      for (i = 0; i < m->num_vertices; i++)
        if (m->vertices[i].weight_count > m->max_joints_per_vert) {
          m->max_joints_per_vert = m->vertices[i].weight_count;
        }
      return;
    } else if (strcmp_sp(s + 1, "shader %s\n")) {
      char name[40];
      sscanf(s + 1, "shader \"%[^\"]s\"\n", name);
      m->shader = my_strdup(name);
      {
        /*TODO: check if this texture is already loaded*/
        char tex_name[40];
        sprintf(tex_name, "%s.tga", name);
        if (!load_texture(tex_name, &m->texture)) {
          printf("No texture '%s'\n", tex_name);
          exit(1);
        }
      }
    } else if (strcmp_sp(s + 1, "numverts %d\n")) {
      sscanf(s + 1, "numverts %d\n", &m->num_vertices);
      m->vertices = ALLOCATE(m->num_vertices, Md5_vertex);
      m->points = ALLOCATE(m->num_vertices, Md5_vertex);
    } else if (strcmp_sp(s + 1, "numtris %d\n")) {
      sscanf(s + 1, "numtris %d\n", &m->num_tris);
      m->tris = ALLOCATE(m->num_tris, Md5_triangle);
    } else if (strcmp_sp(s + 1, "numweights %d\n")) {
      sscanf(s + 1, "numweights %d\n", &m->num_weights);
      m->weights = ALLOCATE(m->num_weights, Md5_weight);
    } else if (strcmp_sp(s + 1, "vert ")) {
      Md5_vertex *v;
      int index;
      V2f tex;
      int weightIndex;
      int weightCount;
      sscanf(s + 1, "vert %d ( %f %f ) %d %d\n",
          &index,
          &tex.x,
          &tex.y,
          &weightIndex,
          &weightCount);
      v = m->vertices + index;
      v->tex.x = tex.x;
      v->tex.y = tex.y;
      v->weight_index = weightIndex;
      v->weight_count = weightCount;
    } else if (strcmp_sp(s + 1, "tri ")) {
      Md5_triangle *t;
      int index, i0, i1, i2;
      sscanf(s + 1, "tri %d %d %d %d\n",
          &index, &i0, &i1, &i2);
      t = m->tris + index;
      t->index[0] = i0;
      t->index[1] = i1;
      t->index[2] = i2;
    } else if (strcmp_sp(s + 1, "weight ")) {
      Md5_weight *w;
      int index;
      int joint;
      float bias;
      V3f pos;
      sscanf(s + 1, "weight %d %d %f ( %f %f %f )\n",
          &index, &joint, &bias, &pos.x, &pos.y, &pos.z);
      w = m->weights + index;
      w->joint_index = joint;
      w->weight = bias;
      w->pos.x = pos.x;
      w->pos.y = pos.y;
      w->pos.z = pos.z;
    }
  }
}
Ejemplo n.º 21
0
RenderObject::RenderObject(ID3D11Device * device, const std::string &file_path, aiMesh * src_mesh, aiMaterial * src_material)

{

    HRESULT hr;

    this->idx_count = src_mesh->mNumFaces * 3;

    this->idx_offset = 0;

    UINT idx_size = sizeof(UINT);

    UINT idx_buffer_size = idx_size * this->idx_count;

    UINT * source_indices = new UINT[this->idx_count];

    for (UINT face_idx=0; face_idx < src_mesh->mNumFaces; ++face_idx)

    {

        aiFace * face = &src_mesh->mFaces[face_idx];

        source_indices[3*face_idx+0] = face->mIndices[0];

        source_indices[3*face_idx+1] = face->mIndices[1];

        source_indices[3*face_idx+2] = face->mIndices[2];

    }



    D3D11_BUFFER_DESC ib_desc = {

        idx_buffer_size,            // Byte Width

        D3D11_USAGE_DEFAULT,        // Usage

        D3D11_BIND_INDEX_BUFFER,    // Bind Flags

        0,                            // CPU Access

        0,                            // Misc Flags

        0,                            // Structure Byte Stride

    };



    D3D11_SUBRESOURCE_DATA ib_data = {

        (void *) source_indices,    // Source Data

        0,                            // Line Pitch

        0                            // Slice Pitch

    };

    device->CreateBuffer(&ib_desc, &ib_data, &this->idx_buffer);

    delete [] source_indices;



    this->vtx_count = src_mesh->mNumVertices;

    this->vtx_offset = 0;

    void * source_data[MAX_VTX_BUFFERS] = {nullptr};

    UINT source_strides[MAX_VTX_BUFFERS];



    source_data[0] = (void *) src_mesh->mVertices;

    source_strides[0] = sizeof(aiVector3D);

    source_data[1] = (void *) src_mesh->mNormals;

    source_strides[1] = sizeof(aiVector3D);

    source_data[2] = (void *) src_mesh->mTextureCoords[0];

    source_strides[2] = sizeof(aiVector3D);



    this->vtx_layout.key = 0;

    this->vtx_layout.desc.position = VTXLAYOUTDESC_POSITION_FLOAT3;

    this->vtx_layout.desc.normal = VTXLAYOUTDESC_NBT_FLOAT3;

    this->vtx_layout.desc.tc_count = 1;

    this->vtx_layout.desc.tc0 = VTXLAYOUTDESC_TEXCOORD_FLOAT2;



    this->vtx_buffer_count = 3;



    for (UINT idx=0; idx<MAX_VTX_BUFFERS; ++idx)

    {

        this->vtx_buffers[idx] = nullptr;

    }



    for (UINT buffer_idx = 0; buffer_idx < this->vtx_buffer_count; ++buffer_idx)

    {

        UINT element_size = source_strides[buffer_idx];

        UINT buffer_size = element_size * this->vtx_count;

        this->vtx_strides[buffer_idx] = source_strides[buffer_idx];

        this->vtx_offsets[buffer_idx] = 0;

        D3D11_BUFFER_DESC vb_desc = {

            buffer_size,                // Byte Width

            D3D11_USAGE_DEFAULT,        // Usage

            D3D11_BIND_VERTEX_BUFFER,   // Bind Flags

            0,                          // CPU Access

            0,                          // Misc Flags

            0,                          // Structure Byte Stride

        };



        D3D11_SUBRESOURCE_DATA vb_data = {

            source_data[buffer_idx],    // Source Data

            0,                          // Line Pitch

            0                           // Slice Pitch

        };



        device->CreateBuffer(&vb_desc, &vb_data, &this->vtx_buffers[buffer_idx]);

    }



    if (src_material->GetTextureCount(aiTextureType_DIFFUSE) > 0)

    {

        aiString texture_filename;

        src_material->GetTexture(aiTextureType_DIFFUSE, 0, &texture_filename);

        std::string full_path = std::string(file_path.c_str()) + std::string(texture_filename.data);

        wchar_t wc_path[MAX_PATH];

        mbstowcs_s(nullptr, wc_path, full_path.c_str(), MAX_PATH);



        ID3D11ShaderResourceView * srv;

        hr = load_texture(device, wc_path, &srv);

        _ASSERT(SUCCEEDED(hr));



        this->material_properties[Scene::DIFFUSE_TEX] = (void *) srv;

    }



    if (src_material->GetTextureCount(aiTextureType_SPECULAR) > 0)

    {

        aiString texture_filename;

        src_material->GetTexture(aiTextureType_SPECULAR, 0, &texture_filename);

        std::string full_path = std::string(file_path.c_str()) + std::string(texture_filename.data);

        wchar_t wc_path[MAX_PATH];

        mbstowcs_s(nullptr, wc_path, full_path.c_str(), MAX_PATH);



        ID3D11ShaderResourceView * srv;

        hr = load_texture(device, wc_path, &srv);

        _ASSERT(SUCCEEDED(hr));



        this->material_properties[Scene::SPECULAR_TEX] = (void *) srv;

    }



    if (src_material->GetTextureCount(aiTextureType_NORMALS) > 0)

    {

        aiString texture_filename;

        src_material->GetTexture(aiTextureType_NORMALS, 0, &texture_filename);

        std::string full_path = std::string(file_path.c_str()) + std::string(texture_filename.data);

        wchar_t wc_path[MAX_PATH];

        mbstowcs_s(nullptr, wc_path, full_path.c_str(), MAX_PATH);



        ID3D11ShaderResourceView * srv;

        hr = load_texture(device, wc_path, &srv);

        _ASSERT(SUCCEEDED(hr));



        this->material_properties[Scene::NORMAL_TEX] = (void *) srv;

    }

}
Ejemplo n.º 22
0
void RenderObject::pre_render() {

	recursive_pre_render(scene->mRootNode);

	//Init materials:
	for(unsigned int i= 0; i < scene->mNumMaterials; ++i) {
		const aiMaterial * mtl = scene->mMaterials[i];
		Material mtl_data;

		aiString path;
		if(mtl->GetTextureCount(aiTextureType_DIFFUSE) > 0 &&
			mtl->GetTexture(aiTextureType_DIFFUSE, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
			std::string p(path.data);
			mtl_data.texture = load_texture(p);
		} else if(mtl->GetTextureCount(aiTextureType_AMBIENT) > 0 &&
			mtl->GetTexture(aiTextureType_AMBIENT, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
			std::string p(path.data);
			mtl_data.texture = load_texture(p);
		}

		if ( !mtl_data.texture ){
			fprintf(stderr, "RenderObject `%s' texture failed to load.\n", name.c_str());
			util_abort();
		}

		//Check for normalmap:
		if(mtl->GetTextureCount(aiTextureType_HEIGHT) > 0 &&
			mtl->GetTexture(aiTextureType_HEIGHT, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
			const std::string p(path.data);
			mtl_data.normal_map = load_texture(p);
		}

		if(mtl->GetTextureCount(aiTextureType_SHININESS) > 0 &&
		   mtl->GetTexture(aiTextureType_SHININESS, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
			const std::string p(path.data);
			mtl_data.specular_map = load_texture(p);
		}

		if(mtl->GetTextureCount(aiTextureType_OPACITY) > 0 &&
		   mtl->GetTexture(aiTextureType_OPACITY, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
			const std::string p(path.data);
			mtl_data.alpha_map = load_texture(p);
		}

		aiString name;
		if(AI_SUCCESS == mtl->Get(AI_MATKEY_NAME, name))
			fprintf(verbose, "Loaded material %d %s\n", i, name.data);

		aiColor4D value;
		if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_DIFFUSE, &value))
			color4_to_vec4(&value, mtl_data.diffuse);

		if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_SPECULAR, &value))
			color4_to_vec4(&value, mtl_data.specular);

		if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_AMBIENT, &value))
			color4_to_vec4(&value, mtl_data.ambient);

		if(AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_EMISSIVE, &value))
			color4_to_vec4(&value, mtl_data.emission);

		unsigned int max = 1;
		float strength;
		int ret1 = aiGetMaterialFloatArray(mtl, AI_MATKEY_SHININESS, &mtl_data.shininess, &max);
		if(ret1 == AI_SUCCESS) {
			max = 1;
			int ret2 = aiGetMaterialFloatArray(mtl, AI_MATKEY_SHININESS_STRENGTH, &strength, &max);
			if(ret2 == AI_SUCCESS)
				mtl_data.shininess *= strength;
		} else {
			mtl_data.shininess = 0.0f;
		}

		if ( mtl_data.shininess < 0.001f ){ /* arbitrary small value */
			mtl_data.shininess = 0.001f; /* in glsl pow(x,0) is undefined */
			mtl_data.specular = glm::vec4(0.f, 0.f, 0.f, 0.f);
		}

		max = 1;

		materials.push_back(mtl_data);
	}

}
Ejemplo n.º 23
0
//	PMD解析
int mmdpiPmdAnalyze::analyze( void )
{
	adjust_material = new MMDPI_MATERIAL[ material_num ];
	for( dword i = 0; i < material_num; i ++ )
		adjust_material[ i ].face_num = material[ i ].face_vert_count;

	adjust_vertex = new MMDPI_BLOCK_VERTEX();
	adjust_vertex->alloc( mmdpiPmdLoad::vertex_num );

	for( dword i = 0; i < mmdpiPmdLoad::vertex_num; i ++ )
	{
		MMDPI_PMD_VERTEX_PTR	ver = &vertex[ i ];

		adjust_vertex->ver[ i ].x = ver->pos[ 0 ];
		adjust_vertex->ver[ i ].y = ver->pos[ 1 ];
		adjust_vertex->ver[ i ].z = ver->pos[ 2 ];

		adjust_vertex->uv[ i ].x = ver->uv[ 0 ];
		adjust_vertex->uv[ i ].y = 1 - ver->uv[ 1 ];
		adjust_vertex->uv[ i ].z = 0;
		adjust_vertex->uv[ i ].w = 0;

		adjust_vertex->nor[ i ].x = ver->nor[ 0 ];
		adjust_vertex->nor[ i ].y = ver->nor[ 1 ];
		adjust_vertex->nor[ i ].z = ver->nor[ 2 ];

		//	ボーン
		adjust_vertex->index[ i ].x = ( float )ver->bone_num[ 0 ];
		adjust_vertex->index[ i ].y = ( float )ver->bone_num[ 1 ];
		adjust_vertex->index[ i ].z = ( float )0;
		adjust_vertex->index[ i ].w = ( float )0;
			
		//	重み
		adjust_vertex->weight[ i ].x = ver->bone_weight / 100.0f;
		adjust_vertex->weight[ i ].y = 1.0f - adjust_vertex->weight[ i ].x;
		adjust_vertex->weight[ i ].z = 0;
		adjust_vertex->weight[ i ].w = 0;
	}

	//	最適化
	mmdpiAdjust::adjust_material_bone( material_num, adjust_material, mmdpiPmdLoad::bone_num, face, adjust_vertex );
	mmdpiAdjust::adjust_polygon( face, face_num, adjust_vertex, mmdpiPmdLoad::vertex_num );
	mmdpiAdjust::adjust_face( face, face_num, mmdpiPmdLoad::vertex_num );
	mmdpiAdjust::adjust_bone();
	
	//	テクスチャ
	load_texture();
		
	//skin = new MMDPI_SKIN_INFO[ skin_num ];
	//for( uint i = 0; i < skin_num; i ++ )
	//{
	//	a_skin[ i ].skin_flag = 0;
	//	a_skin[ i ].skin_name = skin[ i ].skin_name;
	//}

	//	マテリアル情報の保存
	for( dword j = 0; j < get_face_num(); j ++ )
	{
		MMDPI_BLOCK_FACE_PTR	f = &get_face_block()[ j ];
		for( dword i = 0; i < f->material_num; i ++ )
		{
			MMDPI_MATERIAL_PTR		m		= f->material[ i ];
			MMDPI_PMD_MATERIAL_PTR	mpmx	= &material[ m->pid ];
		
			m->edge_size = mpmx->edge_flag * 0.02f;

			m->edge_color.r = 0;
			m->edge_color.g = 0;
			m->edge_color.b = 0;
			m->edge_color.a = 1;

			m->opacity = mpmx->alpha;
		}
	}

	return 0;
}
 void ResStarlingAtlas::_restore(Restorable* r, void*)
 {
     load_texture(_imagePath, _texture, true, true, &RestoreResourcesContext::instance);
     _texture->reg(CLOSURE(this, &ResStarlingAtlas::_restore), 0);
 }
Ejemplo n.º 25
0
int main () {
	restart_gl_log ();
	start_gl ();
	// tell GL to only draw onto a pixel if the shape is closer to the viewer
	glEnable (GL_DEPTH_TEST); // enable depth-testing
	// depth-testing interprets a smaller value as "closer"

	glDepthFunc (GL_LESS);
	assert (load_mesh ("monkey.obj"));

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

	GLuint points_vbo;
	if (NULL != g_vp) {
		glGenBuffers (1, &points_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat), g_vp,
									GL_STATIC_DRAW);
		glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (0);
		printf ("enabled points\n");
	}
	
	GLuint normals_vbo;
	if (NULL != g_vn) {
		glGenBuffers (1, &normals_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, normals_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat), g_vn,
									GL_STATIC_DRAW);
		glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (1);
		printf ("enabled normals\n");
	}
	
	GLuint texcoords_vbo;
	if (NULL != g_vt) {
		glGenBuffers (1, &texcoords_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
		glBufferData (GL_ARRAY_BUFFER, 2 * g_point_count * sizeof (GLfloat), g_vt,
									GL_STATIC_DRAW);
		glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (2);
		printf ("enabled texcoords\n");
	}
	
	GLuint shader_programme = create_programme_from_files ("test_vs.glsl",
																												 "test_fs.glsl");
	
	/* if converting to GLSL 410 do this to replace GLSL texture bindings:
	 GLint diffuse_map_loc, specular_map_loc, ambient_map_loc, emission_map_loc;
	 diffuse_map_loc = glGetUniformLocation (shader_programme, "diffuse_map");
	 specular_map_loc = glGetUniformLocation (shader_programme, "specular_map");
	 ambient_map_loc = glGetUniformLocation (shader_programme, "ambient_map");
	 emission_map_loc = glGetUniformLocation (shader_programme, "emission_map");
	 assert (diffuse_map_loc > -1);
	 assert (specular_map_loc > -1);
	 assert (ambient_map_loc > -1);
	 assert (emission_map_loc > -1);
	 glUseProgram (shader_programme);
	 glUniform1i (diffuse_map_loc, 0);
	 glUniform1i (specular_map_loc, 1);
	 glUniform1i (ambient_map_loc, 2);
	 glUniform1i (emission_map_loc, 3);*/
	
	// load texture
	GLuint tex_diff, tex_spec, tex_amb, tex_emiss;
	glActiveTexture (GL_TEXTURE0);
	assert (load_texture ("boulder_diff.png", &tex_diff));
	glActiveTexture (GL_TEXTURE1);
	assert (load_texture ("boulder_spec.png", &tex_spec));
	glActiveTexture (GL_TEXTURE2);
	assert (load_texture ("ao.png", &tex_amb));
	glActiveTexture (GL_TEXTURE3);
	assert (load_texture ("tileable9b_emiss.png", &tex_emiss));
	
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
		
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 90.0f; // 10 degrees per second
	// don't start at zero, or we will be too close
	float cam_pos[] = {0.0f, 0.0f, 5.0f};
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1],
																							-cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	int view_mat_location = glGetUniformLocation (shader_programme, "view");
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	int proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	glUseProgram (shader_programme);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
	glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
	glFrontFace (GL_CCW); // GL_CCW for counter clock-wise
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current in-use shader
		glDrawArrays (GL_TRIANGLES, 0, g_point_count);
		// update other events like input handling 
		glfwPollEvents ();
		
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		// update view matrix
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1],
				-cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
Ejemplo n.º 26
0
int main () {
	restart_gl_log ();
	// use GLFW and GLEW to start GL context. see gl_utils.cpp for details
	start_gl ();

	// tell GL to only draw onto a pixel if the shape is closer to the viewer
	glEnable (GL_DEPTH_TEST); // enable depth-testing
	glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"

	/* OTHER STUFF GOES HERE NEXT */
	GLfloat points[] = {
		-0.5f, -0.5f,  0.0f,
		 0.5f, -0.5f,  0.0f,
		 0.5f,  0.5f,  0.0f,
		 0.5f,  0.5f,  0.0f,
		-0.5f,  0.5f,  0.0f,
		-0.5f, -0.5f,  0.0f
	};
	
	// 2^16 = 65536
	GLfloat texcoords[] = {
		0.0f, 0.0f,
		1.0f, 0.0f,
		1.0f, 1.0f,
		1.0f, 1.0f,
		0.0f, 1.0f,
		0.0f, 0.0f
	};
	
	GLuint points_vbo;
	glGenBuffers (1, &points_vbo);
	glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
	glBufferData (GL_ARRAY_BUFFER, 18 * sizeof (GLfloat), points, GL_STATIC_DRAW);
	
	GLuint texcoords_vbo;
	glGenBuffers (1, &texcoords_vbo);
	glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
	glBufferData (GL_ARRAY_BUFFER, 12 * sizeof (GLfloat), texcoords, GL_STATIC_DRAW);
	
	GLuint vao;
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);
	glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
	glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
	glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
	glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); // normalise!
	glEnableVertexAttribArray (0);
	glEnableVertexAttribArray (1);
	
	GLuint shader_programme = create_programme_from_files (
		"test_vs.glsl", "test_fs.glsl");
	
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
		
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 10.0f; // 10 degrees per second
	float cam_pos[] = {0.0f, 0.0f, 2.0f}; // don't start at zero, or we will be too close
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	int view_mat_location = glGetUniformLocation (shader_programme, "view");
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	int proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	glUseProgram (shader_programme);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
	// load texture
	GLuint tex;
	assert (load_texture ("skulluvmap.png", &tex));
	
	
	glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
	glFrontFace (GL_CCW); // GL_CCW for counter clock-wise
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current in-use shader
		glDrawArrays (GL_TRIANGLES, 0, 6);
		// update other events like input handling 
		glfwPollEvents ();
		
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		// update view matrix
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1], -cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
Ejemplo n.º 27
0
void init_room(void)
{
	glm::mat4 P = camera.P;
	glm::mat4 V = camera.V;

	//glClearColor(.5, .5, .5, 1);
	GLfloat vertices[9][8] = {
		//빨간색
		{ -0.90, -0.90, -0.1, 1.0, 1, 0, 0, 0.3 },
		{ 0.50, -0.90, -0.1, 1.0, 1, 0, 0, 0.3 },
		{ -0.20, 0.50, -0.0, 1.0, 1, 0, 0, 0.3 },

		//초록색
		{ -0.70, -0.70, 0.1, 1.0, 0, 1, 0, 0.3 },
		{ 0.70, -0.70, 0.0, 1.0, 0, 1, 0, 0.3 },
		{ 0.00, 0.70, -0.1, 1.0, 0, 1, 0, 0.3 },

		//파란색
		{ -0.50, -0.50, 0.1, 1.0, 0, 0, 1, 0.3 },
		{ 0.90, -0.50, 0.1, 1.0, 0, 0, 1, 0.3 },
		{ 0.20, 0.90, 0.1, 1.0, 0, 0, 1, 0.3 },
	};


#define	VERT	8.0f
	static const GLfloat positions[8][4] =
	{
		{ -VERT, -VERT, -VERT, VERT },
		{ -VERT, -VERT, VERT, VERT },
		{ -VERT, VERT, -VERT, VERT },
		{ -VERT, VERT, VERT, VERT },
		{ VERT, -VERT, -VERT, VERT },
		{ VERT, -VERT, VERT, VERT },
		{ VERT, VERT, -VERT, VERT },
		{ VERT, VERT, VERT, VERT },
	};

	static const GLushort indices[] =
	{
		0, 1, 2, 3, 6, 7, 4, 5,         // First strip
		0xFFFF,                         // <<-- This is the restart index
		2, 6, 0, 4, 1, 5, 3, 7          // Second strip
	};
	GLuint	buf_attribs, buf_indices;

	glGenVertexArrays(1, &vao_room);
	glBindVertexArray(vao_room);

	glGenBuffers(1, &buf_attribs);
	glBindBuffer(GL_ARRAY_BUFFER, buf_attribs);
	glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
	glGenBuffers(1, &buf_indices);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buf_indices);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);


	h_prog_room = build_program_from_files("tex_cubemap_room.vert", "tex_cubemap_room.frag");

	glUseProgram(h_prog_room);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat)* 4, BUFFER_OFFSET(0));
	glEnableVertexAttribArray(0);

	glUniform1i(glGetUniformLocation(h_prog_room, "tex"), tex_unit);

	//P = glm::perspective(45.0f, 1.0f, 0.1f, 10.0f);
	//V = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -6.0f));
	//glm::mat4	M = glm::mat4(1.0f);

	//glUniformMatrix4fv(glGetUniformLocation(h_prog_room, "MVP"), 1, GL_FALSE, glm::value_ptr(P*V*M));


	//h_prog_cubemap = build_program_from_files("tex_cubemap.vert", "tex_cubemap.frag");
	//glUseProgram(h_prog_cubemap);
	//glUniform1i(glGetUniformLocation(h_prog_cubemap, "tex"), tex_unit);

	glEnable(GL_CULL_FACE);
	//glEnable(GL_DEPTH_TEST);

	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	load_texture();

}
Ejemplo n.º 28
0
int main () {
    // start GL context and O/S window using the GLFW helper library
    if (!glfwInit ()) {
        fprintf (stderr, "ERROR: could not start GLFW3\n");
        return 1;
    }
    
    // uncomment these lines if on Apple OS X
    glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    
    GLFWwindow* window = glfwCreateWindow (640, 480, "Cube to Sphere", NULL, NULL);
    if (!window) {
        fprintf (stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }
    GLFWwindow* window2 = glfwCreateWindow (640, 480, "Just checking", NULL, NULL);
    if (!window2) {
        fprintf (stderr, "ERROR: could not open window with GLFW3\n");
        glfwTerminate();
        return 1;
    }
    glfwMakeContextCurrent (window);
    
    //start GLEW extension handler
    glewExperimental = GL_TRUE;
    glewInit ();
    
    // get version info
    const GLubyte* renderer = glGetString (GL_RENDERER); // get renderer string
    const GLubyte* version = glGetString (GL_VERSION); // version as a string
    printf ("Renderer: %s\n", renderer);
    printf ("OpenGL version supported %s\n", version);
    //CLGLUtils::init();
    boost::compute::context context;
    try {
        context = boost::compute::opengl_create_shared_context();
        
    } catch (std::exception e) {
        std::cerr<<"Failed to initialize a CLGL context"<<e.what()<<std::endl;
        exit(0);
    }
    
    // tell GL to only draw onto a pixel if the shape is closer to the viewer
    glEnable (GL_DEPTH_TEST); // enable depth-testing
    glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"
    
    // OTHER STUFF GOES HERE NEXT
    float points[] = {
        -1.0f,  1.0f, -1.0f,
        -1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f,
        
        -1.0f, -1.0f,  1.0f,
        -1.0f, -1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f,  1.0f,
        -1.0f, -1.0f,  1.0f,
        
        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        
        -1.0f, -1.0f,  1.0f,
        -1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f, -1.0f,  1.0f,
        -1.0f, -1.0f,  1.0f,
        
        -1.0f,  1.0f, -1.0f,
        1.0f,  1.0f, -1.0f,
        1.0f,  1.0f,  1.0f,
        1.0f,  1.0f,  1.0f,
        -1.0f,  1.0f,  1.0f,
        -1.0f,  1.0f, -1.0f,
        
        -1.0f, -1.0f, -1.0f,
        -1.0f, -1.0f,  1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        -1.0f, -1.0f,  1.0f,
        1.0f, -1.0f,  1.0f
    };
    
    
    GLuint vbo;
    glGenBuffers (1, &vbo);
    glBindBuffer (GL_ARRAY_BUFFER, vbo);
    glBufferData (GL_ARRAY_BUFFER, 3 * 36 * sizeof (float), &points, GL_STATIC_DRAW);
    
    
    GLuint vao;
    glGenVertexArrays (1, &vao);
    glBindVertexArray (vao);
    glEnableVertexAttribArray (0);
    glBindBuffer (GL_ARRAY_BUFFER, vbo);
    glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);



    //Create Cube map
    GLuint cube_map_texture;
    
    create_cube_map ((resource_dir+"negz.jpg").c_str(), (resource_dir+"posz.jpg").c_str(), (resource_dir+"posy.jpg").c_str(), (resource_dir+"negy.jpg").c_str(), (resource_dir+"negx.jpg").c_str(), (resource_dir+"posx.jpg").c_str(), &cube_map_texture);
    boost::shared_ptr<boost::compute::opengl_texture> cl_cube_map_texture;
    try {
        cl_cube_map_texture = boost::shared_ptr<boost::compute::opengl_texture>(new boost::compute::opengl_texture(context,GL_TEXTURE_2D_ARRAY,0,cube_map_texture,boost::compute::memory_object::mem_flags::read_only));
    } catch ( const std::exception& e ) {
        std::cerr << e.what() << std::endl;
    }
    
    const char* vertex_shader =
    "#version 400\n"
    "in vec3 vp;"
    "uniform mat4 P, V;"
   // "uniform vec3 vertOut;"
    "out vec3 texcoords;"
    "vec3 newP;"
    "void main () {"
    "    texcoords = vp;"
   // "    vertOut = vp;"
    "    gl_Position = P * V * vec4 (vp, 1.0);"
    "}";
    
    const char* fragment_shader = loadShader(resource_dir+"fragmentShader.frag").c_str();

    
    /*"#version 400\n"
    "in vec3 texcoords;"
    "uniform samplerCube cube_texture;"
    "out vec4 frag_colour;"
    "vec4 cubeToLatLon(samplerCube cubemap, vec3 inUV) {"
    "vec3 cubmapTexCoords;"
    //"cubmapTexCoords.x = inUV.x*sqrt(1 - ( (inUV.y * inUV.y)/2 ) - ( (inUV.z * inUV.z)/2 ) + ( ( (inUV.y * inUV.y) * (inUV.z * inUV.z))/3));"
    "cubmapTexCoords.x = inUV.x;"
    //"cubmapTexCoords.y= inUV.y*sqrt(1 - ( (inUV.z * inUV.z)/2 ) - ( (inUV.x * inUV.x)/2 ) + ( ( (inUV.z * inUV.z) * (inUV.x * inUV.x))/3));"
    "cubmapTexCoords.y = inUV.y;"
    "cubmapTexCoords.z = inUV.z*sqrt(1 - ( (inUV.x * inUV.x)/2 ) - ( (inUV.y * inUV.y)/2 ) + ( ( (inUV.x * inUV.x) * (inUV.y * inUV.y))/3));"
    //"cubmapTexCoords.z = inUV.z;"
    "return texture(cubemap, cubmapTexCoords);"
    "}"
    "void main () {"
    //"  frag_colour = texture (cube_texture, texcoords);"
    "  frag_colour = cubeToLatLon (cube_texture, texcoords);"
    "}";*/
    
    
    GLuint vs = glCreateShader (GL_VERTEX_SHADER);
    glShaderSource (vs, 1, &vertex_shader, NULL);
    glCompileShader (vs);
    GLuint fs = glCreateShader (GL_FRAGMENT_SHADER);
    glShaderSource (fs, 1, &fragment_shader, NULL);
    glCompileShader (fs);
    
    
    GLuint cube_sp = glCreateProgram ();
    glAttachShader (cube_sp, fs);
    glAttachShader (cube_sp, vs);
    glLinkProgram (cube_sp);
    
    //*-----------------------------Compile Shaders for second window - square --------*/
    
    glfwMakeContextCurrent(window2);
    
    //start GLEW extension handler
    glewExperimental = GL_TRUE;
    glewInit ();
    glEnable (GL_DEPTH_TEST); // enable depth-testing
    glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"
    
    float squarePoints[] =
    {
        -1.0f,  1.0f, -1.0f,
        -1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f, -1.0f, -1.0f,
        1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f, -1.0f
    };
    
    GLfloat texcoords[] = {
        0.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 1.0f,
        1.0f, 1.0f,
        0.0f, 1.0f,
        0.0f, 0.0f
    };
    
    GLuint vbo_square;
    glGenBuffers (1, &vbo_square);
    glBindBuffer (GL_ARRAY_BUFFER, vbo_square);
    glBufferData (GL_ARRAY_BUFFER, 3 * 6 * sizeof (float), &squarePoints, GL_STATIC_DRAW);
    
    GLuint texcoords_vbo;
    glGenBuffers (1, &texcoords_vbo);
    glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
    glBufferData (GL_ARRAY_BUFFER, 12 * sizeof (GLfloat), texcoords, GL_STATIC_DRAW);
    
    GLuint vao_square;
    glGenVertexArrays (1, &vao_square);
    glBindVertexArray (vao_square);
    glBindBuffer (GL_ARRAY_BUFFER, vbo_square);
    glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
    glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
    glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, NULL); // normalise!
    glEnableVertexAttribArray (0);
    glEnableVertexAttribArray (1);
    
   

    GLuint square_sp = create_programme_from_files((resource_dir+"square.vert").c_str(), (resource_dir+"square.frag").c_str());
    
    GLuint tex;
    assert (load_texture ((resource_dir+"negz.jpg").c_str(), &tex));
    //*----------------------------------------------------------------------------------*/
    glfwMakeContextCurrent (window);

    
    int cube_V_location = glGetUniformLocation (cube_sp, "V");
    int cube_P_location = glGetUniformLocation (cube_sp, "P");
    //int cube_vertOut = glGetUniformLocation (cube_sp, "vertOut");
    
    /*-------------------------------CREATE GLOBAL CAMERA--------------------------------*/
    #define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
    // input variables
    float near = 0.1f; // clipping plane
    float far = 100.0f; // clipping plane
    float fovy = 80.0f; // 67 degrees
    float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
    proj_mat = perspective (fovy, aspect, near, far);
    
    float cam_speed = 3.0f; // 1 unit per second
    float cam_heading_speed = 50.0f; // 30 degrees per second
    float cam_heading = 0.0f; // y-rotation in degrees
    mat4 T = translate (identity_mat4 (), vec3 (-cam_pos.v[0], -cam_pos.v[1], -cam_pos.v[2]));
    mat4 R = rotate_y_deg (identity_mat4 (), -cam_heading);
    versor q = quat_from_axis_deg (-cam_heading, 0.0f, 1.0f, 0.0f);
    view_mat = R * T;
    // keep track of some useful vectors that can be used for keyboard movement
    vec4 fwd (0.0f, 0.0f, -1.0f, 0.0f);
    vec4 rgt (1.0f, 0.0f, 0.0f, 0.0f);
    vec4 up (0.0f, 1.0f, 0.0f, 0.0f);
    
    
    
    /*---------------------------SET RENDERING DEFAULTS---------------------------*/
    glUseProgram (cube_sp);
    glUniformMatrix4fv (cube_V_location, 1, GL_FALSE, R.m);
    glUniformMatrix4fv (cube_P_location, 1, GL_FALSE, proj_mat.m);
    // unique model matrix for each sphere
    mat4 model_mat = identity_mat4 ();
    
    glEnable (GL_DEPTH_TEST); // enable depth-testing
    glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"
    glEnable (GL_CULL_FACE); // cull face
    glCullFace (GL_BACK); // cull back face
    glFrontFace (GL_CCW); // set counter-clock-wise vertex order to mean the front
    glClearColor (0.2, 0.2, 0.2, 1.0); // grey background to help spot mistakes
    glViewport (0, 0, g_gl_width, g_gl_height);
    
    while (!glfwWindowShouldClose (window) && !glfwWindowShouldClose (window2)) {
        // update timers
        static double previous_seconds = glfwGetTime ();
        double current_seconds = glfwGetTime ();
        double elapsed_seconds = current_seconds - previous_seconds;
        previous_seconds = current_seconds;
        //_update_fps_counter (window);
        
        // wipe the drawing surface clear
        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        // render a sky-box using the cube-map texture
        glDepthMask (GL_FALSE);
        glUseProgram (cube_sp);
        glActiveTexture (GL_TEXTURE0);
        glBindTexture (GL_TEXTURE_CUBE_MAP, cube_map_texture);
        glBindVertexArray (vao);
        glDrawArrays (GL_TRIANGLES, 0, 36);
        glDepthMask (GL_TRUE);
        
        //*---------------------------------Display for second window-------------------*/
        
        glfwMakeContextCurrent (window2);
        glUseProgram (square_sp);
        
        int cubemap_vert = glGetUniformLocation (square_sp, "cubeMap_texcoords");
        
        
        glEnable (GL_DEPTH_TEST); // enable depth-testing
        glDepthFunc (GL_LESS); // depth-testing interprets a smaller value as "closer"
        glEnable (GL_CULL_FACE); // cull face
        glCullFace (GL_BACK); // cull back face
        glFrontFace (GL_CCW); // set counter-clock-wise vertex order to mean the front
        glClearColor (0.3, 0.2, 0.3, 1.0); // grey background to help spot mistakes
        glViewport (0, 0, g_gl_width, g_gl_height);
        
        glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        
        glDepthMask (GL_FALSE);
        glUseProgram (square_sp);
        glBindVertexArray (vao_square);
        glDrawArrays (GL_TRIANGLES, 0, 6);
        glDepthMask (GL_TRUE);

        
        //*------------------------------GO back to cubemap window--------------------*/
        glfwMakeContextCurrent (window);
        
        // update other events like input handling
        glfwPollEvents ();
        
        // control keys
        bool cam_moved = false;
        vec3 move (0.0, 0.0, 0.0);
        float cam_yaw = 0.0f; // y-rotation in degrees
        float cam_pitch = 0.0f;
        float cam_roll = 0.0;
        if (glfwGetKey (window, GLFW_KEY_A)) {
            move.v[0] -= cam_speed * elapsed_seconds;
            cam_moved = true;
            print(move);
        }
        if (glfwGetKey (window, GLFW_KEY_D)) {
            move.v[0] += cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_Q)) {
            move.v[1] += cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_E)) {
            move.v[1] -= cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_W)) {
            move.v[2] -= cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_S)) {
            move.v[2] += cam_speed * elapsed_seconds;
            cam_moved = true;
        }
        if (glfwGetKey (window, GLFW_KEY_LEFT)) {
            cam_yaw += cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_yaw = quat_from_axis_deg (
                                               cam_yaw, up.v[0], up.v[1], up.v[2]
                                               );
            q = q_yaw * q;
        }
        if (glfwGetKey (window, GLFW_KEY_RIGHT)) {
            cam_yaw -= cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_yaw = quat_from_axis_deg (
                                               cam_yaw, up.v[0], up.v[1], up.v[2]
                                               );
            q = q_yaw * q;
        }
        if (glfwGetKey (window, GLFW_KEY_UP)) {
            cam_pitch += cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_pitch = quat_from_axis_deg (
                                                 cam_pitch, rgt.v[0], rgt.v[1], rgt.v[2]
                                                 );
            q = q_pitch * q;
        }
        if (glfwGetKey (window, GLFW_KEY_DOWN)) {
            cam_pitch -= cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_pitch = quat_from_axis_deg (
                                                 cam_pitch, rgt.v[0], rgt.v[1], rgt.v[2]
                                                 );
            q = q_pitch * q;
        }
        if (glfwGetKey (window, GLFW_KEY_Z)) {
            cam_roll -= cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_roll = quat_from_axis_deg (
                                                cam_roll, fwd.v[0], fwd.v[1], fwd.v[2]
                                                );
            q = q_roll * q;
        }
        if (glfwGetKey (window, GLFW_KEY_C)) {
            cam_roll += cam_heading_speed * elapsed_seconds;
            cam_moved = true;
            versor q_roll = quat_from_axis_deg (
                                                cam_roll, fwd.v[0], fwd.v[1], fwd.v[2]
                                                );
            q = q_roll * q;
        }
        // update view matrix
        if (cam_moved) {
            cam_heading += cam_yaw;
            
            // re-calculate local axes so can move fwd in dir cam is pointing
            R = quat_to_mat4 (q);
            fwd = R * vec4 (0.0, 0.0, -1.0, 0.0);
            rgt = R * vec4 (1.0, 0.0, 0.0, 0.0);
            up = R * vec4 (0.0, 1.0, 0.0, 0.0);
            
            cam_pos = cam_pos + vec3 (fwd) * -move.v[2];
            cam_pos = cam_pos + vec3 (up) * move.v[1];
            cam_pos = cam_pos + vec3 (rgt) * move.v[0];
            mat4 T = translate (identity_mat4 (), vec3 (cam_pos));
            
            view_mat = inverse (R) * inverse (T);
            //std::cout<<inverse(R).m<<std::endl;
            // cube-map view matrix has rotation, but not translation
            glUseProgram (cube_sp);
            glUniformMatrix4fv (cube_V_location, 1, GL_FALSE, inverse (R).m);
        }
        
        
        if (GLFW_PRESS == glfwGetKey (window, GLFW_KEY_ESCAPE)) {
            glfwSetWindowShouldClose (window, 1);
        }
        if (GLFW_PRESS == glfwGetKey (window2, GLFW_KEY_ESCAPE)) {
            glfwSetWindowShouldClose (window2, 1);
        }
        // put the stuff we've been drawing onto the display
        glfwSwapBuffers (window);
        
        glfwMakeContextCurrent (window2);
        glfwSwapBuffers (window2);
        glfwMakeContextCurrent (window);
    }
    
    // close GL context and any other GLFW resources
    glfwTerminate();
    return 0;
}
Ejemplo n.º 29
0
void Level::add_texture(const char *filename, unsigned long index)
{
    if (this->_textures.size() <= index)
        this->_textures.resize(index + 1, false);
    this->_textures[index] = load_texture(filename);
}
Ejemplo n.º 30
0
void tile::draw() const {
    load_texture();
    texture_.set_as_current_texture();

    draw(texture_);
}