bool FileSystem::FolderRemove(const String& path, bool recursive /*= true*/) const { if (!IsFolderExist(path)) return false; if (!recursive) return RemoveDirectoryA(path.Data()) == TRUE; WIN32_FIND_DATA f; HANDLE h = FindFirstFile((path + "/*").Data(), &f); if (h != INVALID_HANDLE_VALUE) { do { if (strcmp(f.cFileName, ".") == 0 || strcmp(f.cFileName, "..") == 0) continue; if (f.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) FolderRemove(path + "/" + f.cFileName, true); else FileDelete(path + "/" + f.cFileName); } while (FindNextFile(h, &f)); } FindClose(h); return RemoveDirectoryA(path.Data()) == TRUE; }
bool FileSystem::FileMove(const String& source, const String& dest) const { String destFolder = GetParentPath(dest); if (!IsFolderExist(destFolder)) FolderCreate(destFolder); return MoveFileA(source.Data(), dest.Data()) == TRUE; }
bool FileSystem::SetFileEditDate(const String& path, const TimeStamp& time) const { FILETIME lastWriteTime; HANDLE hFile = CreateFileA(path.Data(), GENERIC_READ | FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFile == NULL) return false; SYSTEMTIME stLocal, stUTC; stLocal.wSecond = time.mSecond; stLocal.wDayOfWeek = 0; stLocal.wMilliseconds = 0; stLocal.wMinute = time.mMinute; stLocal.wHour = time.mHour; stLocal.wDay = time.mDay; stLocal.wMonth = time.mMonth; stLocal.wYear = time.mYear; TzSpecificLocalTimeToSystemTime(NULL, &stLocal, &stUTC); SystemTimeToFileTime(&stUTC, &lastWriteTime); if (!SetFileTime(hFile, NULL, NULL, &lastWriteTime)) { auto error = GetLastError(); printf("err %i\n", error); CloseHandle(hFile); return false; } CloseHandle(hFile); return true; }
void Sound::Load_Stream(const String& fileName) { if(fileName.Count()) return; name = fileName; FMOD_RESULT s_result = FMOD_OK; if(sound != nullptr) { s_result = FMOD_Sound_Release(sound); check_error(s_result); } s_result = FMOD_System_CreateSound(fmodSystem, fileName.Data(), FMOD_SOFTWARE | FMOD_UNICODE | FMOD_CREATESTREAM, nullptr, &sound); check_error(s_result); switch(type) { case MUSIC: FMOD_Sound_SetSoundGroup(sound, musicGroup); break; case SOUND_EFFECT: FMOD_Sound_SetSoundGroup(sound, noiseGroup); break; } }
void System::SetWindowTitle(const String& title) { #if defined __PLATFORM_WIN32 //m_TitleName = title; SetWindowText(m_RenderWindowParam.handle, title.Data()); #endif // #if defined __PLATFORM_WIN32 }
bool FileSystem::FolderCreate(const String& path, bool recursive /*= true*/) const { if (IsFolderExist(path)) return true; if (!recursive) return CreateDirectoryA(path.Data(), NULL) == TRUE; if (CreateDirectoryA(path.Data(), NULL) == TRUE) return true; String extrPath = ExtractPathStr(path); if (extrPath == path) return false; return FolderCreate(extrPath, true); }
FileInfo FileSystem::GetFileInfo(const String& path) const { FileInfo res; res.path = "invalid_file"; FILETIME creationTime, lastAccessTime, lastWriteTime; HANDLE hFile = CreateFileA(path.Data(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (hFile == NULL || hFile == INVALID_HANDLE_VALUE) { auto err = GetLastError(); return res; } if (!GetFileTime(hFile, &creationTime, &lastAccessTime, &lastWriteTime)) { CloseHandle(hFile); return res; } SYSTEMTIME stUTC, stLocal; FileTimeToSystemTime(&creationTime, &stUTC); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); res.createdDate = TimeStamp(stLocal.wSecond, stLocal.wMinute, stLocal.wHour, stLocal.wDay, stLocal.wMonth, stLocal.wYear); FileTimeToSystemTime(&lastAccessTime, &stUTC); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); res.accessDate = TimeStamp(stLocal.wSecond, stLocal.wMinute, stLocal.wHour, stLocal.wDay, stLocal.wMonth, stLocal.wYear); FileTimeToSystemTime(&lastWriteTime, &stUTC); SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal); res.editDate = TimeStamp(stLocal.wSecond, stLocal.wMinute, stLocal.wHour, stLocal.wDay, stLocal.wMonth, stLocal.wYear); res.path = path; String extension = path.SubStr(path.FindLast(".") + 1); res.fileType = FileType::File; for (auto iext : mInstance->mExtensions) { if (iext.Value().Contains(extension)) { res.fileType = iext.Key(); break; } } DWORD dwSizeHigh = 0, dwSizeLow = 0; dwSizeLow = GetFileSize(hFile, &dwSizeHigh); res.size = (dwSizeHigh * (MAXDWORD+1)) + dwSizeLow; CloseHandle(hFile); return res; }
bool FileSystem::IsFileExist(const String& path) const { DWORD tp = GetFileAttributes(path.Data()); if (tp == INVALID_FILE_ATTRIBUTES) return false; if (tp & FILE_ATTRIBUTE_DIRECTORY) return false; return true; }
bool MaterialManager::CreateResourceHandles(ResourceFileNameInfo* resName) { String ext = FileSystem::Instance().GetExtension(resName->filename); ext.ToLowerCase(); String relativePathName = resName->path + CORRECT_SLASH + resName->filename; String rname; BaseMaterial* material = NULL; if (ext==".emt") { // 打开材质脚本,获取材质名称 TiXmlDocument matDoc(relativePathName.Data()); matDoc.LoadFile(); TiXmlElement* elem = matDoc.FirstChildElement(); if (!elem) return false; const char* name = elem->Attribute("name"); if (!name) return false; material = new Material(relativePathName); rname = name; } else if (ext==".cgfx") { material = new EffectMaterial(relativePathName); rname = resName->filename; } if (material) { AssertFatal(m_ResourceMap.find(rname)==m_ResourceMap.end(), "MaterialManager::CreateResourceHandles(): Specified resource name already exists."); m_ResourceMap[rname] = material; material->m_ResourceName = rname; return true; } return false; }
bool FontManager::CreateResourceHandles(ResourceFileNameInfo* resName) { String relativePathName = resName->path + CORRECT_SLASH + resName->filename; // 获取字体信息 FT_Face ft_face; FT_New_Face(g_FTLibrary, relativePathName.Data(), 0, &ft_face); Font* font = new Font(relativePathName); AssertFatal(m_ResourceMap.find(ft_face->family_name)==m_ResourceMap.end(), "FontManager::CreateResourceHandles(): Specified resource name already exists."); m_ResourceMap[ft_face->family_name] = font; font->m_ResourceName = resName->filename; FT_Done_Face(ft_face); return true; }
// 将场景保存到文件 bool GameGrid::SaveScene(const String &filename) { ofstream fout(filename.Data()); if (!fout.is_open()) return false; // 在x、y、z方向上依次遍历 for (int x=0; x<WORLD_SIZE; x++) for (int y=0; y<WORLD_SIZE; y++) for (int z=0; z<WORLD_SIZE; z++) { if (m_World[x][y][z].obj) fout << 1 << " "; else fout << 0 << " "; } fout.close(); return true; }
// 从文件载入场景 bool GameGrid::LoadScene(const String &filename) { ifstream fin(filename.Data()); if (!fin.is_open()) return false; for (int x=0; x<WORLD_SIZE; x++) for (int y=0; y<WORLD_SIZE; y++) for (int z=0; z<WORLD_SIZE; z++) { int b; fin >> b; if (b) AddBox(Point3(x, y, z)); else RemoveBox(Point3(x, y, z)); } fin.close(); return true; }
bool DXShader::Load(const String& vertexFileName, const String& pixelFileName) { HRESULT hr = S_OK; String vertexFile("data/shaders/dx/"); vertexFile.Append(vertexFileName); // create vertex shader void* vBuffer = nullptr; unsigned vSize = load_binary_file(&vBuffer, vertexFile.Data()); hr = _Device->CreateVertexShader(vBuffer, vSize, NULL, &vertexShader); if(FAILED(hr)) { delete[] vBuffer; LOG_ISSUE("DIRECTX ERROR: %s - failed to load vertex shader: %s", hresult_text(hr).Data(), vertexFileName.Data()); return false; } // create input layout const D3D11_INPUT_ELEMENT_DESC basicVertexLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC particleVertexLayoutDesc[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC* inputLayoutDesc = (layoutType == 0) ? basicVertexLayoutDesc : particleVertexLayoutDesc; unsigned inputDescSize = (layoutType == 0) ? ARRAYSIZE(basicVertexLayoutDesc) : ARRAYSIZE(particleVertexLayoutDesc); hr = _Device->CreateInputLayout(inputLayoutDesc, inputDescSize, vBuffer, vSize, &inputLayout); delete[] vBuffer; if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to create input layout " "for vertex shader: %s", hresult_text(hr).Data(), vertexFileName.Data()); return false; } // create pixel shader String pixelFile("shaders/dx/"); pixelFile.Append(pixelFileName); void* psBuffer = nullptr; unsigned psSize = load_binary_file(&psBuffer, pixelFile.Data()); hr = _Device->CreatePixelShader(psBuffer, psSize, NULL, &pixelShader); delete[] psBuffer; if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to load pixel shader: %s", hresult_text(hr).Data(), pixelFileName.Data()); return false; } // initialize constants numVertexConstants = 3; vertexConstants[0].name = "model"; vertexConstants[0].type = ShaderConstant::MAT4X4; vertexConstants[1].name = "view"; vertexConstants[1].type = ShaderConstant::MAT4X4; vertexConstants[2].name = "projection"; vertexConstants[2].type = ShaderConstant::MAT4X4; numPixelConstants = 1; pixelConstants[0].name = "color"; pixelConstants[0].type = ShaderConstant::VEC4; int count = 0; for(int i = 0; i < numVertexConstants; i++) { vertexConstants[i].location = count; count += vertexConstants[i].GetSize(); } count = 0; for(int i = 0; i < numPixelConstants; i++) { pixelConstants[i].location = count; count += pixelConstants[i].GetSize(); } // create constant buffers int vertexConstantBufferSize = 0; for(int i = 0; i < numVertexConstants; i++) vertexConstantBufferSize += vertexConstants[i].GetSize(); D3D11_BUFFER_DESC constantBufferDesc = {0}; constantBufferDesc.ByteWidth = sizeof(float) * vertexConstantBufferSize; constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC; constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; _Device->CreateBuffer(&constantBufferDesc, nullptr, &vertCB); if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to create constant buffer " "for shaders: %s and %s", hresult_text(hr).Data(), vertexFileName.Data(), pixelFileName.Data()); return false; } int pixelConstantBufferSize = 0; for(int i = 0; i < numPixelConstants; i++) pixelConstantBufferSize += pixelConstants[i].GetSize(); D3D11_BUFFER_DESC pixelCBDesc = {0}; pixelCBDesc.ByteWidth = sizeof(float) * pixelConstantBufferSize; pixelCBDesc.Usage = D3D11_USAGE_DYNAMIC; pixelCBDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; pixelCBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; _Device->CreateBuffer(&pixelCBDesc, nullptr, &pixelCB); if(FAILED(hr)) { LOG_ISSUE("DIRECTX ERROR: %s - failed to create pixel constant buffer " "for shaders: %s and %s", hresult_text(hr).Data(), vertexFileName.Data(), pixelFileName.Data()); return false; } return true; }
bool FileSystem::FileDelete(const String& file) const { return DeleteFileA(file.Data()) == TRUE; }
bool FileSystem::FileCopy(const String& source, const String& dest) const { FileDelete(dest); FolderCreate(ExtractPathStr(dest)); return CopyFileA(source.Data(), dest.Data(), TRUE) == TRUE; }
intptr GetExportAddress(const String& Name) { return (intptr)GetProcAddress(m_Module, Name.Data()); }
bool System::CreateRenderWindow(const String& title, unsigned int width, unsigned int height, unsigned int bits, bool fullscreen) { m_TitleName = title; m_RenderWindowParam.width = width; m_RenderWindowParam.height = height; m_RenderWindowParam.colorDepthBit = bits; m_FullScreen = fullscreen; Log.OutputTime(); Log << "Creating render window: width = " << width << ", height = " << height << ", color depth = " << bits << ", fullscreen = " << fullscreen << "\n"; #if defined __PLATFORM_WIN32 WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; RECT WindowRect; WindowRect.left = (long)0; WindowRect.right = (long)width; WindowRect.top = (long)0; WindowRect.bottom = (long)height; HINSTANCE hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) Platform::WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = title.Data(); AssertFatal(RegisterClass(&wc), "System::CreateRenderWindow() : Failed to register window class."); if (fullscreen) { DEVMODE dmScreenSettings; memset (&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = bits; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH |DM_PELSHEIGHT; AssertFatal(ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN)==DISP_CHANGE_SUCCESSFUL, "System::CreateRenderWindow() : Unable to use selected display mode."); } if (fullscreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; ShowCursor(false); } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; } AdjustWindowRectEx (&WindowRect, dwStyle, false, dwExStyle); m_RenderWindowParam.handle = CreateWindowEx( dwExStyle, title.Data(), title.Data(), dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, (GetSystemMetrics(SM_CXSCREEN) - WindowRect.right) / 2, (GetSystemMetrics(SM_CYSCREEN) - WindowRect.bottom) / 2, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, NULL, NULL, hInstance, NULL); AssertFatal(m_RenderWindowParam.handle, "System::CreateRenderWindow(): Error creating render window."); ShowWindow(m_RenderWindowParam.handle,SW_SHOW); // Show The Window SetForegroundWindow(m_RenderWindowParam.handle); // Slightly Higher Priority SetFocus(m_RenderWindowParam.handle); // Sets Keyboard Focus To The Window #elif defined __PLATFORM_LINUX // 建立与X Server的连接,获取Display RenderWindowHandle* handle = &m_RenderWindowParam.handle; handle->display = g_Display = XOpenDisplay(0); Display* display = static_cast<Display*>(handle->display); handle->screen = DefaultScreen(display); Window rootwin = XDefaultRootWindow(display); Visual* visual = XDefaultVisualOfScreen(XDefaultScreenOfDisplay(display)); unsigned int screen_width = DisplayWidth(display, handle->screen); unsigned int screen_height = DisplayHeight(display, handle->screen); // 创建X窗体 XSetWindowAttributes attrib; attrib.colormap = XCreateColormap(display, rootwin, visual, AllocNone); attrib.border_pixel = 0; attrib.event_mask = ExposureMask | KeyPressMask | StructureNotifyMask; handle->window = XCreateWindow(display, rootwin, (screen_width - width) / 2, (screen_height - height) / 2, width, height, 1, XDefaultDepth(display, 0), InputOutput, visual, CWBorderPixel | CWColormap | CWEventMask, &attrib); XStoreName(display, handle->window, title.Data()); XSizeHints* hint; hint = XAllocSizeHints(); hint->x = (screen_width - width) / 2; hint->y = (screen_height - height) / 2; hint->width = width; hint->height = height; hint->flags = USPosition | USSize; XSetNormalHints(display, handle->window, hint); XFree(hint); // 显示窗口 XMapWindow(display, handle->window); // 刷新缓冲 XFlush(display); #endif // #if defined __PLATFORM_WIN32 return true; }
Error Open(const Path& Command, const Path& WorkingDirectory, const Array<String>& Arguments, bool bRedirectStdInOut) { LD_ASSERT(!IsAttached()); // Escape and pack arguments into a single command line incase it has spaces! String CommandLine = Command.ToString().DoubleQuoted(); for (const String& Arg : Arguments) { if (Arg.IndexOf(" ") != Arg.EndCharIterator()) { CommandLine += Arg.DoubleQuoted(); } else { CommandLine += Arg; } CommandLine += " "; } if (bRedirectStdInOut) { // Setup security attributes. ZeroMemory(&m_SecurityAttributes, sizeof(SECURITY_ATTRIBUTES)); m_SecurityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); m_SecurityAttributes.bInheritHandle = TRUE; m_SecurityAttributes.lpSecurityDescriptor = NULL; // Create pipes to redirect the stdin/stdout and ensure our side of the pipes // (read for stdout, write for stdin) are not inheritable. BOOL Result = CreatePipe(&m_StdOutRead, &m_StdOutWrite, &m_SecurityAttributes, 0); if (!Result) { LogLastSystemError("CreateProcess"); return ErrorType::Failure; } Result = SetHandleInformation(&m_StdOutRead, HANDLE_FLAG_INHERIT, 0); if (!Result) { LogLastSystemError("SetHandleInformation"); return ErrorType::Failure; } Result = CreatePipe(&m_StdInRead, &m_StdInWrite, &m_SecurityAttributes, 0); if (!Result) { LogLastSystemError("CreateProcess"); return ErrorType::Failure; } Result = SetHandleInformation(&m_StdInWrite, HANDLE_FLAG_INHERIT, 0); if (!Result) { LogLastSystemError("SetHandleInformation"); return ErrorType::Failure; } } else { m_StdInRead = INVALID_HANDLE_VALUE; m_StdInWrite = INVALID_HANDLE_VALUE; m_StdOutRead = INVALID_HANDLE_VALUE; m_StdOutWrite = INVALID_HANDLE_VALUE; } // Setup process information. ZeroMemory(&m_ProcessInfo, sizeof(PROCESS_INFORMATION)); // Setup startup info. ZeroMemory(&m_StartupInfo, sizeof(STARTUPINFOA)); m_StartupInfo.cb = sizeof(STARTUPINFOA); if (bRedirectStdInOut) { m_StartupInfo.hStdError = m_StdOutWrite; m_StartupInfo.hStdOutput = m_StdOutWrite; m_StartupInfo.hStdInput = m_StdInRead; m_StartupInfo.dwFlags |= STARTF_USESTDHANDLES; } // Store state. m_Attached = true; m_bRedirectStdInOut = bRedirectStdInOut; // Time to create the process at last! BOOL Result = CreateProcessA( nullptr, // lpApplicationName (LPSTR)CommandLine.Data(), // lpCommandLine nullptr, // lpProcessAttributes nullptr, // lpThreadAttributes true, // bInheritHandles 0, // dwCreationFlags nullptr, // lpEnvironment (LPCSTR)WorkingDirectory.ToString().Data(), // lpCurrentDirectory &m_StartupInfo, // lpStartupInfo &m_ProcessInfo // lpProcessInformation ); if (!Result) { Detach(); LogLastSystemError("CreateProcess"); return ErrorType::Failure; } return ErrorType::Success; }
void WriteString(const String& value) { std::uint32_t len = value.Length(); WriteBuffer(&len, sizeof(len)); WriteBuffer((void*)value.Data(), len*sizeof(wchar_t)); }