assimp_view.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2021, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #include "assimp_view.h"
  35. #include <assimp/StringUtils.h>
  36. #include <map>
  37. #ifdef __MINGW32__
  38. #include <mmsystem.h>
  39. #else
  40. #include <timeapi.h>
  41. #endif
  42. using namespace std;
  43. namespace AssimpView {
  44. extern std::string g_szNormalsShader;
  45. extern std::string g_szDefaultShader;
  46. extern std::string g_szPassThroughShader;
  47. //-------------------------------------------------------------------------------
  48. HINSTANCE g_hInstance = nullptr;
  49. HWND g_hDlg = nullptr;
  50. IDirect3D9 *g_piD3D = nullptr;
  51. IDirect3DDevice9 *g_piDevice = nullptr;
  52. IDirect3DVertexDeclaration9 *gDefaultVertexDecl = nullptr;
  53. double g_fFPS = 0.0f;
  54. char g_szFileName[MAX_PATH];
  55. ID3DXEffect *g_piDefaultEffect = nullptr;
  56. ID3DXEffect *g_piNormalsEffect = nullptr;
  57. ID3DXEffect *g_piPassThroughEffect = nullptr;
  58. ID3DXEffect *g_piPatternEffect = nullptr;
  59. bool g_bMousePressed = false;
  60. bool g_bMousePressedR = false;
  61. bool g_bMousePressedM = false;
  62. bool g_bMousePressedBoth = false;
  63. float g_fElpasedTime = 0.0f;
  64. D3DCAPS9 g_sCaps;
  65. bool g_bLoadingFinished = false;
  66. HANDLE g_hThreadHandle = nullptr;
  67. float g_fWheelPos = -10.0f;
  68. bool g_bLoadingCanceled = false;
  69. IDirect3DTexture9 *g_pcTexture = nullptr;
  70. bool g_bPlay = false;
  71. double g_dCurrent = 0.;
  72. // default pp steps
  73. unsigned int ppsteps = aiProcess_CalcTangentSpace | // calculate tangents and bitangents if possible
  74. aiProcess_JoinIdenticalVertices | // join identical vertices/ optimize indexing
  75. aiProcess_ValidateDataStructure | // perform a full validation of the loader's output
  76. aiProcess_ImproveCacheLocality | // improve the cache locality of the output vertices
  77. aiProcess_RemoveRedundantMaterials | // remove redundant materials
  78. aiProcess_FindDegenerates | // remove degenerated polygons from the import
  79. aiProcess_FindInvalidData | // detect invalid model data, such as invalid normal vectors
  80. aiProcess_GenUVCoords | // convert spherical, cylindrical, box and planar mapping to proper UVs
  81. aiProcess_TransformUVCoords | // preprocess UV transformations (scaling, translation ...)
  82. aiProcess_FindInstances | // search for instanced meshes and remove them by references to one master
  83. aiProcess_LimitBoneWeights | // limit bone weights to 4 per vertex
  84. aiProcess_OptimizeMeshes | // join small meshes, if possible;
  85. aiProcess_SplitByBoneCount | // split meshes with too many bones. Necessary for our (limited) hardware skinning shader
  86. 0;
  87. unsigned int ppstepsdefault = ppsteps;
  88. bool nopointslines = false;
  89. extern bool g_bWasFlipped /*= false*/;
  90. aiMatrix4x4 g_mWorld;
  91. aiMatrix4x4 g_mWorldRotate;
  92. aiVector3D g_vRotateSpeed = aiVector3D(0.5f, 0.5f, 0.5f);
  93. // NOTE: The second light direction is now computed from the first
  94. aiVector3D g_avLightDirs[1] = { aiVector3D(-0.5f, 0.6f, 0.2f) };
  95. D3DCOLOR g_avLightColors[3] = {
  96. D3DCOLOR_ARGB(0xFF, 0xFF, 0xFF, 0xFF),
  97. D3DCOLOR_ARGB(0xFF, 0xFF, 0x00, 0x00),
  98. D3DCOLOR_ARGB(0xFF, 0x05, 0x05, 0x05),
  99. };
  100. POINT g_mousePos;
  101. POINT g_LastmousePos;
  102. bool g_bFPSView = false;
  103. bool g_bInvert = false;
  104. EClickPos g_eClick = EClickPos_Circle;
  105. unsigned int g_iCurrentColor = 0;
  106. float g_fLightIntensity = 1.0f;
  107. float g_fLightColor = 1.0f;
  108. RenderOptions g_sOptions;
  109. Camera g_sCamera;
  110. AssetHelper *g_pcAsset = nullptr;
  111. //
  112. // Contains the mask image for the HUD
  113. // (used to determine the position of a click)
  114. //
  115. unsigned char *g_szImageMask = nullptr;
  116. float g_fLoadTime = 0.0f;
  117. //-------------------------------------------------------------------------------
  118. // Entry point for the loader thread
  119. // The loader thread loads the asset while the progress dialog displays the
  120. // smart progress bar
  121. //-------------------------------------------------------------------------------
  122. DWORD WINAPI LoadThreadProc(LPVOID lpParameter) {
  123. UNREFERENCED_PARAMETER(lpParameter);
  124. // get current time
  125. double fCur = (double)timeGetTime();
  126. aiPropertyStore *props = aiCreatePropertyStore();
  127. aiSetImportPropertyInteger(props, AI_CONFIG_IMPORT_TER_MAKE_UVS, 1);
  128. aiSetImportPropertyFloat(props, AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE, g_smoothAngle);
  129. aiSetImportPropertyInteger(props, AI_CONFIG_PP_SBP_REMOVE, nopointslines ? aiPrimitiveType_LINE | aiPrimitiveType_POINT : 0);
  130. aiSetImportPropertyInteger(props, AI_CONFIG_GLOB_MEASURE_TIME, 1);
  131. //aiSetImportPropertyInteger(props,AI_CONFIG_PP_PTV_KEEP_HIERARCHY,1);
  132. // Call ASSIMPs C-API to load the file
  133. g_pcAsset->pcScene = (aiScene *)aiImportFileExWithProperties(g_szFileName,
  134. ppsteps | /* configurable pp steps */
  135. aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing
  136. aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes
  137. aiProcess_Triangulate | // triangulate polygons with more than 3 edges
  138. aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space
  139. aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives
  140. 0,
  141. nullptr,
  142. props);
  143. aiReleasePropertyStore(props);
  144. // get the end time of zje operation, calculate delta t
  145. double fEnd = (double)timeGetTime();
  146. g_fLoadTime = (float)((fEnd - fCur) / 1000);
  147. g_bLoadingFinished = true;
  148. // check whether the loading process has failed ...
  149. if (nullptr == g_pcAsset->pcScene) {
  150. CLogDisplay::Instance().AddEntry("[ERROR] Unable to load this asset:",
  151. D3DCOLOR_ARGB(0xFF, 0xFF, 0, 0));
  152. // print ASSIMPs error string to the log display
  153. CLogDisplay::Instance().AddEntry(aiGetErrorString(),
  154. D3DCOLOR_ARGB(0xFF, 0xFF, 0, 0));
  155. return 1;
  156. }
  157. return 0;
  158. }
  159. //-------------------------------------------------------------------------------
  160. // load the current asset
  161. // THe path to the asset is specified in the global path variable
  162. //-------------------------------------------------------------------------------
  163. int LoadAsset() {
  164. // set the world and world rotation matrices to the identity
  165. g_mWorldRotate = aiMatrix4x4();
  166. g_mWorld = aiMatrix4x4();
  167. // char szTemp[MAX_PATH+64];
  168. // sprintf(szTemp,"Starting to load %s",g_szFileName);
  169. CLogWindow::Instance().WriteLine(
  170. "----------------------------------------------------------------------------");
  171. // CLogWindow::Instance().WriteLine(szTemp);
  172. // CLogWindow::Instance().WriteLine(
  173. // "----------------------------------------------------------------------------");
  174. CLogWindow::Instance().SetAutoUpdate(false);
  175. // create a helper thread to load the asset
  176. DWORD dwID;
  177. g_bLoadingCanceled = false;
  178. g_pcAsset = new AssetHelper();
  179. g_hThreadHandle = CreateThread(nullptr, 0, &LoadThreadProc, nullptr, 0, &dwID);
  180. if (!g_hThreadHandle) {
  181. CLogDisplay::Instance().AddEntry(
  182. "[ERROR] Unable to create helper thread for loading",
  183. D3DCOLOR_ARGB(0xFF, 0xFF, 0, 0));
  184. return 0;
  185. }
  186. // show the progress bar dialog
  187. DialogBox(g_hInstance, MAKEINTRESOURCE(IDD_LOADDIALOG),
  188. g_hDlg, &ProgressMessageProc);
  189. // update the log window
  190. CLogWindow::Instance().SetAutoUpdate(true);
  191. CLogWindow::Instance().Update();
  192. // now we should have loaded the asset. Check this ...
  193. g_bLoadingFinished = false;
  194. if (!g_pcAsset || !g_pcAsset->pcScene) {
  195. if (g_pcAsset) {
  196. delete g_pcAsset;
  197. g_pcAsset = nullptr;
  198. }
  199. return 0;
  200. }
  201. // allocate a new MeshHelper array and build a new instance
  202. // for each mesh in the original asset
  203. g_pcAsset->apcMeshes = new AssetHelper::MeshHelper *[g_pcAsset->pcScene->mNumMeshes]();
  204. for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes; ++i)
  205. g_pcAsset->apcMeshes[i] = new AssetHelper::MeshHelper();
  206. // create animator
  207. g_pcAsset->mAnimator = new SceneAnimator(g_pcAsset->pcScene);
  208. // build a new caption string for the viewer
  209. static const size_t Size = MAX_PATH + 10;
  210. char szOut[Size];
  211. ai_snprintf(szOut, Size, AI_VIEW_CAPTION_BASE " [%s]", g_szFileName);
  212. SetWindowText(g_hDlg, szOut);
  213. // scale the asset vertices to fit into the viewer window
  214. ScaleAsset();
  215. // reset the camera view to the default position
  216. g_sCamera.vPos = aiVector3D(0.0f, 0.0f, -10.0f);
  217. g_sCamera.vLookAt = aiVector3D(0.0f, 0.0f, 1.0f);
  218. g_sCamera.vUp = aiVector3D(0.0f, 1.0f, 0.0f);
  219. g_sCamera.vRight = aiVector3D(0.0f, 1.0f, 0.0f);
  220. // build native D3D vertex/index buffers, textures, materials
  221. if (1 != CreateAssetData())
  222. return 0;
  223. if (!g_pcAsset->pcScene->HasAnimations()) {
  224. EnableWindow(GetDlgItem(g_hDlg, IDC_PLAY), FALSE);
  225. EnableWindow(GetDlgItem(g_hDlg, IDC_SLIDERANIM), FALSE);
  226. } else {
  227. EnableWindow(GetDlgItem(g_hDlg, IDC_PLAY), TRUE);
  228. EnableWindow(GetDlgItem(g_hDlg, IDC_SLIDERANIM), TRUE);
  229. }
  230. CLogDisplay::Instance().AddEntry("[OK] The asset has been loaded successfully");
  231. CDisplay::Instance().FillDisplayList();
  232. CDisplay::Instance().FillAnimList();
  233. CDisplay::Instance().FillDefaultStatistics();
  234. // render the scene once
  235. CDisplay::Instance().OnRender();
  236. g_pcAsset->iNormalSet = AssetHelper::ORIGINAL;
  237. g_bWasFlipped = false;
  238. return 1;
  239. }
  240. //-------------------------------------------------------------------------------
  241. // Delete the loaded asset
  242. // The function does nothing is no asset is loaded
  243. //-------------------------------------------------------------------------------
  244. int DeleteAsset(void) {
  245. if (!g_pcAsset) {
  246. return 0;
  247. }
  248. // don't anymore know why this was necessary ...
  249. CDisplay::Instance().OnRender();
  250. // delete everything
  251. DeleteAssetData();
  252. for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes; ++i) {
  253. delete g_pcAsset->apcMeshes[i];
  254. }
  255. aiReleaseImport(g_pcAsset->pcScene);
  256. delete[] g_pcAsset->apcMeshes;
  257. delete g_pcAsset->mAnimator;
  258. delete g_pcAsset;
  259. g_pcAsset = nullptr;
  260. // reset the caption of the viewer window
  261. SetWindowText(g_hDlg, AI_VIEW_CAPTION_BASE);
  262. // clear UI
  263. CDisplay::Instance().ClearAnimList();
  264. CDisplay::Instance().ClearDisplayList();
  265. CMaterialManager::Instance().Reset();
  266. UpdateWindow(g_hDlg);
  267. return 1;
  268. }
  269. //-------------------------------------------------------------------------------
  270. // Calculate the boundaries of a given node and all of its children
  271. // The boundaries are in Worldspace (AABB)
  272. // piNode Input node
  273. // p_avOut Receives the min/max boundaries. Must point to 2 vec3s
  274. // piMatrix Transformation matrix of the graph at this position
  275. //-------------------------------------------------------------------------------
  276. int CalculateBounds(aiNode *piNode, aiVector3D *p_avOut, const aiMatrix4x4 &piMatrix) {
  277. ai_assert(nullptr != piNode);
  278. ai_assert(nullptr != p_avOut);
  279. aiMatrix4x4 mTemp = piNode->mTransformation;
  280. mTemp.Transpose();
  281. aiMatrix4x4 aiMe = mTemp * piMatrix;
  282. for (unsigned int i = 0; i < piNode->mNumMeshes; ++i) {
  283. for (unsigned int a = 0; a < g_pcAsset->pcScene->mMeshes[piNode->mMeshes[i]]->mNumVertices; ++a) {
  284. aiVector3D pc = g_pcAsset->pcScene->mMeshes[piNode->mMeshes[i]]->mVertices[a];
  285. aiVector3D pc1;
  286. D3DXVec3TransformCoord((D3DXVECTOR3 *)&pc1, (D3DXVECTOR3 *)&pc,
  287. (D3DXMATRIX *)&aiMe);
  288. p_avOut[0].x = min(p_avOut[0].x, pc1.x);
  289. p_avOut[0].y = min(p_avOut[0].y, pc1.y);
  290. p_avOut[0].z = min(p_avOut[0].z, pc1.z);
  291. p_avOut[1].x = max(p_avOut[1].x, pc1.x);
  292. p_avOut[1].y = max(p_avOut[1].y, pc1.y);
  293. p_avOut[1].z = max(p_avOut[1].z, pc1.z);
  294. }
  295. }
  296. for (unsigned int i = 0; i < piNode->mNumChildren; ++i) {
  297. CalculateBounds(piNode->mChildren[i], p_avOut, aiMe);
  298. }
  299. return 1;
  300. }
  301. //-------------------------------------------------------------------------------
  302. // Scale the asset that it fits perfectly into the viewer window
  303. // The function calculates the boundaries of the mesh and modifies the
  304. // global world transformation matrix according to the aset AABB
  305. //-------------------------------------------------------------------------------
  306. int ScaleAsset(void) {
  307. aiVector3D aiVecs[2] = { aiVector3D(1e10f, 1e10f, 1e10f),
  308. aiVector3D(-1e10f, -1e10f, -1e10f) };
  309. if (g_pcAsset->pcScene->mRootNode) {
  310. aiMatrix4x4 m;
  311. CalculateBounds(g_pcAsset->pcScene->mRootNode, aiVecs, m);
  312. }
  313. aiVector3D vDelta = aiVecs[1] - aiVecs[0];
  314. aiVector3D vHalf = aiVecs[0] + (vDelta / 2.0f);
  315. float fScale = 10.0f / vDelta.Length();
  316. g_mWorld = aiMatrix4x4(
  317. 1.0f, 0.0f, 0.0f, 0.0f,
  318. 0.0f, 1.0f, 0.0f, 0.0f,
  319. 0.0f, 0.0f, 1.0f, 0.0f,
  320. -vHalf.x, -vHalf.y, -vHalf.z, 1.0f) *
  321. aiMatrix4x4(
  322. fScale, 0.0f, 0.0f, 0.0f,
  323. 0.0f, fScale, 0.0f, 0.0f,
  324. 0.0f, 0.0f, fScale, 0.0f,
  325. 0.0f, 0.0f, 0.0f, 1.0f);
  326. return 1;
  327. }
  328. //-------------------------------------------------------------------------------
  329. // Generate a vertex buffer which holds the normals of the asset as
  330. // a list of unconnected lines
  331. // pcMesh Input mesh
  332. // pcSource Source mesh from ASSIMP
  333. //-------------------------------------------------------------------------------
  334. int GenerateNormalsAsLineList(AssetHelper::MeshHelper *pcMesh, const aiMesh *pcSource) {
  335. ai_assert(nullptr != pcMesh);
  336. ai_assert(nullptr != pcSource);
  337. if (!pcSource->mNormals) return 0;
  338. // create vertex buffer
  339. if (FAILED(g_piDevice->CreateVertexBuffer(sizeof(AssetHelper::LineVertex) *
  340. pcSource->mNumVertices * 2,
  341. D3DUSAGE_WRITEONLY,
  342. AssetHelper::LineVertex::GetFVF(),
  343. D3DPOOL_DEFAULT, &pcMesh->piVBNormals, nullptr))) {
  344. CLogDisplay::Instance().AddEntry("Failed to create vertex buffer for the normal list",
  345. D3DCOLOR_ARGB(0xFF, 0xFF, 0, 0));
  346. return 2;
  347. }
  348. // now fill the vertex buffer with data
  349. AssetHelper::LineVertex *pbData2;
  350. pcMesh->piVBNormals->Lock(0, 0, (void **)&pbData2, 0);
  351. for (unsigned int x = 0; x < pcSource->mNumVertices; ++x) {
  352. pbData2->vPosition = pcSource->mVertices[x];
  353. ++pbData2;
  354. aiVector3D vNormal = pcSource->mNormals[x];
  355. vNormal.Normalize();
  356. // scalo with the inverse of the world scaling to make sure
  357. // the normals have equal length in each case
  358. // TODO: Check whether this works in every case, I don't think so
  359. vNormal.x /= g_mWorld.a1 * 4;
  360. vNormal.y /= g_mWorld.b2 * 4;
  361. vNormal.z /= g_mWorld.c3 * 4;
  362. pbData2->vPosition = pcSource->mVertices[x] + vNormal;
  363. ++pbData2;
  364. }
  365. pcMesh->piVBNormals->Unlock();
  366. return 1;
  367. }
  368. //-------------------------------------------------------------------------------
  369. // Create the native D3D representation of the asset: vertex buffers,
  370. // index buffers, materials ...
  371. //-------------------------------------------------------------------------------
  372. int CreateAssetData() {
  373. if (!g_pcAsset) return 0;
  374. // reset all subsystems
  375. CMaterialManager::Instance().Reset();
  376. CDisplay::Instance().Reset();
  377. for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes; ++i) {
  378. const aiMesh *mesh = g_pcAsset->pcScene->mMeshes[i];
  379. // create the material for the mesh
  380. if (!g_pcAsset->apcMeshes[i]->piEffect) {
  381. CMaterialManager::Instance().CreateMaterial(
  382. g_pcAsset->apcMeshes[i], mesh);
  383. }
  384. // create vertex buffer
  385. if (FAILED(g_piDevice->CreateVertexBuffer(sizeof(AssetHelper::Vertex) *
  386. mesh->mNumVertices,
  387. D3DUSAGE_WRITEONLY,
  388. 0,
  389. D3DPOOL_DEFAULT, &g_pcAsset->apcMeshes[i]->piVB, nullptr))) {
  390. MessageBox(g_hDlg, "Failed to create vertex buffer",
  391. "ASSIMP Viewer Utility", MB_OK);
  392. return 2;
  393. }
  394. DWORD dwUsage = 0;
  395. if (g_pcAsset->apcMeshes[i]->piOpacityTexture || 1.0f != g_pcAsset->apcMeshes[i]->fOpacity)
  396. dwUsage |= D3DUSAGE_DYNAMIC;
  397. unsigned int nidx = 0;
  398. switch (mesh->mPrimitiveTypes) {
  399. case aiPrimitiveType_POINT:
  400. nidx = 1;
  401. break;
  402. case aiPrimitiveType_LINE:
  403. nidx = 2;
  404. break;
  405. case aiPrimitiveType_TRIANGLE:
  406. nidx = 3;
  407. break;
  408. default:
  409. CLogWindow::Instance().WriteLine("Unknown primitive type");
  410. break;
  411. };
  412. unsigned int numIndices = mesh->mNumFaces * 3;
  413. if (0 == numIndices && nidx == 1) {
  414. numIndices = mesh->mNumVertices;
  415. }
  416. // check whether we can use 16 bit indices
  417. if (numIndices >= 65536) {
  418. // create 32 bit index buffer
  419. if (FAILED(g_piDevice->CreateIndexBuffer(4 * numIndices,
  420. D3DUSAGE_WRITEONLY | dwUsage,
  421. D3DFMT_INDEX32,
  422. D3DPOOL_DEFAULT,
  423. &g_pcAsset->apcMeshes[i]->piIB,
  424. nullptr))) {
  425. MessageBox(g_hDlg, "Failed to create 32 Bit index buffer",
  426. "ASSIMP Viewer Utility", MB_OK);
  427. return 2;
  428. }
  429. // now fill the index buffer
  430. unsigned int *pbData;
  431. g_pcAsset->apcMeshes[i]->piIB->Lock(0, 0, (void **)&pbData, 0);
  432. for (unsigned int x = 0; x < mesh->mNumFaces; ++x) {
  433. for (unsigned int a = 0; a < nidx; ++a) {
  434. *pbData++ = mesh->mFaces[x].mIndices[a];
  435. }
  436. }
  437. } else {
  438. // create 16 bit index buffer
  439. if (FAILED(g_piDevice->CreateIndexBuffer(2 *
  440. numIndices,
  441. D3DUSAGE_WRITEONLY | dwUsage,
  442. D3DFMT_INDEX16,
  443. D3DPOOL_DEFAULT,
  444. &g_pcAsset->apcMeshes[i]->piIB,
  445. nullptr))) {
  446. MessageBox(g_hDlg, "Failed to create 16 Bit index buffer",
  447. "ASSIMP Viewer Utility", MB_OK);
  448. return 2;
  449. }
  450. // now fill the index buffer
  451. uint16_t *pbData;
  452. g_pcAsset->apcMeshes[i]->piIB->Lock(0, 0, (void **)&pbData, 0);
  453. for (unsigned int x = 0; x < mesh->mNumFaces; ++x) {
  454. for (unsigned int a = 0; a < nidx; ++a) {
  455. *pbData++ = (uint16_t)mesh->mFaces[x].mIndices[a];
  456. }
  457. }
  458. }
  459. g_pcAsset->apcMeshes[i]->piIB->Unlock();
  460. // collect weights on all vertices. Quick and careless
  461. std::vector<std::vector<aiVertexWeight>> weightsPerVertex(mesh->mNumVertices);
  462. for (unsigned int a = 0; a < mesh->mNumBones; a++) {
  463. const aiBone *bone = mesh->mBones[a];
  464. for (unsigned int b = 0; b < bone->mNumWeights; b++)
  465. weightsPerVertex[bone->mWeights[b].mVertexId].push_back(aiVertexWeight(a, bone->mWeights[b].mWeight));
  466. }
  467. // now fill the vertex buffer
  468. AssetHelper::Vertex *pbData2;
  469. g_pcAsset->apcMeshes[i]->piVB->Lock(0, 0, (void **)&pbData2, 0);
  470. for (unsigned int x = 0; x < mesh->mNumVertices; ++x) {
  471. pbData2->vPosition = mesh->mVertices[x];
  472. if (nullptr == mesh->mNormals)
  473. pbData2->vNormal = aiVector3D(0.0f, 0.0f, 0.0f);
  474. else
  475. pbData2->vNormal = mesh->mNormals[x];
  476. if (nullptr == mesh->mTangents) {
  477. pbData2->vTangent = aiVector3D(0.0f, 0.0f, 0.0f);
  478. pbData2->vBitangent = aiVector3D(0.0f, 0.0f, 0.0f);
  479. } else {
  480. pbData2->vTangent = mesh->mTangents[x];
  481. pbData2->vBitangent = mesh->mBitangents[x];
  482. }
  483. if (mesh->HasVertexColors(0)) {
  484. pbData2->dColorDiffuse = D3DCOLOR_ARGB(
  485. ((unsigned char)max(min(mesh->mColors[0][x].a * 255.0f, 255.0f), 0.0f)),
  486. ((unsigned char)max(min(mesh->mColors[0][x].r * 255.0f, 255.0f), 0.0f)),
  487. ((unsigned char)max(min(mesh->mColors[0][x].g * 255.0f, 255.0f), 0.0f)),
  488. ((unsigned char)max(min(mesh->mColors[0][x].b * 255.0f, 255.0f), 0.0f)));
  489. } else
  490. pbData2->dColorDiffuse = D3DCOLOR_ARGB(0xFF, 0xff, 0xff, 0xff);
  491. // ignore a third texture coordinate component
  492. if (mesh->HasTextureCoords(0)) {
  493. pbData2->vTextureUV = aiVector2D(
  494. mesh->mTextureCoords[0][x].x,
  495. mesh->mTextureCoords[0][x].y);
  496. } else
  497. pbData2->vTextureUV = aiVector2D(0.5f, 0.5f);
  498. if (mesh->HasTextureCoords(1)) {
  499. pbData2->vTextureUV2 = aiVector2D(
  500. mesh->mTextureCoords[1][x].x,
  501. mesh->mTextureCoords[1][x].y);
  502. } else
  503. pbData2->vTextureUV2 = aiVector2D(0.5f, 0.5f);
  504. // Bone indices and weights
  505. if (mesh->HasBones()) {
  506. unsigned char boneIndices[4] = { 0, 0, 0, 0 };
  507. unsigned char boneWeights[4] = { 0, 0, 0, 0 };
  508. ai_assert(weightsPerVertex[x].size() <= 4);
  509. for (unsigned int a = 0; a < weightsPerVertex[x].size(); a++) {
  510. boneIndices[a] = static_cast<unsigned char>(weightsPerVertex[x][a].mVertexId);
  511. boneWeights[a] = (unsigned char)(weightsPerVertex[x][a].mWeight * 255.0f);
  512. }
  513. memcpy(pbData2->mBoneIndices, boneIndices, sizeof(boneIndices));
  514. memcpy(pbData2->mBoneWeights, boneWeights, sizeof(boneWeights));
  515. } else {
  516. memset(pbData2->mBoneIndices, 0, sizeof(pbData2->mBoneIndices));
  517. memset(pbData2->mBoneWeights, 0, sizeof(pbData2->mBoneWeights));
  518. }
  519. ++pbData2;
  520. }
  521. g_pcAsset->apcMeshes[i]->piVB->Unlock();
  522. // now generate the second vertex buffer, holding all normals
  523. if (!g_pcAsset->apcMeshes[i]->piVBNormals) {
  524. GenerateNormalsAsLineList(g_pcAsset->apcMeshes[i], mesh);
  525. }
  526. }
  527. return 1;
  528. }
  529. //-------------------------------------------------------------------------------
  530. // Delete all effects, textures, vertex buffers ... associated with
  531. // an asset
  532. //-------------------------------------------------------------------------------
  533. int DeleteAssetData(bool bNoMaterials) {
  534. if (!g_pcAsset) return 0;
  535. // TODO: Move this to a proper destructor
  536. for (unsigned int i = 0; i < g_pcAsset->pcScene->mNumMeshes; ++i) {
  537. if (g_pcAsset->apcMeshes[i]->piVB) {
  538. g_pcAsset->apcMeshes[i]->piVB->Release();
  539. g_pcAsset->apcMeshes[i]->piVB = nullptr;
  540. }
  541. if (g_pcAsset->apcMeshes[i]->piVBNormals) {
  542. g_pcAsset->apcMeshes[i]->piVBNormals->Release();
  543. g_pcAsset->apcMeshes[i]->piVBNormals = nullptr;
  544. }
  545. if (g_pcAsset->apcMeshes[i]->piIB) {
  546. g_pcAsset->apcMeshes[i]->piIB->Release();
  547. g_pcAsset->apcMeshes[i]->piIB = nullptr;
  548. }
  549. // TODO ... unfixed memory leak
  550. // delete storage eventually allocated to hold a copy
  551. // of the original vertex normals
  552. //if (g_pcAsset->apcMeshes[i]->pvOriginalNormals)
  553. //{
  554. // delete[] g_pcAsset->apcMeshes[i]->pvOriginalNormals;
  555. //}
  556. if (!bNoMaterials) {
  557. if (g_pcAsset->apcMeshes[i]->piEffect) {
  558. g_pcAsset->apcMeshes[i]->piEffect->Release();
  559. g_pcAsset->apcMeshes[i]->piEffect = nullptr;
  560. }
  561. if (g_pcAsset->apcMeshes[i]->piDiffuseTexture) {
  562. g_pcAsset->apcMeshes[i]->piDiffuseTexture->Release();
  563. g_pcAsset->apcMeshes[i]->piDiffuseTexture = nullptr;
  564. }
  565. if (g_pcAsset->apcMeshes[i]->piNormalTexture) {
  566. g_pcAsset->apcMeshes[i]->piNormalTexture->Release();
  567. g_pcAsset->apcMeshes[i]->piNormalTexture = nullptr;
  568. }
  569. if (g_pcAsset->apcMeshes[i]->piSpecularTexture) {
  570. g_pcAsset->apcMeshes[i]->piSpecularTexture->Release();
  571. g_pcAsset->apcMeshes[i]->piSpecularTexture = nullptr;
  572. }
  573. if (g_pcAsset->apcMeshes[i]->piAmbientTexture) {
  574. g_pcAsset->apcMeshes[i]->piAmbientTexture->Release();
  575. g_pcAsset->apcMeshes[i]->piAmbientTexture = nullptr;
  576. }
  577. if (g_pcAsset->apcMeshes[i]->piEmissiveTexture) {
  578. g_pcAsset->apcMeshes[i]->piEmissiveTexture->Release();
  579. g_pcAsset->apcMeshes[i]->piEmissiveTexture = nullptr;
  580. }
  581. if (g_pcAsset->apcMeshes[i]->piOpacityTexture) {
  582. g_pcAsset->apcMeshes[i]->piOpacityTexture->Release();
  583. g_pcAsset->apcMeshes[i]->piOpacityTexture = nullptr;
  584. }
  585. if (g_pcAsset->apcMeshes[i]->piShininessTexture) {
  586. g_pcAsset->apcMeshes[i]->piShininessTexture->Release();
  587. g_pcAsset->apcMeshes[i]->piShininessTexture = nullptr;
  588. }
  589. }
  590. }
  591. return 1;
  592. }
  593. //-------------------------------------------------------------------------------
  594. // Switch between zoom/rotate view and the standard FPS view
  595. // g_bFPSView specifies the view mode to setup
  596. //-------------------------------------------------------------------------------
  597. int SetupFPSView() {
  598. if (!g_bFPSView) {
  599. g_sCamera.vPos = aiVector3D(0.0f, 0.0f, g_fWheelPos);
  600. g_sCamera.vLookAt = aiVector3D(0.0f, 0.0f, 1.0f);
  601. g_sCamera.vUp = aiVector3D(0.0f, 1.0f, 0.0f);
  602. g_sCamera.vRight = aiVector3D(0.0f, 1.0f, 0.0f);
  603. } else {
  604. g_fWheelPos = g_sCamera.vPos.z;
  605. g_sCamera.vPos = aiVector3D(0.0f, 0.0f, -10.0f);
  606. g_sCamera.vLookAt = aiVector3D(0.0f, 0.0f, 1.0f);
  607. g_sCamera.vUp = aiVector3D(0.0f, 1.0f, 0.0f);
  608. g_sCamera.vRight = aiVector3D(0.0f, 1.0f, 0.0f);
  609. }
  610. return 1;
  611. }
  612. //-------------------------------------------------------------------------------
  613. // Initialize the IDIrect3D interface
  614. // Called by the WinMain
  615. //-------------------------------------------------------------------------------
  616. int InitD3D(void) {
  617. if (nullptr == g_piD3D) {
  618. g_piD3D = Direct3DCreate9(D3D_SDK_VERSION);
  619. if (nullptr == g_piD3D) return 0;
  620. }
  621. return 1;
  622. }
  623. //-------------------------------------------------------------------------------
  624. // Release the IDirect3D interface.
  625. // NOTE: Assumes that the device has already been deleted
  626. //-------------------------------------------------------------------------------
  627. int ShutdownD3D(void) {
  628. ShutdownDevice();
  629. if (nullptr != g_piD3D) {
  630. g_piD3D->Release();
  631. g_piD3D = nullptr;
  632. }
  633. return 1;
  634. }
  635. template <class TComPtr>
  636. inline void SafeRelease(TComPtr *&ptr) {
  637. if (nullptr != ptr) {
  638. ptr->Release();
  639. ptr = nullptr;
  640. }
  641. }
  642. //-------------------------------------------------------------------------------
  643. // Shutdown the D3D device object and all resources associated with it
  644. // NOTE: Assumes that the asset has already been deleted
  645. //-------------------------------------------------------------------------------
  646. int ShutdownDevice(void) {
  647. // release other subsystems
  648. CBackgroundPainter::Instance().ReleaseNativeResource();
  649. CLogDisplay::Instance().ReleaseNativeResource();
  650. // release global shaders that have been allocated
  651. SafeRelease(g_piDefaultEffect);
  652. SafeRelease(g_piNormalsEffect);
  653. SafeRelease(g_piPassThroughEffect);
  654. SafeRelease(g_piPatternEffect);
  655. SafeRelease(g_pcTexture);
  656. SafeRelease(gDefaultVertexDecl);
  657. // delete the main D3D device object
  658. SafeRelease(g_piDevice);
  659. // deleted the one channel image allocated to hold the HUD mask
  660. delete[] g_szImageMask;
  661. g_szImageMask = nullptr;
  662. return 1;
  663. }
  664. //-------------------------------------------------------------------------------
  665. //-------------------------------------------------------------------------------
  666. int CreateHUDTexture() {
  667. // lock the memory resource ourselves
  668. HRSRC res = FindResource(nullptr, MAKEINTRESOURCE(IDR_HUD), RT_RCDATA);
  669. HGLOBAL hg = LoadResource(nullptr, res);
  670. void *pData = LockResource(hg);
  671. if (FAILED(D3DXCreateTextureFromFileInMemoryEx(g_piDevice,
  672. pData, SizeofResource(nullptr, res),
  673. D3DX_DEFAULT_NONPOW2,
  674. D3DX_DEFAULT_NONPOW2,
  675. 1,
  676. 0,
  677. D3DFMT_A8R8G8B8,
  678. D3DPOOL_MANAGED,
  679. D3DX_DEFAULT,
  680. D3DX_DEFAULT,
  681. 0,
  682. nullptr,
  683. nullptr,
  684. &g_pcTexture))) {
  685. CLogDisplay::Instance().AddEntry("[ERROR] Unable to load HUD texture",
  686. D3DCOLOR_ARGB(0xFF, 0xFF, 0, 0));
  687. g_pcTexture = nullptr;
  688. g_szImageMask = nullptr;
  689. FreeResource(hg);
  690. return 0;
  691. }
  692. FreeResource(hg);
  693. D3DSURFACE_DESC sDesc;
  694. g_pcTexture->GetLevelDesc(0, &sDesc);
  695. // lock the memory resource ourselves
  696. res = FindResource(nullptr, MAKEINTRESOURCE(IDR_HUDMASK), RT_RCDATA);
  697. hg = LoadResource(nullptr, res);
  698. pData = LockResource(hg);
  699. IDirect3DTexture9 *pcTex;
  700. if (FAILED(D3DXCreateTextureFromFileInMemoryEx(g_piDevice,
  701. pData, SizeofResource(nullptr, res),
  702. sDesc.Width,
  703. sDesc.Height,
  704. 1,
  705. 0,
  706. D3DFMT_L8,
  707. D3DPOOL_MANAGED, // unnecessary
  708. D3DX_DEFAULT,
  709. D3DX_DEFAULT,
  710. 0,
  711. nullptr,
  712. nullptr,
  713. &pcTex))) {
  714. CLogDisplay::Instance().AddEntry("[ERROR] Unable to load HUD mask texture",
  715. D3DCOLOR_ARGB(0xFF, 0xFF, 0, 0));
  716. g_szImageMask = nullptr;
  717. FreeResource(hg);
  718. return 0;
  719. }
  720. FreeResource(hg);
  721. // lock the texture and copy it to get a pointer
  722. D3DLOCKED_RECT sRect;
  723. pcTex->LockRect(0, &sRect, nullptr, D3DLOCK_READONLY);
  724. unsigned char *szOut = new unsigned char[sDesc.Width * sDesc.Height];
  725. unsigned char *_szOut = szOut;
  726. unsigned char *szCur = (unsigned char *)sRect.pBits;
  727. for (unsigned int y = 0; y < sDesc.Height; ++y) {
  728. memcpy(_szOut, szCur, sDesc.Width);
  729. szCur += sRect.Pitch;
  730. _szOut += sDesc.Width;
  731. }
  732. pcTex->UnlockRect(0);
  733. pcTex->Release();
  734. g_szImageMask = szOut;
  735. return 1;
  736. }
  737. //-------------------------------------------------------------------------------
  738. //-------------------------------------------------------------------------------
  739. int CreateDevice(bool p_bMultiSample, bool p_bSuperSample, bool bHW /*= true*/) {
  740. D3DDEVTYPE eType = bHW ? D3DDEVTYPE_HAL : D3DDEVTYPE_REF;
  741. // get the client rectangle of the window.
  742. RECT sRect;
  743. GetWindowRect(GetDlgItem(g_hDlg, IDC_RT), &sRect);
  744. sRect.right -= sRect.left;
  745. sRect.bottom -= sRect.top;
  746. D3DPRESENT_PARAMETERS sParams;
  747. memset(&sParams, 0, sizeof(D3DPRESENT_PARAMETERS));
  748. // get the current display mode
  749. D3DDISPLAYMODE sMode;
  750. g_piD3D->GetAdapterDisplayMode(0, &sMode);
  751. // fill the presentation parameter structure
  752. sParams.Windowed = TRUE;
  753. sParams.hDeviceWindow = GetDlgItem(g_hDlg, IDC_RT);
  754. sParams.EnableAutoDepthStencil = TRUE;
  755. sParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  756. sParams.BackBufferWidth = (UINT)sRect.right;
  757. sParams.BackBufferHeight = (UINT)sRect.bottom;
  758. sParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
  759. sParams.BackBufferCount = 1;
  760. // check whether we can use a D32 depth buffer format
  761. if (SUCCEEDED(g_piD3D->CheckDepthStencilMatch(0, eType,
  762. D3DFMT_X8R8G8B8, D3DFMT_X8R8G8B8, D3DFMT_D32))) {
  763. sParams.AutoDepthStencilFormat = D3DFMT_D32;
  764. } else
  765. sParams.AutoDepthStencilFormat = D3DFMT_D24X8;
  766. // find the highest multisample type available on this device
  767. D3DMULTISAMPLE_TYPE sMS = D3DMULTISAMPLE_2_SAMPLES;
  768. D3DMULTISAMPLE_TYPE sMSOut = D3DMULTISAMPLE_NONE;
  769. DWORD dwQuality = 0;
  770. if (p_bMultiSample) {
  771. while ((D3DMULTISAMPLE_TYPE)(D3DMULTISAMPLE_16_SAMPLES + 1) !=
  772. (sMS = (D3DMULTISAMPLE_TYPE)(sMS + 1))) {
  773. if (SUCCEEDED(g_piD3D->CheckDeviceMultiSampleType(0, eType,
  774. sMode.Format, TRUE, sMS, &dwQuality))) {
  775. sMSOut = sMS;
  776. }
  777. }
  778. if (0 != dwQuality) dwQuality -= 1;
  779. sParams.MultiSampleQuality = dwQuality;
  780. sParams.MultiSampleType = sMSOut;
  781. }
  782. // get the device capabilities. If the hardware vertex shader is too old, we prefer software vertex processing
  783. g_piD3D->GetDeviceCaps(0, D3DDEVTYPE_HAL, &g_sCaps);
  784. DWORD creationFlags = D3DCREATE_MULTITHREADED;
  785. if (g_sCaps.VertexShaderVersion >= D3DVS_VERSION(2, 0))
  786. creationFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  787. else
  788. creationFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  789. // create the D3D9 device object. with software-vertexprocessing if VS2.0 isn`t supported in hardware
  790. if (FAILED(g_piD3D->CreateDevice(0, eType, g_hDlg, creationFlags, &sParams, &g_piDevice))) {
  791. // if hardware fails use software rendering instead
  792. if (bHW) return CreateDevice(p_bMultiSample, p_bSuperSample, false);
  793. return 0;
  794. }
  795. // create a vertex declaration to match the vertex
  796. D3DVERTEXELEMENT9 *vdecl = AssetHelper::Vertex::GetDeclarationElements();
  797. if (FAILED(g_piDevice->CreateVertexDeclaration(vdecl, &gDefaultVertexDecl))) {
  798. MessageBox(g_hDlg, "Failed to create vertex declaration", "Init", MB_OK);
  799. return 0;
  800. }
  801. g_piDevice->SetVertexDeclaration(gDefaultVertexDecl);
  802. // get the capabilities of the device object
  803. g_piDevice->GetDeviceCaps(&g_sCaps);
  804. if (g_sCaps.PixelShaderVersion < D3DPS_VERSION(3, 0)) {
  805. EnableWindow(GetDlgItem(g_hDlg, IDC_LOWQUALITY), FALSE);
  806. }
  807. // compile the default material shader (gray gouraud/phong)
  808. ID3DXBuffer *piBuffer = nullptr;
  809. if (FAILED(D3DXCreateEffect(g_piDevice,
  810. g_szDefaultShader.c_str(),
  811. (UINT)g_szDefaultShader.length(),
  812. nullptr,
  813. nullptr,
  814. AI_SHADER_COMPILE_FLAGS,
  815. nullptr,
  816. &g_piDefaultEffect, &piBuffer))) {
  817. if (piBuffer) {
  818. MessageBox(g_hDlg, (LPCSTR)piBuffer->GetBufferPointer(), "HLSL", MB_OK);
  819. piBuffer->Release();
  820. }
  821. return 0;
  822. }
  823. if (piBuffer) {
  824. piBuffer->Release();
  825. piBuffer = nullptr;
  826. }
  827. // use Fixed Function effect when working with shaderless cards
  828. if (g_sCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
  829. g_piDefaultEffect->SetTechnique("DefaultFXSpecular_FF");
  830. // create the shader used to draw the HUD
  831. if (FAILED(D3DXCreateEffect(g_piDevice,
  832. g_szPassThroughShader.c_str(), (UINT)g_szPassThroughShader.length(),
  833. nullptr, nullptr, AI_SHADER_COMPILE_FLAGS, nullptr, &g_piPassThroughEffect, &piBuffer))) {
  834. if (piBuffer) {
  835. MessageBox(g_hDlg, (LPCSTR)piBuffer->GetBufferPointer(), "HLSL", MB_OK);
  836. piBuffer->Release();
  837. }
  838. return 0;
  839. }
  840. if (piBuffer) {
  841. piBuffer->Release();
  842. piBuffer = nullptr;
  843. }
  844. // use Fixed Function effect when working with shaderless cards
  845. if (g_sCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
  846. g_piPassThroughEffect->SetTechnique("PassThrough_FF");
  847. // create the shader used to visualize normal vectors
  848. if (FAILED(D3DXCreateEffect(g_piDevice,
  849. g_szNormalsShader.c_str(), (UINT)g_szNormalsShader.length(),
  850. nullptr, nullptr, AI_SHADER_COMPILE_FLAGS, nullptr, &g_piNormalsEffect, &piBuffer))) {
  851. if (piBuffer) {
  852. MessageBox(g_hDlg, (LPCSTR)piBuffer->GetBufferPointer(), "HLSL", MB_OK);
  853. piBuffer->Release();
  854. }
  855. return 0;
  856. }
  857. if (piBuffer) {
  858. piBuffer->Release();
  859. piBuffer = nullptr;
  860. }
  861. //MessageBox( g_hDlg, "Failed to create vertex declaration", "Init", MB_OK);
  862. // use Fixed Function effect when working with shaderless cards
  863. if (g_sCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
  864. g_piNormalsEffect->SetTechnique("RenderNormals_FF");
  865. g_piDevice->SetRenderState(D3DRS_DITHERENABLE, TRUE);
  866. // create the texture for the HUD
  867. CreateHUDTexture();
  868. CBackgroundPainter::Instance().RecreateNativeResource();
  869. CLogDisplay::Instance().RecreateNativeResource();
  870. g_piPassThroughEffect->SetTexture("TEXTURE_2D", g_pcTexture);
  871. return 1;
  872. }
  873. //-------------------------------------------------------------------------------
  874. int CreateDevice() {
  875. return CreateDevice(g_sOptions.bMultiSample,
  876. g_sOptions.bSuperSample);
  877. }
  878. //-------------------------------------------------------------------------------
  879. int GetProjectionMatrix(aiMatrix4x4 &p_mOut) {
  880. const float fFarPlane = 100.0f;
  881. const float fNearPlane = 0.1f;
  882. const float fFOV = (float)(45.0 * 0.0174532925);
  883. const float s = 1.0f / tanf(fFOV * 0.5f);
  884. const float Q = fFarPlane / (fFarPlane - fNearPlane);
  885. RECT sRect;
  886. GetWindowRect(GetDlgItem(g_hDlg, IDC_RT), &sRect);
  887. sRect.right -= sRect.left;
  888. sRect.bottom -= sRect.top;
  889. const float fAspect = (float)sRect.right / (float)sRect.bottom;
  890. p_mOut = aiMatrix4x4(
  891. s / fAspect, 0.0f, 0.0f, 0.0f,
  892. 0.0f, s, 0.0f, 0.0f,
  893. 0.0f, 0.0f, Q, 1.0f,
  894. 0.0f, 0.0f, -Q * fNearPlane, 0.0f);
  895. return 1;
  896. }
  897. //-------------------------------------------------------------------------------
  898. aiVector3D GetCameraMatrix(aiMatrix4x4 &p_mOut) {
  899. D3DXMATRIX view;
  900. D3DXMatrixIdentity(&view);
  901. D3DXVec3Normalize((D3DXVECTOR3 *)&g_sCamera.vLookAt, (D3DXVECTOR3 *)&g_sCamera.vLookAt);
  902. D3DXVec3Cross((D3DXVECTOR3 *)&g_sCamera.vRight, (D3DXVECTOR3 *)&g_sCamera.vUp, (D3DXVECTOR3 *)&g_sCamera.vLookAt);
  903. D3DXVec3Normalize((D3DXVECTOR3 *)&g_sCamera.vRight, (D3DXVECTOR3 *)&g_sCamera.vRight);
  904. D3DXVec3Cross((D3DXVECTOR3 *)&g_sCamera.vUp, (D3DXVECTOR3 *)&g_sCamera.vLookAt, (D3DXVECTOR3 *)&g_sCamera.vRight);
  905. D3DXVec3Normalize((D3DXVECTOR3 *)&g_sCamera.vUp, (D3DXVECTOR3 *)&g_sCamera.vUp);
  906. view._11 = g_sCamera.vRight.x;
  907. view._12 = g_sCamera.vUp.x;
  908. view._13 = g_sCamera.vLookAt.x;
  909. view._14 = 0.0f;
  910. view._21 = g_sCamera.vRight.y;
  911. view._22 = g_sCamera.vUp.y;
  912. view._23 = g_sCamera.vLookAt.y;
  913. view._24 = 0.0f;
  914. view._31 = g_sCamera.vRight.z;
  915. view._32 = g_sCamera.vUp.z;
  916. view._33 = g_sCamera.vLookAt.z;
  917. view._34 = 0.0f;
  918. view._41 = -D3DXVec3Dot((D3DXVECTOR3 *)&g_sCamera.vPos, (D3DXVECTOR3 *)&g_sCamera.vRight);
  919. view._42 = -D3DXVec3Dot((D3DXVECTOR3 *)&g_sCamera.vPos, (D3DXVECTOR3 *)&g_sCamera.vUp);
  920. view._43 = -D3DXVec3Dot((D3DXVECTOR3 *)&g_sCamera.vPos, (D3DXVECTOR3 *)&g_sCamera.vLookAt);
  921. view._44 = 1.0f;
  922. memcpy(&p_mOut, &view, sizeof(aiMatrix4x4));
  923. return g_sCamera.vPos;
  924. }
  925. } // namespace AssimpView