void __cdecl AppWarning(const TCHAR *format, ...) { if(!format) return; va_list arglist; va_start(arglist, format); if(bLogStarted) { OpenLogFile(); LogFile.WriteStr(TEXT("Warning -- ")); String strOut = FormattedStringva(format, arglist); LogFile.WriteAsUTF8(strOut, strOut.Length()); LogFile.WriteAsUTF8(TEXT("\r\n")); CloseLogFile(); } OSDebugOut(TEXT("Warning -- ")); OSDebugOutva(format, arglist); OSDebugOut(TEXT("\r\n")); //------------------------------------------------------ // NOTE: // If you're seeting this, you can safely continue running, but I recommend fixing whatever's causing this warning. // // The debug output window contains the warning that has occured. //------------------------------------------------------ #if defined(_DEBUG) && defined(_WIN32) if(bDebugBreak && OSDebuggerPresent()) { ProgramBreak(); } #endif }
BOOL ConfigFile::SaveAs(CTSTR lpPath) { XFile newFile; String tmpPath = lpPath; tmpPath.AppendString(TEXT(".tmp")); if (newFile.Open(tmpPath, XFILE_WRITE, XFILE_CREATEALWAYS)) { if (newFile.Write("\xEF\xBB\xBF", 3) != 3) return FALSE; if (!newFile.WriteAsUTF8(lpFileData)) return FALSE; newFile.Close(); if (!OSRenameFile(tmpPath, lpPath)) Log(TEXT("ConfigFile::SaveAs: Unable to move new config file %s to %s"), tmpPath.Array(), lpPath); strFileName = lpPath; return TRUE; } return FALSE; }
//////////////////////////////////////////////////// // 从文件中读入数据,获取的数据添加到流的尾部 // 该操作从字节边界开始,将剩余未写位数跳过 // file:文件句柄 XBOOL XStream::ReadFromFile(XFile&file,int nLength) { if(nLength<=0) nLength=BLOCKSIZE; //XU8Array data; //data.SetSize(nLength); FlushWriteBits(); SetSize(writePos+nLength); nLength=file.Read(m_pData+writePos,nLength); //::fread(data,1,nLength,file); if(nLength>0) { //Append(data,nLength); writePos+=nLength; } return nLength; }
XBOOL XFile::LoadText(XPCTSTR strFile, XString8 &strTxt) { XFile file; if(!file.Open(strFile,XFile::XREAD)) return XFALSE; int l=file.GetLength(); if(l<=0) {file.Close();return XFALSE;} strTxt.SetSize(l+1,XFALSE); file.Read(strTxt.GetData(),l); file.Close(); return XTRUE; }
BOOL ConfigFile::LoadFile(DWORD dwOpenMode) { XFile file; if(!file.Open(strFileName, XFILE_READ, dwOpenMode)) { //Log(TEXT("Couldn't load config file: \"%s\""), (TSTR)strFileName); return 0; } if(bOpen) Close(); dwLength = (DWORD)file.GetFileSize(); if (dwLength >= 3) // remove BOM if present { char buff[3]; file.Read(&buff, 3); if (memcmp(buff, "\xEF\xBB\xBF", 3)) file.SetPos(0, XFILE_BEGIN); else dwLength -= 3; } LPSTR lpTempFileData = (LPSTR)Allocate(dwLength+5); file.Read(&lpTempFileData[2], dwLength); lpTempFileData[0] = lpTempFileData[dwLength+2] = 13; lpTempFileData[1] = lpTempFileData[dwLength+3] = 10; lpTempFileData[dwLength+4] = 0; file.Close(); lpFileData = utf8_createTstr(lpTempFileData); dwLength = slen(lpFileData); Free(lpTempFileData); bOpen = 1; return 1; }
/*@ XBitmap::LoadBMP(const char* filename) @group loading a bitmap @remarks Load a bitmap from a file. This method works faster than Load() but can only load bitmpas in OS2-BMP format @parameters char * fileName filename of the file to load @exceptions If the method fails to create a new bitmap an exception of the type XException is thrown. */ void XBitmap :: LoadBMP(const char* filename) { if (hbm) GpiDeleteBitmap(hbm); hbm = 0; XFile file; PBITMAPFILEHEADER p; if (file.Open(filename, XFILE_FAIL_IF_NEW | XFILE_OPEN_EXISTING, XFILE_READONLY, XFILE_SHARE_DENYNONE ) == 0) { XFileInfo info; file.GetFileInfo(&info); file.Seek(0, XFILE_BEGIN); p = (PBITMAPFILEHEADER) malloc(info.GetFileSize()); file.Read(p, info.GetFileSize()); file.Close(); } else OOLThrow( "couldnït open file!", -1); if (owner ) { hps = WinGetPS(owner->GetHandle()); hbm = GpiCreateBitmap(hps, (PBITMAPINFOHEADER2) &p->bmp, CBM_INIT, (PBYTE) p + p->offBits, (PBITMAPINFO2) &p->bmp); if(hbm == 0) OOLThrow("error creating bitmap", 3); } else SetData((BITMAPINFOHEADER2 *) &p->bmp, p->offBits); free(p); XSize s; GetDimensions(&s); width = cx = s.GetWidth(); height = cy = s.GetHeight(); if (hbm == GPI_ERROR) { ULONG error = WinGetLastError(XApplication::GetApplication()->GetAnchorBlock()); OOLThrow("couldnït load bitmap", error); } return; }
~FLVFileStream() { UINT64 fileSize = fileOut.GetPos(); fileOut.Close(); XFile file; if(file.Open(strFile, XFILE_WRITE, XFILE_OPENEXISTING)) { double doubleFileSize = double(fileSize); double doubleDuration = double(lastTimeStamp/1000); file.SetPos(metaDataPos+0x28, XFILE_BEGIN); QWORD outputVal = *reinterpret_cast<QWORD*>(&doubleDuration); outputVal = fastHtonll(outputVal); file.Write(&outputVal, 8); file.SetPos(metaDataPos+0x3B, XFILE_BEGIN); outputVal = *reinterpret_cast<QWORD*>(&doubleFileSize); outputVal = fastHtonll(outputVal); file.Write(&outputVal, 8); file.Close(); } }
void XConfig::WriteFileItem(XFile &file, int indent, XBaseItem *baseItem) { int j; if(baseItem->IsData()) { XDataItem *item = static_cast<XDataItem*>(baseItem); String strItem; for(j=0; j<indent; j++) strItem << TEXT(" "); if( item->strName.IsValid() && ( item->strName[0] == ' ' || item->strName[0] == '\t' || item->strName[0] == '{' || item->strName[item->strName.Length()-1] == ' ' || item->strName[item->strName.Length()-1] == '\t' || schr(item->strName, '\n') || schr(item->strName, '"') || schr(item->strName, ':') )) { strItem << ConvertToTextString(item->strName); } else strItem << item->strName; strItem << TEXT(" : "); if( item->strData.IsValid() && ( item->strData[0] == ' ' || item->strData[0] == '\t' || item->strData[0] == '{' || item->strData[item->strData.Length()-1] == ' ' || item->strData[item->strData.Length()-1] == '\t' || schr(item->strData, '\n') || schr(item->strData, '"') || schr(item->strData, ':') )) { strItem << ConvertToTextString(item->strData); } else strItem << item->strData; strItem << TEXT("\r\n"); file.WriteAsUTF8(strItem); } else if(baseItem->IsElement()) { XElement *element = static_cast<XElement*>(baseItem); String strElement; for(j=0; j<indent; j++) strElement << TEXT(" "); if( element->strName.IsValid() && ( element->strName[0] == ' ' || element->strName[0] == '\t' || element->strName[0] == '{' || element->strName[element->strName.Length()-1] == ' ' || element->strName[element->strName.Length()-1] == '\t' || schr(element->strName, '\n') || schr(element->strName, '"') || schr(element->strName, ':') )) { strElement << ConvertToTextString(element->strName); } else strElement << element->strName; strElement << TEXT(" : {\r\n"); file.WriteAsUTF8(strElement); strElement.Clear(); WriteFileData(file, indent+1, element); for(j=0; j<indent; j++) strElement << TEXT(" "); strElement << TEXT("}\r\n"); file.WriteAsUTF8(strElement); } }
BOOL HTTPGetFile (CTSTR url, CTSTR outputPath, CTSTR extraHeaders, int *responseCode) { HINTERNET hSession = NULL; HINTERNET hConnect = NULL; HINTERNET hRequest = NULL; URL_COMPONENTS urlComponents; BOOL secure = FALSE; BOOL ret = FALSE; String hostName, path; const TCHAR *acceptTypes[] = { TEXT("*/*"), NULL }; hostName.SetLength(256); path.SetLength(1024); zero(&urlComponents, sizeof(urlComponents)); urlComponents.dwStructSize = sizeof(urlComponents); urlComponents.lpszHostName = hostName; urlComponents.dwHostNameLength = hostName.Length(); urlComponents.lpszUrlPath = path; urlComponents.dwUrlPathLength = path.Length(); WinHttpCrackUrl(url, 0, 0, &urlComponents); if (urlComponents.nPort == 443) secure = TRUE; hSession = WinHttpOpen(OBS_VERSION_STRING, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) goto failure; hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (!hConnect) goto failure; hRequest = WinHttpOpenRequest(hConnect, TEXT("GET"), path, NULL, WINHTTP_NO_REFERER, acceptTypes, secure ? WINHTTP_FLAG_SECURE|WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) goto failure; BOOL bResults = WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); else goto failure; TCHAR statusCode[8]; DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); if (!WinHttpQueryHeaders (hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) goto failure; *responseCode = wcstoul(statusCode, NULL, 10); if (bResults && *responseCode == 200) { BYTE buffer[16384]; DWORD dwSize, dwOutSize; XFile updateFile; if (!updateFile.Open(outputPath, XFILE_WRITE, CREATE_ALWAYS)) goto failure; do { // Check for available data. dwSize = 0; if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) goto failure; if (!WinHttpReadData(hRequest, (LPVOID)buffer, dwSize, &dwOutSize)) { goto failure; } else { if (!dwOutSize) break; if (!updateFile.Write(buffer, dwOutSize)) goto failure; } } while (dwSize > 0); updateFile.Close(); } ret = TRUE; failure: if (hSession) WinHttpCloseHandle(hSession); if (hConnect) WinHttpCloseHandle(hConnect); if (hRequest) WinHttpCloseHandle(hRequest); return ret; }
bool Display(float timeDelta) { if( Device ) { //update audio AudioUpdate(); //keyboard if( ::GetAsyncKeyState('W') & 0x8000f) { TheCamera.walk(40.0f * timeDelta); //D3DXMATRIX forwardMovement; //D3DXMatrixRotationY(&forwardMovement, avatarYaw); //D3DXVECTOR3 v(0,0,forwardSpeed); //D3DXVECTOR4 vec4; //D3DXVec3Transform(&vec4, &v, &forwardMovement); //avatarDirection.x = v.x = vec4.x; //avatarDirection.y = v.y = vec4.y; //avatarDirection.z = v.z = vec4.z; //AvatarPosition.z += v.z; //AvatarPosition.x += v.x; } if( ::GetAsyncKeyState('S') & 0x8000f) { TheCamera.walk(-40.0f * timeDelta); //D3DXMATRIX forwardMovement; //D3DXMatrixRotationY(&forwardMovement, avatarYaw); //D3DXVECTOR3 v(0,0,-forwardSpeed); //D3DXVECTOR4 vec4; //D3DXVec3Transform(&vec4, &v, &forwardMovement); //avatarDirection.x = v.x = vec4.x; //avatarDirection.y = v.y = vec4.y; //avatarDirection.z = v.z = vec4.z; //AvatarPosition.z += v.z; //AvatarPosition.x += v.x; } if( ::GetAsyncKeyState('A') & 0x8000f) { TheCamera.yaw(-4.0f * timeDelta); //avatarYaw -= rotationSpeed; } if( ::GetAsyncKeyState('D') & 0x8000f) { TheCamera.yaw(4.0f * timeDelta); //avatarYaw -= rotationSpeed; } if( ::GetAsyncKeyState('I') & 0x8000f) { TheCamera.pitch(-4.0f * timeDelta); } if( ::GetAsyncKeyState('K') & 0x8000f) { TheCamera.pitch(4.0f * timeDelta); } D3DXVECTOR3 f = TheCamera.GetPosition(); if(f.x > 190) f.x = 190; if(f.x < -190) f.x = -190; if(f.z > 190) f.z = 190; if(f.z < -190) f.z = -190; //if(f.y > 390) // f.y = 390; //if(f.y < 10) // f.y = 10; float height = TheTerrain->getHeight(f.x, f.z); f.y = height + 5.0f; TheCamera.setPosition(&f); //camera stuff D3DXMATRIX V, o; TheCamera.getViewMatrix(&V); Device->SetTransform(D3DTS_VIEW, &V); //UpdateCameraThirdPerson(); // // Draw the scene: // Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, 0xff000000, 1.0f, 0L); Device->BeginScene(); D3DXMATRIX I; D3DXMatrixIdentity(&I); if(TheTerrain) TheTerrain->draw(&I, false); //Device->SetTexture(0, Armor) D3DXMATRIX i, tripler, grow; Collides(); DisplayTime(); DisplayRemaining(); // //Barrels1 // if(BoolTrash[0]) { D3DXMatrixTranslation(&tripler, TrashPositions[0].x + 0,TrashPositions[0].y, TrashPositions[0].z-10); D3DXMatrixScaling(&grow, .05,.05,.05); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Barrels.Draw(NULL); } // //Barrels2 // if(BoolTrash[1]) { D3DXMatrixTranslation(&tripler, TrashPositions[1].x +0,TrashPositions[1].y,TrashPositions[1].z-10); D3DXMatrixScaling(&grow, .05,.05,.05); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Barrels.Draw(NULL); } // //Dalek1 // if(BoolTrash[2]) { D3DXMatrixTranslation(&tripler, TrashPositions[2].x +0,TrashPositions[2].y+8,TrashPositions[2].z-10); D3DXMatrixScaling(&grow, .05,.05,.05); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Dalek.Draw(NULL); } // //Dalek2 // if(BoolTrash[3]) { D3DXMatrixTranslation(&tripler,TrashPositions[3].x +0,TrashPositions[3].y+8,TrashPositions[3].z-10); D3DXMatrixScaling(&grow, .05,.05,.05); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Dalek.Draw(NULL); } // //Tank1 // if(BoolTrash[4]) { D3DXMatrixTranslation(&tripler, TrashPositions[4].x +40,TrashPositions[4].y+14,TrashPositions[4].z+0); D3DXMatrixScaling(&grow, .1,.1,.1); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); tank.Draw(NULL); } // //Tank2 // if(BoolTrash[5]) { D3DXMatrixTranslation(&tripler, TrashPositions[5].x +40,TrashPositions[5].y+14,TrashPositions[5].z+0); D3DXMatrixScaling(&grow, .1,.1,.1); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); tank.Draw(NULL); } // //Table1 // if(BoolTrash[6]) { D3DXMatrixTranslation(&tripler, TrashPositions[6].x +0,TrashPositions[6].y,TrashPositions[6].z-10); D3DXMatrixScaling(&grow, 10,10,10); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Table.Draw(NULL); } // //Table2 // if(BoolTrash[7]) { D3DXMatrixTranslation(&tripler, TrashPositions[7].x +0,TrashPositions[7].y,TrashPositions[7].z-10); D3DXMatrixScaling(&grow,10,10,10); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Table.Draw(NULL); } // //Ton1 // if(BoolTrash[8]) { D3DXMatrixTranslation(&tripler, TrashPositions[8].x +0,TrashPositions[8].y,TrashPositions[8].z-10); D3DXMatrixScaling(&grow,10,10,10); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Ton.Draw(NULL); } // //Ton2 // if(BoolTrash[9]) { D3DXMatrixTranslation(&tripler, TrashPositions[9].x +0,TrashPositions[8].y,TrashPositions[9].z-10); D3DXMatrixScaling(&grow,10,10,10); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Ton.Draw(NULL); } for(int i = 0; i < numbertrees; i++) { D3DXMatrixTranslation(&tripler, TreePositions[i].x +0,TreePositions[i].y,TreePositions[i].z-10); D3DXMatrixScaling(&grow,5,5,5); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Tree.Draw(NULL); } if(messageDone) { if(allfound) { sprintf(buffers, "Seconds taken to find all objects: %i", seconds); ::MessageBoxA(0, buffers, "Congratulations", 0); //::PostQuitMessage(0); messageDone = false; } } renderSkybox(Device, TheCamera); DrawMinimap(); Device->EndScene(); Device->Present(0, 0, 0, 0); } if(GetTickCount() - dwFinalTick > 1000) { seconds = seconds + 1; dwInitialTick = dwFinalTick; dwFinalTick = GetTickCount(); countDown = countDown+ 1; } return true; }
xf_error_codes create(const char *name, dword flags) { xf_error_codes err=xf->create(name,flags|XF_OPEN_READ); if (!err) {return begin();} errorn=err; return err; };
bool Setup() { D3DXVECTOR3 lightDirection(0.0f, 1.0f, 0.0f); TheTerrain = new Terrain(Device, "Faces.raw", 734,1024,20,1.0f); TheTerrain->genTexture(&lightDirection); TheTerrain->loadTexture("Faces.jpg"); D3DXCreateFont(Device, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &m_font ); // // Lights. // Barrels.init(Device, "barells/barrels.x"); Dalek.init(Device, "dalek/dalek.x"); tank.init(Device, "Oiltank/tank.x"); Table.init(Device, "table/table.x"); Ton.init(Device, "ton/ton3.x"); Tree.init(Device, "trees/palm_tree_3.x"); numbertrees = rand() % 100 - 1; for(int i = 0; i < 10; i++) BoolTrash[i] = true; D3DXCreateSprite(Device, &spriteMap); D3DXCreateSprite(Device, &spritePlayer); for(int i = 0; i < 10; i++) { D3DXCreateSprite(Device, &spriteTrash[i]); } D3DXCreateTextureFromFile(Device, "Map.png", &texMap); srand(GetTickCount()); TrashPositions[0].x = rand() % 360 - 180; TrashPositions[0].z = rand() % 360 - 180; float height = TheTerrain->getHeight(TrashPositions[0].x, TrashPositions[0].z); TrashPositions[0].y = height; TrashPositions[1].x = rand() % 360 - 180; TrashPositions[1].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[1].x, TrashPositions[1].z); TrashPositions[1].y = height; TrashPositions[2].x = rand() % 360 - 180; TrashPositions[2].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[2].x, TrashPositions[2].z); TrashPositions[2].y = height; TrashPositions[3].x = rand() % 360 - 180; TrashPositions[3].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[3].x, TrashPositions[3].z); TrashPositions[3].y = height; TrashPositions[4].x = rand() % 360 - 180; TrashPositions[4].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[4].x, TrashPositions[4].z); TrashPositions[4].y = height; TrashPositions[5].x = rand() % 360 - 180; TrashPositions[5].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[5].x, TrashPositions[5].z); TrashPositions[5].y = height; TrashPositions[6].x = rand() % 360 - 180; TrashPositions[6].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[6].x, TrashPositions[6].z); TrashPositions[6].y = height; TrashPositions[7].x = rand() % 360 - 180; TrashPositions[7].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[7].x, TrashPositions[7].z); TrashPositions[7].y = height; TrashPositions[8].x = rand() % 360 - 180; TrashPositions[8].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[8].x, TrashPositions[8].z); TrashPositions[8].y = height; TrashPositions[9].x = rand() % 360 - 180; TrashPositions[9].z = rand() % 360 - 180; height = TheTerrain->getHeight(TrashPositions[9].x, TrashPositions[9].z); TrashPositions[9].y = height; for(int i = 0; i < numbertrees; i++) { TreePositions[i].x = rand() % 360 - 180; TreePositions[i].z = rand() % 360 - 180; height = TheTerrain->getHeight(TreePositions[i].x, TreePositions[i].z); TreePositions[i].y = height; } D3DXVECTOR3 lightDir(0.707f, -0.707f, 0.707f); D3DXCOLOR color(1.0f, 1.0f, 1.0f, 1.0f); D3DLIGHT9 light = d3d::InitDirectionalLight(&lightDir, &color); Device->SetLight(0, &light); Device->LightEnable(0, true); Device->SetRenderState(D3DRS_NORMALIZENORMALS, true); Device->SetRenderState(D3DRS_SPECULARENABLE, true); //build skybox BuildSkybox(Device); // // Set Camera. // D3DXVECTOR3 pos(-0.0f, -197.0f, -0.0f); D3DXVECTOR3 target(0.0, 0.0f, 0.0f); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMATRIX V; D3DXMatrixLookAtLH(&V, &pos, &target, &up); Device->SetTransform(D3DTS_VIEW, &V); D3DXVECTOR3 pos2(-0.0f, -10.0f, 0.0f); D3DXVECTOR3 target2(0.0, 0.0f, 0.0f); D3DXVECTOR3 up2(0.0f, 1.0f, 0.0f); // D3DXMATRIX V; D3DXMatrixLookAtLH(&mview, &pos2, &target2, &up2); //Device->SetTransform(D3DTS_VIEW, &mview); // // Set projection matrix. // D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI / 4.0f, // 45 - degree (float)Width / (float)Height, 1.0f, 20001.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); D3DXMatrixPerspectiveFovLH(&mprojection, D3DX_PI / 4.0f, (float)Width / (float)Height, 1.0f, 20001.0f); //Device->SetTransform(D3DTS_PROJECTION, &mprojection); return true; }
~MP4FileStream() { if(!bStreamOpened) return; App->EnableSceneSwitching(false); //--------------------------------------------------- //HWND hwndProgressDialog = CreateDialog(hinstMain, MAKEINTRESOURCE(IDD_BUILDINGMP4), hwndMain, (DLGPROC)MP4ProgressDialogProc); //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETRANGE32, 0, 100); mdatStop = fileOut.GetPos(); BufferOutputSerializer output(endBuffer); //set a reasonable initial buffer size endBuffer.SetSize((videoFrames.Num() + audioFrames.Num()) * 20 + 131072); UINT64 audioFrameSize = App->GetAudioEncoder()->GetFrameSize(); DWORD macTime = fastHtonl(DWORD(GetMacTime())); UINT videoDuration = fastHtonl(lastVideoTimestamp + App->GetFrameTime()); UINT audioDuration = fastHtonl(lastVideoTimestamp + DWORD(double(audioFrameSize)*1000.0/double(App->GetSampleRateHz()))); UINT width, height; App->GetOutputSize(width, height); LPCSTR lpVideoTrack = "Video Media Handler"; LPCSTR lpAudioTrack = "Sound Media Handler"; const char videoCompressionName[31] = "AVC Coding"; //------------------------------------------- // get video headers DataPacket videoHeaders; App->GetVideoHeaders(videoHeaders); List<BYTE> SPS, PPS; LPBYTE lpHeaderData = videoHeaders.lpPacket+11; SPS.CopyArray(lpHeaderData+2, fastHtons(*(WORD*)lpHeaderData)); lpHeaderData += SPS.Num()+3; PPS.CopyArray(lpHeaderData+2, fastHtons(*(WORD*)lpHeaderData)); //------------------------------------------- // get AAC headers if using AAC List<BYTE> AACHeader; if(!bMP3) { DataPacket data; App->GetAudioHeaders(data); AACHeader.CopyArray(data.lpPacket+2, data.size-2); } //------------------------------------------- EndChunkInfo(videoChunks, videoSampleToChunk, curVideoChunkOffset, numVideoSamples); EndChunkInfo(audioChunks, audioSampleToChunk, curAudioChunkOffset, numAudioSamples); if (numVideoSamples > 1) GetVideoDecodeTime(videoFrames.Last(), true); if (numAudioSamples > 1) GetAudioDecodeTime(audioFrames.Last(), true); UINT audioUnitDuration = fastHtonl(UINT(lastAudioTimeVal)); //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 25, 0); //------------------------------------------- // sound descriptor thingy. this part made me die a little inside admittedly. UINT maxBitRate = fastHtonl(App->GetAudioEncoder()->GetBitRate()*1000); List<BYTE> esDecoderDescriptor; BufferOutputSerializer esDecoderOut(esDecoderDescriptor); esDecoderOut.OutputByte(bMP3 ? 107 : 64); esDecoderOut.OutputByte(0x15); //stream/type flags. always 0x15 for my purposes. esDecoderOut.OutputByte(0); //buffer size, just set it to 1536 for both mp3 and aac esDecoderOut.OutputWord(WORD_BE(0x600)); esDecoderOut.OutputDword(maxBitRate); //max bit rate (cue bill 'o reily meme for these two) esDecoderOut.OutputDword(maxBitRate); //avg bit rate if(!bMP3) //if AAC, put in headers { esDecoderOut.OutputByte(0x5); //decoder specific descriptor type /*esDecoderOut.OutputByte(0x80); //some stuff that no one should probably care about esDecoderOut.OutputByte(0x80); esDecoderOut.OutputByte(0x80);*/ esDecoderOut.OutputByte(AACHeader.Num()); esDecoderOut.Serialize((LPVOID)AACHeader.Array(), AACHeader.Num()); } List<BYTE> esDescriptor; BufferOutputSerializer esOut(esDescriptor); esOut.OutputWord(0); //es id esOut.OutputByte(0); //stream priority esOut.OutputByte(4); //descriptor type /*esOut.OutputByte(0x80); //some stuff that no one should probably care about esOut.OutputByte(0x80); esOut.OutputByte(0x80);*/ esOut.OutputByte(esDecoderDescriptor.Num()); esOut.Serialize((LPVOID)esDecoderDescriptor.Array(), esDecoderDescriptor.Num()); esOut.OutputByte(0x6); //config descriptor type /*esOut.OutputByte(0x80); //some stuff that no one should probably care about esOut.OutputByte(0x80); esOut.OutputByte(0x80);*/ esOut.OutputByte(1); //len esOut.OutputByte(2); //SL value(? always 2) //------------------------------------------- PushBox(output, DWORD_BE('moov')); //------------------------------------------------------ // header PushBox(output, DWORD_BE('mvhd')); output.OutputDword(0); //version and flags (none) output.OutputDword(macTime); //creation time output.OutputDword(macTime); //modified time output.OutputDword(DWORD_BE(1000)); //time base (milliseconds, so 1000) output.OutputDword(videoDuration); //duration (in time base units) output.OutputDword(DWORD_BE(0x00010000)); //fixed point playback speed 1.0 output.OutputWord(WORD_BE(0x0100)); //fixed point vol 1.0 output.OutputQword(0); //reserved (10 bytes) output.OutputWord(0); output.OutputDword(DWORD_BE(0x00010000)); output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00000000)); //window matrix row 1 (1.0, 0.0, 0.0) output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00010000)); output.OutputDword(DWORD_BE(0x00000000)); //window matrix row 2 (0.0, 1.0, 0.0) output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x40000000)); //window matrix row 3 (0.0, 0.0, 16384.0) output.OutputDword(0); //prevew start time (time base units) output.OutputDword(0); //prevew duration (time base units) output.OutputDword(0); //still poster frame (timestamp of frame) output.OutputDword(0); //selection(?) start time (time base units) output.OutputDword(0); //selection(?) duration (time base units) output.OutputDword(0); //current time (0, time base units) output.OutputDword(DWORD_BE(3)); //next free track id (1-based rather than 0-based) PopBox(output); //mvhd //------------------------------------------------------ // audio track PushBox(output, DWORD_BE('trak')); PushBox(output, DWORD_BE('tkhd')); //track header output.OutputDword(DWORD_BE(0x00000007)); //version (0) and flags (0xF) output.OutputDword(macTime); //creation time output.OutputDword(macTime); //modified time output.OutputDword(DWORD_BE(1)); //track ID output.OutputDword(0); //reserved output.OutputDword(audioDuration); //duration (in time base units) output.OutputQword(0); //reserved output.OutputWord(0); //video layer (0) output.OutputWord(WORD_BE(0)); //quicktime alternate track id output.OutputWord(WORD_BE(0x0100)); //volume output.OutputWord(0); //reserved output.OutputDword(DWORD_BE(0x00010000)); output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00000000)); //window matrix row 1 (1.0, 0.0, 0.0) output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00010000)); output.OutputDword(DWORD_BE(0x00000000)); //window matrix row 2 (0.0, 1.0, 0.0) output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x40000000)); //window matrix row 3 (0.0, 0.0, 16384.0) output.OutputDword(0); //width (fixed point) output.OutputDword(0); //height (fixed point) PopBox(output); //tkhd /*PushBox(output, DWORD_BE('edts')); PushBox(output, DWORD_BE('elst')); output.OutputDword(0); //version and flags (none) output.OutputDword(DWORD_BE(1)); //count output.OutputDword(audioDuration); //duration output.OutputDword(0); //start time output.OutputDword(DWORD_BE(0x00010000)); //playback speed (1.0) PopBox(); //elst PopBox(); //tdst*/ PushBox(output, DWORD_BE('mdia')); PushBox(output, DWORD_BE('mdhd')); output.OutputDword(0); //version and flags (none) output.OutputDword(macTime); //creation time output.OutputDword(macTime); //modified time output.OutputDword(DWORD_BE(App->GetSampleRateHz())); //time scale output.OutputDword(audioUnitDuration); output.OutputDword(bMP3 ? DWORD_BE(0x55c40000) : DWORD_BE(0x15c70000)); PopBox(output); //mdhd PushBox(output, DWORD_BE('hdlr')); output.OutputDword(0); //version and flags (none) output.OutputDword(0); //quicktime type (none) output.OutputDword(DWORD_BE('soun')); //media type output.OutputDword(0); //manufacturer reserved output.OutputDword(0); //quicktime component reserved flags output.OutputDword(0); //quicktime component reserved mask output.Serialize((LPVOID)lpAudioTrack, (DWORD)strlen(lpAudioTrack)+1); //track name PopBox(output); //hdlr PushBox(output, DWORD_BE('minf')); PushBox(output, DWORD_BE('smhd')); output.OutputDword(0); //version and flags (none) output.OutputDword(0); //balance (fixed point) PopBox(output); //vdhd PushBox(output, DWORD_BE('dinf')); PushBox(output, DWORD_BE('dref')); output.OutputDword(0); //version and flags (none) output.OutputDword(DWORD_BE(1)); //count PushBox(output, DWORD_BE('url ')); output.OutputDword(DWORD_BE(0x00000001)); //version (0) and flags (1) PopBox(output); //url PopBox(output); //dref PopBox(output); //dinf PushBox(output, DWORD_BE('stbl')); PushBox(output, DWORD_BE('stsd')); output.OutputDword(0); //version and flags (none) output.OutputDword(DWORD_BE(1)); //count PushBox(output, DWORD_BE('mp4a')); output.OutputDword(0); //reserved (6 bytes) output.OutputWord(0); output.OutputWord(WORD_BE(1)); //dref index output.OutputWord(0); //quicktime encoding version output.OutputWord(0); //quicktime encoding revision output.OutputDword(0); //quicktime audio encoding vendor output.OutputWord(0); //channels (ignored) output.OutputWord(WORD_BE(16)); //sample size output.OutputWord(0); //quicktime audio compression id output.OutputWord(0); //quicktime audio packet size output.OutputDword(DWORD_BE(App->GetSampleRateHz()<<16)); //sample rate (fixed point) PushBox(output, DWORD_BE('esds')); output.OutputDword(0); //version and flags (none) output.OutputByte(3); //ES descriptor type /*output.OutputByte(0x80); output.OutputByte(0x80); output.OutputByte(0x80);*/ output.OutputByte(esDescriptor.Num()); output.Serialize((LPVOID)esDescriptor.Array(), esDescriptor.Num()); PopBox(output); PopBox(output); PopBox(output); //stsd PushBox(output, DWORD_BE('stts')); //list of keyframe (i-frame) IDs output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(audioDecodeTimes.Num())); for(UINT i=0; i<audioDecodeTimes.Num(); i++) { output.OutputDword(fastHtonl(audioDecodeTimes[i].count)); output.OutputDword(fastHtonl(audioDecodeTimes[i].val)); } PopBox(output); //stss PushBox(output, DWORD_BE('stsc')); //sample to chunk list output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(audioSampleToChunk.Num())); for(UINT i=0; i<audioSampleToChunk.Num(); i++) { SampleToChunk &stc = audioSampleToChunk[i]; output.OutputDword(fastHtonl(stc.firstChunkID)); output.OutputDword(fastHtonl(stc.samplesPerChunk)); output.OutputDword(DWORD_BE(1)); } PopBox(output); //stsc //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 30, 0); //ProcessEvents(); PushBox(output, DWORD_BE('stsz')); //sample sizes output.OutputDword(0); //version and flags (none) output.OutputDword(0); //block size for all (0 if differing sizes) output.OutputDword(fastHtonl(audioFrames.Num())); for(UINT i=0; i<audioFrames.Num(); i++) output.OutputDword(fastHtonl(audioFrames[i].size)); PopBox(output); //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 40, 0); //ProcessEvents(); if(audioChunks.Num() && audioChunks.Last() > 0xFFFFFFFFLL) { PushBox(output, DWORD_BE('co64')); //chunk offsets output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(audioChunks.Num())); for(UINT i=0; i<audioChunks.Num(); i++) output.OutputQword(fastHtonll(audioChunks[i])); PopBox(output); //co64 } else { PushBox(output, DWORD_BE('stco')); //chunk offsets output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(audioChunks.Num())); for(UINT i=0; i<audioChunks.Num(); i++) output.OutputDword(fastHtonl((DWORD)audioChunks[i])); PopBox(output); //stco } PopBox(output); //stbl PopBox(output); //minf PopBox(output); //mdia PopBox(output); //trak //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 50, 0); //ProcessEvents(); //------------------------------------------------------ // video track PushBox(output, DWORD_BE('trak')); PushBox(output, DWORD_BE('tkhd')); //track header output.OutputDword(DWORD_BE(0x00000007)); //version (0) and flags (0x7) output.OutputDword(macTime); //creation time output.OutputDword(macTime); //modified time output.OutputDword(DWORD_BE(2)); //track ID output.OutputDword(0); //reserved output.OutputDword(videoDuration); //duration (in time base units) output.OutputQword(0); //reserved output.OutputWord(0); //video layer (0) output.OutputWord(0); //quicktime alternate track id (0) output.OutputWord(0); //track audio volume (this is video, so 0) output.OutputWord(0); //reserved output.OutputDword(DWORD_BE(0x00010000)); output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00000000)); //window matrix row 1 (1.0, 0.0, 0.0) output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00010000)); output.OutputDword(DWORD_BE(0x00000000)); //window matrix row 2 (0.0, 1.0, 0.0) output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x00000000)); output.OutputDword(DWORD_BE(0x40000000)); //window matrix row 3 (0.0, 0.0, 16384.0) output.OutputDword(fastHtonl(width<<16)); //width (fixed point) output.OutputDword(fastHtonl(height<<16)); //height (fixed point) PopBox(output); //tkhd /*PushBox(output, DWORD_BE('edts')); PushBox(output, DWORD_BE('elst')); output.OutputDword(0); //version and flags (none) output.OutputDword(DWORD_BE(1)); //count output.OutputDword(videoDuration); //duration output.OutputDword(0); //start time output.OutputDword(DWORD_BE(0x00010000)); //playback speed (1.0) PopBox(); //elst PopBox(); //tdst*/ PushBox(output, DWORD_BE('mdia')); PushBox(output, DWORD_BE('mdhd')); output.OutputDword(0); //version and flags (none) output.OutputDword(macTime); //creation time output.OutputDword(macTime); //modified time output.OutputDword(DWORD_BE(1000)); //time scale output.OutputDword(videoDuration); output.OutputDword(DWORD_BE(0x55c40000)); PopBox(output); //mdhd PushBox(output, DWORD_BE('hdlr')); output.OutputDword(0); //version and flags (none) output.OutputDword(0); //quicktime type (none) output.OutputDword(DWORD_BE('vide')); //media type output.OutputDword(0); //manufacturer reserved output.OutputDword(0); //quicktime component reserved flags output.OutputDword(0); //quicktime component reserved mask output.Serialize((LPVOID)lpVideoTrack, (DWORD)strlen(lpVideoTrack)+1); //track name PopBox(output); //hdlr PushBox(output, DWORD_BE('minf')); PushBox(output, DWORD_BE('vmhd')); output.OutputDword(DWORD_BE(0x00000001)); //version (0) and flags (1) output.OutputWord(0); //quickdraw graphic mode (copy = 0) output.OutputWord(0); //quickdraw red value output.OutputWord(0); //quickdraw green value output.OutputWord(0); //quickdraw blue value PopBox(output); //vdhd PushBox(output, DWORD_BE('dinf')); PushBox(output, DWORD_BE('dref')); output.OutputDword(0); //version and flags (none) output.OutputDword(DWORD_BE(1)); //count PushBox(output, DWORD_BE('url ')); output.OutputDword(DWORD_BE(0x00000001)); //version (0) and flags (1) PopBox(output); //url PopBox(output); //dref PopBox(output); //dinf PushBox(output, DWORD_BE('stbl')); PushBox(output, DWORD_BE('stsd')); output.OutputDword(0); //version and flags (none) output.OutputDword(DWORD_BE(1)); //count PushBox(output, DWORD_BE('avc1')); output.OutputDword(0); //reserved 6 bytes output.OutputWord(0); output.OutputWord(WORD_BE(1)); //index output.OutputWord(0); //encoding version output.OutputWord(0); //encoding revision level output.OutputDword(0); //encoding vendor output.OutputDword(0); //temporal quality output.OutputDword(0); //spatial quality output.OutputWord(fastHtons(width)); //width output.OutputWord(fastHtons(height)); //height output.OutputDword(DWORD_BE(0x00480000)); //fixed point width pixel resolution (72.0) output.OutputDword(DWORD_BE(0x00480000)); //fixed point height pixel resolution (72.0) output.OutputDword(0); //quicktime video data size output.OutputWord(WORD_BE(1)); //frame count(?) output.OutputByte((BYTE)strlen(videoCompressionName)); //compression name length output.Serialize(videoCompressionName, 31); //31 bytes for the name output.OutputWord(WORD_BE(24)); //bit depth output.OutputWord(0xFFFF); //quicktime video color table id (none = -1) PushBox(output, DWORD_BE('avcC')); output.OutputByte(1); //version output.OutputByte(100); //h264 profile ID output.OutputByte(0); //h264 compatible profiles output.OutputByte(0x1f); //h264 level output.OutputByte(0xff); //reserved output.OutputByte(0xe1); //first half-byte = no clue. second half = sps count output.OutputWord(fastHtons(SPS.Num())); //sps size output.Serialize(SPS.Array(), SPS.Num()); //sps data output.OutputByte(1); //pps count output.OutputWord(fastHtons(PPS.Num())); //pps size output.Serialize(PPS.Array(), PPS.Num()); //pps data PopBox(output); //avcC PopBox(output); //avc1 PopBox(output); //stsd PushBox(output, DWORD_BE('stts')); //frame times output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(videoDecodeTimes.Num())); for(UINT i=0; i<videoDecodeTimes.Num(); i++) { output.OutputDword(fastHtonl(videoDecodeTimes[i].count)); output.OutputDword(fastHtonl(videoDecodeTimes[i].val)); } PopBox(output); //stts //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 60, 0); //ProcessEvents(); if (IFrameIDs.Num()) { PushBox(output, DWORD_BE('stss')); //list of keyframe (i-frame) IDs output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(IFrameIDs.Num())); output.Serialize(IFrameIDs.Array(), IFrameIDs.Num()*sizeof(UINT)); PopBox(output); //stss } PushBox(output, DWORD_BE('ctts')); //list of composition time offsets output.OutputDword(0); //version (0) and flags (none) //output.OutputDword(DWORD_BE(0x01000000)); //version (1) and flags (none) output.OutputDword(fastHtonl(compositionOffsets.Num())); for(UINT i=0; i<compositionOffsets.Num(); i++) { output.OutputDword(fastHtonl(compositionOffsets[i].count)); output.OutputDword(fastHtonl(compositionOffsets[i].val)); } PopBox(output); //ctts //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 70, 0); //ProcessEvents(); PushBox(output, DWORD_BE('stsc')); //sample to chunk list output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(videoSampleToChunk.Num())); for(UINT i=0; i<videoSampleToChunk.Num(); i++) { SampleToChunk &stc = videoSampleToChunk[i]; output.OutputDword(fastHtonl(stc.firstChunkID)); output.OutputDword(fastHtonl(stc.samplesPerChunk)); output.OutputDword(DWORD_BE(1)); } PopBox(output); //stsc PushBox(output, DWORD_BE('stsz')); //sample sizes output.OutputDword(0); //version and flags (none) output.OutputDword(0); //block size for all (0 if differing sizes) output.OutputDword(fastHtonl(videoFrames.Num())); for(UINT i=0; i<videoFrames.Num(); i++) output.OutputDword(fastHtonl(videoFrames[i].size)); PopBox(output); if(videoChunks.Num() && videoChunks.Last() > 0xFFFFFFFFLL) { PushBox(output, DWORD_BE('co64')); //chunk offsets output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(videoChunks.Num())); for(UINT i=0; i<videoChunks.Num(); i++) output.OutputQword(fastHtonll(videoChunks[i])); PopBox(output); //co64 } else { PushBox(output, DWORD_BE('stco')); //chunk offsets output.OutputDword(0); //version and flags (none) output.OutputDword(fastHtonl(videoChunks.Num())); for(UINT i=0; i<videoChunks.Num(); i++) output.OutputDword(fastHtonl((DWORD)videoChunks[i])); PopBox(output); //stco } PopBox(output); //stbl PopBox(output); //minf PopBox(output); //mdia PopBox(output); //trak //SendMessage(GetDlgItem(hwndProgressDialog, IDC_PROGRESS1), PBM_SETPOS, 80, 0); //ProcessEvents(); //------------------------------------------------------ // info thingy PushBox(output, DWORD_BE('udta')); PushBox(output, DWORD_BE('meta')); output.OutputDword(0); //version and flags (none) PushBox(output, DWORD_BE('hdlr')); output.OutputDword(0); //version and flags (none) output.OutputDword(0); //quicktime type output.OutputDword(DWORD_BE('mdir')); //metadata type output.OutputDword(DWORD_BE('appl')); //quicktime manufacturer reserved thingy output.OutputDword(0); //quicktime component reserved flag output.OutputDword(0); //quicktime component reserved flag mask output.OutputByte(0); //null string PopBox(output); //hdlr PushBox(output, DWORD_BE('ilst')); PushBox(output, DWORD_BE('\xa9too')); PushBox(output, DWORD_BE('data')); output.OutputDword(DWORD_BE(1)); //version (1) + flags (0) output.OutputDword(0); //reserved LPSTR lpVersion = OBS_VERSION_STRING_ANSI; output.Serialize(lpVersion, (DWORD)strlen(lpVersion)); PopBox(output); //data PopBox(output); //@too PopBox(output); //ilst PopBox(output); //meta PopBox(output); //udta PopBox(output); //moov fileOut.Serialize(endBuffer.Array(), (DWORD)output.GetPos()); fileOut.Close(); XFile file; if(file.Open(strFile, XFILE_WRITE, XFILE_OPENEXISTING)) { #ifdef USE_64BIT_MP4 file.SetPos((INT64)mdatStart+8, XFILE_BEGIN); UINT64 size = fastHtonll(mdatStop-mdatStart); file.Write(&size, 8); #else file.SetPos((INT64)mdatStart, XFILE_BEGIN); UINT size = fastHtonl((DWORD)(mdatStop-mdatStart)); file.Write(&size, 4); #endif file.Close(); } App->EnableSceneSwitching(true); //DestroyWindow(hwndProgressDialog); }
xf_error_codes close(void) { end(); xf_error_codes err=xf->close(); if (err) errorn=err; return err; };
bool XConfig::Open(CTSTR lpFile) { if(RootElement) { if(strFileName.CompareI(lpFile)) return true; Close(); } //------------------------------------- XFile file; if(!file.Open(lpFile, XFILE_READ, XFILE_OPENALWAYS)) return false; RootElement = new XElement(this, NULL, TEXT("Root")); strFileName = lpFile; DWORD dwFileSize = (DWORD)file.GetFileSize(); LPSTR lpFileDataUTF8 = (LPSTR)Allocate(dwFileSize+1); zero(lpFileDataUTF8, dwFileSize+1); file.Read(lpFileDataUTF8, dwFileSize); TSTR lpFileData = utf8_createTstr(lpFileDataUTF8); Free(lpFileDataUTF8); //------------------------------------- // remove comments TSTR lpComment, lpEndComment; while(lpComment = sstr(lpFileData, TEXT("/*"))) { lpEndComment = sstr(lpFileData, TEXT("*/")); assert(lpEndComment); assert(lpComment < lpEndComment); if(!lpEndComment || (lpComment > lpEndComment)) { file.Close(); Close(false); Free(lpFileData); CrashError(TEXT("Error parsing X file '%s'"), strFileName.Array()); } mcpy(lpComment, lpEndComment+3, slen(lpEndComment+3)+1); } //------------------------------------- TSTR lpTemp = lpFileData; if(!ReadFileData(RootElement, 0, lpTemp)) { for(DWORD i=0; i<RootElement->SubItems.Num(); i++) delete RootElement->SubItems[i]; CrashError(TEXT("Error parsing X file '%s'"), strFileName.Array()); Free(lpFileData); Close(false); file.Close(); } Free(lpFileData); file.Close(); return true; }
bool Display(float timeDelta) { if( Device ) { if(::GetAsyncKeyState('P') & 0x8000f) pause = true; if(::GetAsyncKeyState('W') & 0x8000f) TheCamera.walk(1.0 * DTime); if(::GetAsyncKeyState('S') & 0x8000f) TheCamera.walk(-1.0 * DTime); if(::GetAsyncKeyState('A') & 0x8000f) TheCamera.strafe(-1.0 * DTime); if(::GetAsyncKeyState('D') & 0x8000f) TheCamera.strafe(1.0 * DTime); if(::GetAsyncKeyState('F') & 0x8000f) TheCamera.fly(-1.0 * DTime); if(::GetAsyncKeyState('R') & 0x8000f) TheCamera.fly(1.0 * DTime); if(::GetAsyncKeyState(VK_UP) & 0x8000f) TheCamera.pitch(-.250 * DTime); if(::GetAsyncKeyState(VK_DOWN) & 0x8000f) TheCamera.pitch(.250 * DTime); if(::GetAsyncKeyState(VK_LEFT) & 0x8000f) TheCamera.yaw(-.250 * DTime); if(::GetAsyncKeyState(VK_RIGHT) & 0x8000f) TheCamera.yaw(.250 * DTime); if(::GetAsyncKeyState(VK_HOME) & 0x8000f) TheCamera.roll(.250 * DTime); if(::GetAsyncKeyState(VK_END) & 0x8000f) TheCamera.roll(-.250 * DTime); if(TheCamera._up.y < 0) TheCamera._up.y *= -1; Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff0000ff, 1.0f, 0); Device->BeginScene(); DrawWalls(); D3DXMATRIX i, tripler, grow; D3DXMatrixIdentity(&i); Device->SetTransform(D3DTS_WORLD, &i); //1 D3DXMatrixTranslation(&tripler, TigerPos.x, TigerPos.y, TigerPos.z); D3DXMatrixScaling(&grow, 5/sizeModifier, 5/sizeModifier, 5/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Tiger.Draw(Stone); //2 D3DXMatrixTranslation(&tripler, CastlePos.x, CastlePos.y, CastlePos.z); D3DXMatrixScaling(&grow, 2.5/sizeModifier, 1/sizeModifier, 2.5/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Castle.Draw(Stone); //3 D3DXMatrixTranslation(&tripler, GrenadePos.x, GrenadePos.y, GrenadePos.z); D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Grenade.Draw(Stone); //4 D3DXMatrixTranslation(&tripler, ManorPos.x, ManorPos.y, ManorPos.z); D3DXMatrixScaling(&grow, 5000/sizeModifier, 5000/sizeModifier, 50); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Manor.Draw(Stone); //5 D3DXMatrixTranslation(&tripler, MonsterPos.x, MonsterPos.y, MonsterPos.z); D3DXMatrixScaling(&grow, 1/sizeModifier, 1/sizeModifier, 1/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Monster.Draw(Stone); //6 D3DXMatrixTranslation(&tripler, RavengerSirenPos.x, RavengerSirenPos.y, RavengerSirenPos.z); D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); RavengerSiren.Draw(Stone); //7 D3DXMatrixTranslation(&tripler, SectoidPos.x, SectoidPos.y, SectoidPos.z); D3DXMatrixScaling(&grow, 3/sizeModifier, 3/sizeModifier, 3/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Sectoid.Draw(Stone); //8 D3DXMatrixTranslation(&tripler, SlendermanPos.x, SlendermanPos.y, SlendermanPos.z); D3DXMatrixScaling(&grow, .05/sizeModifier, .05/sizeModifier, .05/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Slenderman.Draw(Stone); //9 D3DXMatrixTranslation(&tripler, SoccerPos.x, SoccerPos.y, SoccerPos.z); D3DXMatrixScaling(&grow, .05/sizeModifier, .05/sizeModifier, .05/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Soccer.Draw(Stone); //10 D3DXMatrixTranslation(&tripler, TurretPos.x, TurretPos.y, TurretPos.z); D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Turret.Draw(Stone); //11 D3DXMatrixTranslation(&tripler, UltramanPos.x, UltramanPos.y, UltramanPos.z); D3DXMatrixScaling(&grow, .01/sizeModifier, .01/sizeModifier, .01/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Ultraman.Draw(Stone); //12 D3DXMatrixTranslation(&tripler, ZombiePos.x, ZombiePos.y, ZombiePos.z); D3DXMatrixScaling(&grow, .1/sizeModifier, .1/sizeModifier, .1/sizeModifier); D3DXMatrixMultiply(&tripler, &grow, &tripler); Device->SetTransform(D3DTS_WORLD, &tripler); Zombie.Draw(Stone); if(!shrunk && p.z > 10) { shrunk = true; sound.AudioPlay(Voice); ::MessageBoxA(0, "OH NO! you appear to be Shrinking\nStart Running to try and reach the manor", "Oh No!", MB_OK); DTime *= 5; } else if(shrunk) { if(sizeModifier >1) { sizeModifier-=.005; } else if(message) { message = false; ::MessageBoxA(0, "It's too late, however you seem to be at the entrance to a castle and there appears to be some createures on the inside.\nMaybe you should try to approach one of them, Be Careful Though: they could be Evil", "Too Late", MB_OK); } } static bool approach = false; if(!approach) if(p.z > 125) { ::MessageBoxA(0, "The creatures seem to be frozen and have had all their color drained...\nThey look like they were once the things that only exis in nightmares\nWhat kind of Powerfull Monster could have done this?\nMaybe you shouldn't have ignored those warnings.", "", MB_OK); approach = true; } static bool bang = false; if(p.z > 0) { if(!bang) { bang = true; sound.AudioPlay(Bang); } Device->SetStreamSource(0, VBufferGround, 0, sizeof(Vertex)); Device->SetFVF(FVF_VERTEX); Device->SetTexture(0, DoNot); Device->SetTransform(D3DTS_WORLD, &i); Device->DrawPrimitive(D3DPT_TRIANGLELIST, 36, 2); Device->SetRenderState(D3DRS_ALPHABLENDENABLE, false); } D3DXMATRIX V, T; TheCamera.getViewMatrix(&V); Device->SetTransform(D3DTS_VIEW, &V); TheCamera.getPosition(&p); if (p.y != 8.5) p.y = 8.5; TheCamera.setPosition(&p); TheCamera.getLook(&t); Device->EndScene(); Device->Present(0, 0, 0, 0); } return true; }
bool Setup() { Tiger.init(Device, "Tiger.X");//1 Castle.init(Device, "Castle.X");//2 Grenade.init(Device, "Grenade.X");//3 Manor.init(Device, "Manor.X");//4 Monster.init(Device, "Monster.X");//5 RavengerSiren.init(Device, "RavengerSiren.X");//6 Sectoid.init(Device, "Sectoid.X");//7 Slenderman.init(Device, "Slenderman.X");//8 Soccer.init(Device, "Soccer.X");//9 Turret.init(Device, "Turret.X");//10 Ultraman.init(Device, "Ultraman.X");//11 Zombie.init(Device, "Zombie.X");//12 //Set texture filters. Device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); Device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); // // Create the BackDrop quad. // // //Ground // Device->CreateVertexBuffer(42 * sizeof(Vertex), D3DUSAGE_WRITEONLY, FVF_VERTEX, D3DPOOL_MANAGED, &VBufferGround, 0); Vertex* VGround; VBufferGround->Lock(0, 0, (void**)&VGround, 0); VGround[0] = Vertex(-0500.0f, 0.0f,-0500.0f, 0.0f, 1.0f, 0.0f, 0.0f, 100.0f); VGround[1] = Vertex(-0500.0f, 0.0f,0500.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); VGround[2] = Vertex( 0500.0f, 0.0f,0500.0f, 0.0f, 1.0f, 0.0f, 100.0f, 0.0f); VGround[3] = Vertex(-0500.0f, 0.0f,-0500.0f, 0.0f, 1.0f, 0.0f, 0.0f, 100.0f); VGround[4] = Vertex(0500.0f, 0.0f,0500.0f, 0.0f, 1.0f, 0.0f, 100.0f, 0.0f); VGround[5] = Vertex(0500.0f, 0.0f,-0500.0f, 0.0f, 1.0f, 0.0f, 100.0f, 100.0f); // //Sky // VGround[6] = Vertex(0500.0f, 1000.0f,0500.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f); VGround[7] = Vertex(-0500.0f, 1000.0f, 0500.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f); VGround[8] = Vertex( -0500.0f, 1000.0f, -0500.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); VGround[9] = Vertex(0500.0f, 1000.0f,500.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f); VGround[10] = Vertex( -0500.0f, 1000.0f,-0500.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f); VGround[11] = Vertex( 0500.0f, 1000.0f,-0500.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f); // //North // VGround[12] = Vertex(-0500.0f, -000.0f, 0500.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); VGround[13] = Vertex(-0500.0f, 1000.0f, 0500.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); VGround[14] = Vertex( 0500.0f, 1000.0f, 0500.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); VGround[15] = Vertex(-0500.0f, -000.0f, 0500.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); VGround[16] = Vertex( 0500.0f, 1000.0f, 0500.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); VGround[17] = Vertex( 0500.0f, -000.0f, 0500.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); // //South // VGround[18] = Vertex( 0500.0f, -0000.0f, -0500.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); VGround[19] = Vertex( 0500.0f, 1000.0f, -0500.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); VGround[20] = Vertex(-0500.0f, 1000.0f, -0500.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); VGround[21] = Vertex( 0500.0f, -0000.0f, -0500.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f); VGround[22] = Vertex(-0500.0f, 1000.0f, -0500.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f); VGround[23] = Vertex(-0500.0f, -0000.0f, -0500.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); // //East // VGround[24] = Vertex( 0500.0f, -0000.0f, 0500.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); VGround[25] = Vertex( 0500.0f, 1000.0f, 0500.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f); VGround[26] = Vertex( 0500.0f, 1000.0f, -0500.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); VGround[27] = Vertex( 0500.0f, -0000.0f, 0500.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f); VGround[28] = Vertex( 0500.0f, 1000.0f, -0500.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f); VGround[29] = Vertex( 0500.0f, -0000.0f, -0500.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f); // ////West // VGround[30] = Vertex(-0500.0f, -0000.0f, -0500.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); VGround[31] = Vertex(-0500.0f, 1000.0f, -0500.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f); VGround[32] = Vertex(-0500.0f, 1000.0f, 0500.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); VGround[33] = Vertex(-0500.0f, -0000.0f, -0500.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f); VGround[34] = Vertex(-0500.0f, 1000.0f, 0500.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f); VGround[35] = Vertex(-0500.0f, -0000.0f, 0500.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f); // //Message // VGround[36] = Vertex(-10.0f, 12.5f, 20.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); VGround[37] = Vertex(-10.0f, 20.5f, 20.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f); VGround[38] = Vertex( 10.0f, 20.5f, 20.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); VGround[39] = Vertex(-10.0f, 12.5f, 20.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f); VGround[40] = Vertex( 10.0f, 20.5f, 20.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f); VGround[41] = Vertex( 10.0f, 12.5f, 20.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f); VBufferGround->Unlock(); //Materials Mtrls[0] = d3d::RED_MTRL; Mtrls[1] = d3d::BLUE_MTRL; Mtrls[2] = d3d::GREEN_MTRL; Mtrls[3] = d3d::YELLOW_MTRL; Mtrls[4] = d3d::WHITE_MTRL; Mtrls[5] = d3d::CYAN_MTRL; Mtrls[6] = d3d::ORANGE_MTRL; Mtrls[7] = d3d::BLACK_MTRL; // // Load the textures and set filters. // D3DXCreateTextureFromFile(Device, "Clouds.jpg", &TexSky); D3DXCreateTextureFromFile(Device, "Sky.jpg", &TexDirections); D3DXCreateTextureFromFile(Device, "Grass.jpg", &TexGround); D3DXCreateTextureFromFile(Device, "Wood.jpg", &TexWood); D3DXCreateTextureFromFile(Device, "Stone.jpg", &Stone); D3DXCreateTextureFromFile(Device, "DoNot.png", &DoNot); // // set alpha blending stuff // // use alpha channel in texture for alpha Device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); Device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); // set blending factors so that alpha component determines transparency Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); // // disable lighting // Device->SetRenderState(D3DRS_LIGHTING, false); // // set camera // D3DXVECTOR3 dir(0.0f, -1.0f, 0.0f); D3DXVECTOR3 pos(0.0f, 123.0f, 0.0f); TheCamera.setPosition(&camStart); TheCamera.getPosition(&p); TheCamera.getLook(&t); D3DXMATRIX proj; D3DXMatrixPerspectiveFovLH( &proj, D3DX_PI * 0.5f, // 90 - degree (float)Width / (float)Height, 1.0f, 1000.0f); Device->SetTransform(D3DTS_PROJECTION, &proj); return true; }
LONG CALLBACK OBSExceptionHandler (PEXCEPTION_POINTERS exceptionInfo) { HANDLE hProcess; HMODULE hDbgHelp; MINIDUMP_EXCEPTION_INFORMATION miniInfo; STACKFRAME64 frame = {0}; CONTEXT context = *exceptionInfo->ContextRecord; SYMBOL_INFO *symInfo; DWORD64 fnOffset; TCHAR logPath[MAX_PATH]; OSVERSIONINFOEX osInfo; SYSTEMTIME timeInfo; ENUMERATELOADEDMODULES64 fnEnumerateLoadedModules64; SYMSETOPTIONS fnSymSetOptions; SYMINITIALIZE fnSymInitialize; STACKWALK64 fnStackWalk64; SYMFUNCTIONTABLEACCESS64 fnSymFunctionTableAccess64; SYMGETMODULEBASE64 fnSymGetModuleBase64; SYMFROMADDR fnSymFromAddr; SYMCLEANUP fnSymCleanup; MINIDUMPWRITEDUMP fnMiniDumpWriteDump; SYMGETMODULEINFO64 fnSymGetModuleInfo64; DWORD i; DWORD64 InstructionPtr; DWORD imageType; TCHAR searchPath[MAX_PATH], *p; static BOOL inExceptionHandler = FALSE; moduleinfo_t moduleInfo; //always break into a debugger if one is present if (IsDebuggerPresent ()) return EXCEPTION_CONTINUE_SEARCH; //exception codes < 0x80000000 are typically informative only and not crash worthy //0xe06d7363 indicates a c++ exception was thrown, let's just hope it was caught. //this is no longer needed since we're an unhandled handler vs a vectored handler /*if (exceptionInfo->ExceptionRecord->ExceptionCode < 0x80000000 || exceptionInfo->ExceptionRecord->ExceptionCode == 0xe06d7363 || exceptionInfo->ExceptionRecord->ExceptionCode == 0x800706b5) return EXCEPTION_CONTINUE_SEARCH;*/ //uh oh, we're crashing inside ourselves... this is really bad! if (inExceptionHandler) return EXCEPTION_CONTINUE_SEARCH; inExceptionHandler = TRUE; //load dbghelp dynamically hDbgHelp = LoadLibrary (TEXT("DBGHELP")); if (!hDbgHelp) return EXCEPTION_CONTINUE_SEARCH; fnEnumerateLoadedModules64 = (ENUMERATELOADEDMODULES64)GetProcAddress (hDbgHelp, "EnumerateLoadedModulesW64"); fnSymSetOptions = (SYMSETOPTIONS)GetProcAddress (hDbgHelp, "SymSetOptions"); fnSymInitialize = (SYMINITIALIZE)GetProcAddress (hDbgHelp, "SymInitialize"); fnSymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64)GetProcAddress (hDbgHelp, "SymFunctionTableAccess64"); fnSymGetModuleBase64 = (SYMGETMODULEBASE64)GetProcAddress (hDbgHelp, "SymGetModuleBase64"); fnStackWalk64 = (STACKWALK64)GetProcAddress (hDbgHelp, "StackWalk64"); fnSymFromAddr = (SYMFROMADDR)GetProcAddress (hDbgHelp, "SymFromAddrW"); fnSymCleanup = (SYMCLEANUP)GetProcAddress (hDbgHelp, "SymCleanup"); fnSymGetModuleInfo64 = (SYMGETMODULEINFO64)GetProcAddress (hDbgHelp, "SymGetModuleInfo64"); fnMiniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress (hDbgHelp, "MiniDumpWriteDump"); if (!fnEnumerateLoadedModules64 || !fnSymSetOptions || !fnSymInitialize || !fnSymFunctionTableAccess64 || !fnSymGetModuleBase64 || !fnStackWalk64 || !fnSymFromAddr || !fnSymCleanup || !fnSymGetModuleInfo64) { FreeLibrary (hDbgHelp); return EXCEPTION_CONTINUE_SEARCH; } hProcess = GetCurrentProcess(); fnSymSetOptions (SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_LOAD_ANYTHING); GetModuleFileName (NULL, searchPath, _countof(searchPath)-1); p = srchr (searchPath, '\\'); if (p) *p = 0; //create a log file GetSystemTime (&timeInfo); for (i = 1;;) { tsprintf_s (logPath, _countof(logPath)-1, TEXT("%s\\crashDumps\\OBSCrashLog%.4d-%.2d-%.2d_%d.txt"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i); if (GetFileAttributes(logPath) == INVALID_FILE_ATTRIBUTES) break; i++; } XFile crashDumpLog; if (!crashDumpLog.Open(logPath, XFILE_WRITE, XFILE_CREATENEW)) { FreeLibrary (hDbgHelp); return EXCEPTION_CONTINUE_SEARCH; } //initialize debug symbols fnSymInitialize (hProcess, NULL, TRUE); #ifdef _WIN64 InstructionPtr = context.Rip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp; imageType = IMAGE_FILE_MACHINE_AMD64; #else InstructionPtr = context.Eip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp; imageType = IMAGE_FILE_MACHINE_I386; #endif frame.AddrFrame.Mode = AddrModeFlat; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; symInfo = (SYMBOL_INFO *)LocalAlloc (LPTR, sizeof(*symInfo) + 256); symInfo->SizeOfStruct = sizeof(SYMBOL_INFO); symInfo->MaxNameLen = 256; fnOffset = 0; //get os info memset (&osInfo, 0, sizeof(osInfo)); osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!GetVersionEx ((OSVERSIONINFO *)&osInfo)) { osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx ((OSVERSIONINFO *)&osInfo); } String cpuInfo; HKEY key; // get cpu info if(RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), &key) == ERROR_SUCCESS) { DWORD dwSize = 1024; cpuInfo.SetLength(dwSize); if (RegQueryValueEx(key, TEXT("ProcessorNameString"), NULL, NULL, (LPBYTE)cpuInfo.Array(), &dwSize) != ERROR_SUCCESS) cpuInfo = TEXT("<unable to query>"); RegCloseKey(key); } else cpuInfo = TEXT("<unable to query>"); //determine which module the crash occured in scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = InstructionPtr; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); BOOL isPlugin = FALSE; if (sstr (moduleInfo.moduleName, TEXT("plugins\\"))) isPlugin = TRUE; String strModuleInfo; String crashMessage; fnEnumerateLoadedModules64(hProcess, (PENUMLOADED_MODULES_CALLBACK64)RecordAllLoadedModules, (VOID *)&strModuleInfo); crashMessage << TEXT("OBS has encountered an unhandled exception and has terminated. If you are able to\r\n") TEXT("reproduce this crash, please submit this crash report on the forums at\r\n") TEXT("http://www.obsproject.com/ - include the contents of this crash log and the\r\n") TEXT("minidump .dmp file (if available) as well as your regular OBS log files and\r\n") TEXT("a description of what you were doing at the time of the crash.\r\n") TEXT("\r\n") TEXT("This crash appears to have occured in the '") << moduleInfo.moduleName << TEXT("' module.\r\n\r\n"); crashDumpLog.WriteStr(crashMessage.Array()); crashDumpLog.WriteStr(FormattedString(TEXT("**** UNHANDLED EXCEPTION: %x\r\nFault address: %I64p (%s)\r\n"), exceptionInfo->ExceptionRecord->ExceptionCode, InstructionPtr, moduleInfo.moduleName)); crashDumpLog.WriteStr(TEXT("OBS version: ") OBS_VERSION_STRING TEXT("\r\n")); crashDumpLog.WriteStr(FormattedString(TEXT("Windows version: %d.%d (Build %d) %s\r\nCPU: %s\r\n\r\n"), osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, osInfo.szCSDVersion, cpuInfo.Array())); crashDumpLog.WriteStr(TEXT("Crashing thread stack trace:\r\n")); #ifdef _WIN64 crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #else crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #endif crashDumpLog.FlushFileBuffers(); while (fnStackWalk64 (imageType, hProcess, GetCurrentThread(), &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL)) { scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = frame.AddrPC.Offset; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); p = srchr (moduleInfo.moduleName, '\\'); if (p) p++; else p = moduleInfo.moduleName; #ifdef _WIN64 if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); } #else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); } #endif crashDumpLog.FlushFileBuffers(); } //if we manually crashed due to a deadlocked thread, record some extra info if (exceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) { HANDLE hVideoThread = NULL, hEncodeThread = NULL; App->GetThreadHandles (&hVideoThread, &hEncodeThread); if (hVideoThread) { crashDumpLog.WriteStr(TEXT("\r\nVideo thread stack trace:\r\n")); #ifdef _WIN64 crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #else crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #endif crashDumpLog.FlushFileBuffers(); context.ContextFlags = CONTEXT_ALL; GetThreadContext (hVideoThread, &context); ZeroMemory (&frame, sizeof(frame)); #ifdef _WIN64 InstructionPtr = context.Rip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp; imageType = IMAGE_FILE_MACHINE_AMD64; #else InstructionPtr = context.Eip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp; imageType = IMAGE_FILE_MACHINE_I386; #endif frame.AddrFrame.Mode = AddrModeFlat; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; while (fnStackWalk64 (imageType, hProcess, hVideoThread, &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL)) { scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = frame.AddrPC.Offset; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); p = srchr (moduleInfo.moduleName, '\\'); if (p) p++; else p = moduleInfo.moduleName; #ifdef _WIN64 if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); } #else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); } #endif crashDumpLog.FlushFileBuffers(); } } if (hEncodeThread) { crashDumpLog.WriteStr(TEXT("\r\nEncode thread stack trace:\r\n")); #ifdef _WIN64 crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #else crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #endif crashDumpLog.FlushFileBuffers(); context.ContextFlags = CONTEXT_ALL; GetThreadContext (hEncodeThread, &context); ZeroMemory (&frame, sizeof(frame)); #ifdef _WIN64 InstructionPtr = context.Rip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp; imageType = IMAGE_FILE_MACHINE_AMD64; #else InstructionPtr = context.Eip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp; imageType = IMAGE_FILE_MACHINE_I386; #endif frame.AddrFrame.Mode = AddrModeFlat; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; while (fnStackWalk64 (imageType, hProcess, hEncodeThread, &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL)) { scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = frame.AddrPC.Offset; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); p = srchr (moduleInfo.moduleName, '\\'); if (p) p++; else p = moduleInfo.moduleName; #ifdef _WIN64 if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); } #else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); } #endif crashDumpLog.FlushFileBuffers(); } } } //generate a minidump if possible if (fnMiniDumpWriteDump) { TCHAR dumpPath[MAX_PATH]; HANDLE hFile; tsprintf_s (dumpPath, _countof(dumpPath)-1, TEXT("%s\\crashDumps\\OBSCrashDump%.4d-%.2d-%.2d_%d.dmp"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i); hFile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { MINIDUMP_TYPE dumpFlags = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData); miniInfo.ClientPointers = TRUE; miniInfo.ExceptionPointers = exceptionInfo; miniInfo.ThreadId = GetCurrentThreadId (); if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, dumpFlags, &miniInfo, NULL, NULL)) { crashDumpLog.WriteStr(FormattedString(TEXT("\r\nA minidump was saved to %s.\r\nPlease include this file when posting a crash report.\r\n"), dumpPath)); } else { CloseHandle (hFile); DeleteFile (dumpPath); } } } else { crashDumpLog.WriteStr(TEXT("\r\nA minidump could not be created. Please check dbghelp.dll is present.\r\n")); } crashDumpLog.WriteStr("\r\nList of loaded modules:\r\n"); #ifdef _WIN64 crashDumpLog.WriteStr("Base Address Module\r\n"); #else crashDumpLog.WriteStr("Base Address Module\r\n"); #endif crashDumpLog.WriteStr(strModuleInfo); crashDumpLog.Close(); LocalFree (symInfo); fnSymCleanup (hProcess); if (OBSMessageBox(hwndMain, TEXT("Woops! OBS has crashed. Would you like to view a crash report?"), NULL, MB_ICONERROR | MB_YESNO) == IDYES) ShellExecute(NULL, NULL, logPath, NULL, searchPath, SW_SHOWDEFAULT); FreeLibrary (hDbgHelp); //we really shouldn't be returning here, if we're at the bottom of the VEH chain this is a pretty legitimate crash //and if we return we could end up invoking a second crash handler or other weird / annoying things //ExitProcess(exceptionInfo->ExceptionRecord->ExceptionCode); return EXCEPTION_CONTINUE_SEARCH; }
void SdtpCatalogDataProvider::fetch(int type, void *param) { switch(type) { case FoldersRecursive: { XFolder* parent = static_cast<XFolder*>(param); Q_CHECK_PTR(parent); QUrl url( QString(SDTP_URL_GETALLCATS) ); createRequest(url, FoldersRecursive, parent); break; } case Folders: { XFolder* parent = static_cast<XFolder*>(param); Q_CHECK_PTR(parent); QUrl url( QString(SDTP_URL_GETCATS).arg(parent->id()) ); createRequest(url, Folders, parent); break; } case Files: { XFolder* parent = static_cast<XFolder*>(param); Q_CHECK_PTR(parent); QUrl url( QString(SDTP_URL_GETFILES).arg(parent->id()) ); createRequest(url, Files, parent); break; } case FileDetails: { XFile* file = static_cast<XFile*>(param); Q_CHECK_PTR(file); QUrl url( QString(SDTP_URL_GETDETAILS).arg(file->id()) ); createRequest(url, FileDetails, file); break; } case Thumbnail: { XFile* file = static_cast<XFile*>(param); Q_CHECK_PTR(file); QUrl url( file->thumbLink() ); createRequest(url, Thumbnail, file); break; } default: qDebug("Unknown request type '%d'", static_cast<quint32>(type)); } }
void ConfigFile::SetKey(CTSTR lpSection, CTSTR lpKey, CTSTR newvalue) { assert(lpSection); assert(lpKey); TSTR lpTemp = lpFileData, lpEnd = &lpFileData[dwLength], lpSectionStart; DWORD dwSectionNameSize = slen(lpSection), dwKeyNameSize = slen(lpKey); BOOL bInSection = 0; do { lpTemp = sstr(lpTemp, TEXT("\n[")); if(!lpTemp) break; lpTemp += 2; if((scmpi_n(lpTemp, lpSection, dwSectionNameSize) == 0) && (lpTemp[dwSectionNameSize] == ']')) { bInSection = 1; lpSectionStart = lpTemp = schr(lpTemp, '\n')+1; break; } }while(lpTemp < lpEnd); if(!bInSection) { lpTemp -= 2; XFile file(strFileName, XFILE_WRITE, XFILE_CREATEALWAYS); file.Write("\xEF\xBB\xBF", 3); file.WriteAsUTF8(&lpFileData[2], dwLength-4); file.Write("\r\n[", 3); file.WriteAsUTF8(lpSection, dwSectionNameSize); file.Write("]\r\n", 3); file.WriteAsUTF8(lpKey, dwKeyNameSize); file.Write("=", 1); file.WriteAsUTF8(newvalue, slen(newvalue)); file.Write("\r\n", 2); file.Close(); if(LoadFile(XFILE_OPENEXISTING)) LoadData(); return; } do { if(*lpTemp == '[') { XFile file(strFileName, XFILE_WRITE, XFILE_CREATEALWAYS); file.Write("\xEF\xBB\xBF", 3); file.WriteAsUTF8(&lpFileData[2], DWORD(lpSectionStart-lpFileData-2)); file.WriteAsUTF8(lpKey, dwKeyNameSize); file.Write("=", 1); file.WriteAsUTF8(newvalue, slen(newvalue)); file.Write("\r\n", 2); file.WriteAsUTF8(lpSectionStart, slen(lpSectionStart)-2); file.Close(); if(LoadFile(XFILE_OPENEXISTING)) LoadData(); return; } else if(*(LPWORD)lpTemp == '//') { lpTemp = schr(lpTemp, '\n')+1; continue; } else if(bInSection) { if((scmpi_n(lpTemp, lpKey, dwKeyNameSize) == 0) && (lpTemp[dwKeyNameSize] == '=')) { lpTemp = &lpTemp[dwKeyNameSize+1]; TSTR lpNextLine = schr(lpTemp, '\r'); int newlen = slen(newvalue); if ((*lpTemp == '\r' && *newvalue == '\0') || (lpNextLine - lpTemp == newlen && !scmp_n(lpTemp, newvalue, newlen))) return; String tmpFileName = strFileName; tmpFileName += TEXT(".tmp"); XFile file; if (file.Open(tmpFileName, XFILE_WRITE, XFILE_CREATEALWAYS)) { if (file.Write("\xEF\xBB\xBF", 3) != 3) return; if (!file.WriteAsUTF8(&lpFileData[2], DWORD(lpTemp - lpFileData - 2))) return; if (!file.WriteAsUTF8(newvalue, slen(newvalue))) return; if (!file.WriteAsUTF8(lpNextLine, slen(lpNextLine) - 2)) return; file.Close(); if (!OSRenameFile(tmpFileName, strFileName)) Log(TEXT("ConfigFile::SetKey: Unable to move new config file %s to %s"), tmpFileName.Array(), strFileName.Array()); } if(LoadFile(XFILE_OPENEXISTING)) LoadData(); return; } } lpTemp = schr(lpTemp, '\n')+1; }while(lpTemp < lpEnd); XFile file(strFileName, XFILE_WRITE, XFILE_CREATEALWAYS); file.Write("\xEF\xBB\xBF", 3); file.WriteAsUTF8(&lpFileData[2], DWORD(lpSectionStart-lpFileData-2)); file.WriteAsUTF8(lpKey, dwKeyNameSize); file.Write("=", 1); file.WriteAsUTF8(newvalue, slen(newvalue)); file.Write("\r\n", 2); file.WriteAsUTF8(lpSectionStart, slen(lpSectionStart)-2); file.Close(); if(LoadFile(XFILE_OPENEXISTING)) LoadData(); }
//ugh yet more string parsing, you think you escape it for one minute and then bam! you discover yet more string parsing code needs to be written BOOL LocaleStringLookup::LoadStringFile(CTSTR lpFile, bool bClear) { if(bClear) { cache.Clear(); delete top; top = new StringLookupNode; } else if(!top) top = new StringLookupNode; //------------------------ XFile file; if(!file.Open(lpFile, XFILE_READ, XFILE_OPENEXISTING)) return FALSE; String fileString; file.ReadFileToString(fileString); file.Close(); if(fileString.IsEmpty()) return FALSE; //------------------------ fileString.FindReplace(TEXT("\r"), TEXT(" ")); TSTR lpTemp = fileString.Array()-1; TSTR lpNextLine; do { ++lpTemp; lpNextLine = schr(lpTemp, '\n'); while(*lpTemp == ' ' || *lpTemp == L' ' || *lpTemp == '\t') ++lpTemp; if(!*lpTemp || *lpTemp == '\n') continue; if(lpNextLine) *lpNextLine = 0; //---------- TSTR lpValueStart = lpTemp; while(*lpValueStart && *lpValueStart != ' ' && *lpValueStart != L' ' && *lpValueStart != '\t') ++lpValueStart; String lookupVal, strVal; TCHAR prevChar = *lpValueStart; *lpValueStart = 0; lookupVal = lpTemp; *lpValueStart = prevChar; String value = lpValueStart; value.KillSpaces(); if(value.IsValid() && value[0] == '"') { value = String::RepresentationToString(value); strVal = value; } else strVal = value; if(lookupVal.IsValid()) AddLookupString(lookupVal, strVal); //---------- if(lpNextLine) *lpNextLine = '\n'; }while(lpTemp = lpNextLine); //------------------------ return TRUE; }
//=============================================== // XDisplayGeometry virtual slots... //----------------------------------------------- bool XDisplayGeometry::slotRun (int index) { // ... // this page does not need to offer a dialog because // we will call an external program called XFine here // --- if (index == Geometry) { // log(L_INFO,"XDisplayGeometry::call XFine...\n"); // ... // next is calling the external program called xfine // the return code of the program which is written to // stdout will tell us how to proceed // --- // 1: xfine was successful, but the user canceled. // 2: xfine was successful. The user selected "Save settings" // --- bool modelineChanged = false; // ... // get the mFiles pointer wrapper from the Intro // object which has read all the data files // --- QDict<XFile>* mFilePtr = mIntro->getFiles(); XWrapFile < QDict<XFile> > mFiles (mFilePtr); // ... // call xfine now and handle the return value... // --- removeXFineCache(); XRunXFine xfineThread; xfineThread.start(); mFrame -> disableInteraction(); while (xfineThread.running()) { qApp->processEvents(); usleep (50000); } mFrame -> enableInteraction(); int code = xfineThread.getReturnCode(); switch (code) { case 0: log (L_ERROR, "XDisplayGeometry::XFine called failed\n" ); break; case 1: modelineChanged = false; break; case 2: modelineChanged = true; break; } // ... // if the xfine call has build the modeline cache // holding the modeline changes we had to set the // ImportXFineCache variable for all desktops // --- if (modelineChanged) { XData* sys = NULL; XFile* map = mFiles["sys_DESKTOP"]; for (int n=0; n < map->getDeviceCount(); n++) { sys = map -> getDevice (n); if (! sys) { continue; } sys -> setPair ("ImportXFineCache","yes"); } resetPage ( PAGE_RELOAD ); } } #if 0 if (XTemplate::slotRun (index)) { log(L_INFO,"XDisplayGeometry::slotRun() called: %d\n",index); // ... // this function is called if the geometry page is activated. // use this function to init the dialog with the current // setup of the geometry // --- mStatus -> message (mText["RunXGeometry"]); } #endif return (TRUE); }
int kbc() { char ac[1024]; /* sprintf(ac, "c:\\basic\\examples\\kbasic\\sub\\sub2.kbasic"); sprintf(ac, "c:\\basic\\examples\\kbasic\\important\\type.kbasic"); sprintf(ac, "c:\\basic\\examples\\kbasic\\examples\\array.kbasic"); sprintf(ac, "c:\\basic\\examples\\kbasic\\keyword\\goto.kbasic"); */ bool bSilent = false; bool bDebug = false; bool bUseCache = false; char *acLicense = ""; char *acProjectName = ""; char *acLogin = ""; char *acProjectType = ""; char *acTranslation = ""; char *acSQL = ""; char *acMenu = ""; sLogin = ""; sProjectName = ""; sProjectType = ""; sTranslation = ""; sSQL = ""; sMenu = ""; int i = 1; for (; i < MAIN_argc; i++){ const char *ac = MAIN_argv[i]; if (utility::my_stricmp(ac, "-Silent") == 0) bSilent = true; else if (utility::my_stricmp(ac, "-Debug") == 0) bDebug = true; else if (utility::my_stricmp(ac, "-UseCache") == 0) bUseCache = true; else if (utility::my_strnicmp(ac, "-License", 8) == 0){ acLicense = (char *) ac + 8; if (acLicense == 0) acLicense = ""; /* } else if (utility::my_strnicmp(ac, "-ProjectName", 12) == 0){ acProjectName = (char *) ac + 12; //CONSOLE printError(ac); // CONSOLE printError("\n"); if (acProjectName == 0) sProjectName = ""; else sProjectName = acProjectName; */ } else if (utility::my_strnicmp(ac, "-Login", 6) == 0){ acLogin = (char *) ac + 6; if (acLogin == 0) sLogin = ""; else sLogin = acLogin; } else if (utility::my_strnicmp(ac, "-ProjectType", 12) == 0){ acProjectType = (char *) ac + 12; //CONSOLE printError(ac); // CONSOLE printError("\n"); if (acProjectType == 0) sProjectType = ""; else sProjectType = acProjectType; // CONSOLE printError("2222222222\n"); } else if (utility::my_strnicmp(ac, "-Translation", 12) == 0){ acTranslation = (char *) ac + 12; if (acTranslation == 0) sTranslation = ""; else sTranslation = acTranslation; } else if (utility::my_strnicmp(ac, "-SQL", 4) == 0){ acSQL = (char *) ac + 4; if (acSQL == 0) sSQL = ""; else sSQL = acSQL; // printf(acSQL); } else if (utility::my_strnicmp(ac, "-Menu", 5) == 0){ acMenu = (char *) ac + 5; if (acMenu == 0) sMenu = ""; else sMenu = acMenu; } else break; } /* bSilent = false; bDebug = false; bUseCache = true; sProjectName = "KBasic Default Project"; sProjectType = "With Forms MainWindow (you must have myMenuBar created)"; sTranslation = "&Window;Help;C&ontents;A&bout;Cl&ose;Close &All;&Tile;&Cascade;Arrange &icons;Ne&xt;Pre&vious;"; sSQL = "QPSQL;localhost;test;postgres;test"; */ // if (bUseCache) printf("!!!!!"); // sprintf(ac, ""); //if (MAIN_argc > 1 && i <= MAIN_argc) sprintf(ac, "%s", MAIN_argv[i]); //sprintf(ac, "C:/kbasic16/kbide/examples/kbasic/builtin/__class__.kbasic"); //if (utility::my_stricmp(ac, "") == 0) return 0; //bUseCache = false; { sKBasicPath = MAIN_argv[0]; bool bDebug = false; #ifdef WINDOWS // HIDE bDebug = sKBasicPath.contains("Debug"); // HIDE #endif // HIDE sKBasicPath = sKBasicPath.replace("\\", "/"); #ifdef WINDOWS // HIDE sKBasicPath = sKBasicPath.replace("/Debug", "", false); // HIDE sKBasicPath = sKBasicPath.replace("/Release", "", false); // HIDE sKBasicPath = sKBasicPath.replace(".exe", "", false); // HIDE #endif // HIDE if (bDebug){ int n = sKBasicPath.findRev("/"); if (n >= 0) sKBasicPath = sKBasicPath.left(n); sKBasicPath = sKBasicPath.replace("kbc", "kbide/ide/cache"); } else { sKBasicPath = sKBasicPath.replace("kbc", "ide/cache"); } if (sKBasicPath.isEmpty()) return 0; } // if (checkLicense(acLicense) == false) return 0; // checkSerialNo(); textbuffer *myTextbuffer = new textbuffer(); // needed to truncate big input strings or zero terminate them cache *my_cache = new cache(); token *myToken = new token(); scanner *myScanner = new scanner(myToken, my_cache); char *acText; bool b = true; if (utility::readSourceFile(&acText, cachePath("project.name").ascii(), myTextbuffer)){ acText = utility::eatUTF16DOM(acText); sProjectName = acText; } // if (b && (b = utility::readSourceFile(&acText, "c:/kbasic16/kbide/ide/cache/C__kbasic16_kbide_examples_kbasic_builtin___class__.kbasic.scanner", myTextbuffer))){} { // delete runtime.parser file XString m = cachePath("runtime.parser"); //CONSOLE printError(cachePath("runtime.parser").ascii()); XFile f(m.ascii()); if (!f.open(Truncate)){ CONSOLE printError("Could not create runtime parser file: "); CONSOLE printError(m.ascii()); b = false; } else { f.close(); } } XString m = cachePath("compiler.output"); finfo.setName(m.ascii()); char acInfo[1024]; //if (utility::my_stricmp(ac, "") == 0) if (b){ { if (!finfo.open(Truncate)){ CONSOLE printError("Could not write compiler output file:"); CONSOLE printError(m.ascii()); b = false; } } finfo.close(); XString sFiles = ""; if (b){ // read compiler.input file XString m = cachePath("compiler.input"); XFile f(m.ascii()); if (!f.open(ReadOnly)){ CONSOLE printError("Could not read compiler input file:"); CONSOLE printError(m.ascii()); b = false; } else { int i = 0; char acBuffer[10240]; int nSize = f.size(); while (i < nSize && (i = f.readBlock(acBuffer, 10240)) > 0){ acBuffer[i] = 0; const char *ac = utility::eatUTF16DOM(acBuffer); sFiles += ac; } //sFiles = sFiles.appendNull(); f.close(); } } if (my_cache){ my_cache->setMode(bSilent, bDebug); // important, setting right file name for caching // sort input files so that non-cached files are at the end, otherwise IDs of classes will collide if (bUseCache){ #define MAX_INPUTFILES 512 struct inputfile { XString sFilename; int nDate; }; inputfile files[MAX_INPUTFILES]; int nCounter = 0; int n = 0; int n0 = 0; bool bFirst = true; do { if (nCounter >= MAX_INPUTFILES){ nCounter = 0; CONSOLE printError("too many input files to compile (> 512)"); break; } n = sFiles.find("\n", n); XString s = sFiles.mid(n0, n >= 0 ? n - n0 : sFiles.length()); if (n == -1 & bFirst == false) break; XFileInfo k(s.ascii()); int r = k.lastModified(); files[nCounter].sFilename = s; files[nCounter].nDate = r; nCounter++; n0 = n + 1; n++; if (bFirst) bFirst = false; } while (true); bool bRedo = false; do { bRedo = false; for (int i = 0; i < nCounter; i++){ if (i + 1 < nCounter){ if (files[i].nDate > files[i + 1].nDate){ inputfile file = files[i + 1]; files[i + 1] = files[i]; files[i] = file; bRedo = true; break; } } } } while (bRedo); sFiles = ""; for (int i = 0; i < nCounter; i++){ sFiles = sFiles + files[i].sFilename + "\n"; } } } if (finfo.open(Truncate)){ sprintf(acInfo, "Scanning..."); finfo.writeBlock(acInfo, strlen(acInfo)); finfo.close(); } if (finfo.open(Truncate)){ sprintf(acInfo, "%s", cachePath("default.kbasic").ascii()); finfo.writeBlock(acInfo, strlen(acInfo)); finfo.close(); } if (b && (b = utility::readSourceFile(&acText, cachePath("default.kbasic").ascii(), myTextbuffer))){ acText = utility::eatUTF16DOM(acText); } if (b && (b = myScanner->scan(acText, (char *) cachePath("default.kbasic").ascii(), bSilent, bDebug, false, bUseCache))){} // filename if (b){ int n = 0; int n0 = 0; bool bFirst = true; do { n = sFiles.find("\n", n); XString s = sFiles.mid(n0, n >= 0 ? n - n0 : sFiles.length()); if (n == -1 & bFirst == false) break; bFirst = false; n0 = n + 1; n++; const char *ac99 = s.ascii(); if (b && (b = utility::readSourceFile(&acText, ac99, myTextbuffer))){ acText = utility::eatUTF16DOM(acText); } XString sFile = ac99; if (sFile.endsWith(".kbasic_form")){ XString sLanguage = ""; XString sExt = getFilenameExtension(sFile); XString q = sFile.left(sFile.length() - sExt.length() - 1); if (q.count(".") > 1){ sLanguage = getFilenameExtension(q); if (sLanguage.contains("/") || sLanguage.contains("\\")){ sLanguage = ""; } } if (sLanguage.length() == 0){ // if (!sTranslation.contains(sLanguage, false)){ acText = prepareSourceCode(ac99, acText, sFile); } else { /* char ac[1111]; sprintf(ac, "omit %s %s", sFile.ascii(), sLanguage.ascii()); CONSOLE printError(ac);*/ continue; // acText = ""; } } else if (sFile.endsWith(".kbasic_menubar")){ XString sLanguage = ""; XString sExt = getFilenameExtension(sFile); XString q = sFile.left(sFile.length() - sExt.length() - 1); if (q.count(".") > 1){ sLanguage = getFilenameExtension(q); if (sLanguage.contains("/") || sLanguage.contains("\\")){ sLanguage = ""; } } if (sLanguage.length() == 0){ // if (!sTranslation.contains(sLanguage, false)){ acText = prepareSourceCode(ac99, acText, sFile); } else { continue; // acText = ""; } } else if (sFile.endsWith(".kbasic_toolbar")){ XString sLanguage = ""; XString sExt = getFilenameExtension(sFile); XString q = sFile.left(sFile.length() - sExt.length() - 1); if (q.count(".") > 1){ sLanguage = getFilenameExtension(q); if (sLanguage.contains("/") || sLanguage.contains("\\")){ sLanguage = ""; } } if (sLanguage.length() == 0){ // if (!sTranslation.contains(sLanguage, false)){ acText = prepareSourceCode(ac99, acText, sFile); } else { continue; // acText = ""; } } else if (sFile.endsWith(".kbasic_report")){ XString sLanguage = ""; XString sExt = getFilenameExtension(sFile); XString q = sFile.left(sFile.length() - sExt.length() - 1); if (q.count(".") > 1){ sLanguage = getFilenameExtension(q); if (sLanguage.contains("/") || sLanguage.contains("\\")){ sLanguage = ""; } } if (sLanguage.length() == 0){ // if (!sTranslation.contains(sLanguage, false)){ acText = prepareSourceCode(ac99, acText, sFile); } else { continue; //acText = ""; } } else if (sFile.endsWith(".kbasic_module")){ #ifdef WINDOWS // HIDE if (sFile.endsWith(".linux.kbasic_module")) continue; // HIDE if (sFile.endsWith(".mac.kbasic_module")) continue; // HIDE #elif defined(MAC) // HIDE if (sFile.endsWith(".linux.kbasic_module")) continue; // HIDE if (sFile.endsWith(".windows.kbasic_module")) continue; // HIDE #elif defined(LINUX) // HIDE if (sFile.endsWith(".windows.kbasic_module")) continue; // HIDE if (sFile.endsWith(".mac.kbasic_module")) continue; // HIDE #endif // HIDE // UNHIDE if (sFile.endsWith(".windows.kbasic_module")) continue; // UNHIDE if (sFile.endsWith(".mac.kbasic_module")) continue; acText = prepareSourceCode(ac99, acText, sFile); } else if (sFile.endsWith(".kbasic_class")){ #ifdef WINDOWS // HIDE if (sFile.endsWith(".linux.kbasic_class")) continue; // HIDE if (sFile.endsWith(".mac.kbasic_class")) continue; // HIDE #elif defined(MAC) // HIDE if (sFile.endsWith(".linux.kbasic_class")) continue; // HIDE if (sFile.endsWith(".windows.kbasic_class")) continue; // HIDE #elif defined(LINUX) // HIDE if (sFile.endsWith(".windows.kbasic_class")) continue; // HIDE if (sFile.endsWith(".mac.kbasic_class")) continue; // HIDE #endif // HIDE // UNHIDE if (sFile.endsWith(".windows.kbasic_class")) continue; // HIDE // UNHIDE if (sFile.endsWith(".mac.kbasic_class")) continue; // HIDE acText = prepareSourceCode(ac99, acText, sFile); } else if (sFile.endsWith(".kbasic")){ #ifdef WINDOWS // HIDE if (sFile.endsWith(".linux.kbasic")) continue; // HIDE if (sFile.endsWith(".mac.kbasic")) continue; // HIDE #elif defined(MAC) // HIDE if (sFile.endsWith(".linux.kbasic")) continue; // HIDE if (sFile.endsWith(".windows.kbasic")) continue; // HIDE #elif defined(LINUX) // HIDE if (sFile.endsWith(".windows.kbasic")) continue; // HIDE if (sFile.endsWith(".mac.kbasic")) continue; // HIDE #endif // HIDE // UNHIDEif (sFile.endsWith(".windows.kbasic")) continue; // UNHIDEif (sFile.endsWith(".mac.kbasic")) continue; } if (finfo.open(Truncate)){ finfo.writeBlock((void *) ac99, strlen(ac99)); finfo.close(); } if (b && (b = myScanner->scanAdditional(acText, (char *) ac99, bSilent, bDebug, bUseCache))){} // filename if (!b) break; } while (true); } if (b) { if (finfo.open(Truncate)){ sprintf(acInfo, "%s", cachePath("default2.kbasic").ascii()); finfo.writeBlock(acInfo, strlen(acInfo)); finfo.close(); } if (b && (b = utility::readSourceFile(&acText, cachePath("default2.kbasic").ascii(), myTextbuffer))){ acText = utility::eatUTF16DOM(acText); } if (b && (b = myScanner->scanAdditional(acText, (char *) cachePath("default2.kbasic").ascii(), bSilent, bDebug, bUseCache))){} // filename } myScanner->addEOFToken(); /* } else { if (b && (b = utility::readSourceFile(&acText, ac, myTextbuffer))){} if (b && (b = myScanner->scan(acText, ac, bSilent, bDebug, true, bUseCache))){} // filename*/ } //delete myToken; // if (utility::readSourceFile(&acText, ac, myTextbuffer)){ // if (myScanner->scanAdditional(acText, filename)){ if (b){ if (finfo.open(Truncate)){ sprintf(acInfo, "Parsing..."); finfo.writeBlock(acInfo, strlen(acInfo)); finfo.close(); } pcode *myPcode = new pcode(""); // myPcode->setInfoWindow(myInfoConsole); parser *myParser = new parser(myPcode, my_cache); // myParser->setInfoWindow(myInfoConsole); //bool b = false; /* if (strcmp(acDir, "examples\\veryoldbasic\\") == 0 && (b = myParser->parseVeryOldBasic(myToken, bSilent, bDebug))){} else if (strcmp(acDir, "examples\\oldbasic\\") == 0 && (b = myParser->parseOldBasic(myToken, bSilent, bDebug))){} else if (strcmp(acDir, "examples\\kbasic\\") == 0 && (b = myParser->parseKBasic(myToken, bSilent, bDebug))){} else */ //bUseCache = false; // CONSOLE printError("myParser->parseKBasic(myToken, bSilent, bDebug, bUseCache);"); b = myParser->parseKBasic(myToken, bSilent, bDebug, bUseCache); if (b){ // CONSOLE printError("b=true"); XString m;// = path(sKBasicPath); m = cachePath("runtime.pcode"); XFile f(m.ascii()); if (!f.open(Truncate)){ CONSOLE printError("Could not create runtime pcode file"); b = false; } else { //const char *aa = myPcode->ba->getMem(); int n = myPcode->ba->getSize(); n = f.writeBlock (myPcode->ba->getMem(), n); f.close(); } } delete myParser; delete myPcode; } delete myScanner; delete myToken; delete myTextbuffer; delete my_cache; { XString m; m = cachePath("compiler.done"); XFile f(m.ascii()); if (!f.open(Truncate)){ CONSOLE printError("Could not create runtime done file"); b = false; } else { f.close(); } } return b ? 0 : -1; }