Beispiel #1
0
bool EAE_Engine::Time::Initialize( std::string* o_errorMessage )
{
	bool wereThereErrors = false;

	// Get the frequency of the high-resolution performance counter
	{
		LARGE_INTEGER countsPerSecond;
		if ( QueryPerformanceFrequency( &countsPerSecond ) != FALSE )
		{
			if ( countsPerSecond.QuadPart != 0 )
			{
				s_secondsPerCount = 1.0 / static_cast<double>( countsPerSecond.QuadPart );
			}
			else
			{
				wereThereErrors = true;
				if ( o_errorMessage )
				{
					*o_errorMessage = "This hardware doesn't support high resolution performance counters!";
				}
				goto OnExit;
			}
		}
		else
		{
			wereThereErrors = true;
			if ( o_errorMessage )
			{
				*o_errorMessage = GetLastWindowsError();
			}
			goto OnExit;
		}
	}
	// Store how many counts have elapsed so far
	if ( QueryPerformanceCounter( &s_totalCountsElapsed_atInitializion ) == FALSE )
	{
		wereThereErrors = true;
		if ( o_errorMessage )
		{
			*o_errorMessage = GetLastWindowsError();
		}
		goto OnExit;
	}
	s_isInitialized = true;
	
	// We also need to init the s_fixedUpdateAccumulatTime
	s_fixedUpdateAccumulatTime = 0.0f;
	s_fixedUpdateRunTimesOnThisFrame = 0;
	s_fixedUpdateBlendAlphaOnThisFrame = 0.0f;

OnExit:

	return !wereThereErrors;
}
int AssetBuilder::DoesFileExist(lua_State* io_luaState)
{
	const char* i_FilePath;
	{
		if (lua_isstring(io_luaState, 1))
		{
			i_FilePath = lua_tostring(io_luaState, 1);
		}
		else
		{
			return luaL_error(io_luaState,
				"Argument #1 must be a string (instead of a %s)",
				luaL_typename(io_luaState, 1));
		}
	}

	// Try to get information about the file
	WIN32_FIND_DATA fileData;
	HANDLE file = FindFirstFile(i_FilePath, &fileData);
	if (file != INVALID_HANDLE_VALUE)
	{
		if (FindClose(file) != FALSE)
		{
			lua_pushboolean(io_luaState, true);
			int returnValueCount = 1;
			return returnValueCount;
		}
		else
		{
			std::stringstream errorMessage; 
			errorMessage << GetLastWindowsError().c_str() << i_FilePath;
			return luaL_error(io_luaState, errorMessage.str().c_str());
		}
	}
	else
	{
		DWORD errorCode;
		std::string errorMessage = GetLastWindowsError(&errorCode);
		if ((errorCode == ERROR_FILE_NOT_FOUND) || (errorCode == ERROR_PATH_NOT_FOUND))
		{
			int returnValueCount = 1;
			lua_pushboolean(io_luaState, false);
			return returnValueCount;
		}
		else
		{
			std::stringstream errorMessage;
			errorMessage << GetLastWindowsError().c_str() << i_FilePath;
			return luaL_error(io_luaState, errorMessage.str().c_str());
		}
	}
}
int AssetBuilder::GetLastWriteTime(lua_State* io_luaState)
{
	//Argument#1: The path
	const char * i_path;
	{
		if (lua_isstring(io_luaState, 1))
		{
			i_path = lua_tostring(io_luaState, 1);
		}
		else
		{
			return luaL_error(io_luaState, "Argument#1 should be of type string (instead of %s)", 
								luaL_typename(io_luaState, 1));
		}
	}

	// Get the last time that the file was written to
	ULARGE_INTEGER lastWriteTime_int;
	{
		WIN32_FIND_DATA fileData;
		{
			HANDLE file = FindFirstFile( i_path, &fileData );
			if ( file != INVALID_HANDLE_VALUE )
			{
				if ( FindClose( file ) == FALSE )
				{
					std::stringstream errorMessage;
					errorMessage << GetLastWindowsError() << i_path;
					return luaL_error(io_luaState, errorMessage.str().c_str());
				}
			}
			else
			{
				std::stringstream errorMessage;
				errorMessage << GetLastWindowsError() << i_path;
				return luaL_error(io_luaState, errorMessage.str().c_str());
			}
		}
		FILETIME fileTime = fileData.ftLastWriteTime;
		lastWriteTime_int.HighPart = fileTime.dwHighDateTime;
		lastWriteTime_int.LowPart = fileTime.dwLowDateTime;
	}

	const lua_Number lastWriteTime = static_cast<lua_Number>(lastWriteTime_int.QuadPart);
	lua_pushnumber(io_luaState, lastWriteTime);

	int returnValueCount = 1;
	return returnValueCount;
}
	bool Sprite::LoadTextureAndSamplerRegister(const char* iTexturePath, const char* iSamplerName, IDirect3DDevice9 * i_direct3dDevice
#ifdef EAE2014_SHOULDALLRETURNVALUESBECHECKED
		, std::string* o_errorMessage
#endif
		)
	{
		assert(i_direct3dDevice && iTexturePath && iSamplerName);

		bool WereThereErrors = false;

		HRESULT result = D3DXCreateTextureFromFile(i_direct3dDevice, iTexturePath, &m_texture);

		if (FAILED(result))
		{
			WereThereErrors = true;
#ifdef EAE2014_SHOULDALLRETURNVALUESBECHECKED
			if (o_errorMessage)
			{
				std::stringstream errorMessage;
				errorMessage << "Failed to load texture: " << GetLastWindowsError();
				*o_errorMessage = errorMessage.str();
			}
#endif
			goto OnExit;
		}

		D3DXHANDLE samplerHandle = m_pfragmentShaderConsts->GetConstantByName(NULL, iSamplerName);

		if (samplerHandle == NULL)
		{
			WereThereErrors = true;
#ifdef EAE2014_SHOULDALLRETURNVALUESBECHECKED
			if (o_errorMessage)
			{
				std::stringstream errorMessage;
				errorMessage << "Failed to get Constant by name: " << GetLastWindowsError();
				*o_errorMessage = errorMessage.str();
			}
#endif
			goto OnExit;
		}

		m_samplerRegister = static_cast<DWORD>(m_pfragmentShaderConsts->GetSamplerIndex(samplerHandle));

	OnExit:
		return !WereThereErrors;
	}
bool AssetBuilder::GetAssetBuilderEnvironmentVariable(const char* i_key, std::string& o_value)
{
	// Windows requires a character buffer
	// to copy the environment variable into.
	// An arbitrary value is chosen that "should" be "big enough":
	const DWORD maxCharacterCount = 512;
	char buffer[maxCharacterCount];
	// Ask Windows for the environment variable
	const DWORD characterCount = GetEnvironmentVariable( i_key, buffer, maxCharacterCount );
	if ( characterCount > 0 )
	{
		if ( characterCount <= maxCharacterCount )
		{
			o_value = buffer;
			return true;
		}
		else
		{
			// If you're seeing this error you will need to increase maxCharacterCount
			std::stringstream errorMessage;
			errorMessage << "The environment variable \"" << i_key << "\" requires " << characterCount <<
				" characters and the provided buffer only has room for " << maxCharacterCount;
			OutputErrorMessage( errorMessage.str().c_str() );
			return false;
		}
	}
	else
	{
		DWORD errorCode;
		std::string errorString = GetLastWindowsError( &errorCode );
		if ( errorCode == ERROR_ENVVAR_NOT_FOUND )
		{
			// If you're seeing this error and the environment variable is spelled correctly
			// it _probably_ means that you are debugging and haven't set up the environment.
			//	* Right click the project name and choose "Properties"
			//	* In the tree view to the left select "Configuration Properties->Debugging"
			//	* In the "Environment" field make sure that you have this environment variable set like:
			//		* someKey=$(someKey)
			std::string errorMessage = std::string( "The environment variable \"" ) +
				i_key + "\" doesn't exist";
			OutputErrorMessage( errorMessage.c_str() );
		}
		else
		{
			std::string errorMessage = std::string( "Windows failed to get the environment variable \"" ) +
				i_key + "\": " + errorString;
			OutputErrorMessage( errorMessage.c_str() );
		}
		return false;
	}
}
int AssetBuilder::CopyAssetFile(lua_State* io_luaState)
{
	// Argument #1: The source path
	const char* i_path_source;
	{
		if (lua_isstring(io_luaState, 1))
		{
			i_path_source = lua_tostring(io_luaState, 1);
		}
		else
		{
			return luaL_error(io_luaState, "Argument#1 should of string type, (instead of a %s)", luaL_typename(io_luaState, 1));
		}
	}

	// Argument #2: The target path
	const char* i_path_target;
	{
		if (lua_isstring(io_luaState, 2))
		{
			i_path_target = lua_tostring(io_luaState, 2);
		}
		else
		{
			return luaL_error(io_luaState, "Argument#2 should of string type, (instead of a %s)", luaL_typename(io_luaState, 2));
		}
	}

	// Copy the file
	const BOOL noErrorIfTargetFileAlreadyExists = FALSE;
	if (CopyFile(i_path_source, i_path_target, noErrorIfTargetFileAlreadyExists) != FALSE)
	{
		lua_pushboolean(io_luaState, true); // If successful, return a boolean "true"
		int returnValueCount = 1;

		return returnValueCount;
	}
	else
	{
		const std::string errorMessage = GetLastWindowsError();
		return luaL_error(io_luaState, errorMessage.c_str());	// On failure, return a boolean "false" _and_ the error message

	}

	int returnValueCount = 0;
	return returnValueCount;
}
bool Tools::cEntityBuilder::Build_derived( const char* i_fileName_source, const char* i_fileName_target ) const
{
	// For now textures don't get "built";
	// instead, copy the source texture as-is to the target
	BOOL shouldFailIfDestinationFileAlreadyExists = FALSE;
	if ( CopyFile( i_fileName_source, i_fileName_target, shouldFailIfDestinationFileAlreadyExists ) == TRUE )
	{
		return true;
	}
	else
	{
		std::string errorMessage = std::string( "Couldn't copy " ) + i_fileName_source + " to " + i_fileName_target + ":  "
			+ GetLastWindowsError();
		FormatAndOutputErrorMessage( errorMessage );
		return false;
	}
}
Beispiel #8
0
/**
 ****************************************************************************************************
	\fn			bool Destroy( void )
	\brief		Destroy the window
	\param		NONE
	\return		boolean
	\retval		SUCCESS success
	\retval		FAIL otherwise
 ****************************************************************************************************
*/
bool RendererEngine::Window::Destroy( void )
{
	bool bErrorFound = FAIL;

	// If the window is created outside, then no need to destroy it here
	if( !_applicationInstance )
		return SUCCESS;

	if ( _window )
	{
		if ( DestroyWindow( _window ) == SUCCESS )
			LogMessage( "Destroyed the main window" );
		else
		{
			LogMessage( std::string( "Windows failed to destroy the main window: " ) + GetLastWindowsError() );
			bErrorFound = SUCCESS;
		}
		_window = NULL;
	}

	return !bErrorFound;
}
bool eae6320::Graphics::ShutDown()
{
	bool wereThereErrors = false;

	if ( s_openGlRenderingContext != NULL )
	{
		ReleaseObjects();

		if ( wglMakeCurrent( s_deviceContext, NULL ) != FALSE )
		{
			if ( wglDeleteContext( s_openGlRenderingContext ) == FALSE )
			{
				std::stringstream errorMessage;
				errorMessage << "Windows failed to delete the OpenGL rendering context: " << GetLastWindowsError();
				UserOutput::Print( errorMessage.str() );
			}
		}
		else
		{
			std::stringstream errorMessage;
			errorMessage << "Windows failed to unset the current OpenGL rendering context: " << GetLastWindowsError();
			UserOutput::Print( errorMessage.str() );
		}
		s_openGlRenderingContext = NULL;
	}

	if ( s_deviceContext != NULL )
	{
		// The documentation says that this call isn't necessary when CS_OWNDC is used
		ReleaseDC( s_renderingWindow, s_deviceContext );
		s_deviceContext = NULL;
	}

	s_renderingWindow = NULL;

	return !wereThereErrors;
}
Beispiel #10
0
/**
 ****************************************************************************************************
	\fn			bool Build_derived( const char* i_fileName_source, const char* i_fileName_target ) const
	\brief		Output input file
	\param		i_fileName_source name of source file
	\param		i_fileName_targe name of target file
	\return		NONE

	\date		15 February 2013
	\author		Sherly Yunita \n
				Rewrite to output as binary data \n
				\n\n

	\date		1 March 2013
	\author		Sherly Yunita \n
				Get tangents and biNormal data \n
				\n\n
****************************************************************************************************
*/
bool Tools::cMeshBuilder::Build_derived( const char* i_fileName_source, const char* i_fileName_target ) const
{
	// For now mesh don't get "built";
	// instead, copy the source mesh as-is to the target
	/* Sherly 15 February 2013 marked
	BOOL shouldFailIfDestinationFileAlreadyExists = FALSE;
	if ( CopyFile( i_fileName_source, i_fileName_target, shouldFailIfDestinationFileAlreadyExists ) == TRUE )
	{
		return true;
	}
	else
	{
		std::string errorMessage = std::string( "Couldn't copy " ) + i_fileName_source + " to " + i_fileName_target + ":  "
			+ GetLastWindowsError();
		FormatAndOutputErrorMessage( errorMessage );
		return false;
	}*/

	ParserHelper parserHelper;

	std::ifstream in;
	std::ofstream out;

	in.open( i_fileName_source );
	if( in.fail() )
	{
		std::string errorMessage = std::string( "Couldn't open source file " ) + i_fileName_source + ":  " + GetLastWindowsError();
		FormatAndOutputErrorMessage( errorMessage );
		return false;
	}

	out.open( i_fileName_target, std::ios::binary );
	if( out.fail() )
	{
		std::string errorMessage = std::string( "Couldn't create target file " ) + i_fileName_target + ":  "
			+ GetLastWindowsError();
		FormatAndOutputErrorMessage( errorMessage );
		return false;
	}

	typedef struct _s_vertex_
	{
		Parser::S_FLOAT3 position;
		Parser::S_FLOAT3 normal;
		Parser::S_FLOAT3 tangent;	// Sherly 1 March 2013 added
		Parser::S_FLOAT3 biNormal;	// Sherly 1 March 2013 added
		Parser::S_FLOAT2 texcoord;
		unsigned int colour;
	} S_VERTEX;

	char chInput[MAX_INPUT_LEN];
	bool validArrayData = false;
	UINT32 totalVertices;
	UINT32 totalPrimitives;
	std::vector<uint16_t> index;
	std::vector<S_VERTEX> vertex;
	S_VERTEX tempVertex = {
		{ 0.0f, 0.0f, 0.0f },
		{ 0.0f, 0.0f, 0.0f },
		{ 0.0f, 0.0f, 0.0f },
		{ 0.0f, 0.0f, 0.0f },
		{ 0.0f, 0.0f },
		0
	};
	Parser::E_INPUT_TYPE currMajorData = Parser::E_INPUT_TYPE_TOTAL;
	Parser::E_INPUT_TYPE currMinorType = Parser::E_INPUT_TYPE_TOTAL;

	in.getline( &chInput[0], MAX_INPUT_LEN );
	parserHelper.CleanInputString( chInput );

	do
	{
		// Skip comment
		if( chInput[0] == '/' && chInput[1] == '/' )
		{
			in.getline( &chInput[0], MAX_INPUT_LEN );
			parserHelper.CleanInputString( chInput );
		}

		// Check for tags
		// {
		if( chInput[0] == '<' )
		{
			// Closing tag
			if( chInput[1] == '/' )
			{
				char *tagStr;
				char *nextToken = NULL;
				tagStr = strtok_s( chInput, "</>", &nextToken );

				Parser::E_INPUT_TYPE currInputType = parserHelper.SetInputType( tagStr );
				
				if( currMajorData == currInputType )
				{
					currMajorData = Parser::E_INPUT_TYPE_TOTAL;
					currMinorType = Parser::E_INPUT_TYPE_TOTAL;
				}
				else if( currMinorType == currInputType )
				{
					currMinorType = Parser::E_INPUT_TYPE_TOTAL;
				}
				else
				{
					FormatAndOutputErrorMessage( "Invalid closing tag" );
					return false;
				}
			}
			// Start tag
			else
			{
				char *tagStr;
				char *nextToken = NULL;
				tagStr = strtok_s( chInput, "</>", &nextToken );

				Parser::E_INPUT_TYPE currInputType = parserHelper.SetInputType( tagStr );

				if( (currInputType == Parser::E_TYPE_VERTEX)
					|| (currInputType == Parser::E_TYPE_INDEX)
					)
				{
					currMajorData = currInputType;

					in.getline( &chInput[0], MAX_INPUT_LEN );
					parserHelper.CleanInputString( chInput );

					if( currMajorData == Parser::E_TYPE_VERTEX )
					{
						totalVertices = atoi( chInput );
					}
					else
					{
						totalPrimitives = atoi( chInput );
						totalPrimitives /= 3;
					}
				}
				else
				{
					currMinorType = currInputType;
				}
			}
		}
		// }
		else
		{
			switch( currMajorData )
			{
			case Parser::E_TYPE_VERTEX:
				if( strcmp(chInput, "}") == 0 )
				{
					if( validArrayData )
					{
						vertex.push_back( tempVertex );
						validArrayData = false;
					}
					else
					{
						FormatAndOutputErrorMessage( "Invalid array data" );
						return false;
					}
					break;
				}
				else if( strcmp(chInput, "{") == 0 )
				{
					validArrayData = true;
					break;
				}

				if( validArrayData )
				{
					switch( currMinorType )
					{
					case Parser::E_TYPE_POSITION:
						tempVertex.position = parserHelper.ParseVector3Input( chInput );	break;

					case Parser::E_TYPE_NORMAL:
						tempVertex.normal = parserHelper.ParseVector3Input( chInput );	break;

					// Sherly 1 March 2013 added
					// {
					case Parser::E_TYPE_TANGENT:
						tempVertex.tangent = parserHelper.ParseVector3Input( chInput ); break;

					case Parser::E_TYPE_BI_NORMAL:
						tempVertex.biNormal = parserHelper.ParseVector3Input( chInput ); break;
					// }

					case Parser::E_TYPE_UV:
						tempVertex.texcoord = parserHelper.ParseVector2Input( chInput );	break;

					case Parser::E_TYPE_COLOUR:
						tempVertex.colour = parserHelper.ParseColourInput( chInput );	break;
					}
				}
				break;

			case Parser::E_TYPE_INDEX:
				char *token = NULL;
				char *nextToken = NULL;

				token = strtok_s( chInput, ",", &nextToken );
				index.push_back( atoi(token) );

				token = strtok_s( NULL, ",", &nextToken );
				index.push_back( atoi(token) );

				token = strtok_s( NULL, " ", &nextToken );
				index.push_back( atoi(token) );
				nextToken = NULL;
				break;
			}
		}

		in.getline( &chInput[0], MAX_INPUT_LEN );
		parserHelper.CleanInputString( chInput );
	} while( !in.eof() );

	out.write( reinterpret_cast <const char*> (&totalVertices), sizeof(totalVertices) );
	out.write( reinterpret_cast <const char*> (&totalPrimitives), sizeof(totalPrimitives) );
	for( unsigned int i = 0; i < totalVertices; i++ )
		out.write( reinterpret_cast <const char*> (&vertex[i]), sizeof(S_VERTEX) );
	for( unsigned int i = 0; i < index.size(); i++ )
		out.write( reinterpret_cast <const char*>(&index[i]), sizeof(uint16_t) );

	in.close();
	out.close();

	return true;
}
Beispiel #11
0
	bool Materials::LoadTexture(const char* const i_path, GLuint& o_texture, std::string* o_errorMessage)
	{
		bool wereThereErrors = false;
		HANDLE fileHandle = INVALID_HANDLE_VALUE;
		void* fileContents = NULL;
		o_texture = 0;

		// Open the texture file
		{
			const DWORD desiredAccess = FILE_GENERIC_READ;
			const DWORD otherProgramsCanStillReadTheFile = FILE_SHARE_READ;
			SECURITY_ATTRIBUTES* useDefaultSecurity = NULL;
			const DWORD onlySucceedIfFileExists = OPEN_EXISTING;
			const DWORD useDefaultAttributes = FILE_ATTRIBUTE_NORMAL;
			const HANDLE dontUseTemplateFile = NULL;
			fileHandle = CreateFile(i_path, desiredAccess, otherProgramsCanStillReadTheFile,
				useDefaultSecurity, onlySucceedIfFileExists, useDefaultAttributes, dontUseTemplateFile);
			if (fileHandle == INVALID_HANDLE_VALUE)
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					std::string windowsErrorMessage(GetLastWindowsError());
					std::stringstream errorMessage;
					errorMessage << "Windows failed to open the texture file: " << windowsErrorMessage;
					*o_errorMessage = errorMessage.str();
				}
				goto OnExit;
			}
		}
		// Get the file's size
		size_t fileSize;
		{
			LARGE_INTEGER fileSize_integer;
			if (GetFileSizeEx(fileHandle, &fileSize_integer) != FALSE)
			{
				assert(fileSize_integer.QuadPart <= SIZE_MAX);
				fileSize = static_cast<size_t>(fileSize_integer.QuadPart);
			}
			else
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					std::string windowsErrorMessage(GetLastWindowsError());
					std::stringstream errorMessage;
					errorMessage << "Windows failed to get the size of the texture file: " << windowsErrorMessage;
					*o_errorMessage = errorMessage.str();
				}
				goto OnExit;
			}
		}
		// Read the file's contents into temporary memory
		fileContents = malloc(fileSize);
		if (fileContents)
		{
			DWORD bytesReadCount;
			OVERLAPPED* readSynchronously = NULL;
			assert(fileSize < (uint64_t(1) << (sizeof(DWORD) * 8)));
			if (ReadFile(fileHandle, fileContents, static_cast<DWORD>(fileSize),
				&bytesReadCount, readSynchronously) == FALSE)
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					std::string windowsErrorMessage(GetLastWindowsError());
					std::stringstream errorMessage;
					errorMessage << "Windows failed to read the contents of the texture file: " << windowsErrorMessage;
					*o_errorMessage = errorMessage.str();
				}
				goto OnExit;
			}
		}
		else
		{
			wereThereErrors = true;
			if (o_errorMessage)
			{
				std::stringstream errorMessage;
				errorMessage << "Failed to allocate " << fileSize << " bytes to read in the texture " << i_path;
				*o_errorMessage = errorMessage.str();
			}
			goto OnExit;
		}

		// Create a new texture and make it active
		{
			const GLsizei textureCount = 1;
			glGenTextures(textureCount, &o_texture);
			const GLenum errorCode = glGetError();
			if (errorCode == GL_NO_ERROR)
			{
				// This code only supports 2D textures;
				// if you want to support other types you will need to improve this code.
				glBindTexture(GL_TEXTURE_2D, o_texture);
				const GLenum errorCode = glGetError();
				if (errorCode != GL_NO_ERROR)
				{
					wereThereErrors = true;
					if (o_errorMessage)
					{
						std::stringstream errorMessage;
						errorMessage << "OpenGL failed to bind a new texture: " <<
							reinterpret_cast<const char*>(gluErrorString(errorCode));
						*o_errorMessage = errorMessage.str();
					}
					goto OnExit;
				}
			}
			else
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					std::stringstream errorMessage;
					errorMessage << "OpenGL failed to get an unused texture ID: " <<
						reinterpret_cast<const char*>(gluErrorString(errorCode));
					*o_errorMessage = errorMessage.str();
				}
				goto OnExit;
			}
		}

		// Extract the data
		const uint8_t* currentPosition = reinterpret_cast<uint8_t*>(fileContents);
		// Verify that the file is a valid DDS
		{
			const size_t fourCcCount = 4;
			const uint8_t* const fourCc = currentPosition;
			const uint8_t fourCc_dds[fourCcCount] = { 'D', 'D', 'S', ' ' };
			// Each of the four characters can be compared in a single operation by casting to a uint32_t
			const bool isDds = *reinterpret_cast<const uint32_t*>(fourCc) == *reinterpret_cast<const uint32_t*>(fourCc_dds);
			if (isDds)
			{
				currentPosition += fourCcCount;
			}
			else
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					char fourCcString[fourCcCount + 1] = { 0 };	// Add NULL terminator
					memcpy(fourCcString, currentPosition, fourCcCount);
					std::stringstream errorMessage;
					errorMessage << "The texture file \"" << i_path << "\" isn't a valid DDS. The Four CC is \"" << fourCcString << "\""
						" instead of \"DDS \"";
					*o_errorMessage = errorMessage.str();
				}
				goto OnExit;
			}
		}
		// Extract the header
		// (this struct can also be found in Dds.h in the DirectX header files
		// or here as of this comment: https://msdn.microsoft.com/en-us/library/windows/desktop/bb943982(v=vs.85).aspx )
		struct sDdsHeader
		{
			uint32_t structSize;
			uint32_t flags;
			uint32_t height;
			uint32_t width;
			uint32_t pitchOrLinearSize;
			uint32_t depth;
			uint32_t mipMapCount;
			uint32_t reserved1[11];
			struct
			{
				uint32_t structSize;
				uint32_t flags;
				uint8_t fourCc[4];
				uint32_t rgbBitCount;
				uint32_t bitMask_red;
				uint32_t bitMask_green;
				uint32_t bitMask_blue;
				uint32_t bitMask_alpha;
			} pixelFormat;
			uint32_t caps[4];
			uint32_t reserved2;
		};
		const sDdsHeader* ddsHeader = reinterpret_cast<const sDdsHeader*>(currentPosition);
		currentPosition += sizeof(sDdsHeader);
		// Convert the DDS format into an OpenGL format
		GLenum format;
		{
			// This code can only handle the two basic formats that the example TextureBuilder will create.
			// If a DDS in a different format is provided to TextureBuilder it will be passed through unchanged
			// and this code won't work.
			// Similarly, if you improve the example TextureBuilder to support more formats
			// you will also have to update this code to support them.
			const uint8_t fourCc_dxt1[] = { 'D', 'X', 'T', '1' };	// No alpha channel
			const uint8_t fourCc_dxt5[] = { 'D', 'X', 'T', '5' };	// Alpha channel
			const uint32_t fourCc_texture = *reinterpret_cast<const uint32_t*>(ddsHeader->pixelFormat.fourCc);
			if (fourCc_texture == *reinterpret_cast<const uint32_t*>(fourCc_dxt1))
			{
				format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
			}
			else if (fourCc_texture == *reinterpret_cast<const uint32_t*>(fourCc_dxt5))
			{
				format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
			}
			else
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					char fourCcString[5] = { 0 };	// Add NULL terminator
					memcpy(fourCcString, ddsHeader->pixelFormat.fourCc, 4);
					std::stringstream errorMessage;
					errorMessage << "The texture file \"" << i_path << "\" has an unsupported format \"" << fourCcString << "\"";
					*o_errorMessage = errorMessage.str();
				}
				goto OnExit;
			}
		}
		// Iterate through each MIP map level and fill in the OpenGL texture
		{
			GLsizei currentWidth = ddsHeader->width;
			GLsizei currentHeight = ddsHeader->height;
			const GLsizei blockSize = format == GL_COMPRESSED_RGB_S3TC_DXT1_EXT ? 8 : 16;
			const GLint borderWidth = 0;
			for (uint32_t mipMapLevel = 0; mipMapLevel < ddsHeader->mipMapCount; ++mipMapLevel)
			{
				const GLsizei mipMapSize = ((currentWidth + 3) / 4) * ((currentHeight + 3) / 4) * blockSize;
				glCompressedTexImage2D(GL_TEXTURE_2D, static_cast<GLint>(mipMapLevel), format, currentWidth, currentHeight,
					borderWidth, mipMapSize, currentPosition);
				const GLenum errorCode = glGetError();
				if (errorCode == GL_NO_ERROR)
				{
					currentPosition += static_cast<size_t>(mipMapSize);
					currentWidth = std::max(1, (currentWidth / 2));
					currentHeight = std::max(1, (currentHeight / 2));
				}
				else
				{
					wereThereErrors = true;
					if (o_errorMessage)
					{
						std::stringstream errorMessage;
						errorMessage << "OpenGL rejected compressed texture data: " <<
							reinterpret_cast<const char*>(gluErrorString(errorCode));
						*o_errorMessage = errorMessage.str();
					}
					goto OnExit;
				}
			}
		}

		assert(currentPosition == (reinterpret_cast<uint8_t*>(fileContents) + fileSize));

	OnExit:

		if (fileContents != NULL)
		{
			free(fileContents);
			fileContents = NULL;
		}
		if (fileHandle != INVALID_HANDLE_VALUE)
		{
			if (CloseHandle(fileHandle) == FALSE)
			{
				wereThereErrors = true;
				if (o_errorMessage)
				{
					std::string windowsErrorMessage(GetLastWindowsError());
					std::stringstream errorMessage;
					errorMessage << "\nWindows failed to close the texture file handle: " << windowsErrorMessage;
					*o_errorMessage += errorMessage.str();
				}
			}
			fileHandle = INVALID_HANDLE_VALUE;
		}
		if (wereThereErrors && (o_texture != 0))
		{
			const GLsizei textureCount = 1;
			glDeleteTextures(textureCount, &o_texture);
			assert(glGetError == GL_NO_ERROR);
			o_texture = 0;
		}

		return !wereThereErrors;
	}
int AssetBuilder::CreateDirectoryIfNecessary(lua_State* io_luaState)
{
	// Argument #1: The path
	std::string i_path;
	{
		if (lua_isstring(io_luaState, 1))
		{
			i_path = lua_tostring(io_luaState, 1);
		}
		else
		{
			return luaL_error(io_luaState, "Argument#1 should of string type, (instead of a %s)", luaL_typename(io_luaState, 1));
		}
	}

	// If the path is to a file (likely), remove it so that only the directory remains
	std::string directory;
	{
		size_t pos_slash = i_path.find_last_of("\\/");
		if (pos_slash != std::string::npos)
		{
			directory = i_path.substr(0, pos_slash);
		}
		else
		{
			directory = i_path;
		}
	}

	// Get the path in a form Windows likes (without any ".."s).
	// Windows requires a character buffer
	// to copy the path variable into.
	// An arbitrary value is chosen that "should" be "big enough":
	const DWORD maxCharacterCount = MAX_PATH;
	char buffer[maxCharacterCount];
	{
		char** pathIsDirectory = NULL;
		DWORD characterCount = GetFullPathName(directory.c_str(), maxCharacterCount, buffer, pathIsDirectory);
		if (characterCount > 0)
		{
			if (characterCount <= maxCharacterCount)
			{
				// Create the directory
				int result;
				{
					HWND noWindowIsDisplayed = NULL;
					const SECURITY_ATTRIBUTES* useDefaultSecurityAttributes = NULL;
					result = SHCreateDirectoryEx(noWindowIsDisplayed, buffer, useDefaultSecurityAttributes);
				}
				if (result == ERROR_SUCCESS)
				{
					std::cout << "Created directory " << buffer << "\n";
					int returnValueCount = 0;
					return returnValueCount;
				}
				else if ((result == ERROR_FILE_EXISTS) || (result == ERROR_ALREADY_EXISTS))
				{
					// If the file already exists that's ok,
					// still don't return anything but don't print a message
					int returnValueCount = 0;
					return returnValueCount;
				}
				else
				{
					const std::string errorMessage = GetFormattedWindowsError(result);
					return luaL_error(io_luaState, errorMessage.c_str());	// Throw an error
				}
			}
			else
			{
				// If you're seeing this error you will need to increase maxCharacterCount
				std::stringstream errorMessage;
				errorMessage << "The full path of \"" << directory << "\" requires " << characterCount <<
					" characters and the provided buffer only has room for " << maxCharacterCount;
				return luaL_error(io_luaState, errorMessage.str().c_str());	// Throw an error
			}
		}
		else
		{
			const std::string errorMessage = GetLastWindowsError();
			return luaL_error(io_luaState, errorMessage.c_str());	// Throw an error
		}
	}
}
bool eae6320::Graphics::ShutDown()
{
	bool wereThereErrors = false;

	if ( s_openGlRenderingContext != NULL )
	{
		if ( s_programId != 0 )
		{
			glDeleteProgram( s_programId );
			const GLenum errorCode = glGetError();
			if ( errorCode != GL_NO_ERROR )
			{
				std::stringstream errorMessage;
				errorMessage << "OpenGL failed to delete the program: " <<
					reinterpret_cast<const char*>( gluErrorString( errorCode ) );
				UserOutput::Print( errorMessage.str() );
			}
			s_programId = 0;
		}
		if ( s_vertexArrayId != 0 )
		{
			const GLsizei arrayCount = 1;
			glDeleteVertexArrays( arrayCount, &s_vertexArrayId );
			const GLenum errorCode = glGetError();
			if ( errorCode != GL_NO_ERROR )
			{
				std::stringstream errorMessage;
				errorMessage << "OpenGL failed to delete the vertex array: " <<
					reinterpret_cast<const char*>( gluErrorString( errorCode ) );
				UserOutput::Print( errorMessage.str() );
			}
			s_vertexArrayId = 0;
		}

		if ( wglMakeCurrent( s_deviceContext, NULL ) != FALSE )
		{
			if ( wglDeleteContext( s_openGlRenderingContext ) == FALSE )
			{
				std::stringstream errorMessage;
				errorMessage << "Windows failed to delete the OpenGL rendering context: " << GetLastWindowsError();
				UserOutput::Print( errorMessage.str() );
			}
		}
		else
		{
			std::stringstream errorMessage;
			errorMessage << "Windows failed to unset the current OpenGL rendering context: " << GetLastWindowsError();
			UserOutput::Print( errorMessage.str() );
		}
		s_openGlRenderingContext = NULL;
	}

	if ( s_deviceContext != NULL )
	{
		// The documentation says that this call isn't necessary when CS_OWNDC is used
		ReleaseDC( s_renderingWindow, s_deviceContext );
		s_deviceContext = NULL;
	}

	s_renderingWindow = NULL;

	return !wereThereErrors;
}
Beispiel #14
0
/**
 ****************************************************************************************************
	\fn			bool UnregisterClass( void )
	\brief		Unregister window class
	\param		NONE
	\return		boolean
	\retval		SUCCESS success
	\retval		FAIL otherwise
 ****************************************************************************************************
*/
bool RendererEngine::Window::UnregisterClass( void )
{
	bool bErrorFound = FAIL;

	if ( _class )
	{
		if ( ::UnregisterClass( _windowName, _applicationInstance ) == SUCCESS )
		{
			LogMessage( "Unregistered the main window class" );
		}
		else
		{
			LogMessage( std::string( "Windows failed to unregister the main window's class: " ) + GetLastWindowsError() );
		}
		_class = NULL;
	}

	return !bErrorFound;
}
Beispiel #15
0
/**
 ****************************************************************************************************
	\fn			bool RegisterClass( void )
	\brief		Register the window class
	\param		NONE
	\return		boolean
	\retval		SUCCESS success
	\retval		FAIL otherwise
 ****************************************************************************************************
*/
bool RendererEngine::Window::RegisterClass( void )
{
	WNDCLASSEX wndClassEx = { 0 };
	wndClassEx.cbSize = sizeof( WNDCLASSEX );
	wndClassEx.hInstance = _applicationInstance;

	// The class's style
	// (We don't have to worry about any of these)
	wndClassEx.style = 0;
	// The function that will process all of the messages
	// that Windows will send to windows of this class
	wndClassEx.lpfnWndProc = OnMessageReceived;
	// Extra bytes can be set aside in the class for user data
	// (This is rarely used, but can be useful)
	wndClassEx.cbClsExtra = 0;
	// Extra bytes can be set aside for each window of the class,
	// but this is usually specified for each window individually
	wndClassEx.cbWndExtra = 0;
	// The large and small icons windows of this class should use
	// (These can be found in the Resources folder; feel free to change them)
	wndClassEx.hIcon = LoadIcon( _applicationInstance, MAKEINTRESOURCE( IDI_RENDERER ) );
	wndClassEx.hIconSm = LoadIcon( _applicationInstance, MAKEINTRESOURCE( IDI_SMALL ) );
	// The cursor that should display when the mouse pointer is over windows of this class
	wndClassEx.hCursor = LoadCursor( NULL, IDC_ARROW );
	// The brush windows of this class will use as a background
	// (Setting this is a bit confusing, so don't be alarmed if the next line looks scary)
	wndClassEx.hbrBackground = reinterpret_cast<HBRUSH>( IntToPtr( COLOR_BACKGROUND + 1 ) );
	// A menu can be specified that all windows of this class would use by default,
	// but usually this is set for each window individually
	wndClassEx.lpszMenuName = NULL;
	// The class name (see comments where this is initialized)
	wndClassEx.lpszClassName = _windowName;

	// Now we can provide this information to Windows.
	// If all goes well, the class will be successfully registered
	// and we can specify it by name when creating our windows.
	_class = RegisterClassEx( &wndClassEx );
	if ( _class != NULL )
	{
		LogMessage( "Registered the main window class" );
		return SUCCESS;
	}
	else
	{
		LogMessage( std::string( "Windows failed to register the main window's class: " ) + GetLastWindowsError() );
		return FAIL;
	}
}
Beispiel #16
0
/**
 ****************************************************************************************************
	\fn			bool Create( const int i_initialWindowDisplay )
	\brief		Create the window
	\param		i_initialWindowDisplay the initial state of the window
	\return		boolean
	\retval		SUCCESS success
	\retval		FAIL otherwise
 ****************************************************************************************************
*/
bool RendererEngine::Window::Create( const int i_initialWindowDisplayState )
{
	// The window's style
	DWORD windowStyle =
		// "Overlapped" is basically the same as "top-level"
		WS_OVERLAPPED
		// The caption is the title bar when in windowed-mode
		| WS_CAPTION
		// The window should never change dimensions, so only a minimize box is allowed
		| WS_MINIMIZEBOX
		// The system menu appears when you right-click the title bar
		| WS_SYSMENU;
	// The window's extended style
	DWORD windowStyle_extended =
		// The following is a macro to make the extended style the default top-level look
		WS_EX_OVERLAPPEDWINDOW;
	// The width and height of the window
	// (The renderer is concerned about the width and height of the actual "client area",
	// which is the part of the window that doesn't include the borders and title bar.
	// the initial window, then, will created with default values that Windows chooses
	// and then resized after creation)
	int width = CW_USEDEFAULT;
	int height = CW_USEDEFAULT;
	// The initial position of the window
	// (We don't care, and will let Windows decide)
	int position_x = CW_USEDEFAULT;
	int position_y = CW_USEDEFAULT;
	// Handle to the parent of this window
	// (Since this is our main window, it can't have a parent)
	HWND hParent = NULL;
	// Handle to the menu for this window
	HMENU hMenu = NULL;
	// Handle to the instance of the application this window should be associated with
	HINSTANCE hApplication = _applicationInstance;
	// Any arbitrary pointer can be associated with this window;
	// usually an application's representation of the window will be used, like this:
	void* userData = this;
	// (Since the main window is a global singleton, though, this program won't actually use this)

	// Ask Windows to create the specified window.
	// CreateWindowEx() will return a handle to the window,
	// which is what we'll use to communicate with Windows about this window
	_window = CreateWindowEx( windowStyle_extended, _windowName, _windowName, windowStyle,
		position_x, position_y, width, height,
		hParent, hMenu, hApplication, userData );
	if ( _window )
	{
		// Change the window's size based on the requested user settings
		{
			// Calculate how much of the window is coming from the "non-client area"
			// (the borders and title bar)
			RECT windowCoordinates;
			struct
			{
				long width;
				long height;
			} nonClientAreaSize;
			{
				// Get the coordinates of the entire window
				if ( GetWindowRect( _window, &windowCoordinates ) == FAIL )
				{
					LogMessage( std::string( "Windows failed to get the coordinates of the main window: " ) + GetLastWindowsError() );
					return FAIL;
				}
				// Get the dimensions of the client area
				RECT clientDimensions;
				if ( GetClientRect( _window, &clientDimensions ) == FAIL )
				{
					LogMessage( std::string( "Windows failed to get the dimensions of the main window's client area: " )
						+ GetLastWindowsError() );
					return FAIL;
				}
				// Get the difference between them
				nonClientAreaSize.width = ( windowCoordinates.right - windowCoordinates.left ) - clientDimensions.right;
				nonClientAreaSize.height = ( windowCoordinates.bottom - windowCoordinates.top ) - clientDimensions.bottom;
			}
			// Resize the window
			{
				BOOL shouldTheResizedWindowBeRedrawn = SUCCESS;
				if ( MoveWindow( _window, windowCoordinates.left, windowCoordinates.top,
					m_u32Width + nonClientAreaSize.width, m_u32Height + nonClientAreaSize.height,
					shouldTheResizedWindowBeRedrawn ) == FAIL )
				{
					LogMessage( std::string( "Windows failed to resize the main window: " ) + GetLastWindowsError() );
					return FAIL;
				}
			}
		}

		// Display the window in the initial state that Windows requested
		ShowWindow( _window, i_initialWindowDisplayState );

		LogMessage( "Created the main window" );
		return SUCCESS;
	}
	else
	{
		LogMessage( std::string( "Windows failed to create the main window: " ) + GetLastWindowsError() );
		return FAIL;
	}
}