Example #1
0
	std::string ResLoader::Locate(std::string const & name)
	{
#if defined(KLAYGE_PLATFORM_ANDROID)
		android_app* state = Context::Instance().AppState();
		AAssetManager* am = state->activity->assetManager;
		AAsset* asset = AAssetManager_open(am, name.c_str(), AASSET_MODE_UNKNOWN);
		if (asset != nullptr)
		{
			AAsset_close(asset);
			return name;
		}
#elif defined(KLAYGE_PLATFORM_IOS)
		std::string::size_type found = name.find_last_of(".");
		if (found != std::string::npos)
		{
			std::string::size_type found2 = name.find_last_of("/");
			CFBundleRef main_bundle = CFBundleGetMainBundle();
			CFStringRef file_name = CFStringCreateWithCString(kCFAllocatorDefault,
				name.substr(found2 + 1, found - found2 - 1).c_str(), kCFStringEncodingASCII);
			CFStringRef file_ext = CFStringCreateWithCString(kCFAllocatorDefault,
				name.substr(found + 1).c_str(), kCFStringEncodingASCII);
			CFURLRef file_url = CFBundleCopyResourceURL(main_bundle, file_name, file_ext, NULL);
			CFRelease(file_name);
			CFRelease(file_ext);
			if (file_url != nullptr)
			{
				CFStringRef file_path = CFURLCopyFileSystemPath(file_url, kCFURLPOSIXPathStyle);

				char const * path = CFStringGetCStringPtr(file_path, CFStringGetSystemEncoding());
				std::string const res_name(path);

				CFRelease(file_url);
				CFRelease(file_path);

				return res_name;
			}
		}
#else
		typedef KLAYGE_DECLTYPE(paths_) PathsType;
		KLAYGE_FOREACH(PathsType::const_reference path, paths_)
		{
			std::string const res_name(path + name);

			if (filesystem::exists(filesystem::path(res_name)))
			{
				return res_name;
			}
			else
			{
				std::string::size_type const pkt_offset(res_name.find("//"));
				if (pkt_offset != std::string::npos)
				{
					std::string pkt_name = res_name.substr(0, pkt_offset);
					filesystem::path pkt_path(pkt_name);
					if (filesystem::exists(pkt_path)
							&& (filesystem::is_regular_file(pkt_path)
									|| filesystem::is_symlink(pkt_path)))
					{
						std::string::size_type const password_offset = pkt_name.find("|");
						std::string password;
						if (password_offset != std::string::npos)
						{
							password = pkt_name.substr(password_offset + 1);
							pkt_name = pkt_name.substr(0, password_offset - 1);
						}
						std::string const file_name = res_name.substr(pkt_offset + 2);

#ifdef KLAYGE_TR2_LIBRARY_FILESYSTEM_V3_SUPPORT
						uint64_t timestamp = filesystem::last_write_time(pkt_path).time_since_epoch().count();
#else
						uint64_t timestamp = filesystem::last_write_time(pkt_path);
#endif
						ResIdentifierPtr pkt_file = MakeSharedPtr<ResIdentifier>(name, timestamp,
							MakeSharedPtr<std::ifstream>(pkt_name.c_str(), std::ios_base::binary));
						if (*pkt_file)
						{
							if (Find7z(pkt_file, password, file_name) != 0xFFFFFFFF)
							{
								return res_name;
							}
						}
					}
				}
			}
		}
void showGraph(TGraph* graph, 
	       const std::string& xAxisTitle,
	       Float_t* genX, 
	       double yMin, double yMax, const std::string& yAxisTitle,
	       const std::string& outputFileName)
{
  TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 600);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);

  canvas->SetTopMargin(0.10);
  canvas->SetLeftMargin(0.16);
  canvas->SetRightMargin(0.14);
  canvas->SetBottomMargin(0.12);

  int numPoints = graph->GetN();
  double xMin, xMax, yDummy;
  graph->GetPoint(0, xMin, yDummy);
  graph->GetPoint(numPoints - 1, xMax, yDummy);

  TH1* dummyHistogram = new TH1D("dummyHistogram", "dummyHistogram", numPoints/100, xMin, xMax);
  dummyHistogram->SetStats(false);
  dummyHistogram->SetMinimum(yMin);
  dummyHistogram->SetMaximum(yMax);

  TAxis* xAxis = dummyHistogram->GetXaxis();
  xAxis->SetTitle(xAxisTitle.data());
  xAxis->SetTitleOffset(1.15);

  TAxis* yAxis = dummyHistogram->GetYaxis();
  yAxis->SetTitle(yAxisTitle.data());
  yAxis->SetTitleOffset(1.15);

  dummyHistogram->Draw("axis");

  TGraph* genMarker = 0;
  if ( genX ) {
    genMarker = new TGraph(2);
    genMarker->SetPoint(0, xMin, *genX);
    genMarker->SetPoint(1, xMax, *genX);
    genMarker->SetLineColor(8);
    genMarker->SetLineWidth(1);
    genMarker->SetMarkerColor(8);
    genMarker->SetMarkerStyle(20);
    genMarker->SetMarkerSize(1);
    genMarker->Draw("L");
  }

  graph->SetLineColor(1);
  graph->SetLineWidth(2);
  graph->SetMarkerColor(1);
  graph->SetMarkerStyle(20);
  graph->SetMarkerSize(1);
  graph->Draw("L");

  canvas->Update();
  size_t idx = outputFileName.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName, 0, idx);
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());

  delete dummyHistogram;
  delete genMarker;
  delete canvas;  
}
Example #3
0
// Returns the current directory
std::string GetCurrentDir()
{
    // Get the current working directory (getcwd uses malloc)
#ifdef _WIN32
    wchar_t *dir;
    if (!(dir = _wgetcwd(nullptr, 0))) {
#else
    char *dir;
    if (!(dir = getcwd(nullptr, 0))) {
#endif
        LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: %s",
                GetLastErrorMsg());
        return nullptr;
    }
#ifdef _WIN32
    std::string strDir = Common::UTF16ToUTF8(dir);
#else
    std::string strDir = dir;
#endif
    free(dir);
    return strDir;
}

// Sets the current directory to the given directory
bool SetCurrentDir(const std::string &directory)
{
#ifdef _WIN32
    return _wchdir(Common::UTF8ToUTF16W(directory).c_str()) == 0;
#else
    return chdir(directory.c_str()) == 0;
#endif
}

#if defined(__APPLE__)
std::string GetBundleDirectory()
{
    CFURLRef BundleRef;
    char AppBundlePath[MAXPATHLEN];
    // Get the main bundle for the app
    BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);
    CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));
    CFRelease(BundleRef);
    CFRelease(BundlePath);

    return AppBundlePath;
}
#endif

#ifdef _WIN32
std::string& GetExeDirectory()
{
    static std::string exe_path;
    if (exe_path.empty())
    {
        wchar_t wchar_exe_path[2048];
        GetModuleFileNameW(nullptr, wchar_exe_path, 2048);
        exe_path = Common::UTF16ToUTF8(wchar_exe_path);
        exe_path = exe_path.substr(0, exe_path.find_last_of('\\'));
    }
    return exe_path;
}
#else
/**
 * @return The user’s home directory on POSIX systems
 */
static const std::string& GetHomeDirectory() {
    static std::string home_path;
    if (home_path.empty()) {
        const char* envvar = getenv("HOME");
        if (envvar) {
            home_path = envvar;
        } else {
            auto pw = getpwuid(getuid());
            ASSERT_MSG(pw, "$HOME isn’t defined, and the current user can’t be found in /etc/passwd.");
            home_path = pw->pw_dir;
        }
    }
    return home_path;
}

/**
 * Follows the XDG Base Directory Specification to get a directory path
 * @param envvar The XDG environment variable to get the value from
 * @return The directory path
 * @sa http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
 */
static const std::string GetUserDirectory(const std::string& envvar) {
    const char* directory = getenv(envvar.c_str());

    std::string user_dir;
    if (directory) {
        user_dir = directory;
    } else {
        std::string subdirectory;
        if (envvar == "XDG_DATA_HOME")
            subdirectory = DIR_SEP ".local" DIR_SEP "share";
        else if (envvar == "XDG_CONFIG_HOME")
            subdirectory = DIR_SEP ".config";
        else if (envvar == "XDG_CACHE_HOME")
            subdirectory = DIR_SEP ".cache";
        else
            ASSERT_MSG(false, "Unknown XDG variable %s.", envvar.c_str());
        user_dir = GetHomeDirectory() + subdirectory;
    }

    ASSERT_MSG(!user_dir.empty(), "User directory %s musn’t be empty.", envvar.c_str());
    ASSERT_MSG(user_dir[0] == '/', "User directory %s must be absolute.", envvar.c_str());

    return user_dir;
}
#endif

std::string GetSysDirectory()
{
    std::string sysDir;

#if defined (__APPLE__)
    sysDir = GetBundleDirectory();
    sysDir += DIR_SEP;
    sysDir += SYSDATA_DIR;
#else
    sysDir = SYSDATA_DIR;
#endif
    sysDir += DIR_SEP;

    LOG_DEBUG(Common_Filesystem, "Setting to %s:", sysDir.c_str());
    return sysDir;
}

// Returns a string with a Citra data dir or file in the user's home
// directory. To be used in "multi-user" mode (that is, installed).
const std::string& GetUserPath(const unsigned int DirIDX, const std::string &newPath)
{
    static std::string paths[NUM_PATH_INDICES];

    // Set up all paths and files on the first run
    if (paths[D_USER_IDX].empty())
    {
#ifdef _WIN32
        paths[D_USER_IDX]   = GetExeDirectory() + DIR_SEP USERDATA_DIR DIR_SEP;
        paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
        paths[D_CACHE_IDX]  = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
#else
        if (FileUtil::Exists(ROOT_DIR DIR_SEP USERDATA_DIR)) {
            paths[D_USER_IDX]   = ROOT_DIR DIR_SEP USERDATA_DIR DIR_SEP;
            paths[D_CONFIG_IDX] = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
            paths[D_CACHE_IDX]  = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
        } else {
            std::string data_dir   = GetUserDirectory("XDG_DATA_HOME");
            std::string config_dir = GetUserDirectory("XDG_CONFIG_HOME");
            std::string cache_dir  = GetUserDirectory("XDG_CACHE_HOME");

            paths[D_USER_IDX]   = data_dir   + DIR_SEP EMU_DATA_DIR DIR_SEP;
            paths[D_CONFIG_IDX] = config_dir + DIR_SEP EMU_DATA_DIR DIR_SEP;
            paths[D_CACHE_IDX]  = cache_dir  + DIR_SEP EMU_DATA_DIR DIR_SEP;
        }
#endif

        paths[D_GAMECONFIG_IDX]     = paths[D_USER_IDX] + GAMECONFIG_DIR DIR_SEP;
        paths[D_MAPS_IDX]           = paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
        paths[D_SDMC_IDX]           = paths[D_USER_IDX] + SDMC_DIR DIR_SEP;
        paths[D_NAND_IDX]           = paths[D_USER_IDX] + NAND_DIR DIR_SEP;
        paths[D_SYSDATA_IDX]        = paths[D_USER_IDX] + SYSDATA_DIR DIR_SEP;
        paths[D_SHADERCACHE_IDX]    = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
        paths[D_SHADERS_IDX]        = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
        paths[D_STATESAVES_IDX]     = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
        paths[D_SCREENSHOTS_IDX]    = paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
        paths[D_DUMP_IDX]           = paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
        paths[D_DUMPFRAMES_IDX]     = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
        paths[D_DUMPAUDIO_IDX]      = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
        paths[D_DUMPTEXTURES_IDX]   = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
        paths[D_LOGS_IDX]           = paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
        paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
        paths[F_LOGGERCONFIG_IDX]   = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
        paths[F_MAINLOG_IDX]        = paths[D_LOGS_IDX] + MAIN_LOG;
    }

    if (!newPath.empty())
    {
        if (!FileUtil::IsDirectory(newPath))
        {
            LOG_ERROR(Common_Filesystem, "Invalid path specified %s", newPath.c_str());
            return paths[DirIDX];
        }
        else
        {
            paths[DirIDX] = newPath;
        }

        switch (DirIDX)
        {
        case D_ROOT_IDX:
            paths[D_USER_IDX]           = paths[D_ROOT_IDX] + DIR_SEP;
            paths[D_SYSCONF_IDX]        = paths[D_USER_IDX] + SYSCONF_DIR + DIR_SEP;
            paths[F_SYSCONF_IDX]        = paths[D_SYSCONF_IDX] + SYSCONF;
            break;

        case D_USER_IDX:
            paths[D_USER_IDX]           = paths[D_ROOT_IDX] + DIR_SEP;
            paths[D_CONFIG_IDX]         = paths[D_USER_IDX] + CONFIG_DIR DIR_SEP;
            paths[D_GAMECONFIG_IDX]     = paths[D_USER_IDX] + GAMECONFIG_DIR DIR_SEP;
            paths[D_MAPS_IDX]           = paths[D_USER_IDX] + MAPS_DIR DIR_SEP;
            paths[D_CACHE_IDX]          = paths[D_USER_IDX] + CACHE_DIR DIR_SEP;
            paths[D_SDMC_IDX]           = paths[D_USER_IDX] + SDMC_DIR DIR_SEP;
            paths[D_NAND_IDX]           = paths[D_USER_IDX] + NAND_DIR DIR_SEP;
            paths[D_SHADERCACHE_IDX]    = paths[D_USER_IDX] + SHADERCACHE_DIR DIR_SEP;
            paths[D_SHADERS_IDX]        = paths[D_USER_IDX] + SHADERS_DIR DIR_SEP;
            paths[D_STATESAVES_IDX]     = paths[D_USER_IDX] + STATESAVES_DIR DIR_SEP;
            paths[D_SCREENSHOTS_IDX]    = paths[D_USER_IDX] + SCREENSHOTS_DIR DIR_SEP;
            paths[D_DUMP_IDX]           = paths[D_USER_IDX] + DUMP_DIR DIR_SEP;
            paths[D_DUMPFRAMES_IDX]     = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
            paths[D_DUMPAUDIO_IDX]      = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
            paths[D_DUMPTEXTURES_IDX]   = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
            paths[D_LOGS_IDX]           = paths[D_USER_IDX] + LOGS_DIR DIR_SEP;
            paths[D_SYSCONF_IDX]        = paths[D_USER_IDX] + SYSCONF_DIR DIR_SEP;
            paths[F_EMUCONFIG_IDX]      = paths[D_CONFIG_IDX] + EMU_CONFIG;
            paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
            paths[F_LOGGERCONFIG_IDX]   = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
            paths[F_MAINLOG_IDX]        = paths[D_LOGS_IDX] + MAIN_LOG;
            break;

        case D_CONFIG_IDX:
            paths[F_EMUCONFIG_IDX]      = paths[D_CONFIG_IDX] + EMU_CONFIG;
            paths[F_DEBUGGERCONFIG_IDX] = paths[D_CONFIG_IDX] + DEBUGGER_CONFIG;
            paths[F_LOGGERCONFIG_IDX]   = paths[D_CONFIG_IDX] + LOGGER_CONFIG;
            break;

        case D_DUMP_IDX:
            paths[D_DUMPFRAMES_IDX]     = paths[D_DUMP_IDX] + DUMP_FRAMES_DIR DIR_SEP;
            paths[D_DUMPAUDIO_IDX]      = paths[D_DUMP_IDX] + DUMP_AUDIO_DIR DIR_SEP;
            paths[D_DUMPTEXTURES_IDX]   = paths[D_DUMP_IDX] + DUMP_TEXTURES_DIR DIR_SEP;
            break;

        case D_LOGS_IDX:
            paths[F_MAINLOG_IDX]        = paths[D_LOGS_IDX] + MAIN_LOG;
        }
    }

    return paths[DirIDX];
}

size_t WriteStringToFile(bool text_file, const std::string &str, const char *filename)
{
    return FileUtil::IOFile(filename, text_file ? "w" : "wb").WriteBytes(str.data(), str.size());
}

size_t ReadFileToString(bool text_file, const char *filename, std::string &str)
{
    IOFile file(filename, text_file ? "r" : "rb");

    if (!file)
        return false;

    str.resize(static_cast<u32>(file.GetSize()));
    return file.ReadArray(&str[0], str.size());
}
Example #4
0
std::string strip_extension(const std::string& fname)
{
	return fname.substr(0, fname.find_last_of('.'));
}
/// processes all 'driver' options in the XML file
void process_xml_options(const std::string& xml_fname)
{
  // *************************************************************
  // going to remove any path from the argument and change to that
  // path; this is done so that all files referenced from the
  // local path of the XML file are found
  // *************************************************************

  // set the filename to use as the argument, by default
  std::string filename = xml_fname;

  // get the current pathname
  size_t BUFSIZE = 128;
  boost::shared_array<char> cwd;
  while (true)
  {
    cwd = boost::shared_array<char>((new char[BUFSIZE]));
    if (getcwd(cwd.get(), BUFSIZE) == cwd.get())
      break;
    if (errno != ERANGE)
    {
      std::cerr << "process_xml_options() - unable to allocate sufficient memory!" << std::endl;
      return;
    }
    BUFSIZE *= 2;
  }

  // separate the path from the filename
  size_t last_path_sep = xml_fname.find_last_of('/');
  if (last_path_sep != std::string::npos)
  {
    // get the new working path
    std::string pathname = xml_fname.substr(0,last_path_sep+1);

    // change to the new working path
    chdir(pathname.c_str());

    // get the new filename
    filename = xml_fname.substr(last_path_sep+1,std::string::npos);
  }

  // read the XML Tree 
  shared_ptr<const XMLTree> driver_tree = XMLTree::read_from_xml(filename);
  if (!driver_tree)
  {
    std::cerr << "process_xml_options() - unable to open file " << xml_fname;
    std::cerr << " for reading" << std::endl;
    chdir(cwd.get());
    return;
  }
  
  // find the driver tree 
  driver_tree = find_subtree(driver_tree, "driver");

  // make sure that the driver node was found
  if (!driver_tree)
  {
    chdir(cwd.get());
    return;
  }

  // process tags
  process_tag("window", driver_tree, process_window_tag);
  process_tag("camera", driver_tree, process_camera_tag);

  // change back to current directory 
  chdir(cwd.get());
}
//OpenGL initialization function
void OnInit() { 
	//get the mesh path for loading of textures	
	std::string mesh_path = mesh_filename.substr(0, mesh_filename.find_last_of("/")+1);

	//load the obj model
	if(!obj.Load(mesh_filename.c_str(), meshes, vertices, indices, materials)) { 
		cout<<"Cannot load the 3ds mesh"<<endl;
		exit(EXIT_FAILURE);
	} 
	GL_CHECK_ERRORS

	//load material textures  
	for(size_t k=0;k<materials.size();k++) {
		//if the diffuse texture name is not empty
		if(materials[k]->map_Kd != "") { 
			//generate a new OpenGL array texture
			GLuint id = 0;
			glGenTextures(1, &id);
			glBindTexture(GL_TEXTURE_2D, id);
			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_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			int texture_width = 0, texture_height = 0, channels=0;		 	

			const string& filename =  materials[k]->map_Kd;

			std::string full_filename = mesh_path;
			full_filename.append(filename);
			//use SOIL to load the texture
			GLubyte* pData = SOIL_load_image(full_filename.c_str(), &texture_width, &texture_height, &channels, SOIL_LOAD_AUTO);
			if(pData == NULL) {
				cerr<<"Cannot load image: "<<full_filename.c_str()<<endl;
				exit(EXIT_FAILURE);
			} 

			//Flip the image on Y axis
			int i,j;
			for( j = 0; j*2 < texture_height; ++j )
			{
				int index1 = j * texture_width * channels;
				int index2 = (texture_height - 1 - j) * texture_width * channels;
				for( i = texture_width * channels; i > 0; --i )
				{
					GLubyte temp = pData[index1];
					pData[index1] = pData[index2];
					pData[index2] = temp;
					++index1;
					++index2;
				}
			} 
			//get the image format
			GLenum format = GL_RGBA;
			switch(channels) {
				case 2:	format = GL_RG32UI; break;
				case 3: format = GL_RGB;	break;
				case 4: format = GL_RGBA;	break;
			}
			//allocate texture 
			glTexImage2D(GL_TEXTURE_2D, 0, format, texture_width, texture_height, 0, format, GL_UNSIGNED_BYTE, pData);

			//release the SOIL image data
			SOIL_free_image_data(pData);

			//add loaded texture ID to vector
			textures.push_back(id);
		}
	} 
	GL_CHECK_ERRORS

	//load flat shader
	flatShader.LoadFromFile(GL_VERTEX_SHADER, "shaders/flat.vert");
	flatShader.LoadFromFile(GL_FRAGMENT_SHADER, "shaders/flat.frag");
	//compile and link shader
	flatShader.CreateAndLinkProgram();
	flatShader.Use();	
		//add attribute and uniform
		flatShader.AddAttribute("vVertex");
		flatShader.AddUniform("MVP"); 
	flatShader.UnUse();

	//load mesh rendering shader
	shader.LoadFromFile(GL_VERTEX_SHADER, "shaders/shader.vert");
	shader.LoadFromFile(GL_FRAGMENT_SHADER, "shaders/shader.frag");
	//compile and link shader
	shader.CreateAndLinkProgram();
	shader.Use();	
		//add attribute and uniform
		shader.AddAttribute("vVertex");
		shader.AddAttribute("vNormal");
		shader.AddAttribute("vUV");		
		shader.AddUniform("MV");
		shader.AddUniform("N");
		shader.AddUniform("P");
		shader.AddUniform("textureMap");
		shader.AddUniform("useDefault");		
		shader.AddUniform("light_position");
		shader.AddUniform("diffuse_color");
		//set values of constant uniforms as initialization	
		glUniform1i(shader("textureMap"), 0);
	shader.UnUse();

	GL_CHECK_ERRORS

	//setup the vertex array object and vertex buffer object for the mesh
	//geometry handling 
	glGenVertexArrays(1, &vaoID);
	glGenBuffers(1, &vboVerticesID);
	glGenBuffers(1, &vboIndicesID); 
	 
	//here we are using interleaved attributes so we can just push data to one
	//buffer object and then assign different atribute pointer to identofy the 
	//different attributes
	glBindVertexArray(vaoID);	
		glBindBuffer (GL_ARRAY_BUFFER, vboVerticesID);
		//pass mesh vertices
		glBufferData (GL_ARRAY_BUFFER, sizeof(Vertex)*vertices.size(), &(vertices[0].pos.x), GL_STATIC_DRAW);
		GL_CHECK_ERRORS
		//enable vertex attribute array for vertex position
		glEnableVertexAttribArray(shader["vVertex"]);
		glVertexAttribPointer(shader["vVertex"], 3, GL_FLOAT, GL_FALSE,sizeof(Vertex),0);
		GL_CHECK_ERRORS 
		//enable vertex attribute array for vertex normal
		glEnableVertexAttribArray(shader["vNormal"]);
		glVertexAttribPointer(shader["vNormal"], 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(offsetof(Vertex, normal)) );
 
		GL_CHECK_ERRORS
		//enable vertex attribute array for vertex texture coordinates
		glEnableVertexAttribArray(shader["vUV"]);
		glVertexAttribPointer(shader["vUV"], 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)(offsetof(Vertex, uv)) );
 
		GL_CHECK_ERRORS
			
		//if we have a single material, it means the 3ds model contains one mesh
		//we therefore load it into an element array buffer
		if(materials.size()==1) {
			//pass indices to the element array buffer if there is a single material			
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIndicesID);
			glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort)*indices.size(), &(indices[0]), GL_STATIC_DRAW);
		}
		GL_CHECK_ERRORS
	glBindVertexArray(0); 

	//setup vao and vbo stuff for the light position crosshair
	glm::vec3 crossHairVertices[6];
	crossHairVertices[0] = glm::vec3(-0.5f,0,0);
	crossHairVertices[1] = glm::vec3(0.5f,0,0);
	crossHairVertices[2] = glm::vec3(0, -0.5f,0);
	crossHairVertices[3] = glm::vec3(0, 0.5f,0);
	crossHairVertices[4] = glm::vec3(0,0, -0.5f);
	crossHairVertices[5] = glm::vec3(0,0, 0.5f);

	//setup light gizmo vertex array and vertex buffer object IDs
	glGenVertexArrays(1, &lightVAOID);
	glGenBuffers(1, &lightVerticesVBO);   
	glBindVertexArray(lightVAOID);	

		glBindBuffer (GL_ARRAY_BUFFER, lightVerticesVBO);
		//pass crosshair vertices to the buffer object
		glBufferData (GL_ARRAY_BUFFER, sizeof(crossHairVertices), &(crossHairVertices[0].x), GL_STATIC_DRAW);
		GL_CHECK_ERRORS
		//enable vertex attribute array for vertex position
		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0,0);
	
	GL_CHECK_ERRORS 
	
	//use spherical coordinates to get the light position
	lightPosOS.x = radius * cos(theta)*sin(phi);
	lightPosOS.y = radius * cos(phi);
	lightPosOS.z = radius * sin(theta)*sin(phi);

	//enable depth test and culling
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE); 

	//set the background colour to corn blue 
	glClearColor(0.5,0.5,1,1);
	cout<<"Initialization successfull"<<endl;
}
Example #7
0
GLuint load_texture_from_file(std::string filename)
{
   //define return variable
   GLuint texture;

   //strip extension
   std::string extension;
   int delimiter_index = filename.find_last_of('.');
   //if a '.' was found
   if (delimiter_index != std::string::npos)
   {
      //get extension substring
      extension = filename.substr(delimiter_index + 1);
      //convert to uppercase
      std::transform(extension.begin(), extension.end(), extension.begin(), ::toupper);
      //get c_string
      const char* ext = extension.c_str();
      //check filetype
      if (strcmp(ext, "JPG") || strcmp(ext, "BMP") || strcmp(ext, "PNG"))
      {
         //make the texture
         glGenTextures(1, &texture);
         
         //bind the texture
         glBindTexture(GL_TEXTURE_2D, texture);

         //set our texture filtering
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

         //set our texture parameters
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

         //load .jpg using SOIL
         int width, height;
         unsigned char* image = SOIL_load_image(filename.c_str(), &width, &height, 0, SOIL_LOAD_RGB);

         //generate the texture from image
         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);

         //generate mipmaps (openGL scaling objects)
         glGenerateMipmap(GL_TEXTURE_2D);

         //free the texture thing
         glBindTexture(GL_TEXTURE_2D, 0);

         if (texture == -1)
         {
            //THERE WAS AN ERROR - do something
         }
         else
            return texture;
      }
      else
      {
         //disagree.
         //throw an error? prompt the user? be displeased.
         //(tell the user to check the input file type)
      }
   }

   return texture;
}
void BasicOpenGLView::loadMaterial(std::string m_Material)
{
    std::ifstream t(m_Material.c_str());
    std::stringstream buffer;
    buffer << t.rdbuf();

    /**
     * we assume file contents like this:
     * vertex path/to/vertex/shader.vs
     * fragment path/to/fragment/shader.fs
     *
     * with an optional
     * texture path/to/texture.png
     *
     * paths are relative to the m_Material path
     */

    if(mProgram)
    {
        delete mProgram;
        mProgram = NULL;
    }

    if(mTextureHandle)
    {
        glDeleteTextures(1, & mTextureHandle);
        mTextureHandle = 0;
    }

    std::string filePath = m_Material.substr(0, m_Material.find_last_of("/") + 1);

    const std::string vertex("vertex");
    const std::string fragment("fragment");
    const std::string texture("texture");
    const std::string bump("bumpmap");
    const std::string alphatex("alphatex");

    mProgram = new Program();

    std::string line;
    while(std::getline(buffer, line))
    {
        if(line.compare(0, vertex.size(), vertex) == 0)
        {
            std::string vertexPath = filePath + line.substr(vertex.size() + 1);

            std::ifstream v(vertexPath.c_str());
            std::stringstream vbuffer;
            vbuffer << v.rdbuf();

            Shader * vShader = new Shader(vbuffer.str(), Shader::VERTEX);
            if(vShader->load())
            {
                mProgram->push_back(vShader);
            }
        }
        else if(line.compare(0, fragment.size(), fragment) == 0)
        {
            std::string fragmentPath = filePath + line.substr(fragment.size() + 1);

            std::ifstream f(fragmentPath.c_str());
            std::stringstream fbuffer;
            fbuffer << f.rdbuf();

            Shader * fShader = new Shader(fbuffer.str(), Shader::FRAGMENT);
            if(fShader->load())
            {
                mProgram->push_back(fShader);
            }
        }
        else if(line.compare(0, texture.size(), texture) == 0)
        {
            std::string texturePath = filePath + line.substr(texture.size() + 1);

            /**
             * @todo assignment 3
             * use the texturePath to load an image from disc, and transfer its data to
             * OpenGL and store the OpenGL image handle in mTextureHandle
             */
            QImage tex;
            if (tex.load(texturePath.c_str())) {
                QImage ogTex = QGLWidget::convertToGLFormat(tex);

                // copy the texture to opengl
                glGenTextures(1, &mTextureHandle);
                glActiveTexture(GL_TEXTURE0);
                glBindTexture(GL_TEXTURE_2D, mTextureHandle);
                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ogTex.width(), ogTex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, tex.bits());
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            } else {
                printf("Error finding texture\n");
            }
        }
        else if(line.compare(0, bump.size(), bump) == 0)
        {
            std::string texturePath = filePath + line.substr(bump.size() + 1);

            /**
             * @todo assignment 3
             * use the texturePath to load an image from disc, and transfer its data to
             * OpenGL and store the OpenGL image handle in mBumpTextureHandle
             */
            QImage tex;
            if (tex.load(texturePath.c_str())) {
                QImage ogTex = QGLWidget::convertToGLFormat(tex);

                // copy the bumpmap to opengl
                glGenTextures(1, &mBumpTextureHandle);
                glBindTexture(GL_TEXTURE_2D, mBumpTextureHandle);
                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ogTex.width(), ogTex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, tex.bits());
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            } else {
                printf("Error finding bumpmap\n");
            }
        }
        else if(line.compare(0, alphatex.size(), alphatex) == 0)
        {
            std::string texturePath = filePath + line.substr(alphatex.size() + 1);

            /**
             * JB: add in alpha texture
             */
            QImage tex;
            if (tex.load(texturePath.c_str())) {
                QImage ogTex = QGLWidget::convertToGLFormat(tex);

                // copy the bumpmap to opengl
                glGenTextures(1, &mAlphaTextureHandle);
                glBindTexture(GL_TEXTURE_2D, mAlphaTextureHandle);
                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ogTex.width(), ogTex.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, tex.bits());
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            } else {
                printf("Error finding alpha texture\n");
                printf(texturePath.c_str());
            }
        }
        else
        {
            /**
             * unknown file contents
             */
        }
    }

    if(!mProgram->link())
    {
        delete mProgram;
        mProgram = NULL;
    }
}
 // remove the extension from a filename
 std::string
 remove_extension(std::string const& filename)
 {
     std::string::size_type const n = filename.find_last_of('.');
     return std::string(filename.begin(), filename.begin()+n);
 }
Example #10
0
/**
 * @brief appDirPath : 获取 application 所在路径(不包含文件名称)
 * @return : application 所在路径(不包含文件名称)
 */
J_EXTERN_C J_ATTR_EXPORT const char* appDirPath()
{
    static std::string _path = "";
    if (_path.empty()) {
#ifdef __unix__
        std::stringstream ss;
        ss << "/proc/" << getpid() << "/exe";
#endif
        //
        char buffer[J_PATH_MAX + 2];
        unsigned int length = 0;
#ifdef _MSC_VER
        length = (unsigned int)GetModuleFileNameA(NULL, buffer, J_PATH_MAX + 1);
#elif defined(__unix__)
        length = (unsigned int)readlink(ss.str().c_str(), buffer, J_PATH_MAX);
#endif
        //
        if (length == 0) {
            // error
        } else if (length <= J_PATH_MAX) {
            buffer[J_PATH_MAX + 1] = '\0';
            _path = buffer;
        } else {
            // J_PATH_MAX sized buffer wasn't large enough to contain the full path, use heap
            char *bufferNew = 0;
            int i = 1;
            size_t size;
            do {
                ++i;
                size = J_PATH_MAX * i;
                bufferNew = reinterpret_cast<char *>(realloc(bufferNew, (size + 1) * sizeof(char)));
                if (bufferNew) {
#ifdef _MSC_VER
                    length = (unsigned int)GetModuleFileNameA(NULL, buffer, J_PATH_MAX + 1);
#elif defined(__unix__)
                    length = (unsigned int)readlink(ss.str().c_str(), buffer, J_PATH_MAX);
#endif
                }
            } while (bufferNew && length == size);

            if (bufferNew) {
                *(bufferNew + size) = '\0';
            }

            _path = bufferNew;
            free(bufferNew);
        }

        //
        if (!_path.empty()) {
            //
            int index = _path.find_last_of('/');
            if (index == -1) {
                index = _path.find_last_of('\\');
            }
            if (index != -1) {
                _path = _path.substr(0, index);
            }
            // replace '\\' with '/'
            std::string::iterator iter = _path.begin();
            for (; iter != _path.end(); ++iter) {
                if (*iter == '\\') {
                    *iter = '/';
                }
            }
        }
    }

    return _path.c_str();
}
U32 LLControlGroup::loadFromFile(const std::string& filename, bool set_default_values)
{
	if(mIncludedFiles.find(filename) != mIncludedFiles.end())
		return 0; //Already included this file.
	mIncludedFiles.insert(filename);

	std::string name;
	LLSD settings;
	LLSD control_map;
	llifstream infile;
	infile.open(filename);
	if(!infile.is_open())
	{
		llwarns << "Cannot find file " << filename << " to load." << llendl;
		return 0;
	}

	S32 ret = LLSDSerialize::fromXML(settings, infile);

	if (ret <= 0)
	{
		infile.close();
		llwarns << "Unable to open LLSD control file " << filename << ". Trying Legacy Method." << llendl;		
		return loadFromFileLegacy(filename, TRUE, TYPE_STRING);
	}

	U32	validitems = 0;
	bool hidefromsettingseditor = false;
	for(LLSD::map_const_iterator itr = settings.beginMap(); itr != settings.endMap(); ++itr)
	{
		bool persist = true;
		name = (*itr).first;
		control_map = (*itr).second;
		
		if(name == "Include")
		{
			if(control_map.isArray())
			{
#if LL_WINDOWS
				size_t pos = filename.find_last_of("\\");
#else
				size_t pos = filename.find_last_of("/");
#endif			
				if(pos!=std::string::npos)
				{
					const std::string dir = filename.substr(0,++pos);
					for(LLSD::array_const_iterator array_itr = control_map.beginArray(); array_itr != control_map.endArray(); ++array_itr)
						validitems+=loadFromFile(dir+(*array_itr).asString(),set_default_values);
				}
			}
			continue;
		}
		if(control_map.has("Persist")) 
		{
			persist = control_map["Persist"].asInteger();
		}
		
		// Sometimes we want to use the settings system to provide cheap persistence, but we
		// don't want the settings themselves to be easily manipulated in the UI because 
		// doing so can cause support problems. So we have this option:
		if(control_map.has("HideFromEditor"))
		{
			hidefromsettingseditor = control_map["HideFromEditor"].asInteger();
		}
		else
		{
			hidefromsettingseditor = false;
		}
		
		// If the control exists just set the value from the input file.
		LLControlVariable* existing_control = getControl(name);
		if(existing_control)
		{
			if(set_default_values)
			{
				// Override all previously set properties of this control.
				// ... except for type. The types must match.
				eControlType new_type = typeStringToEnum(control_map["Type"].asString());
				if(existing_control->isType(new_type))
				{
					existing_control->setDefaultValue(control_map["Value"]);
					existing_control->setPersist(persist);
					existing_control->setHiddenFromSettingsEditor(hidefromsettingseditor);
					existing_control->setComment(control_map["Comment"].asString());
				}
				else
				{
					llerrs << "Mismatched type of control variable '"
						   << name << "' found while loading '"
						   << filename << "'." << llendl;
				}
			}
			else if(existing_control->isPersisted())
			{
				
				existing_control->setValue(control_map["Value"]);
			}
			// *NOTE: If not persisted and not setting defaults, 
			// the value should not get loaded.
		}
		else
		{
			bool IsCOA = control_map.has("IsCOA") && !!control_map["IsCOA"].asInteger();
			declareControl(name, 
						   typeStringToEnum(control_map["Type"].asString()), 
						   control_map["Value"], 
						   control_map["Comment"].asString(), 
						   persist,
						   hidefromsettingseditor,
						   IsCOA
						   );

		}
		
		++validitems;
	}

	return validitems;
}
Example #12
0
	void ModelRenderer::LoadFromX(const std::string &path)
	{
		// X ファイル とテクスチャのロード
		_mesh = Mesh::CreateFromX(path);
		// マテリアル情報の取得
		D3DXMATERIAL *materials = (D3DXMATERIAL*)(_mesh->GetMaterialBuffer()->GetBufferPointer());
		// テクスチャのロード
		TextureSP texture;
		for(size_t i = 0; i < _mesh->GetMaterialNumber(); i++){
			// 特定の部分でテクスチャが存在しない場合
			if(NULL == materials[i].pTextureFilename){
				texture = NULL;
				_textures.push_back(texture);
				D3DCOLORVALUE value = materials[i].MatD3D.Diffuse;
				// マテリアルから色情報を取得
				D3DXVECTOR4 color = D3DXVECTOR4(value.r, value.g, value.b, value.a);
				_diffuseColors.push_back(color);
				continue;
			}
			_diffuseColors.push_back(D3DXVECTOR4(0,0,0,0));

			//---------------------------------------------------
			// テクスチャのパスを自動的に生成

			// ファイルパスの前部分を格納する
			std::string texturePath;
			// Xファイルのパスから必要部分だけ抜き出す

			// "/" "\\"を検索しパスの区切りの最後の部分を検索する
			// Xファイルとテクスチャは同じフォルダにあるとし、
			// Xファイルのあるフォルダのパスまでを抜き取る

			// パスの最後の"/"を検索
			std::size_t index = path.find_last_of("/");
			if(index != std::string::npos)
			{
				texturePath = path.substr(0, index + 1);
			}
			// 該当なしなら"\\"で再検索
			else
			{
				index = path.find_last_of("\\");
				if(index != std::string::npos)
				{
					// パスの区切りが"\\"のときは"\\"の部分をはずしかわりに"/"をつける
					texturePath = path.substr(0, index);
					texturePath += "/";
				}
			}

			//------------------------------------------------------------------
			// Xファイルに記述されているテクスチャのパスの最後の部分だけを抜き出し前部分に追加
			std::string stringBuffer;
			stringBuffer = materials[i].pTextureFilename;
			// パスの最後の"/"を検索
			index = stringBuffer.find_last_of("/");
			if(index != std::string::npos)
			{
				std::string stringBuffer2;
				stringBuffer2 = stringBuffer.substr(index + 1);
				texturePath += stringBuffer2;
			}
			// 該当なしなら"\\"で再検索
			else{
				index = stringBuffer.find_last_of("\\");
				if(index != std::string::npos)
				{
					std::string stringBuffer2;
					stringBuffer2 = stringBuffer.substr(index + 1);
					texturePath += stringBuffer2;
				}
				// 該当なしならそのまま追加
				else{
					texturePath += stringBuffer;
				}
			}
			// 独自テクスチャクラスとして生成
			texture = Texture::CreateFromFile(texturePath, D3DX_DEFAULT);

			_textures.push_back(texture);
		}
	}
Example #13
0
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void IFCImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
{
    std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile));
    if (!stream) {
        ThrowException("Could not open file for reading");
    }


    // if this is a ifczip file, decompress its contents first
    if(GetExtension(pFile) == "ifczip") {
#ifndef ASSIMP_BUILD_NO_COMPRESSED_IFC
        unzFile zip = unzOpen( pFile.c_str() );
        if(zip == NULL) {
            ThrowException("Could not open ifczip file for reading, unzip failed");
        }

        // chop 'zip' postfix
        std::string fileName = pFile.substr(0,pFile.length() - 3);

        std::string::size_type s = pFile.find_last_of('\\');
        if(s == std::string::npos) {
            s = pFile.find_last_of('/');
        }
        if(s != std::string::npos) {
            fileName = fileName.substr(s+1);
        }

        // search file (same name as the IFCZIP except for the file extension) and place file pointer there
        if(UNZ_OK == unzGoToFirstFile(zip)) {
            do {
                // get file size, etc.
                unz_file_info fileInfo;
                char filename[256];
                unzGetCurrentFileInfo( zip , &fileInfo, filename, sizeof(filename), 0, 0, 0, 0 );
                if (GetExtension(filename) != "ifc") {
                    continue;
                }
                uint8_t* buff = new uint8_t[fileInfo.uncompressed_size];
                LogInfo("Decompressing IFCZIP file");
                unzOpenCurrentFile(zip);
                size_t total = 0;
                int read = 0;
                do {
                    int bufferSize = fileInfo.uncompressed_size < INT16_MAX ? fileInfo.uncompressed_size : INT16_MAX;
                    void* buffer = malloc(bufferSize);
                    read = unzReadCurrentFile(zip, buffer, bufferSize);
                    if (read > 0) {
                        memcpy((char*)buff + total, buffer, read);
                        total += read;
                    }
                    free(buffer);
                } while (read > 0);
                size_t filesize = fileInfo.uncompressed_size;
                if (total == 0 || size_t(total) != filesize)
                {
                    delete[] buff;
                    ThrowException("Failed to decompress IFC ZIP file");
                }
                unzCloseCurrentFile( zip );
                stream.reset(new MemoryIOStream(buff,fileInfo.uncompressed_size,true));
                break;

                if (unzGoToNextFile(zip) == UNZ_END_OF_LIST_OF_FILE) {
                    ThrowException("Found no IFC file member in IFCZIP file (1)");
                }

            } while(true);
        }
        else {
            ThrowException("Found no IFC file member in IFCZIP file (2)");
        }

        unzClose(zip);
#else
        ThrowException("Could not open ifczip file for reading, assimp was built without ifczip support");
#endif
    }

    std::unique_ptr<STEP::DB> db(STEP::ReadFileHeader(stream));
    const STEP::HeaderInfo& head = static_cast<const STEP::DB&>(*db).GetHeader();

    if(!head.fileSchema.size() || head.fileSchema.substr(0,3) != "IFC") {
        ThrowException("Unrecognized file schema: " + head.fileSchema);
    }

    if (!DefaultLogger::isNullLogger()) {
        LogDebug("File schema is \'" + head.fileSchema + '\'');
        if (head.timestamp.length()) {
            LogDebug("Timestamp \'" + head.timestamp + '\'');
        }
        if (head.app.length()) {
            LogDebug("Application/Exporter identline is \'" + head.app  + '\'');
        }
    }

    // obtain a copy of the machine-generated IFC scheme
    ::Assimp::STEP::EXPRESS::ConversionSchema schema;
    Schema_2x3::GetSchema(schema);

    // tell the reader which entity types to track with special care
    static const char* const types_to_track[] = {
        "ifcsite", "ifcbuilding", "ifcproject"
    };

    // tell the reader for which types we need to simulate STEPs reverse indices
    static const char* const inverse_indices_to_track[] = {
        "ifcrelcontainedinspatialstructure", "ifcrelaggregates", "ifcrelvoidselement", "ifcreldefinesbyproperties", "ifcpropertyset", "ifcstyleditem"
    };

    // feed the IFC schema into the reader and pre-parse all lines
    STEP::ReadFile(*db, schema, types_to_track, inverse_indices_to_track);
    const STEP::LazyObject* proj =  db->GetObject("ifcproject");
    if (!proj) {
        ThrowException("missing IfcProject entity");
    }

    ConversionData conv(*db,proj->To<Schema_2x3::IfcProject>(),pScene,settings);
    SetUnits(conv);
    SetCoordinateSpace(conv);
    ProcessSpatialStructures(conv);
    MakeTreeRelative(conv);

    // NOTE - this is a stress test for the importer, but it works only
    // in a build with no entities disabled. See
    //     scripts/IFCImporter/CPPGenerator.py
    // for more information.
    #ifdef ASSIMP_IFC_TEST
        db->EvaluateAll();
    #endif

    // do final data copying
    if (conv.meshes.size()) {
        pScene->mNumMeshes = static_cast<unsigned int>(conv.meshes.size());
        pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
        std::copy(conv.meshes.begin(),conv.meshes.end(),pScene->mMeshes);

        // needed to keep the d'tor from burning us
        conv.meshes.clear();
    }

    if (conv.materials.size()) {
        pScene->mNumMaterials = static_cast<unsigned int>(conv.materials.size());
        pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
        std::copy(conv.materials.begin(),conv.materials.end(),pScene->mMaterials);

        // needed to keep the d'tor from burning us
        conv.materials.clear();
    }

    // apply world coordinate system (which includes the scaling to convert to meters and a -90 degrees rotation around x)
    aiMatrix4x4 scale, rot;
    aiMatrix4x4::Scaling(static_cast<aiVector3D>(IfcVector3(conv.len_scale)),scale);
    aiMatrix4x4::RotationX(-AI_MATH_HALF_PI_F,rot);

    pScene->mRootNode->mTransformation = rot * scale * conv.wcs * pScene->mRootNode->mTransformation;

    // this must be last because objects are evaluated lazily as we process them
    if ( !DefaultLogger::isNullLogger() ){
        LogDebug((Formatter::format(),"STEP: evaluated ",db->GetEvaluatedObjectCount()," object records"));
    }
}
Example #14
0
void MEDITIO::write_ascii (const std::string & fname,
                           const std::vector<Number> * vec,
                           const std::vector<std::string> * solution_names)
{
  // Current lacks in implementation:
  //  (i)   only 3D meshes.
  //  (ii)  only QUAD4, TRI3, TET4 elements, others are omitted !
  //  (iii) no distinction between materials.
  //  (iv)  no vector output, just first scalar as output

  // libmesh_assert three dimensions (should be extended later)
  libmesh_assert_equal_to (MeshOutput<MeshBase>::mesh().mesh_dimension(), 3);

  // Open the output file stream
  std::ofstream out_stream (fname.c_str());

  // Make sure it opened correctly
  if (!out_stream.good())
    libmesh_file_error(fname.c_str());

  // Get a reference to the mesh
  const MeshBase & the_mesh = MeshOutput<MeshBase>::mesh();

  // Begin interfacing with the MEdit data file
  {
    // header:
    out_stream << "MeshVersionFormatted  1\n";
    out_stream << "Dimension  3\n";
    out_stream << "# Mesh generated by libmesh\n\n";

    // write the nodes:
    out_stream << "# Set of mesh vertices\n";
    out_stream << "Vertices\n";
    out_stream << the_mesh.n_nodes() << "\n";

    for (unsigned int v=0; v<the_mesh.n_nodes(); v++)
      out_stream << the_mesh.point(v)(0) << " " << the_mesh.point(v)(1) << " " << the_mesh.point(v)(2) << " 0\n";
  }

  {
    // write the connectivity:
    out_stream << "\n# Set of Polys\n\n";

    // count occurrences of output elements:
    int n_tri3  = 0;
    int n_quad4 = 0;
    int n_tet4  = 0;

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        {
          if ((*it)->type() == TRI3)  n_tri3++;
          if ((*it)->type() == QUAD4) n_quad4++;
          if ((*it)->type() == QUAD9) n_quad4+=4; // (QUAD9 is written as 4 QUAD4.)
          if ((*it)->type() == TET4)  n_tet4++;
        } // for
    }

    // First: write out TRI3 elements:
    out_stream << "Triangles\n";
    out_stream << n_tri3 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        if ((*it)->type() == TRI3)
          out_stream << (*it)->node_id(0)+1  << " "
                     << (*it)->node_id(1)+1  << " "
                     << (*it)->node_id(2)+1  << " 0\n";
    }

    // Second: write out QUAD4 elements:
    out_stream << "Quadrilaterals\n";
    out_stream << n_quad4 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        if ((*it)->type() == QUAD4)
          {
            out_stream << (*it)->node_id(0)+1  << " "
                       << (*it)->node_id(1)+1  << " "
                       << (*it)->node_id(2)+1  << " "
                       << (*it)->node_id(3)+1  <<" 0\n";
          } // if
        else if ((*it)->type() == QUAD9)
          {
            out_stream << (*it)->node_id(0)+1  << " "
                       << (*it)->node_id(4)+1  << " "
                       << (*it)->node_id(8)+1  << " "
                       << (*it)->node_id(7)+1  <<" 0\n";
            out_stream << (*it)->node_id(7)+1  << " "
                       << (*it)->node_id(8)+1  << " "
                       << (*it)->node_id(6)+1  << " "
                       << (*it)->node_id(3)+1  <<" 0\n";
            out_stream << (*it)->node_id(4)+1  << " "
                       << (*it)->node_id(1)+1  << " "
                       << (*it)->node_id(5)+1  << " "
                       << (*it)->node_id(8)+1  <<" 0\n";
            out_stream << (*it)->node_id(8)+1  << " "
                       << (*it)->node_id(5)+1  << " "
                       << (*it)->node_id(2)+1  << " "
                       << (*it)->node_id(6)+1  <<" 0\n";
          } // if
    }


    // Third: write out TET4 elements:
    out_stream << "Tetrahedra\n";
    out_stream << n_tet4 << "\n";

    {
      MeshBase::const_element_iterator       it  = the_mesh.active_elements_begin();
      const MeshBase::const_element_iterator end = the_mesh.active_elements_end();

      for ( ; it != end; ++it)
        if ((*it)->type() == TET4)
          {
            out_stream << (*it)->node_id(0)+1  << " "
                       << (*it)->node_id(1)+1  << " "
                       << (*it)->node_id(2)+1  << " "
                       << (*it)->node_id(3)+1  <<" 0\n";
          } // if
    }

  }
  // end of the out file
  out_stream << '\n' << "# end of file\n";

  // optionally write the data
  if ((solution_names != libmesh_nullptr) &&
      (vec != libmesh_nullptr))
    {
      // Open the ".bb" file stream
      std::size_t idx = fname.find_last_of(".");
      std::string bbname = fname.substr(0,idx) + ".bb";

      std::ofstream bbout (bbname.c_str());

      // Make sure it opened correctly
      if (!bbout.good())
        libmesh_file_error(bbname.c_str());

      // Header: 3: 3D mesh, 1: scalar output, 2: node-indexed
      const std::size_t n_vars = solution_names->size();
      bbout << "3 1 " << the_mesh.n_nodes() << " 2\n";
      for (dof_id_type n=0; n<the_mesh.n_nodes(); n++)
        bbout << std::setprecision(10) << (*vec)[n*n_vars + scalar_idx] << " ";
      bbout << "\n";
    } // endif
}
Example #15
0
void Map::saveOtbm(const std::string& fileName)
{
    try {
        FileStreamPtr fin = g_resources.createFile(fileName);
        if(!fin)
            stdext::throw_exception(stdext::format("failed to open file '%s' for write", fileName));

        fin->cache();
        std::string dir;
        if(fileName.find_last_of('/') == std::string::npos)
            dir = g_resources.getWorkDir();
        else
            dir = fileName.substr(0, fileName.find_last_of('/'));

        uint32 version = 0;
        if(g_things.getOtbMajorVersion() < ClientVersion820)
            version = 1;
        else
            version = 2;

        /// Usually when a map has empty house/spawn file it means the map is new.
        /// TODO: Ask the user for a map name instead of those ugly uses of substr
        std::string::size_type sep_pos;
        std::string houseFile = getHouseFile();
        std::string spawnFile = getSpawnFile();
        std::string cpyf;

        if((sep_pos = fileName.rfind('.')) != std::string::npos && stdext::ends_with(fileName, ".otbm"))
            cpyf = fileName.substr(0, sep_pos);

        if(houseFile.empty())
            houseFile = cpyf + "-houses.xml";

        if(spawnFile.empty())
            spawnFile = cpyf + "-spawns.xml";

        /// we only need the filename to save to, the directory should be resolved by the OTBM loader not here
        if((sep_pos = spawnFile.rfind('/')) != std::string::npos)
            spawnFile = spawnFile.substr(sep_pos + 1);

        if((sep_pos = houseFile.rfind('/')) != std::string::npos)
            houseFile = houseFile.substr(sep_pos + 1);

        fin->addU32(0); // file version
        OutputBinaryTreePtr root(new OutputBinaryTree(fin));
        {
            root->addU32(version);

            Size mapSize = getSize();
            root->addU16(mapSize.width());
            root->addU16(mapSize.height());

            root->addU32(g_things.getOtbMajorVersion());
            root->addU32(g_things.getOtbMinorVersion());

            root->startNode(OTBM_MAP_DATA);
            {
                root->addU8(OTBM_ATTR_DESCRIPTION);
                root->addString(m_attribs.get<std::string>(OTBM_ATTR_DESCRIPTION));

                root->addU8(OTBM_ATTR_SPAWN_FILE);
                root->addString(spawnFile);

                root->addU8(OTBM_ATTR_HOUSE_FILE);
                root->addString(houseFile);

                int px = -1, py = -1, pz =-1;
                bool firstNode = true;

                for(uint8_t z = 0; z <= Otc::MAX_Z; ++z) {
                    for(const auto& it : m_tileBlocks[z]) {
                        const TileBlock& block = it.second;
                        for(const TilePtr& tile : block.getTiles()) {
                            if(unlikely(!tile || tile->isEmpty()))
                                continue;

                            const Position& pos = tile->getPosition();
                            if(unlikely(!pos.isValid()))
                                continue;

                            if(pos.x < px || pos.x >= px + 256
                                    || pos.y < py || pos.y >= py + 256
                                    || pos.z != pz) {
                                if(!firstNode)
                                    root->endNode(); /// OTBM_TILE_AREA

                                firstNode = false;
                                root->startNode(OTBM_TILE_AREA);

                                px = pos.x & 0xFF00;
                                py = pos.y & 0xFF00;
                                pz = pos.z;
                                root->addPos(px, py, pz);
                            }

                            root->startNode(tile->isHouseTile() ? OTBM_HOUSETILE : OTBM_TILE);
                            root->addPoint(Point(pos.x, pos.y) & 0xFF);
                            if(tile->isHouseTile())
                                root->addU32(tile->getHouseId());

                            if(tile->getFlags()) {
                                root->addU8(OTBM_ATTR_TILE_FLAGS);
                                root->addU32(tile->getFlags());
                            }

                            const auto& itemList = tile->getItems();
                            const ItemPtr& ground = tile->getGround();
                            if(ground) {
                                // Those types are called "complex" needs other stuff to be written.
                                // For containers, there is container items, for depot, depot it and so on.
                                if(!ground->isContainer() && !ground->isDepot()
                                        && !ground->isDoor() && !ground->isTeleport()) {
                                    root->addU8(OTBM_ATTR_ITEM);
                                    root->addU16(ground->getServerId());
                                } else
                                    ground->serializeItem(root);
                            }
                            for(const ItemPtr& item : itemList)
                                if(!item->isGround())
                                    item->serializeItem(root);

                            root->endNode(); // OTBM_TILE
                        }
                    }
                }

                if(!firstNode)
                    root->endNode();  // OTBM_TILE_AREA

                root->startNode(OTBM_TOWNS);
                for(const TownPtr& town : g_towns.getTowns()) {
                    root->startNode(OTBM_TOWN);

                    root->addU32(town->getId());
                    root->addString(town->getName());

                    Position townPos = town->getPos();
                    root->addPos(townPos.x, townPos.y, townPos.z);
                    root->endNode();
                }
                root->endNode();

                if(version > 1) {
                    root->startNode(OTBM_WAYPOINTS);
                    for(const auto& it : m_waypoints) {
                        root->startNode(OTBM_WAYPOINT);
                        root->addString(it.second);

                        Position pos = it.first;
                        root->addPos(pos.x, pos.y, pos.z);
                        root->endNode();
                    }
                    root->endNode();
                }
            }
            root->endNode(); // OTBM_MAP_DATA
        }
        root->endNode();

        fin->flush();
        fin->close();
    } catch(std::exception& e) {
        g_logger.error(stdext::format("Failed to save '%s': %s", fileName, e.what()));
    }
}
Example #16
0
bool Maker::SearchImplicitRules(const std::string &goal, const std::string &preferredPath, bool outerMost, bool err, Time &timeval)
{
    std::list<RuleList *>matchedRules;
    size_t n = goal.find_last_of(CmdFiles::DIR_SEP);
    std::string dir;
    std::string name;
    if (n != std::string::npos)
    {
        dir = goal.substr(0, n+1);
        name = goal.substr(n+1);
    }
    else
    {
        name = goal;
    }
    bool nonMatchAnything = false;
    for (RuleContainer::ImplicitIterator it = RuleContainer::Instance()->ImplicitBegin();
             it != RuleContainer::Instance()->ImplicitEnd(); ++it)
    {
        if ((*it)->GetTarget().find_first_of(CmdFiles::DIR_SEP) != std::string::npos)
        {
            size_t start;
            n = Eval::MatchesPattern(goal, (*it)->GetTarget(), start);
            if (n == goal.size())
            {
                matchedRules.push_back(*it);
                if ((*it)->GetTarget() != "%")
                    nonMatchAnything = true;
            }
        }
        else
        {
            size_t start;
            n = Eval::MatchesPattern(name, (*it)->GetTarget(), start);
            if (n == name.size())
            {
                matchedRules.push_back(*it);
                if ((*it)->GetTarget() != "%")
                    nonMatchAnything = true;
            }
        }
    }
    if (nonMatchAnything)
    {
        for (std::list<RuleList *>::iterator it = matchedRules.begin();
             it != matchedRules.end();)
        {
            std::list<RuleList *>::iterator it1 = it;
            ++it;
            if ((*it1)->GetTarget() == "%")
                if (!(*it1)->GetDoubleColon())
                    matchedRules.erase(it1);
        }		
    }
    for (std::list<RuleList *>::iterator it = matchedRules.begin();
         it != matchedRules.end();)
    {
        std::list<RuleList *>::iterator it1 = it;
        ++it;
        if (!(*it1)->HasCommands())
            matchedRules.erase(it1);
    }
    for (std::list<RuleList *>::iterator it = matchedRules.begin();
         it != matchedRules.end(); ++it)
    {
        
        std::string stem = Eval::FindStem(goal, (*it)->GetTarget());
        if (ExistsOrMentioned(stem, *it, preferredPath, dir, false, outerMost))
            return true;
    }
    // no matches so far, dig into indirections...
    for (std::list<RuleList *>::iterator it = matchedRules.begin();
         it != matchedRules.end(); ++it)
    {
        if ((*it)->GetTarget() != "%" || !(*it)->GetDoubleColon())
        {
            std::string stem = Eval::FindStem(goal, (*it)->GetTarget());		
            if (ExistsOrMentioned(stem, *it, preferredPath, dir, true, outerMost))
                return true;
        }
    }
    RuleList *dflt = RuleContainer::Instance()->Lookup(".DEFAULT");
    if (dflt)
    {
        // have a default, enter it
        EnterDefaultRule(goal, dflt);
        return true;
    }
    if (outerMost && err)
    {
        std::set<std::string>::iterator it = ignoreFailedTargets.find(goal);
        if (it == ignoreFailedTargets.end())
        {
            Time time;
            GetFileTime(goal, preferredPath, time);
            if (!time)
            {
                missingTarget = true;
                Eval::error("No rule to make target '" + goal + "'");
            }
            else if (time > timeval)
                timeval = time;
        }
    }
    return false;
}
  void DICOMSegmentationIO::Write()
  {
    ValidateOutputLocation();

    mitk::LocaleSwitch localeSwitch("C");
    LocalFile localFile(this);
    const std::string path = localFile.GetFileName();

    auto input = dynamic_cast<const LabelSetImage *>(this->GetInput());
    if (input == nullptr)
      mitkThrow() << "Cannot write non-image data";

    // Get DICOM information from referenced image
    vector<DcmDataset *> dcmDatasets;
    DcmFileFormat *readFileFormat = new DcmFileFormat();
    try
    {
      // TODO: Generate dcmdataset witk DICOM tags from property list; ATM the source are the filepaths from the
      // property list
      mitk::StringLookupTableProperty::Pointer filesProp =
        dynamic_cast<mitk::StringLookupTableProperty *>(input->GetProperty("files").GetPointer());

      if (filesProp.IsNull())
      {
        mitkThrow() << "No property with dicom file path.";
        return;
      }

      StringLookupTable filesLut = filesProp->GetValue();
      const StringLookupTable::LookupTableType &lookUpTableMap = filesLut.GetLookupTable();

      for (auto it : lookUpTableMap)
      {
        const char *fileName = (it.second).c_str();
        if (readFileFormat->loadFile(fileName, EXS_Unknown).good())
          dcmDatasets.push_back(readFileFormat->getAndRemoveDataset());
      }
    }
    catch (const std::exception &e)
    {
      MITK_ERROR << "An error occurred while getting the dicom informations: " << e.what() << endl;
      return;
    }

    // Iterate over all layers. For each a dcm file will be generated
    for (unsigned int layer = 0; layer < input->GetNumberOfLayers(); ++layer)
    {
      vector<itkInternalImageType::Pointer> segmentations;

      try
      {
        // Cast mitk layer image to itk
        ImageToItk<itkInputImageType>::Pointer imageToItkFilter = ImageToItk<itkInputImageType>::New();
        // BUG: It must be the layer image, but there are some errors with it (dcmqi: generate the dcmSeg "No frame data
        // available") --> input->GetLayerImage(layer)
        imageToItkFilter->SetInput(input);
        imageToItkFilter->Update();

        // Cast from original itk type to dcmqi input itk image type
        typedef itk::CastImageFilter<itkInputImageType, itkInternalImageType> castItkImageFilterType;
        castItkImageFilterType::Pointer castFilter = castItkImageFilterType::New();
        castFilter->SetInput(imageToItkFilter->GetOutput());
        castFilter->Update();

        itkInternalImageType::Pointer itkLabelImage = castFilter->GetOutput();
        itkLabelImage->DisconnectPipeline();

        // Iterate over all labels. For each a segmentation image will be created
        const LabelSet *labelSet = input->GetLabelSet(layer);
        for (auto itLabel = labelSet->IteratorConstBegin(); itLabel != labelSet->IteratorConstEnd(); ++itLabel)
        {
          // Thresold over the image with the given label value
          itk::ThresholdImageFilter<itkInternalImageType>::Pointer thresholdFilter =
            itk::ThresholdImageFilter<itkInternalImageType>::New();
          thresholdFilter->SetInput(itkLabelImage);
          thresholdFilter->ThresholdOutside(itLabel->first, itLabel->first);
          thresholdFilter->SetOutsideValue(0);
          thresholdFilter->Update();
          itkInternalImageType::Pointer segmentImage = thresholdFilter->GetOutput();
          segmentImage->DisconnectPipeline();

          segmentations.push_back(segmentImage);
        }
      }
      catch (const itk::ExceptionObject &e)
      {
        MITK_ERROR << e.GetDescription() << endl;
        return;
      }

      // Create segmentation meta information
      const std::string &tmpMetaInfoFile = this->CreateMetaDataJsonFile(layer);

      MITK_INFO << "Writing image: " << path << std::endl;
      try
      {
        // Convert itk segmentation images to dicom image
        dcmqi::ImageSEGConverter *converter = new dcmqi::ImageSEGConverter();
        DcmDataset *result = converter->itkimage2dcmSegmentation(dcmDatasets, segmentations, tmpMetaInfoFile);

        // Write dicom file
        DcmFileFormat dcmFileFormat(result);

        std::string filePath = path.substr(0, path.find_last_of("."));
        // If there is more than one layer, we have to write more than 1 dicom file
        if (input->GetNumberOfLayers() != 1)
          filePath = filePath + std::to_string(layer) + ".dcm";
        else
          filePath = filePath + ".dcm";

        dcmFileFormat.saveFile(filePath.c_str(), EXS_LittleEndianExplicit);

        // Clean up
        if (converter != nullptr)
          delete converter;
        if (result != nullptr)
          delete result;
      }
      catch (const std::exception &e)
      {
        MITK_ERROR << "An error occurred during writing the DICOM Seg: " << e.what() << endl;
        return;
      }
    } // Write a dcm file for the next layer

    // End of image writing; clean up
    if (readFileFormat)
      delete readFileFormat;

    for (auto obj : dcmDatasets)
      delete obj;
    dcmDatasets.clear();
  }
Example #18
0
void Font::Load( std::string file )
{
	assert( !m_Initialized );

	std::string TexName = file.substr( file.find_last_of( '/' ) + 1, file.find_last_of( '.' ) );// +".png";
	TexName = TexName.substr( TexName.find_last_of( '\\' ) + 1, TexName.find_last_of( '.' ) ) +".png";
	m_Tex = Object_Factory<Texture>::Instance().GetAsset( TexName );
	assert( m_Tex != nullptr );

	std::ifstream Data;
	Data.open( file, std::ios::in | std::ios::binary );
	assert( Data.is_open() );
	Data.seekg( 0, std::ios::beg );

	short buffer[256]; ///memory to read into
	char* buff = (char*)buffer;
	Data.read( buff, 512 );

	assert( !Data.fail() );
	Data.close();

	for ( int i = 0; i < 256; ++i )
	{
		m_Widths[i] = (int)buffer[i];
	}

	m_Shader = Object_Factory<GLSLProgram>::Instance().GetAsset( "font_default.glslp" );
	assert( m_Shader != nullptr );

	uint32_t& Tex_width = m_Tex->width;
	uint32_t& Tex_height = m_Tex->height;

	m_vStride = 5 * sizeof( float );
	m_vCount = 4 * 256;
	m_Vertices = new float[m_vCount * 5];
	//Textures are assumed to have 16 characters per line
	for ( int loop = 0; loop<256; loop++ )
	{
		float cx = ( (float)( loop % 16 ) ) / 16.0f;				/// X Position Of Current Character
		float cy = ( (float)( loop / 16 ) ) / 16.0f;				/// Y Position Of Current Character

		m_Vertices[( loop * 20 )] = 0;
		m_Vertices[1 + ( loop * 20 )] = 0;		/// Vertex Coord (Bottom Left)
		m_Vertices[2 + ( loop * 20 )] = 0;
		m_Vertices[3 + ( loop * 20 )] = cx;
		m_Vertices[4 + ( loop * 20 )] = 1 - ( cy + 1.f / 16 );	/// Texture Coord (Bottom Left)
		
		m_Vertices[5 + ( loop * 20 )] = 1;
		m_Vertices[6 + ( loop * 20 )] = 0;	/// Vertex Coord (Bottom Right)
		m_Vertices[7 + ( loop * 20 )] = 0;
		m_Vertices[8 + ( loop * 20 )] = cx + ( 1.f / 16 );
		m_Vertices[9 + ( loop * 20 )] = 1 - ( cy + 1.f / 16 );	/// Texture Coord (Bottom Right)

		m_Vertices[10 + ( loop * 20 )] = 1;
		m_Vertices[11 + ( loop * 20 )] = 1;	/// Vertex Coord (Top Right)
		m_Vertices[12 + ( loop * 20 )] = 0;
		m_Vertices[13 + ( loop * 20 )] = cx + ( 1.f / 16 );
		m_Vertices[14 + ( loop * 20 )] = 1 - cy;	/// Texture Coord (Top Right)

		m_Vertices[15 + ( loop * 20 )] = 0;
		m_Vertices[16 + ( loop * 20 )] = 1;		/// Vertex Coord (Top Left)
		m_Vertices[17 + ( loop * 20 )] = 0;
		m_Vertices[18 + ( loop * 20 )] = cx;
		m_Vertices[19 + ( loop * 20 )] = 1 - cy;	/// Texture Coord (Top Left)
	}


	Init();
}
bool WorkerCPU::init(const std::string& videoStream)
{
	learningRate = std::stof(cfg.value("LearningRate", "MogParameters"));
	const int nmixtures = std::stoi(cfg.value("NumMixtures", "MogParameters"));
	if(nmixtures <= 0)
	{
		std::cerr << "Parameter NumMixtures is wrong, must be more than 0\n";
		return false;
	}

	// Inicjalizuj frame grabbera
#if defined(SAPERA_SUPPORT)
	// Sprawdz suffix videoStream (.ccf)
	size_t pos = videoStream.find_last_of(".ccf");
	if(pos+1 == videoStream.length())
	{
		grabber = std::unique_ptr<FrameGrabber>(new SaperaFrameGrabber());
	}
	else
#endif
	{
		grabber = std::unique_ptr<FrameGrabber>(new OpenCvFrameGrabber());
	}

	if(!grabber->init(videoStream))
		return false;
	dstFrame = cv::Mat(grabber->frameHeight(), grabber->frameWidth(), CV_8UC1);

	// Pobierz dane o formacie ramki
	int width = grabber->frameWidth();
	int height = grabber->frameHeight();
	int channels = grabber->frameNumChannels();

	mog = cv::BackgroundSubtractorMOG(200, nmixtures,
		std::stof(cfg.value("BackgroundRatio", "MogParameters")));
	mog.initialize(cv::Size(height, width), CV_8UC1);

	std::cout << "\n  frame width: " << width <<
		"\n  frame height: " << height << 
		"\n  num channels: " << channels << "x" << grabber->framePixelDepth() << " bits \n";
	//inputFrameSize = width * height * channels * sizeof(cl_uchar);

	if(channels == 3)
	{
		std::cout << "  preprocessing frame: grayscalling\n";
		preprocess = 1;
	}
	else if(channels == 1 && grabber->needBayer())
	{
		std::string bayerCfg = cfg.value("Bayer", "General");
		if(bayerCfg == "RG") bayer = Bayer_RG;
		else if(bayerCfg == "BG") bayer = Bayer_BG;
		else if(bayerCfg == "GR") bayer = Bayer_GR;
		else if(bayerCfg == "GB") bayer = Bayer_GB;
		else
		{
			std::cerr << "Unknown 'Bayer' parameter (must be RG, BG, GR or GB)";
			return false;
		}
		std::cout << "  preprocessing frame: bayer " << bayerCfg << "\n";
		preprocess = 2;
	}
	else
	{
		std::cout << "  preprocessing frame: none (already monochrome format)\n";
		preprocess = 0;
	}

	showIntermediateFrame = cfg.value("ShowIntermediateFrame", "General") == "yes";
	if(showIntermediateFrame)
		interFrame = cv::Mat(height, width, CV_8UC1);

	return true;
}
ImageTypex::Pointer Image_Convert_Base::GetITKPointer(std::string file_name)
{
	std::string file_suffix;
	//get file name suffix
	if (file_name.empty())
	{
		std::cout<<"input a file name first!"<<std::endl;
		return NULL;
	}
	else
	{
		std::size_t pos = file_name.find_last_of(".");
		file_suffix = file_name.substr(pos);
	}

	if (file_suffix == ".nii")
	{
		//nifti io
		//typedef itk::NiftiImageIO NiftiIOType;
		NiftiIOType::Pointer niftiIO = 
			NiftiIOType::New();	
		//itk read nii file
		//typedef itk::Image<float, 3> ImageType;
		//typedef itk::ImageSeriesReader< ImageType >  ReaderType;
		ReaderType_Convert::Pointer reader = ReaderType_Convert::New();
		reader->SetImageIO(niftiIO);
		reader->SetFileName(file_name);
		try
		{
			reader->Update();
		}
		catch (itk::ExceptionObject& e)
		{
			std::cout<<"read nii error"<<std::endl;
			std::cerr<<e;
		}

		//-------add --------//
		itk::OrientImageFilter<ImageTypex,ImageTypex>::Pointer orientor = 
			itk::OrientImageFilter<ImageTypex,ImageTypex>::New();
		orientor->UseImageDirectionOn();
		orientor->SetDesiredCoordinateOrientation(itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI);
		orientor->SetInput(reader->GetOutput());
		try
		{
			orientor->Update();
		}
		catch (itk::ExceptionObject& e)
		{
			std::cout<<"orientai ror"<<std::endl;
			std::cerr<<e;
			return NULL;
		}

		return orientor->GetOutput();
	}
	else
	{
		return NULL;
	}
}
Example #21
0
bool ImportedModel::initMaterials2(const aiScene* pScene, const std::string& Filename)
{
    // Extract the directory part from the file name
    std::string::size_type SlashIndex = Filename.find_last_of("/");
    std::string Dir;

    if (SlashIndex == std::string::npos)
        Dir = ".";
    else if (SlashIndex == 0)
        Dir = "/";
    else
        Dir = Filename.substr(0, SlashIndex);


    bool Ret = true;

    string fullPath;
    // Initialize the materials
    for (unsigned int i = 0 ; i < pScene->mNumMaterials ; i++)
    {
        const aiMaterial* pMaterial = pScene->mMaterials[i];

        bool success = false;
		/*
        utl::debug("i", i);
        utl::debug("aiTextureType_NONE", pMaterial->GetTextureCount(aiTextureType_NONE));

        utl::debug("aiTextureType_DIFFUSE", pMaterial->GetTextureCount(aiTextureType_DIFFUSE));
        utl::debug("aiTextureType_SPECULAR", pMaterial->GetTextureCount(aiTextureType_SPECULAR));
        utl::debug("aiTextureType_AMBIENT", pMaterial->GetTextureCount(aiTextureType_AMBIENT));
        utl::debug("aiTextureType_EMISSIVE", pMaterial->GetTextureCount(aiTextureType_EMISSIVE));
        utl::debug("aiTextureType_NORMALS", pMaterial->GetTextureCount(aiTextureType_NORMALS));
        utl::debug("aiTextureType_DIFFUSE", pMaterial->GetTextureCount(aiTextureType_DIFFUSE));
        utl::debug("aiTextureType_UNKNOWN", pMaterial->GetTextureCount(aiTextureType_UNKNOWN));
		*/

        /// we're only intersted in teh diffuse texture
        if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0)
        {
            aiString path;

            if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS)
            {
                fullPath = Dir + "/" + path.data;

         //       utl::debug("fullPath", fullPath);
                m_textures[i].m_id = utl::loadTexture(fullPath);

                success = true;
            }
        }

   //     utl::debug(fullPath, m_textures[i].m_id);
   
		
	//     if (!success)
   //         m_textures[i].m_id = utl::loadTexture("Assets/models/weapons/Ak_47/ak-47.jpg");

	//            m_textures[i].m_id = utl::loadTexture("Assets/models/weapons/M9/Tex_0009_1.jpg");
    //    utl::debugLn("final: " + fullPath, m_textures[i].m_id);
    }

    return Ret;
}
Example #22
0
File: usUtils.cpp Project: 0r/MITK
US_BEGIN_NAMESPACE

std::vector<std::string> AutoLoadModulesFromPath(const std::string& absoluteBasePath, const std::string& subDir)
{
  std::vector<std::string> loadedModules;

  std::string loadPath = absoluteBasePath + DIR_SEP + subDir;

  DIR* dir = opendir(loadPath.c_str());
#ifdef CMAKE_INTDIR
  // Try intermediate output directories
  if (dir == NULL)
  {
    std::size_t indexOfLastSeparator = absoluteBasePath.find_last_of(DIR_SEP);
    if (indexOfLastSeparator != std::string::npos)
    {
      std::string intermediateDir = absoluteBasePath.substr(indexOfLastSeparator+1);
      bool equalSubDir = intermediateDir.size() == std::strlen(CMAKE_INTDIR);
      for (std::size_t i = 0; equalSubDir && i < intermediateDir.size(); ++i)
      {
        if (std::tolower(intermediateDir[i]) != std::tolower(CMAKE_INTDIR[i]))
        {
          equalSubDir = false;
        }
      }
      if (equalSubDir)
      {
        loadPath = absoluteBasePath.substr(0, indexOfLastSeparator+1) + subDir + DIR_SEP + CMAKE_INTDIR;
        dir = opendir(loadPath.c_str());
      }
    }
  }
#endif

  if (dir != NULL)
  {
    struct dirent *ent = NULL;
    while ((ent = readdir(dir)) != NULL)
    {
      bool loadFile = true;
#ifdef _DIRENT_HAVE_D_TYPE
      if (ent->d_type != DT_UNKNOWN && ent->d_type != DT_REG)
      {
        loadFile = false;
      }
#endif

      std::string entryFileName(ent->d_name);

      // On Linux, library file names can have version numbers appended. On other platforms, we
      // check the file ending. This could be refined for Linux in the future.
#if !defined(US_PLATFORM_LINUX)
      if (entryFileName.rfind(library_suffix()) != (entryFileName.size() - library_suffix().size()))
      {
        loadFile = false;
      }
#endif
      if (!loadFile) continue;

      std::string libPath = loadPath;
      if (!libPath.empty() && libPath.find_last_of(DIR_SEP) != libPath.size() -1)
      {
        libPath += DIR_SEP;
      }
      libPath += entryFileName;
      US_DEBUG << "Auto-loading module " << libPath;

      if (!load_impl(libPath))
      {
        US_WARN << "Auto-loading of module " << libPath << " failed.";
      }
      else
      {
        loadedModules.push_back(libPath);
      }
    }
    closedir(dir);
  }
  return loadedModules;
}
Example #23
0
bool run_matlab_command(::std::string const& cmd,
						ArgsT const& args,
						ConsumerT& consumer)
{
	int pipefd[2];

	// Create a pipe to let to communicate with MATLAB.
	// Specifically, we want to read the output from MATLAB.
	// So, the parent process read from the pipe, while the child process
	// write on it.
	if (::pipe(pipefd) == -1)
	{
		char const* err_str = ::strerror(errno);
		::std::ostringstream oss;
		oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] pipe(2) failed: "
			<< ::std::string(err_str);
		throw ::std::runtime_error(oss.str());
	}

//	// Install signal handlers
//	struct ::sigaction sig_act;
//	struct ::sigaction old_sigterm_act;
//	struct ::sigaction old_sigint_act;
//	//::memset(&sig_act, 0, sizeof(sig_act));
//	::sigemptyset(&sig_act.sa_mask);
//	sig_act.sa_flags = 0;
//	sig_act.sa_handler = self_type::process_signals;
//	::sigaction(SIGTERM, &sig_act, &old_sigterm_act);
//	::sigaction(SIGINT, &sig_act, &old_sigint_act);

	// Spawn a new process

	// Between fork() and execve() only async-signal-safe functions
	// must be called if multithreaded applications should be supported.
	// That's why the following code is executed before fork() is called.

	::pid_t pid = ::fork();

	// check: pid == -1 --> error
	if (pid == -1)
	{
		char const* err_str = ::strerror(errno);
		::std::ostringstream oss;
		oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] fork(2) failed: "
			<< ::std::string(err_str);
		throw ::std::runtime_error(oss.str());
	}

	if (pid == 0)
	{
		// The child

//		// Cancel signal handler set for parent
//		sig_act.sa_handler = SIG_DFL;
//		::sigaction(SIGTERM, &sig_act, 0);
//		::sigaction(SIGINT, &sig_act, 0);

		// Get the maximum number of files this process is allowed to open
#if defined(F_MAXFD)
		int maxdescs = ::fcntl(-1, F_MAXFD, 0);
		if (maxdescs == -1)
		{
#if defined(_SC_OPEN_MAX)
			maxdescs = ::sysconf(_SC_OPEN_MAX);
#else
			::rlimit limit;
			if (::getrlimit(RLIMIT_NOFILE, &limit) < 0)
			{
				char const* err_str = ::strerror(errno);
				::std::ostringstream oss;
				oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] getrlimit(2) failed: "
					<< ::std::string(err_str);
				throw ::std::runtime_error(oss.str());
			}
			maxdescs = limit.rlim_cur;
#endif // _SC_OPEN_MAX
		}
#else // F_MAXFD
#if defined(_SC_OPEN_MAX)
		int maxdescs = ::sysconf(_SC_OPEN_MAX);
#else // _SC_OPEN_MAX
		::rlimit limit;
		if (::getrlimit(RLIMIT_NOFILE, &limit) < 0)
		{
			char const* err_str = ::strerror(errno);
			::std::ostringstream oss;
			oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] getrlimit(2) failed: "
				<< ::std::string(err_str);
			throw ::std::runtime_error(oss.str());
		}
		maxdescs = limit.rlim_cur;
#endif // _SC_OPEN_MAX
#endif // F_MAXFD
		if (maxdescs == -1)
		{
			maxdescs = 1024;
		}

		::std::vector<bool> close_fd(maxdescs, true);

		// Associate the child's stdout to the pipe write fd.
		close_fd[STDOUT_FILENO] = false;
		if (pipefd[1] != STDOUT_FILENO)
		{
			if (::dup2(pipefd[1], STDOUT_FILENO) != STDOUT_FILENO)
			{
				char const* err_str = ::strerror(errno);
				::std::ostringstream oss;
				oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] dup2(2) failed: "
					<< ::std::string(err_str);
				throw ::std::runtime_error(oss.str());
			}
		}
		else
		{
			close_fd[pipefd[1]] = false;
		}
//			::close(STDOUT_FILENO);
//			::dup(pipefd[1]);

		// Check if the command already has path information
		::std::string cmd_path;
		::std::string cmd_name;
		typename ::std::string::size_type pos;
		pos = cmd.find_last_of('/');
		if (pos != ::std::string::npos)
		{
			cmd_path = cmd.substr(0, pos);
			cmd_name = cmd.substr(pos+1);
		}

		//FIXME: use scoped_ptr in place of "new"

		::std::size_t nargs = args.size()+1;
		char** argv = new char*[nargs + 2];
		argv[0] = new char[cmd_name.size()+1];
		::std::strncpy(argv[0], cmd_name.c_str(), cmd_name.size()+1); // by convention, the first argument is always the command name
		typename ArgsT::size_type i(1);
		typename ArgsT::const_iterator end_it(args.end());
		for (typename ArgsT::const_iterator it = args.begin(); it != end_it; ++it)
		{
			argv[i] = new char[it->size()+1];
			::std::strncpy(argv[i], it->c_str(), it->size()+1);
			++i;
		}
		argv[nargs] = 0;

		//char** envp(0);

		// Close unused file descriptors
#ifdef DCS_DEBUG
		// Keep standard error open for debug
		close_fd[STDERR_FILENO] = false;
#endif // DCS_DEBUG
		for (int fd = 0; fd < maxdescs; ++fd)
		{
			if (close_fd[fd])
			{
				::close(fd);
			}
		}

//[XXX]
#ifdef DCS_DEBUG
::std::cerr << "Executing MATLAB: " << cmd;//XXX
for (::std::size_t i=0; i < args.size(); ++i)//XXX
{//XXX
::std::cerr << " " << args[i] << ::std::flush;//XXX
}//XXX
::std::cerr << ::std::endl;//XXX
#endif // DCS_DEBUG
//[/XXX]
//DCS_DEBUG_TRACE("Executing: " << cmd << " " << args[0] << " " << args[1] << " " << args[2] << " - " << args[3]);

		//::execve(cmd.c_str(), argv, envp);
		::execvp(cmd.c_str(), argv);

		// Actually we should delete argv and envp data. As we must not
		// call any non-async-signal-safe functions though we simply exit.
		::write(STDERR_FILENO, "execvp() failed\n", 17);
		//_exit(EXIT_FAILURE);
		_exit(127);
	}

	// The parent

//		// Associate the parent's stdin to the pipe read fd.
	::close(pipefd[1]);
//		::close(STDIN_FILENO);
//		::dup(pipefd[0]);
	if (pipefd[0] != STDIN_FILENO)
	{
		if (::dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO)
		{
			char const* err_str = ::strerror(errno);
			::std::ostringstream oss;
			oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] dup2(2) failed: "
				<< ::std::string(err_str);
			throw ::std::runtime_error(oss.str());
		}
		::close(pipefd[0]);
	}

	typedef ::boost::iostreams::file_descriptor_source fd_device_type;
	typedef ::boost::iostreams::stream_buffer<fd_device_type> fd_streambuf_type;
	//fd_device_type fd_src(pipefd[0], ::boost::iostreams::close_handle);
	fd_device_type fd_src(STDIN_FILENO, ::boost::iostreams::close_handle);
	fd_streambuf_type fd_buf(fd_src);
	::std::istream is(&fd_buf);

	consumer(is);

DCS_DEBUG_TRACE("END parsing MATLAB output");//XXX
DCS_DEBUG_TRACE("IS state: " << is.good() << " - " << is.eof() << " - " << is.fail() << " - " << is.bad());//XXX

	// Wait the child termination (in order to prevent zombies)
	int status;
//		::pid_t wait_pid;
//		wait_pid = ::wait(&status);
//		if (wait_pid != pid)
//		{
//			throw ::std::runtime_error("[dcs::des::cloud::detail::rls_miso_matlab_app_proxy::run_matlab] Unexpected child process.");
//		}
	if (::waitpid(pid, &status, 0) == -1)
	{
		char const* err_str = ::strerror(errno);
		::std::ostringstream oss;
		oss << "[dcs::des::cloud::detail::matlab::run_matlab_command] waitpid(2) failed: "
			<< ::std::string(err_str);
		throw ::std::runtime_error(oss.str());
	}
DCS_DEBUG_TRACE("MATLAB exited");//XXX
	bool ok(true);
	if (WIFEXITED(status))
	{
DCS_DEBUG_TRACE("MATLAB exited with a call to 'exit(" << WEXITSTATUS(status) << ")'");//XXX
		if (WEXITSTATUS(status))
		{
			// status != 0 --> error in the execution
			::std::clog << "[Warning] MATLAB command exited with status " << WEXITSTATUS(status) << ::std::endl;
			ok = false;
		}
	}
	else if (WIFSIGNALED(status))
	{
DCS_DEBUG_TRACE("MATLAB exited with a call to 'kill(" << WTERMSIG(status) << ")'");//XXX
	   ::std::clog << "[Warning] MATLAB command received signal " << WTERMSIG(status) << ::std::endl;
		ok = false;
	}
	else
	{
DCS_DEBUG_TRACE("MATLAB exited with an unexpected way");//XXX
		ok = false;
	}

//	// Restore signal handler
//	::sigaction(SIGTERM, &old_sigterm_act, 0);
//	::sigaction(SIGINT, &old_sigint_act, 0);
	return ok;
}
void ResourceListBuilder::BuildPakResourceList(const std::string &pakfilename)
{
	// open the pak file in binary read mode
	File pakfile(pakfilename, "rb");

	if (pakfile == NULL)
	{
		// error opening pakfile!
		printf("Could not find pakfile \"%s\".\n", pakfilename.c_str());
		return;
	}

	// Check a pakfile for resources
	// get the header
	size_t pakheadersize = sizeof(pakheader_s);
	pakheader_s pakheader;
	size_t retval = fread(&pakheader, 1, pakheadersize, pakfile);

	if (retval != pakheadersize)
	{
		// unexpected size.
		if (verbal)
		{
			printf("Reading pakfile header failed. Wrong size (" SIZE_T_SPECIFIER " read, " SIZE_T_SPECIFIER " expected).\n", retval, pakheadersize);
			printf("Is \"%s\" a valid pakfile?\n", pakfilename.c_str());
		}
		return;
	}

	// verify pak identity
	if (pakheader.pakid != 1262698832)
	{
		if (verbal)
		{
			printf("Pakfile \"%s\" does not appear to be a Half-Life pakfile (ID mismatch).\n", pakfilename.c_str());
		}
		return;
	}

	// count the number of files in the pak
	size_t fileinfosize = sizeof(fileinfo_s);
	size_t filecount = pakheader.dirsize / fileinfosize;

	// re-verify integrity of header
	if (pakheader.dirsize % fileinfosize != 0 || filecount == 0)
	{
		if (verbal)
		{
			printf("Pakfile \"%s\" does not appear to be a Half-Life pakfile (invalid dirsize).\n", pakfilename.c_str());
		}
		return;
	}

	// load file list to memory
	if(fseek(pakfile, pakheader.diroffset, SEEK_SET))
	{
		if (verbal)
		{
			printf("Error seeking for file list.\nPakfile \"%s\" is not a pakfile, or is corrupted.\n", pakfilename.c_str());
		}
		return;
	}

	std::vector<fileinfo_s> filelist(filecount);
	retval = fread(filelist.data(), 1, pakheader.dirsize, pakfile);
	if (retval != pakheader.dirsize)
	{
		if (verbal)
		{
			printf("Error seeking for file list.\nPakfile \"%s\" is not a pakfile, or is corrupted.\n", pakfilename.c_str());
		}
		return;
	}

	if (verbal)
	{
		printf("Scanning pak file \"%s\" for resources (" SIZE_T_SPECIFIER " files in pak)\n", pakfilename.c_str(), filecount);
	}

	// Read filelist for possible resources
	for (size_t i = 0; i < filecount; i++)
	{
		const std::string fileLower = strToLowerCopy(filelist[i].name);

		const size_t dotIndex = fileLower.find_last_of('.');

		if(dotIndex != std::string::npos)
		{
			const std::string extension = fileLower.substr(dotIndex + 1);

			if (
				extension == "mdl" ||
				extension == "wav" ||
				extension == "spr" ||
				extension == "bmp" ||
				extension == "tga" ||
				extension == "txt" ||
				extension == "wad"
			)
			{
				// resource, add to list
				std::string resStr = replaceCharAllCopy(filelist[i].name, '\\', '/');

				resources[strToLowerCopy(resStr)] = resStr;

				if (resourcedisp)
				{
					printf("Added \"%s\" to resource list\n", resStr.c_str());
				}
			}
		}
	}
}
GLhandleARB LLShaderMgr::loadShaderFile(const std::string& filename, S32 & shader_level, GLenum type, std::map<std::string, std::string>* defines, S32 texture_index_channels)
{
	std::pair<std::multimap<std::string, CachedObjectInfo >::iterator, std::multimap<std::string, CachedObjectInfo>::iterator> range;
	range = mShaderObjects.equal_range(filename);
	for (std::multimap<std::string, CachedObjectInfo>::iterator it = range.first; it != range.second;++it)
	{
		if((*it).second.mLevel == shader_level && (*it).second.mType == type && (*it).second.mDefinitions == (defines ? *defines : std::map<std::string, std::string>()))
		{
			//LL_INFOS("ShaderLoading") << "Loading cached shader for " << filename << LL_ENDL;
			return (*it).second.mHandle;
		}
	}

	GLenum error = GL_NO_ERROR;
	if (gDebugGL)
	{
		error = glGetError();
		if (error != GL_NO_ERROR)
		{
			LL_WARNS("ShaderLoading") << "GL ERROR entering loadShaderFile(): " << error << LL_ENDL;
		}
	}

	LL_DEBUGS("ShaderLoading") << "Loading shader file: " << filename << " class " << shader_level << LL_ENDL;

	if (filename.empty()) 
	{
		return 0;
	}

	//read in from file
	LLFILE* file = NULL;

	S32 try_gpu_class = shader_level;
	S32 gpu_class;

	//find the most relevant file
	for (gpu_class = try_gpu_class; gpu_class > 0; gpu_class--)
	{	//search from the current gpu class down to class 1 to find the most relevant shader
		std::stringstream fname;
		fname << getShaderDirPrefix();
		fname << gpu_class << "/" << filename;
		
 		LL_DEBUGS("ShaderLoading") << "Looking in " << fname.str() << LL_ENDL;
		file = LLFile::fopen(fname.str(), "r");		/* Flawfinder: ignore */
		if (file)
		{
			//LL_INFOS("ShaderLoading") << "Loading file: shaders/class" << gpu_class << "/" << filename << " (Want class " << gpu_class << ")" << LL_ENDL;
			break; // done
		}
	}
	
	if (file == NULL)
	{
		LL_WARNS("ShaderLoading") << "GLSL Shader file not found: " << filename << LL_ENDL;
		return 0;
	}

	//we can't have any lines longer than 1024 characters 
	//or any shaders longer than 4096 lines... deal - DaveP
	GLcharARB buff[1024];
	GLcharARB* text[4096];
	GLuint count = 0;

	S32 major_version = gGLManager.mGLSLVersionMajor;
	S32 minor_version = gGLManager.mGLSLVersionMinor;
	
	if (major_version == 1 && minor_version < 30)
	{
		if (minor_version < 10)
		{
			//should NEVER get here -- if major version is 1 and minor version is less than 10, 
			// viewer should never attempt to use shaders, continuing will result in undefined behavior
			LL_ERRS() << "Unsupported GLSL Version." << LL_ENDL;
		}

		if (minor_version <= 19)
		{
			text[count++] = strdup("#version 110\n");
			text[count++] = strdup("#define ATTRIBUTE attribute\n");
			text[count++] = strdup("#define VARYING varying\n");
			text[count++] = strdup("#define VARYING_FLAT varying\n");
			// Need to enable extensions here instead of in the shader files,
			// before any non-preprocessor directives (per spec)
			text[count++] = strdup("#extension GL_ARB_texture_rectangle : enable\n");
			text[count++] = strdup("#extension GL_ARB_shader_texture_lod : enable\n");
		}
		else if (minor_version <= 29)
		{
			//set version to 1.20
			text[count++] = strdup("#version 120\n");
			text[count++] = strdup("#define FXAA_GLSL_120 1\n");
			text[count++] = strdup("#define FXAA_FAST_PIXEL_OFFSET 0\n");
			text[count++] = strdup("#define ATTRIBUTE attribute\n");
			text[count++] = strdup("#define VARYING varying\n");
			text[count++] = strdup("#define VARYING_FLAT varying\n");
			// Need to enable extensions here instead of in the shader files,
			// before any non-preprocessor directives (per spec)
			text[count++] = strdup("#extension GL_ARB_texture_rectangle : enable\n");
			text[count++] = strdup("#extension GL_ARB_shader_texture_lod : enable\n");
		}
	}
	else
	{  
		if (major_version < 4)
		{
			//set version to 1.30
			text[count++] = strdup("#version 130\n");
			// Need to enable extensions here instead of in the shader files,
			// before any non-preprocessor directives (per spec)
			text[count++] = strdup("#extension GL_ARB_texture_rectangle : enable\n");
			text[count++] = strdup("#extension GL_ARB_shader_texture_lod : enable\n");
			

			//some implementations of GLSL 1.30 require integer precision be explicitly declared
			text[count++] = strdup("precision mediump int;\n");
			text[count++] = strdup("precision highp float;\n");
		}
		else
		{ //set version to 400
			text[count++] = strdup("#version 400\n");
			// Need to enable extensions here instead of in the shader files,
			// before any non-preprocessor directives (per spec)
			text[count++] = strdup("#extension GL_ARB_texture_rectangle : enable\n");
			text[count++] = strdup("#extension GL_ARB_shader_texture_lod : enable\n");
		}
		

		text[count++] = strdup("#define DEFINE_GL_FRAGCOLOR 1\n");
		text[count++] = strdup("#define FXAA_GLSL_130 1\n");

		text[count++] = strdup("#define ATTRIBUTE in\n");

		if (type == GL_VERTEX_SHADER_ARB)
		{ //"varying" state is "out" in a vertex program, "in" in a fragment program 
			// ("varying" is deprecated after version 1.20)
			text[count++] = strdup("#define VARYING out\n");
			text[count++] = strdup("#define VARYING_FLAT flat out\n");
		}
		else
		{
			text[count++] = strdup("#define VARYING in\n");
			text[count++] = strdup("#define VARYING_FLAT flat in\n");
		}

		//backwards compatibility with legacy texture lookup syntax
		text[count++] = strdup("#define texture2D texture\n");
		text[count++] = strdup("#define textureCube texture\n");
		text[count++] = strdup("#define texture2DLod textureLod\n");
		text[count++] = strdup("#define	shadow2D(a,b) vec2(texture(a,b))\n");

		if (major_version > 1 || minor_version >= 40)
		{ //GLSL 1.40 replaces texture2DRect et al with texture
			text[count++] = strdup("#define texture2DRect texture\n");
			text[count++] = strdup("#define shadow2DRect(a,b) vec2(texture(a,b))\n");
		}
	}

	if(defines)
	{
		for (std::map<std::string,std::string>::iterator iter = defines->begin(); iter != defines->end(); ++iter)
	{
		std::string define = "#define " + iter->first + " " + iter->second + "\n";
		text[count++] = (GLcharARB *) strdup(define.c_str());
	}
	}

	if (texture_index_channels > 0 && type == GL_FRAGMENT_SHADER_ARB)
	{
		//use specified number of texture channels for indexed texture rendering

		/* prepend shader code that looks like this:

		uniform sampler2D tex0;
		uniform sampler2D tex1;
		uniform sampler2D tex2;
		.
		.
		.
		uniform sampler2D texN;
		
		VARYING_FLAT ivec4 vary_texture_index;

		vec4 ret = vec4(1,0,1,1);

		vec4 diffuseLookup(vec2 texcoord)
		{
			switch (vary_texture_index.r))
			{
				case 0: ret = texture2D(tex0, texcoord); break;
				case 1: ret = texture2D(tex1, texcoord); break;
				case 2: ret = texture2D(tex2, texcoord); break;
				.
				.
				.
				case N: return texture2D(texN, texcoord); break;
			}

			return ret;
		}
		*/

		text[count++] = strdup("#define HAS_DIFFUSE_LOOKUP 1\n");

		//uniform declartion
		for (S32 i = 0; i < texture_index_channels; ++i)
		{
			std::string decl = llformat("uniform sampler2D tex%d;\n", i);
			text[count++] = strdup(decl.c_str());
		}

		if (texture_index_channels > 1)
		{
			text[count++] = strdup("VARYING_FLAT ivec4 vary_texture_index;\n");
		}

		text[count++] = strdup("vec4 diffuseLookup(vec2 texcoord)\n");
		text[count++] = strdup("{\n");
		
		
		if (texture_index_channels == 1)
		{ //don't use flow control, that's silly
			text[count++] = strdup("return texture2D(tex0, texcoord);\n");
			text[count++] = strdup("}\n");
		}
		else if (major_version > 1 || minor_version >= 30)
		{  //switches are supported in GLSL 1.30 and later
			if (gGLManager.mIsNVIDIA || (gGLManager.mIsATI && gGLManager.mGLVersion < 3.3f))
			{ //switches are unreliable on old drivers
				for (S32 i = 0; i < texture_index_channels; ++i)
				{
					std::string if_string = llformat("\t%sif (vary_texture_index.r == %d) { return texture2D(tex%d, texcoord); }\n", i > 0 ? "else " : "", i, i); 
					text[count++] = strdup(if_string.c_str());
				}
				text[count++] = strdup("\treturn vec4(1,0,1,1);\n");
				text[count++] = strdup("}\n");
			}
			else
			{
				text[count++] = strdup("\tvec4 ret = vec4(1,0,1,1);\n");
				text[count++] = strdup("\tswitch (vary_texture_index.r)\n");
				text[count++] = strdup("\t{\n");
		
				//switch body
				for (S32 i = 0; i < texture_index_channels; ++i)
				{
					std::string case_str = llformat("\t\tcase %d: ret = texture2D(tex%d, texcoord); break;\n", i, i);
					text[count++] = strdup(case_str.c_str());
				}

				text[count++] = strdup("\t}\n");
				text[count++] = strdup("\treturn ret;\n");
				text[count++] = strdup("}\n");
			}
		}
		else
		{ //should never get here.  Indexed texture rendering requires GLSL 1.30 or later 
			// (for passing integers between vertex and fragment shaders)
			LL_ERRS() << "Indexed texture rendering requires GLSL 1.30 or later." << LL_ENDL;
		}
	}
	else
	{
		text[count++] = strdup("#define HAS_DIFFUSE_LOOKUP 0\n");
	}

	//copy file into memory
	while( fgets((char *)buff, 1024, file) != NULL && count < LL_ARRAY_SIZE(text) ) 
	{
		text[count++] = (GLcharARB *)strdup((char *)buff); 
	}
	fclose(file);

	//create shader object
	GLhandleARB ret = glCreateShaderObjectARB(type);
	if (gDebugGL)
	{
		error = glGetError();
		if (error != GL_NO_ERROR)
		{
			LL_WARNS("ShaderLoading") << "GL ERROR in glCreateShaderObjectARB: " << error << LL_ENDL;
			glDeleteObjectARB(ret); //no longer need handle
			ret=0;
		}
	}
	
	//load source
	if(ret)
	{
		glShaderSourceARB(ret, count, (const GLcharARB**) text, NULL);

		if (gDebugGL)
		{
			error = glGetError();
			if (error != GL_NO_ERROR)
			{
				LL_WARNS("ShaderLoading") << "GL ERROR in glShaderSourceARB: " << error << LL_ENDL;
				glDeleteObjectARB(ret); //no longer need handle
				ret=0;
			}
		}
	}

	//compile source
	if(ret)
	{
		glCompileShaderARB(ret);

		if (gDebugGL)
		{
			error = glGetError();
			if (error != GL_NO_ERROR)
			{
				LL_WARNS("ShaderLoading") << "GL ERROR in glCompileShaderARB: " << error << LL_ENDL;
				glDeleteObjectARB(ret); //no longer need handle
				ret=0;
			}
		}
	}

	std::string error_str;

	if (error == GL_NO_ERROR)
	{
		//check for errors
		GLint success = GL_TRUE;
		glGetObjectParameterivARB(ret, GL_OBJECT_COMPILE_STATUS_ARB, &success);
		if (gDebugGL || success == GL_FALSE)
		{
			error = glGetError();
			if (error != GL_NO_ERROR || success == GL_FALSE) 
			{
				//an error occured, print log
				LL_WARNS("ShaderLoading") << "GLSL Compilation Error: (" << error << ") in " << filename << LL_ENDL;
				dumpObjectLog(ret);
				error_str = get_object_log(ret);

#if LL_WINDOWS
				std::stringstream ostr;
				//dump shader source for debugging
				for (GLuint i = 0; i < count; i++)
				{
					ostr << i << ": " << text[i];

					if (i % 128 == 0)
					{ //dump every 128 lines

						LL_WARNS("ShaderLoading") << "\n" << ostr.str() << LL_ENDL;
						ostr = std::stringstream();
					}

				}

				LL_WARNS("ShaderLoading") << "\n" << ostr.str() << LL_ENDL;
#else
				std::string str;
				
				for (GLuint i = 0; i < count; i++) {
					str.append(text[i]);
					
					if (i % 128 == 0)
					{
						LL_WARNS("ShaderLoading") << str << LL_ENDL;
						str = "";
					}
				}
#endif
				glDeleteObjectARB(ret); //no longer need handle
				ret = 0;
			}	
		}
		if(ret)
			dumpObjectLog(ret,false);
	}

	static const LLCachedControl<bool> dump_raw_shaders("ShyotlDumpRawShaders",false);
	if(dump_raw_shaders || !ret)
	{
		std::stringstream ostr;
		for (GLuint i = 0; i < count; i++)
		{
			ostr << text[i];
		}

		std::string delim = gDirUtilp->getDirDelimiter();
		std::string shader_name = filename.substr(filename.find_last_of("/")+1);			//shader_name.glsl
		shader_name = shader_name.substr(0,shader_name.find_last_of("."));					//shader_name
		std::string maindir = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,"shader_dump"+delim);
		//mkdir is NOT recursive. Step through the folders one by one.
		LLFile::mkdir(maindir);																//..Roaming/SecondLife/logs/shader_dump/
		LLFile::mkdir(maindir+="class" + llformat("%i",gpu_class) + delim);					//..shader_dump/class1/
		LLFile::mkdir(maindir+=filename.substr(0,filename.find_last_of("/")+1));			//..shader_dump/class1/windlight/

		LLAPRFile file(maindir + shader_name + (ret ? "" : llformat("_FAILED(%i)",error)) + ".glsl", LL_APR_W);
		file.write(ostr.str().c_str(),ostr.str().length());
		if(!error_str.empty())
		{
			LLAPRFile file2(maindir + shader_name + "_ERROR.txt", LL_APR_W);
			file2.write(error_str.c_str(),error_str.length());
		}
	}
	stop_glerror();

	//free memory
	for (GLuint i = 0; i < count; i++)
	{
		free(text[i]);
	}

	//successfully loaded, save results
	if (ret)
	{
		// Add shader file to map
		mShaderObjects.insert(make_pair(filename,CachedObjectInfo(ret,try_gpu_class,type,defines)));
		shader_level = try_gpu_class;
	}
	else
	{
		if (shader_level > 1)
		{
			shader_level--;
			return loadShaderFile(filename,shader_level,type, defines, texture_index_channels);
		}
		LL_WARNS("ShaderLoading") << "Failed to load " << filename << LL_ENDL;	
	}
	return ret;
}
// Win 32 DIR parser
void ResourceListBuilder::ListDir(const std::string &path, const std::string &filepath, bool reporterror)
{
	WIN32_FIND_DATA filedata;

	// add *.* for searching all files.
	std::string searchdir = path + filepath + "*.*";

	// find first file
	HANDLE filehandle = FindFirstFile(searchdir.c_str(), &filedata);

	if (filehandle == INVALID_HANDLE_VALUE)
	{
		if (firstdir && reporterror)
		{
			if (GetLastError() & ERROR_PATH_NOT_FOUND || GetLastError() & ERROR_FILE_NOT_FOUND)
			{
				printf("The directory you specified (%s) can not be found or is empty.\n", path.c_str());
			}
			else
			{
				printf("There was an error with the directory you specified (%s) - ERROR NO: %lu.\n", path.c_str(), GetLastError());
			}
		}
		return;
	}

	firstdir = false;

	do
	{
		std::string file = filepath + filedata.cFileName;

		// Check for directory
		if (filedata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			// Look for files in subdir, but ignore . and ..
			if (strcmp(filedata.cFileName, ".") && strcmp(filedata.cFileName, ".."))
			{
				// Call this function recursive
				ListDir(path, file + PATH_SEPARATOR, reporterror);
			}
		}
		else
		{
			const std::string fileLower = strToLowerCopy(file);

			const size_t dotIndex = fileLower.find_last_of('.');

			if(dotIndex != std::string::npos)
			{
				const std::string extension = fileLower.substr(dotIndex + 1);

				if (
					extension == "mdl" ||
					extension == "wav" ||
					extension == "spr" ||
					extension == "bmp" ||
					extension == "tga" ||
					extension == "txt" ||
					extension == "wad"
				)
				{
					// resource, add to list
					replaceCharAll(file, '\\', '/'); // replace backslashes

					resources[strToLowerCopy(file)] = file;

					if (resourcedisp)
					{
						printf("Added \"%s\" to resource list\n", file.c_str());
					}
				}

				if ((extension == "pad") && pakparse)
				{
					// get pakfilelist
					BuildPakResourceList(path + file);
				}
			}
		}

	} while (FindNextFile(filehandle, &filedata));

	// Close search
	FindClose(filehandle);
}
void showHistogram2d(TH2* histogram, 
		     const std::string& xAxisTitle, const std::string& yAxisTitle,
		     int zAxisNormOption, double zMin, double zMax, 
		     Float_t* genX, Float_t* genY, 
		     const std::string& outputFileName)
{
  TCanvas* canvas = new TCanvas("canvas", "canvas", 900, 800);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);

  canvas->SetTopMargin(0.10);
  canvas->SetLeftMargin(0.12);
  canvas->SetRightMargin(0.14);
  canvas->SetBottomMargin(0.12);

  histogram->SetTitle("");
  histogram->SetStats(false);
  int numBinsX = histogram->GetNbinsX();
  int numBinsY = histogram->GetNbinsY();
  if ( zAxisNormOption == kNormByQuantiles ) {
    std::vector<double> binContents;
    for ( int iBinX = 1; iBinX <= numBinsX; ++iBinX ) {
      for ( int iBinY = 1; iBinY <= numBinsY; ++iBinY ) {
	binContents.push_back(histogram->GetBinContent(iBinX, iBinY));
      }
    }
    std::sort(binContents.begin(), binContents.end());
    histogram->SetMinimum(binContents[TMath::Nint(0.05*binContents.size())]);
    histogram->SetMaximum(binContents[TMath::Nint(0.95*binContents.size())]);
  } else if ( zAxisNormOption == kNormByNegLogMax ) {
    double maxBinContent = 0.;
    for ( int iBinX = 1; iBinX <= numBinsX; ++iBinX ) {
      for ( int iBinY = 1; iBinY <= numBinsY; ++iBinY ) {
	double binContent = histogram->GetBinContent(iBinX, iBinY);
	if ( binContent > maxBinContent ) {
	  std::cout << "binX = " << iBinX << " (x = " << histogram->GetXaxis()->GetBinCenter(iBinX) << ")," 
		    << " binY = " << iBinY << " (y = " << histogram->GetYaxis()->GetBinCenter(iBinY) << "): maxBinContent = " << maxBinContent << std::endl;
	  maxBinContent = binContent;
	}
      }
    }
    double logMaxBinContent = TMath::Log(maxBinContent);
    for ( int iBinX = 1; iBinX <= numBinsX; ++iBinX ) {
      for ( int iBinY = 1; iBinY <= numBinsY; ++iBinY ) {
	double binContent = histogram->GetBinContent(iBinX, iBinY);
	if ( binContent > 0. ) {
	  histogram->SetBinContent(iBinX, iBinY, -TMath::Log(binContent) + logMaxBinContent);
	} else {
	  histogram->SetBinContent(iBinX, iBinY, -1.);
	}
      }
    }
    histogram->SetMinimum(0.);
    histogram->SetMaximum(zMax);
  } else if ( zAxisNormOption == kNormByValue ) {
    histogram->SetMinimum(zMin);
    histogram->SetMaximum(zMax);
  } else assert(0);

  TAxis* xAxis = histogram->GetXaxis();
  xAxis->SetTitle(xAxisTitle.data());
  xAxis->SetTitleOffset(1.15);

  TAxis* yAxis = histogram->GetYaxis();
  yAxis->SetTitle(yAxisTitle.data());
  yAxis->SetTitleOffset(1.30);

  gStyle->SetPalette(1,0);
  histogram->Draw("COLZ");

  TMarker* genMarker = 0;
  if ( genX && genY ) {
    genMarker = new TMarker(*genX, *genY, 34);
    genMarker->SetMarkerColor(1);
    genMarker->SetMarkerSize(2);
    genMarker->Draw();
  }

  canvas->Update();
  size_t idx = outputFileName.find_last_of('.');
  std::string outputFileName_plot = std::string(outputFileName, 0, idx);
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());

  delete genMarker;
  delete canvas;  
}
Example #28
0
void sqr_tools::CPieceUnitEditImp::CreateRS( std::string pieceName, std::string& rsName )
{
	if (MODEL)
	{
		CEditPieceGroup* pPieceGroup = NULL;
		pPieceGroup = new CEditPieceGroup;
		MODEL->GetEditPieceGroup(pPieceGroup);

		if (pPieceGroup)
		{
			for (unsigned int i = 0; i < pPieceGroup->GetPieceClassNum(); i++)
			{
				CPieceClass& Pc = *pPieceGroup->GetPieceClass(i);
				for( unsigned int j = 0; j < Pc.size(); ++j )
				{
					if (pieceName.compare(Pc[j]->GetPieceName()) != 0)
						continue;

					int maxIndex = 0;
					for (unsigned int k = 0; k < Pc[j]->GetRSNum(); k++)
					{
						std::string rsIndexName = Pc[j]->GetRS(k)->GetRSIndexName();
						if (rsIndexName.substr(0,4) != "默认")
							continue;

						int index;
						std::string strIndex = rsIndexName.substr(4);
						std::stringstream ss(strIndex);
						ss >> index;
						if (index >= maxIndex)
						{
							maxIndex = index + 1;
						}
					}

					std::string pieceResName;
					CPathSetImp::GetInst()->GetResFileName(rsName, pieceResName);
					CEditRenderStyle* pRs = new CEditRenderStyle( pieceResName.c_str(),L"res" );
					if( !pieceResName.empty() )
					{
						if(pRs->BinLoad()<0)
						{
							std::string str = pieceResName + "没载入成功";
							MessageBox(NULL, str.c_str(), "提示",MB_OK);
							return;
						}
					}

					char temp[256];
					sprintf_s(temp, "%i", maxIndex);
					std::string strIndexName = "默认" + string(temp);
					CEditPieceRenderStyle* rs = new CEditPieceRenderStyle((CEditPiece*)Pc[j], pRs);
					rs->SetRSIndexName(strIndexName);

					int index = rsName.find_last_of("\\") + 1;
					rsName = rsName.substr(index) + "(" + strIndexName + ")";
					return;
				}
			}
		}

		pPieceGroup->Release();
	}
}
Example #29
0
std::string get_filename(const std::string& str)
{
  std::size_t found = str.find_last_of("/\\");
  return str.substr(found+1);
}
Example #30
0
bool Model::loadCollada(std::string filename){
    //Load the collada xml file
    rapidxml::file<> xmlFile(filename.c_str());
    rapidxml::xml_document<> doc;
    doc.parse<0>(xmlFile.data());
    
    bool zup = std::string(doc.first_node()->first_node("asset")->first_node("up_axis")->value()) == "Z_UP";
    
    //Load textures
    rapidxml::xml_node<> *images = doc.first_node()->first_node("library_images");
    if(images->first_node("image") == 0){
        Logger::error << "Couldn't load model: file contains no texture data." << std::endl;
        return false;
    }
    std::map<std::string, unsigned int> textures;
    for(rapidxml::xml_node<> *image = images->first_node("image"); image != 0; image = image->next_sibling("image")){
        textures.insert(std::pair<std::string, unsigned int>(image->first_attribute("id")->value(), loadTextureFromPNG(filename.substr(0, filename.find_last_of("\\/")+1) + image->first_node("init_from")->value())));
    }
    
    
    //Load effects
    //TODO: only supports common profiles using phong techniques
    rapidxml::xml_node<> *effectsNode = doc.first_node()->first_node("library_effects");
    if(effectsNode->first_node("effect") == 0){
        Logger::error << "Couldn't load model: file contains no effects data." << std::endl;
        return false;
    }
    std::map<std::string, Material> effects;
    for(rapidxml::xml_node<> *effect = effectsNode->first_node("effect"); effect != 0; effect = effect->next_sibling("effect")){
        rapidxml::xml_node<> *profile = effect->first_node("profile_COMMON");
        if(profile != 0){
            rapidxml::xml_node<> *technique = profile->first_node("technique");
            Material mat;
            rapidxml::xml_node<> *phong = technique->first_node("phong");
            if(phong != 0){                
                if(phong->first_node("emission") != 0){
                    mat.emission = getVec4(phong->first_node("emission")->first_node("color"));
                }
                if(phong->first_node("ambient") != 0){
                    mat.ambient = getVec4(phong->first_node("ambient")->first_node("color"));
                }
                if(phong->first_node("diffuse") != 0){
                    if(phong->first_node("diffuse")->first_node("color") != 0){
                        mat.diffuse = getVec4(phong->first_node("diffuse")->first_node("color"));
                    }
                    if(phong->first_node("diffuse")->first_node("texture") != 0){
                        mat.diffuseTexture = textures.at(searchByAttribute(profile, "sid", 
                                searchByAttribute(profile, "sid", phong->first_node("diffuse")->first_node("texture")->first_attribute("texture")->value(), "newparam")
                                ->first_node("sampler2D")->first_node("source")->value()
                                , "newparam")->first_node("surface")->first_node("init_from")->value());
                    }
                }
                if(phong->first_node("specular") != 0){
                    if(phong->first_node("specular")->first_node("color") != 0){
                        mat.specular = getVec4(phong->first_node("specular")->first_node("color"));
                    }
                    if(phong->first_node("specular")->first_node("texture") != 0){
                        mat.specularTexture = textures.at(searchByAttribute(profile, "sid", 
                                searchByAttribute(profile, "sid", phong->first_node("specular")->first_node("texture")->first_attribute("texture")->value(), "newparam")
                                ->first_node("sampler2D")->first_node("source")->value()
                                , "newparam")->first_node("surface")->first_node("init_from")->value());
                    }
                }
                if(phong->first_node("shininess") != 0){
                    mat.shininess = std::stof(phong->first_node("shininess")->first_node("float")->value());
                }
            } else {
                Logger::error << "Couldn't load model: material doesn't use the phong technique." << std::endl;
                return false;
            }
            if(technique->first_node("extra") != 0 && technique->first_node("extra")->first_node("technique")->first_node("bump") != 0){
                mat.bumpmapTexture = textures.at(searchByAttribute(profile, "sid", 
                                searchByAttribute(profile, "sid", technique->first_node("extra")->first_node("technique")->first_node("bump")->first_node("texture")->first_attribute("texture")->value(), "newparam")
                                ->first_node("sampler2D")->first_node("source")->value()
                                , "newparam")->first_node("surface")->first_node("init_from")->value());
            }
            effects.insert(std::pair<std::string, Material>(effect->first_attribute("id")->value(), mat));
        } else {
            Logger::error << "Couldn't load model: material doesn't have a profile_COMMON tag." << std::endl;
            return false;
        }
    }
    
    
    //Load materials
    //TODO: make them overridable (collada spec))
    rapidxml::xml_node<> *materialsNode = doc.first_node()->first_node("library_materials");
    if(materialsNode->first_node("material") == 0){
        Logger::error << "Couldn't load model: file contains no material data." << std::endl;
        return false;
    }
    std::map<std::string, Material> materials;
    for(rapidxml::xml_node<> *material = materialsNode->first_node("material"); material != 0; material = material->next_sibling("material")){
        materials.insert(std::pair<std::string, Material>(material->first_attribute("id")->value(), effects.at(std::string(material->first_node("instance_effect")->first_attribute("url")->value()).substr(1))));
    }
    
    
    //Load geometry
    std::map<std::string, Mesh> meshes;
    rapidxml::xml_node<> *geometries = doc.first_node()->first_node("library_geometries");
    if(geometries->first_node("geometry") == 0){
        Logger::error << "Couldn't load model: file contains no geometry data." << std::endl;
        return false;
    }
    for(rapidxml::xml_node<> *geometry = geometries->first_node("geometry"); geometry != 0; geometry = geometry->next_sibling("geometry")){
        Mesh mesh;        
        rapidxml::xml_node<> *meshNode = geometry->first_node("mesh");
        if(meshNode == 0){
            Logger::error << "Couldn't load model: The loader can only load geometry of type \"mesh\" (geometry with name: " << geometry->first_attribute("name")->value() << ")." << std::endl;
            return false;
        }
        if(meshNode->first_node("polylist") == 0){
            Logger::error << "Couldn't load model: The loader can only load meshes that use polylists. (geometry with name: " << geometry->first_attribute("name")->value() << ")." << std::endl;
            return false;
        }
        
        //TODO: allow for multiple data types
        //<name, <stride, data>>
        std::map<std::string, std::pair<unsigned int, std::vector<float>>> sources;
        GLenum dataType;
        for(rapidxml::xml_node<> *source = meshNode->first_node("source"); source != 0; source = source->next_sibling("source")){
            std::vector<float> container;
            dataType = readData(&container, source);
            if(dataType == GL_NONE){
                return false;
            }
            sources.insert(std::pair<std::string, std::pair<unsigned int, std::vector<float>>>(source->first_attribute("id")->value(), std::pair<unsigned int, std::vector<float>>(std::stoi(source->first_node("technique_common")->first_node("accessor")->first_attribute("stride")->value()), container)));
        }
        
        //TODO: same data vertex merging (aka indexing)
        for(rapidxml::xml_node<> *polylist = meshNode->first_node("polylist"); polylist != 0; polylist = polylist->next_sibling("polylist")){
            std::vector<float> openglData;
            std::vector<unsigned int> indices;
            std::vector<std::string> tempContainer;
            std::vector<int> colladaIndices;        
            split(polylist->first_node("p")->value(), " ", &tempContainer);
            for(std::string s : tempContainer){
                colladaIndices.push_back(std::stoi(s));
            }
            std::vector<float> vertexData;
            float vertexOffset;
            float vertexStride;
            std::vector<float> normalData;
            float normalOffset;
            float normalStride;
            std::vector<float> uvData;
            float uvOffset;
            float uvStride;
            
            std::pair<unsigned int, std::vector<float>> pair;
            for(rapidxml::xml_node<> *input = polylist->first_node("input"); input != 0; input = input->next_sibling("input")){
                std::string semantic(input->first_attribute("semantic")->value());
                if(semantic == "VERTEX"){
                    pair = sources.at(std::string(meshNode->first_node("vertices")->first_node("input")->first_attribute("source")->value()).substr(1));
                    vertexData = pair.second;
                    vertexOffset = std::stoi(input->first_attribute("offset")->value());
                    vertexStride = pair.first;
                } else if(semantic == "NORMAL"){
                    pair = sources.at(std::string(input->first_attribute("source")->value()).substr(1));
                    normalData = pair.second;
                    normalOffset = std::stoi(input->first_attribute("offset")->value());
                    normalStride = pair.first;
                } else if(semantic == "TEXCOORD"){
                    pair = sources.at(std::string(input->first_attribute("source")->value()).substr(1));
                    uvData = pair.second;
                    uvOffset = std::stoi(input->first_attribute("offset")->value());
                    uvStride = pair.first;
                } else {
                    Logger::error << "Unknown input semantic: " << semantic << std::endl;
                    return 0;
                }
            }            
            PolyGroup poly;
            poly.elements = std::stoi(polylist->first_attribute("count")->value())*3;
            
            //Generate vertices
            for(unsigned int i = 0; i < poly.elements; i++){
                openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride));
                if(zup){
                    openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+2));
                    openglData.push_back(-vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+1));
                } else {
                    openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+1));
                    openglData.push_back(vertexData.at(colladaIndices.at(i*3+vertexOffset)*vertexStride+2));
                }

                openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride));
                if(zup){
                    openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+2));
                    openglData.push_back(-normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+1));
                } else {
                    openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+1));
                    openglData.push_back(normalData.at(colladaIndices.at(i*3+normalOffset)*normalStride+2));
                }

                openglData.push_back(uvData.at(colladaIndices.at(i*3+uvOffset)*uvStride));
                //collada stores the uv data the other way around. how silly.
                openglData.push_back(1.0f - uvData.at(colladaIndices.at(i*3+uvOffset)*uvStride+1));

                //temp index
                indices.push_back(i);
            }
            poly.vaoid = sendToOpengl(openglData, indices);
            poly.material = materials.at(polylist->first_attribute("material")->value());
            mesh.addPolyGroup(poly);
        }
        meshes.insert(std::pair<std::string, Mesh>(geometry->first_attribute("id")->value(), mesh));
        //this->meshes.insert(std::pair<std::string, std::pair<glm::mat4, Mesh>>(std::string(geometry->first_attribute("id")->value()).substr(1), std::pair<glm::mat4, Mesh>(glm::mat4(1.0f), mesh)));
    }
    
    //Load scene
    rapidxml::xml_node<> *scenes = doc.first_node()->first_node("library_visual_scenes");
    if(scenes->first_node("visual_scene") == 0){
        Logger::error << "Couldn't load model: file contains no scene data." << std::endl;
        return false;
    } else {
        rapidxml::xml_node<> *scene = scenes->first_node("visual_scene");
        for(rapidxml::xml_node<> *node = scene->first_node("node"); node != 0; node = node->next_sibling("node")){
            if(node->first_node("instance_geometry") != 0){
                std::vector<float> matrix;
                std::vector<std::string> tempContainer;
                glm::mat4 mat4 = glm::mat4(1.0f);
                if(node->first_node("matrix") == 0){
                    split(node->first_node("translate")->value(), " ", &tempContainer);
                    mat4 = glm::translate(mat4, glm::vec3(std::stof(tempContainer[0]), std::stof(tempContainer[2]), -std::stof(tempContainer[1])));
                    tempContainer.clear();
                    split(searchByAttribute(node, "sid", "rotationX", "rotate")->value(), " ", &tempContainer);
                    mat4 = glm::rotate(mat4, glm::radians(std::stof(tempContainer[3])), glm::vec3(1.0f, 0.0f, 0.0f));
                    tempContainer.clear();
                    split(searchByAttribute(node, "sid", "rotationZ", "rotate")->value(), " ", &tempContainer);
                    mat4 = glm::rotate(mat4, glm::radians(std::stof(tempContainer[3])), glm::vec3(0.0f, 1.0f, 0.0f));
                    tempContainer.clear();
                    split(searchByAttribute(node, "sid", "rotationY", "rotate")->value(), " ", &tempContainer);
                    mat4 = glm::rotate(mat4, glm::radians(std::stof(tempContainer[3])), glm::vec3(0.0f, 0.0f, -1.0f));
                    tempContainer.clear();
                    split(node->first_node("scale")->value(), " ", &tempContainer);
                    mat4 = glm::scale(mat4, glm::vec3(std::stof(tempContainer[0]), std::stof(tempContainer[2]), std::stof(tempContainer[1])));
                    //mat4 = glm::mat4(1.0f);
                } else {
                    split(node->first_node("matrix")->value(), " ", &tempContainer);
                    for(std::string s : tempContainer){
                        matrix.push_back(std::stof(s));
                    }
                    glm::mat4 mat4 = glm::make_mat4(matrix.data());
                    if(std::string(doc.first_node()->first_node("asset")->first_node("up_axis")->value()) == "Z_UP"){
                        mat4 = convertToRightHandedCoords(mat4);
                    }
                }
                this->meshes.insert(std::pair<std::string,std::pair<glm::mat4, Mesh>>(
                        node->first_attribute("id")->value(),
                        std::pair<glm::mat4, Mesh>(
                            mat4,
                            meshes.at(std::string(node->first_node("instance_geometry")->first_attribute("url")->value()).substr(1)))));
            }
        }
    }
    rapidjson::Document animDoc;
    if(readJsonFile(filename.substr(0, filename.find_last_of("/")+1) + "animation.json", animDoc)){
        rapidxml::xml_node<> *animations = doc.first_node()->first_node("library_animations");
        if(animations->first_node("animation") != 0){
            std::map<std::string, std::vector< std::pair<float, glm::vec3> > > locationKeyframes;
            std::map<std::string, std::vector< std::pair<float, glm::vec3> > > rotationKeyframes;
            for(rapidxml::xml_node<> *animNode = animations->first_node("animation"); animNode != 0; animNode = animNode->next_sibling("animation")){
                std::vector<float> inputContainer;
                readData(&inputContainer, searchByAttribute(
                        animNode,
                        "id",
                        std::string(searchByAttribute(
                            animNode->first_node("sampler"),
                            "semantic",
                            "INPUT",
                            "input"
                        )->first_attribute("source")->value()).substr(1),
                        "source"));
                std::vector<float> outputContainer;
                readData(&outputContainer, searchByAttribute(
                        animNode,
                        "id",
                        std::string(searchByAttribute(
                            animNode->first_node("sampler"),
                            "semantic",
                            "OUTPUT",
                            "input"
                        )->first_attribute("source")->value()).substr(1),
                        "source"));/*
                std::vector< std::pair<float, glm::vec3> > keyframes;
                for(int i = 0; i < inputContainer.size(); i++){
                    keyframes.push_back(std::pair<float, glm::vec3>(inputContainer.at(i), outputContainer.at(i)));
                }*/
                std::string target = animNode->first_node("channel")->first_attribute("target")->value();
                std::string meshName = target.substr(0, target.find_first_of("/"));
                if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-2) == "rotation"){
                    if(!rotationKeyframes.count(meshName)){
                        rotationKeyframes.insert(std::pair<std::string, std::vector< std::pair<float, glm::vec3> > >(meshName, std::vector< std::pair<float, glm::vec3> >()));
                    }
                    for(int i = 0; i < inputContainer.size(); i++){
                        if(rotationKeyframes.at(meshName).size() <= i){
                            rotationKeyframes.at(meshName).push_back(std::pair<float, glm::vec3>(inputContainer.at(i), glm::vec3(0.0f, 0.0f, 0.0f)));
                        }
                        if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-1) == "rotationX"){
                            rotationKeyframes.at(meshName).at(i).second.x = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-1) == "rotationY"){
                            rotationKeyframes.at(meshName).at(i).second.y = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")-target.find_first_of("/")-1) == "rotationZ"){
                            rotationKeyframes.at(meshName).at(i).second.z = outputContainer.at(i);
                        }
                    }
                } else if(target.substr(target.find_first_of("/")+1, target.find_first_of(".")) == "location"){
                    if(locationKeyframes.count(meshName)){
                        locationKeyframes.insert(std::pair<std::string, std::vector< std::pair<float, glm::vec3> > >(meshName, std::vector< std::pair<float, glm::vec3> >()));
                    }
                    for(int i = 0; i < inputContainer.size(); i++){
                        if(locationKeyframes.at(meshName).size() <= i){
                            locationKeyframes.at(meshName).push_back(std::pair<float, glm::vec3>(inputContainer.at(i), glm::vec3(0.0f, 0.0f, 0.0f)));
                        }
                        if(target.substr(target.find_first_of(".")+1) == "X"){
                            locationKeyframes.at(meshName).at(i).second.x = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of(".")+1) == "Y"){
                            locationKeyframes.at(meshName).at(i).second.y = outputContainer.at(i);
                        } else if(target.substr(target.find_first_of(".")+1) == "Z"){
                            locationKeyframes.at(meshName).at(i).second.z = outputContainer.at(i);
                        }
                    }
                } else {
                    Logger::info << "unknown animation target: " << target << std::endl;
                }
            }
            for (rapidjson::SizeType i = 0; i < animDoc.Size(); i++) {
                Animation animation;
                rapidjson::Value& animjson = animDoc[i];
                animation.mesh = animjson["mesh"].GetString();
                int start = animjson["startKeyframe"].GetInt();
                int end = animjson["endKeyframe"].GetInt();
                for(int j = start; j <= end; j++){
                    glm::mat4 mat4 = this->meshes.at(animation.mesh).first;
                    glm::vec3 rotation = rotationKeyframes.count(animation.mesh) ? rotationKeyframes.at(animation.mesh).at(j).second : glm::vec3(0.0f, 0.0f, 0.0f);
                    glm::vec3 translation = locationKeyframes.count(animation.mesh) ? locationKeyframes.at(animation.mesh).at(j).second : glm::vec3(0.0f, 0.0f, 0.0f);
                    if(zup){
                        mat4 = glm::translate(mat4, glm::vec3(translation.x, translation.z, -translation.y));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.z), glm::vec3(0.0f, 1.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.y), glm::vec3(0.0f, 0.0f, -1.0f));
                    } else {
                        mat4 = glm::translate(mat4, glm::vec3(translation.x, translation.y, translation.z));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f));
                        mat4 = glm::rotate(mat4, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f));
                    }
                    animation.keyframes.push_back(std::make_pair(rotationKeyframes.at(animation.mesh).at(j).first, mat4));
                }
                this->animations.insert(std::make_pair(animjson["name"].GetString(), animation));
            }
        }
    }
    return true;
}