KX_BlenderSceneConverter.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. /*
  2. * ***** BEGIN GPL LICENSE BLOCK *****
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software Foundation,
  16. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. *
  18. * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
  19. * All rights reserved.
  20. *
  21. * The Original Code is: all of this file.
  22. *
  23. * Contributor(s): none yet.
  24. *
  25. * ***** END GPL LICENSE BLOCK *****
  26. */
  27. /** \file gameengine/Converter/KX_BlenderSceneConverter.cpp
  28. * \ingroup bgeconv
  29. */
  30. #ifdef _MSC_VER
  31. # pragma warning (disable:4786) /* suppress stl-MSVC debug info warning */
  32. #endif
  33. #include "KX_Scene.h"
  34. #include "KX_GameObject.h"
  35. #include "KX_IpoConvert.h"
  36. #include "RAS_MeshObject.h"
  37. #include "KX_PhysicsEngineEnums.h"
  38. #include "PHY_IPhysicsEnvironment.h"
  39. #include "KX_KetsjiEngine.h"
  40. #include "KX_PythonInit.h" // So we can handle adding new text datablocks for Python to import
  41. #include "BL_Material.h"
  42. #include "BL_ActionActuator.h"
  43. #include "KX_BlenderMaterial.h"
  44. #include "BL_System.h"
  45. #include "DummyPhysicsEnvironment.h"
  46. #ifdef WITH_BULLET
  47. #include "CcdPhysicsEnvironment.h"
  48. #endif
  49. #include "KX_LibLoadStatus.h"
  50. #include "KX_BlenderScalarInterpolator.h"
  51. #include "BL_BlenderDataConversion.h"
  52. #include "KX_WorldInfo.h"
  53. /* This little block needed for linking to Blender... */
  54. #ifdef WIN32
  55. #include "BLI_winstuff.h"
  56. #endif
  57. /* This list includes only data type definitions */
  58. #include "DNA_scene_types.h"
  59. #include "DNA_world_types.h"
  60. #include "BKE_main.h"
  61. #include "BKE_fcurve.h"
  62. #include "BLI_math.h"
  63. extern "C"
  64. {
  65. #include "DNA_object_types.h"
  66. #include "DNA_curve_types.h"
  67. #include "DNA_mesh_types.h"
  68. #include "DNA_material_types.h"
  69. #include "BLI_blenlib.h"
  70. #include "MEM_guardedalloc.h"
  71. #include "BKE_global.h"
  72. #include "BKE_animsys.h"
  73. #include "BKE_library.h"
  74. #include "BKE_material.h" // BKE_material_copy
  75. #include "BKE_mesh.h" // BKE_mesh_copy
  76. #include "DNA_space_types.h"
  77. #include "DNA_anim_types.h"
  78. #include "DNA_action_types.h"
  79. #include "RNA_define.h"
  80. #include "../../blender/editors/include/ED_keyframing.h"
  81. }
  82. /* Only for dynamic loading and merging */
  83. #include "RAS_BucketManager.h" // XXX cant stay
  84. #include "KX_BlenderSceneConverter.h"
  85. #include "KX_MeshProxy.h"
  86. extern "C" {
  87. #include "PIL_time.h"
  88. #include "BKE_context.h"
  89. #include "BLO_readfile.h"
  90. #include "BKE_idcode.h"
  91. #include "BKE_report.h"
  92. #include "DNA_space_types.h"
  93. #include "DNA_windowmanager_types.h" /* report api */
  94. #include "../../blender/blenlib/BLI_linklist.h"
  95. }
  96. #include "BLI_task.h"
  97. // This is used to avoid including BLI_task.h in KX_BlenderSceneConverter.h
  98. typedef struct ThreadInfo {
  99. TaskPool *m_pool;
  100. ThreadMutex m_mutex;
  101. } ThreadInfo;
  102. KX_BlenderSceneConverter::KX_BlenderSceneConverter(
  103. Main *maggie,
  104. KX_KetsjiEngine *engine)
  105. :m_maggie(maggie),
  106. m_ketsjiEngine(engine),
  107. m_alwaysUseExpandFraming(false),
  108. m_usemat(false),
  109. m_useglslmat(false),
  110. m_use_mat_cache(true)
  111. {
  112. BKE_main_id_tag_all(maggie, LIB_TAG_DOIT, false); /* avoid re-tagging later on */
  113. m_newfilename = "";
  114. m_threadinfo = new ThreadInfo();
  115. m_threadinfo->m_pool = BLI_task_pool_create(engine->GetTaskScheduler(), NULL);
  116. BLI_mutex_init(&m_threadinfo->m_mutex);
  117. }
  118. KX_BlenderSceneConverter::~KX_BlenderSceneConverter()
  119. {
  120. // clears meshes, and hashmaps from blender to gameengine data
  121. // delete sumoshapes
  122. int numAdtLists = m_map_blender_to_gameAdtList.size();
  123. for (int i = 0; i < numAdtLists; i++) {
  124. BL_InterpolatorList *adtList = *m_map_blender_to_gameAdtList.at(i);
  125. delete (adtList);
  126. }
  127. vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator itw = m_worldinfos.begin();
  128. while (itw != m_worldinfos.end()) {
  129. delete itw->second;
  130. itw++;
  131. }
  132. m_worldinfos.clear();
  133. vector<pair<KX_Scene *,RAS_IPolyMaterial *> >::iterator itp = m_polymaterials.begin();
  134. while (itp != m_polymaterials.end()) {
  135. delete itp->second;
  136. itp++;
  137. }
  138. m_polymaterials.clear();
  139. // delete after RAS_IPolyMaterial
  140. vector<pair<KX_Scene *,BL_Material *> >::iterator itmat = m_materials.begin();
  141. while (itmat != m_materials.end()) {
  142. delete itmat->second;
  143. itmat++;
  144. }
  145. m_materials.clear();
  146. vector<pair<KX_Scene *,RAS_MeshObject *> >::iterator itm = m_meshobjects.begin();
  147. while (itm != m_meshobjects.end()) {
  148. delete itm->second;
  149. itm++;
  150. }
  151. m_meshobjects.clear();
  152. /* free any data that was dynamically loaded */
  153. while (m_DynamicMaggie.size() != 0) {
  154. FreeBlendFile(m_DynamicMaggie[0]);
  155. }
  156. m_DynamicMaggie.clear();
  157. if (m_threadinfo) {
  158. /* Thread infos like mutex must be freed after FreeBlendFile function.
  159. Because it needs to lock the mutex, even if there's no active task when it's
  160. in the scene converter destructor. */
  161. BLI_task_pool_free(m_threadinfo->m_pool);
  162. BLI_mutex_end(&m_threadinfo->m_mutex);
  163. delete m_threadinfo;
  164. }
  165. }
  166. void KX_BlenderSceneConverter::SetNewFileName(const STR_String &filename)
  167. {
  168. m_newfilename = filename;
  169. }
  170. bool KX_BlenderSceneConverter::TryAndLoadNewFile()
  171. {
  172. bool result = false;
  173. return result;
  174. }
  175. Scene *KX_BlenderSceneConverter::GetBlenderSceneForName(const STR_String &name)
  176. {
  177. Scene *sce;
  178. /**
  179. * Find the specified scene by name, or NULL if nothing matches.
  180. */
  181. if ((sce = (Scene *)BLI_findstring(&m_maggie->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
  182. return sce;
  183. for (vector<Main *>::iterator it=m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) {
  184. Main *main = *it;
  185. if ((sce= (Scene *)BLI_findstring(&main->scene, name.ReadPtr(), offsetof(ID, name) + 2)))
  186. return sce;
  187. }
  188. return NULL;
  189. }
  190. void KX_BlenderSceneConverter::ConvertScene(KX_Scene *destinationscene, RAS_IRasterizer *rendertools,
  191. RAS_ICanvas *canvas, bool libloading)
  192. {
  193. //find out which physics engine
  194. Scene *blenderscene = destinationscene->GetBlenderScene();
  195. PHY_IPhysicsEnvironment *phy_env = NULL;
  196. e_PhysicsEngine physics_engine = UseBullet;
  197. // hook for registration function during conversion.
  198. m_currentScene = destinationscene;
  199. destinationscene->SetSceneConverter(this);
  200. // This doesn't really seem to do anything except cause potential issues
  201. // when doing threaded conversion, so it's disabled for now.
  202. // SG_SetActiveStage(SG_STAGE_CONVERTER);
  203. switch (blenderscene->gm.physicsEngine) {
  204. #ifdef WITH_BULLET
  205. case WOPHY_BULLET:
  206. {
  207. SYS_SystemHandle syshandle = SYS_GetSystem(); /*unused*/
  208. int visualizePhysics = SYS_GetCommandLineInt(syshandle, "show_physics", 0);
  209. phy_env = CcdPhysicsEnvironment::Create(blenderscene, visualizePhysics);
  210. physics_engine = UseBullet;
  211. break;
  212. }
  213. #endif
  214. default:
  215. case WOPHY_NONE:
  216. {
  217. // We should probably use some sort of factory here
  218. phy_env = new DummyPhysicsEnvironment();
  219. physics_engine = UseNone;
  220. break;
  221. }
  222. }
  223. destinationscene->SetPhysicsEnvironment(phy_env);
  224. BL_ConvertBlenderObjects(
  225. m_maggie,
  226. destinationscene,
  227. m_ketsjiEngine,
  228. physics_engine,
  229. rendertools,
  230. canvas,
  231. this,
  232. m_alwaysUseExpandFraming,
  233. libloading);
  234. //These lookup are not needed during game
  235. m_map_blender_to_gameactuator.clear();
  236. m_map_blender_to_gamecontroller.clear();
  237. m_map_blender_to_gameobject.clear();
  238. //Clearing this lookup table has the effect of disabling the cache of meshes
  239. //between scenes, even if they are shared in the blend file.
  240. //This cache mecanism is buggy so I leave it disable and the memory leak
  241. //that would result from this is fixed in RemoveScene()
  242. m_map_mesh_to_gamemesh.clear();
  243. }
  244. // This function removes all entities stored in the converter for that scene
  245. // It should be used instead of direct delete scene
  246. // Note that there was some provision for sharing entities (meshes...) between
  247. // scenes but that is now disabled so all scene will have their own copy
  248. // and we can delete them here. If the sharing is reactivated, change this code too..
  249. // (see KX_BlenderSceneConverter::ConvertScene)
  250. void KX_BlenderSceneConverter::RemoveScene(KX_Scene *scene)
  251. {
  252. int i, size;
  253. // delete the scene first as it will stop the use of entities
  254. delete scene;
  255. // delete the entities of this scene
  256. vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator worldit;
  257. size = m_worldinfos.size();
  258. for (i = 0, worldit = m_worldinfos.begin(); i < size; ) {
  259. if (worldit->first == scene) {
  260. delete worldit->second;
  261. *worldit = m_worldinfos.back();
  262. m_worldinfos.pop_back();
  263. size--;
  264. }
  265. else {
  266. i++;
  267. worldit++;
  268. }
  269. }
  270. vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator polymit;
  271. size = m_polymaterials.size();
  272. for (i = 0, polymit = m_polymaterials.begin(); i < size; ) {
  273. if (polymit->first == scene) {
  274. m_polymat_cache[scene].erase(polymit->second->GetBlenderMaterial());
  275. delete polymit->second;
  276. *polymit = m_polymaterials.back();
  277. m_polymaterials.pop_back();
  278. size--;
  279. }
  280. else {
  281. i++;
  282. polymit++;
  283. }
  284. }
  285. m_polymat_cache.erase(scene);
  286. vector<pair<KX_Scene *, BL_Material *> >::iterator matit;
  287. size = m_materials.size();
  288. for (i = 0, matit = m_materials.begin(); i < size; ) {
  289. if (matit->first == scene) {
  290. m_mat_cache[scene].erase(matit->second->material);
  291. delete matit->second;
  292. *matit = m_materials.back();
  293. m_materials.pop_back();
  294. size--;
  295. }
  296. else {
  297. i++;
  298. matit++;
  299. }
  300. }
  301. m_mat_cache.erase(scene);
  302. vector<pair<KX_Scene *, RAS_MeshObject *> >::iterator meshit;
  303. size = m_meshobjects.size();
  304. for (i = 0, meshit = m_meshobjects.begin(); i < size; ) {
  305. if (meshit->first == scene) {
  306. delete meshit->second;
  307. *meshit = m_meshobjects.back();
  308. m_meshobjects.pop_back();
  309. size--;
  310. }
  311. else {
  312. i++;
  313. meshit++;
  314. }
  315. }
  316. }
  317. // use blender materials
  318. void KX_BlenderSceneConverter::SetMaterials(bool val)
  319. {
  320. m_usemat = val;
  321. m_useglslmat = false;
  322. }
  323. void KX_BlenderSceneConverter::SetGLSLMaterials(bool val)
  324. {
  325. m_usemat = val;
  326. m_useglslmat = val;
  327. }
  328. void KX_BlenderSceneConverter::SetCacheMaterials(bool val)
  329. {
  330. m_use_mat_cache = val;
  331. }
  332. bool KX_BlenderSceneConverter::GetMaterials()
  333. {
  334. return m_usemat;
  335. }
  336. bool KX_BlenderSceneConverter::GetGLSLMaterials()
  337. {
  338. return m_useglslmat;
  339. }
  340. bool KX_BlenderSceneConverter::GetCacheMaterials()
  341. {
  342. return m_use_mat_cache;
  343. }
  344. void KX_BlenderSceneConverter::RegisterBlenderMaterial(BL_Material *mat)
  345. {
  346. // First make sure we don't register the material twice
  347. vector<pair<KX_Scene *, BL_Material *> >::iterator it;
  348. for (it = m_materials.begin(); it != m_materials.end(); ++it)
  349. if (it->second == mat)
  350. return;
  351. m_materials.push_back(pair<KX_Scene *, BL_Material *> (m_currentScene, mat));
  352. }
  353. void KX_BlenderSceneConverter::SetAlwaysUseExpandFraming(bool to_what)
  354. {
  355. m_alwaysUseExpandFraming= to_what;
  356. }
  357. void KX_BlenderSceneConverter::RegisterGameObject(KX_GameObject *gameobject, Object *for_blenderobject)
  358. {
  359. /* only maintained while converting, freed during game runtime */
  360. m_map_blender_to_gameobject.insert(CHashedPtr(for_blenderobject), gameobject);
  361. }
  362. /* only need to run this during conversion since
  363. * m_map_blender_to_gameobject is freed after conversion */
  364. void KX_BlenderSceneConverter::UnregisterGameObject(KX_GameObject *gameobject)
  365. {
  366. Object *bobp = gameobject->GetBlenderObject();
  367. if (bobp) {
  368. CHashedPtr bptr(bobp);
  369. KX_GameObject **gobp = m_map_blender_to_gameobject[bptr];
  370. if (gobp && *gobp == gameobject) {
  371. // also maintain m_map_blender_to_gameobject if the gameobject
  372. // being removed is matching the blender object
  373. m_map_blender_to_gameobject.remove(bptr);
  374. }
  375. }
  376. }
  377. KX_GameObject *KX_BlenderSceneConverter::FindGameObject(Object *for_blenderobject)
  378. {
  379. KX_GameObject **obp = m_map_blender_to_gameobject[CHashedPtr(for_blenderobject)];
  380. return obp ? *obp : NULL;
  381. }
  382. void KX_BlenderSceneConverter::RegisterGameMesh(RAS_MeshObject *gamemesh, Mesh *for_blendermesh)
  383. {
  384. if (for_blendermesh) { /* dynamically loaded meshes we don't want to keep lookups for */
  385. m_map_mesh_to_gamemesh.insert(CHashedPtr(for_blendermesh),gamemesh);
  386. }
  387. m_meshobjects.push_back(pair<KX_Scene *, RAS_MeshObject *> (m_currentScene,gamemesh));
  388. }
  389. RAS_MeshObject *KX_BlenderSceneConverter::FindGameMesh(Mesh *for_blendermesh)
  390. {
  391. RAS_MeshObject **meshp = m_map_mesh_to_gamemesh[CHashedPtr(for_blendermesh)];
  392. if (meshp) {
  393. return *meshp;
  394. }
  395. else {
  396. return NULL;
  397. }
  398. }
  399. void KX_BlenderSceneConverter::RegisterPolyMaterial(RAS_IPolyMaterial *polymat)
  400. {
  401. // First make sure we don't register the material twice
  402. vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator it;
  403. for (it = m_polymaterials.begin(); it != m_polymaterials.end(); ++it)
  404. if (it->second == polymat)
  405. return;
  406. m_polymaterials.push_back(pair<KX_Scene *, RAS_IPolyMaterial *> (m_currentScene, polymat));
  407. }
  408. void KX_BlenderSceneConverter::CachePolyMaterial(KX_Scene *scene, Material *mat, RAS_IPolyMaterial *polymat)
  409. {
  410. if (m_use_mat_cache && mat)
  411. m_polymat_cache[scene][mat] = polymat;
  412. }
  413. RAS_IPolyMaterial *KX_BlenderSceneConverter::FindCachedPolyMaterial(KX_Scene *scene, Material *mat)
  414. {
  415. return (m_use_mat_cache) ? m_polymat_cache[scene][mat] : NULL;
  416. }
  417. void KX_BlenderSceneConverter::CacheBlenderMaterial(KX_Scene *scene, Material *mat, BL_Material *blmat)
  418. {
  419. if (m_use_mat_cache && mat)
  420. m_mat_cache[scene][mat] = blmat;
  421. }
  422. BL_Material *KX_BlenderSceneConverter::FindCachedBlenderMaterial(KX_Scene *scene, Material *mat)
  423. {
  424. return (m_use_mat_cache) ? m_mat_cache[scene][mat] : NULL;
  425. }
  426. void KX_BlenderSceneConverter::RegisterInterpolatorList(BL_InterpolatorList *actList, bAction *for_act)
  427. {
  428. m_map_blender_to_gameAdtList.insert(CHashedPtr(for_act), actList);
  429. }
  430. BL_InterpolatorList *KX_BlenderSceneConverter::FindInterpolatorList(bAction *for_act)
  431. {
  432. BL_InterpolatorList **listp = m_map_blender_to_gameAdtList[CHashedPtr(for_act)];
  433. return listp ? *listp : NULL;
  434. }
  435. void KX_BlenderSceneConverter::RegisterGameActuator(SCA_IActuator *act, bActuator *for_actuator)
  436. {
  437. m_map_blender_to_gameactuator.insert(CHashedPtr(for_actuator), act);
  438. }
  439. SCA_IActuator *KX_BlenderSceneConverter::FindGameActuator(bActuator *for_actuator)
  440. {
  441. SCA_IActuator **actp = m_map_blender_to_gameactuator[CHashedPtr(for_actuator)];
  442. return actp ? *actp : NULL;
  443. }
  444. void KX_BlenderSceneConverter::RegisterGameController(SCA_IController *cont, bController *for_controller)
  445. {
  446. m_map_blender_to_gamecontroller.insert(CHashedPtr(for_controller), cont);
  447. }
  448. SCA_IController *KX_BlenderSceneConverter::FindGameController(bController *for_controller)
  449. {
  450. SCA_IController **contp = m_map_blender_to_gamecontroller[CHashedPtr(for_controller)];
  451. return contp ? *contp : NULL;
  452. }
  453. void KX_BlenderSceneConverter::RegisterWorldInfo(KX_WorldInfo *worldinfo)
  454. {
  455. m_worldinfos.push_back(pair<KX_Scene *, KX_WorldInfo *> (m_currentScene, worldinfo));
  456. }
  457. void KX_BlenderSceneConverter::ResetPhysicsObjectsAnimationIpo(bool clearIpo)
  458. {
  459. //TODO this entire function is deprecated, written for 2.4x
  460. //the functionality should be rewritten, currently it does nothing
  461. KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
  462. int numScenes = scenes->size();
  463. int i;
  464. for (i = 0; i < numScenes; i++) {
  465. KX_Scene *scene = scenes->at(i);
  466. CListValue *parentList = scene->GetRootParentList();
  467. int numObjects = parentList->GetCount();
  468. int g;
  469. for (g = 0; g < numObjects; g++) {
  470. KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g);
  471. if (gameObj->IsRecordAnimation()) {
  472. Object *blenderObject = gameObj->GetBlenderObject();
  473. if (blenderObject) {
  474. #if 0
  475. //erase existing ipo's
  476. Ipo* ipo = blenderObject->ipo;//findIpoForName(blenderObject->id.name+2);
  477. if (ipo) { //clear the curve data
  478. if (clearIpo) {//rcruiz
  479. IpoCurve *icu1;
  480. int numCurves = 0;
  481. for ( icu1 = (IpoCurve*)ipo->curve.first; icu1; ) {
  482. IpoCurve* tmpicu = icu1;
  483. /*int i;
  484. BezTriple *bezt;
  485. for ( bezt = tmpicu->bezt, i = 0; i < tmpicu->totvert; i++, bezt++) {
  486. printf("(%f,%f,%f),(%f,%f,%f),(%f,%f,%f)\n",bezt->vec[0][0],bezt->vec[0][1],bezt->vec[0][2],bezt->vec[1][0],bezt->vec[1][1],bezt->vec[1][2],bezt->vec[2][0],bezt->vec[2][1],bezt->vec[2][2]);
  487. }*/
  488. icu1 = icu1->next;
  489. numCurves++;
  490. BLI_remlink( &( blenderObject->ipo->curve ), tmpicu );
  491. if ( tmpicu->bezt )
  492. MEM_freeN( tmpicu->bezt );
  493. MEM_freeN( tmpicu );
  494. localDel_ipoCurve( tmpicu );
  495. }
  496. }
  497. }
  498. else {
  499. ipo = NULL; // XXX add_ipo(blenderObject->id.name+2, ID_OB);
  500. blenderObject->ipo = ipo;
  501. }
  502. #endif
  503. }
  504. }
  505. }
  506. }
  507. }
  508. void KX_BlenderSceneConverter::resetNoneDynamicObjectToIpo()
  509. {
  510. //TODO the functionality should be rewritten
  511. }
  512. // this generates ipo curves for position, rotation, allowing to use game physics in animation
  513. void KX_BlenderSceneConverter::WritePhysicsObjectToAnimationIpo(int frameNumber)
  514. {
  515. KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
  516. int numScenes = scenes->size();
  517. int i;
  518. for (i = 0; i < numScenes; i++) {
  519. KX_Scene *scene = scenes->at(i);
  520. //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
  521. CListValue *parentList = scene->GetObjectList();
  522. int numObjects = parentList->GetCount();
  523. int g;
  524. for (g = 0; g < numObjects; g++) {
  525. KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g);
  526. Object *blenderObject = gameObj->GetBlenderObject();
  527. if (blenderObject && blenderObject->parent == NULL && gameObj->IsRecordAnimation()) {
  528. if (blenderObject->adt == NULL)
  529. BKE_animdata_add_id(&blenderObject->id);
  530. if (blenderObject->adt) {
  531. const MT_Point3 &position = gameObj->NodeGetWorldPosition();
  532. //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
  533. const MT_Matrix3x3 &orn = gameObj->NodeGetWorldOrientation();
  534. position.getValue(blenderObject->loc);
  535. float tmat[3][3];
  536. for (int r = 0; r < 3; r++)
  537. for (int c = 0; c < 3; c++)
  538. tmat[r][c] = (float)orn[c][r];
  539. mat3_to_compatible_eul(blenderObject->rot, blenderObject->rot, tmat);
  540. insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "location", -1, (float)frameNumber, BEZT_KEYTYPE_JITTER, INSERTKEY_FAST);
  541. insert_keyframe(NULL, &blenderObject->id, NULL, NULL, "rotation_euler", -1, (float)frameNumber, BEZT_KEYTYPE_JITTER, INSERTKEY_FAST);
  542. #if 0
  543. const MT_Point3& position = gameObj->NodeGetWorldPosition();
  544. //const MT_Vector3& scale = gameObj->NodeGetWorldScaling();
  545. const MT_Matrix3x3& orn = gameObj->NodeGetWorldOrientation();
  546. float eulerAngles[3];
  547. float eulerAnglesOld[3] = {0.0f, 0.0f, 0.0f};
  548. float tmat[3][3];
  549. // XXX animato
  550. Ipo* ipo = blenderObject->ipo;
  551. //create the curves, if not existing, set linear if new
  552. IpoCurve *icu_lx = findIpoCurve((IpoCurve *)ipo->curve.first,"LocX");
  553. if (!icu_lx) {
  554. icu_lx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_X, 1);
  555. if (icu_lx) icu_lx->ipo = IPO_LIN;
  556. }
  557. IpoCurve *icu_ly = findIpoCurve((IpoCurve *)ipo->curve.first,"LocY");
  558. if (!icu_ly) {
  559. icu_ly = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Y, 1);
  560. if (icu_ly) icu_ly->ipo = IPO_LIN;
  561. }
  562. IpoCurve *icu_lz = findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ");
  563. if (!icu_lz) {
  564. icu_lz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_LOC_Z, 1);
  565. if (icu_lz) icu_lz->ipo = IPO_LIN;
  566. }
  567. IpoCurve *icu_rx = findIpoCurve((IpoCurve *)ipo->curve.first,"RotX");
  568. if (!icu_rx) {
  569. icu_rx = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_X, 1);
  570. if (icu_rx) icu_rx->ipo = IPO_LIN;
  571. }
  572. IpoCurve *icu_ry = findIpoCurve((IpoCurve *)ipo->curve.first,"RotY");
  573. if (!icu_ry) {
  574. icu_ry = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Y, 1);
  575. if (icu_ry) icu_ry->ipo = IPO_LIN;
  576. }
  577. IpoCurve *icu_rz = findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ");
  578. if (!icu_rz) {
  579. icu_rz = verify_ipocurve(&blenderObject->id, ipo->blocktype, NULL, NULL, NULL, OB_ROT_Z, 1);
  580. if (icu_rz) icu_rz->ipo = IPO_LIN;
  581. }
  582. if (icu_rx) eulerAnglesOld[0] = eval_icu( icu_rx, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
  583. if (icu_ry) eulerAnglesOld[1] = eval_icu( icu_ry, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
  584. if (icu_rz) eulerAnglesOld[2] = eval_icu( icu_rz, frameNumber - 1 ) / ((180 / 3.14159265f) / 10);
  585. // orn.getValue((float *)tmat); // uses the wrong ordering, cant use this
  586. for (int r = 0; r < 3; r++)
  587. for (int c = 0; c < 3; c++)
  588. tmat[r][c] = orn[c][r];
  589. // mat3_to_eul( eulerAngles,tmat); // better to use Mat3ToCompatibleEul
  590. mat3_to_compatible_eul( eulerAngles, eulerAnglesOld,tmat);
  591. //eval_icu
  592. for (int x = 0; x < 3; x++)
  593. eulerAngles[x] *= (float) ((180 / 3.14159265f) / 10.0);
  594. //fill the curves with data
  595. if (icu_lx) insert_vert_icu(icu_lx, frameNumber, position.x(), 1);
  596. if (icu_ly) insert_vert_icu(icu_ly, frameNumber, position.y(), 1);
  597. if (icu_lz) insert_vert_icu(icu_lz, frameNumber, position.z(), 1);
  598. if (icu_rx) insert_vert_icu(icu_rx, frameNumber, eulerAngles[0], 1);
  599. if (icu_ry) insert_vert_icu(icu_ry, frameNumber, eulerAngles[1], 1);
  600. if (icu_rz) insert_vert_icu(icu_rz, frameNumber, eulerAngles[2], 1);
  601. // Handles are corrected at the end, testhandles_ipocurve isn't needed yet
  602. #endif
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void KX_BlenderSceneConverter::TestHandlesPhysicsObjectToAnimationIpo()
  609. {
  610. KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
  611. int numScenes = scenes->size();
  612. int i;
  613. for (i = 0; i < numScenes; i++) {
  614. KX_Scene *scene = scenes->at(i);
  615. //PHY_IPhysicsEnvironment* physEnv = scene->GetPhysicsEnvironment();
  616. CListValue *parentList = scene->GetRootParentList();
  617. int numObjects = parentList->GetCount();
  618. int g;
  619. for (g = 0; g < numObjects; g++) {
  620. KX_GameObject *gameObj = (KX_GameObject *)parentList->GetValue(g);
  621. if (gameObj->IsRecordAnimation()) {
  622. Object *blenderObject = gameObj->GetBlenderObject();
  623. if (blenderObject && blenderObject->adt) {
  624. bAction *act = verify_adt_action(&blenderObject->id, false);
  625. FCurve *fcu;
  626. if (!act) {
  627. continue;
  628. }
  629. /* for now, not much choice but to run this on all curves... */
  630. for (fcu = (FCurve *)act->curves.first; fcu; fcu = fcu->next) {
  631. /* Note: calling `sort_time_fcurve()` here is not needed, since
  632. * all keys have been added in 'right' order. */
  633. calchandles_fcurve(fcu);
  634. }
  635. #if 0
  636. // XXX animato
  637. Ipo* ipo = blenderObject->ipo;
  638. //create the curves, if not existing
  639. //testhandles_ipocurve checks for NULL
  640. testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocX"));
  641. testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocY"));
  642. testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"LocZ"));
  643. testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotX"));
  644. testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotY"));
  645. testhandles_ipocurve(findIpoCurve((IpoCurve *)ipo->curve.first,"RotZ"));
  646. #endif
  647. }
  648. }
  649. }
  650. }
  651. }
  652. #ifdef WITH_PYTHON
  653. PyObject *KX_BlenderSceneConverter::GetPyNamespace()
  654. {
  655. return m_ketsjiEngine->GetPyNamespace();
  656. }
  657. #endif
  658. vector<Main *> &KX_BlenderSceneConverter::GetMainDynamic()
  659. {
  660. return m_DynamicMaggie;
  661. }
  662. Main *KX_BlenderSceneConverter::GetMainDynamicPath(const char *path)
  663. {
  664. for (vector<Main *>::iterator it = m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++)
  665. if (BLI_path_cmp((*it)->name, path) == 0)
  666. return *it;
  667. return NULL;
  668. }
  669. void KX_BlenderSceneConverter::MergeAsyncLoads()
  670. {
  671. vector<KX_Scene *> *merge_scenes;
  672. vector<KX_LibLoadStatus *>::iterator mit;
  673. vector<KX_Scene *>::iterator sit;
  674. BLI_mutex_lock(&m_threadinfo->m_mutex);
  675. for (mit = m_mergequeue.begin(); mit != m_mergequeue.end(); ++mit) {
  676. merge_scenes = (vector<KX_Scene *> *)(*mit)->GetData();
  677. for (sit=merge_scenes->begin(); sit!=merge_scenes->end(); ++sit) {
  678. (*mit)->GetMergeScene()->MergeScene(*sit);
  679. delete (*sit);
  680. }
  681. delete merge_scenes;
  682. (*mit)->SetData(NULL);
  683. (*mit)->Finish();
  684. }
  685. m_mergequeue.clear();
  686. BLI_mutex_unlock(&m_threadinfo->m_mutex);
  687. }
  688. void KX_BlenderSceneConverter::FinalizeAsyncLoads()
  689. {
  690. // Finish all loading libraries.
  691. if (m_threadinfo) {
  692. BLI_task_pool_work_and_wait(m_threadinfo->m_pool);
  693. }
  694. // Merge all libraries data in the current scene, to avoid memory leak of unmerged scenes.
  695. MergeAsyncLoads();
  696. }
  697. void KX_BlenderSceneConverter::AddScenesToMergeQueue(KX_LibLoadStatus *status)
  698. {
  699. BLI_mutex_lock(&m_threadinfo->m_mutex);
  700. m_mergequeue.push_back(status);
  701. BLI_mutex_unlock(&m_threadinfo->m_mutex);
  702. }
  703. static void async_convert(TaskPool *pool, void *ptr, int UNUSED(threadid))
  704. {
  705. KX_Scene *new_scene = NULL;
  706. KX_LibLoadStatus *status = (KX_LibLoadStatus *)ptr;
  707. vector<Scene *> *scenes = (vector<Scene *> *)status->GetData();
  708. vector<KX_Scene *> *merge_scenes = new vector<KX_Scene *>(); // Deleted in MergeAsyncLoads
  709. for (unsigned int i = 0; i < scenes->size(); ++i) {
  710. new_scene = status->GetEngine()->CreateScene((*scenes)[i], true);
  711. if (new_scene)
  712. merge_scenes->push_back(new_scene);
  713. status->AddProgress((1.0f / scenes->size()) * 0.9f); // We'll call conversion 90% and merging 10% for now
  714. }
  715. delete scenes;
  716. status->SetData(merge_scenes);
  717. status->GetConverter()->AddScenesToMergeQueue(status);
  718. }
  719. KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFileMemory(void *data, int length, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
  720. {
  721. BlendHandle *bpy_openlib = BLO_blendhandle_from_memory(data, length);
  722. // Error checking is done in LinkBlendFile
  723. return LinkBlendFile(bpy_openlib, path, group, scene_merge, err_str, options);
  724. }
  725. KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFilePath(const char *filepath, char *group, KX_Scene *scene_merge, char **err_str, short options)
  726. {
  727. BlendHandle *bpy_openlib = BLO_blendhandle_from_file(filepath, NULL);
  728. // Error checking is done in LinkBlendFile
  729. return LinkBlendFile(bpy_openlib, filepath, group, scene_merge, err_str, options);
  730. }
  731. static void load_datablocks(Main *main_tmp, BlendHandle *bpy_openlib, const char *path, int idcode)
  732. {
  733. LinkNode *names = NULL;
  734. int totnames_dummy;
  735. names = BLO_blendhandle_get_datablock_names(bpy_openlib, idcode, &totnames_dummy);
  736. int i = 0;
  737. LinkNode *n = names;
  738. while (n) {
  739. BLO_library_link_named_part(main_tmp, &bpy_openlib, idcode, (char *)n->link);
  740. n = (LinkNode *)n->next;
  741. i++;
  742. }
  743. BLI_linklist_free(names, free); /* free linklist *and* each node's data */
  744. }
  745. KX_LibLoadStatus *KX_BlenderSceneConverter::LinkBlendFile(BlendHandle *bpy_openlib, const char *path, char *group, KX_Scene *scene_merge, char **err_str, short options)
  746. {
  747. Main *main_newlib; /* stored as a dynamic 'main' until we free it */
  748. const int idcode = BKE_idcode_from_name(group);
  749. ReportList reports;
  750. static char err_local[255];
  751. // TIMEIT_START(bge_link_blend_file);
  752. KX_LibLoadStatus *status;
  753. /* only scene and mesh supported right now */
  754. if (idcode != ID_SCE && idcode != ID_ME && idcode != ID_AC) {
  755. snprintf(err_local, sizeof(err_local), "invalid ID type given \"%s\"\n", group);
  756. *err_str = err_local;
  757. BLO_blendhandle_close(bpy_openlib);
  758. return NULL;
  759. }
  760. if (GetMainDynamicPath(path)) {
  761. snprintf(err_local, sizeof(err_local), "blend file already open \"%s\"\n", path);
  762. *err_str = err_local;
  763. BLO_blendhandle_close(bpy_openlib);
  764. return NULL;
  765. }
  766. if (bpy_openlib == NULL) {
  767. snprintf(err_local, sizeof(err_local), "could not open blendfile \"%s\"\n", path);
  768. *err_str = err_local;
  769. return NULL;
  770. }
  771. main_newlib = BKE_main_new();
  772. BKE_reports_init(&reports, RPT_STORE);
  773. short flag = 0; /* don't need any special options */
  774. /* created only for linking, then freed */
  775. Main *main_tmp = BLO_library_link_begin(main_newlib, &bpy_openlib, (char *)path);
  776. load_datablocks(main_tmp, bpy_openlib, path, idcode);
  777. if (idcode == ID_SCE && options & LIB_LOAD_LOAD_SCRIPTS) {
  778. load_datablocks(main_tmp, bpy_openlib, path, ID_TXT);
  779. }
  780. /* now do another round of linking for Scenes so all actions are properly loaded */
  781. if (idcode == ID_SCE && options & LIB_LOAD_LOAD_ACTIONS) {
  782. load_datablocks(main_tmp, bpy_openlib, path, ID_AC);
  783. }
  784. BLO_library_link_end(main_tmp, &bpy_openlib, flag, NULL, NULL);
  785. BLO_blendhandle_close(bpy_openlib);
  786. BKE_reports_clear(&reports);
  787. /* done linking */
  788. /* needed for lookups*/
  789. GetMainDynamic().push_back(main_newlib);
  790. BLI_strncpy(main_newlib->name, path, sizeof(main_newlib->name));
  791. status = new KX_LibLoadStatus(this, m_ketsjiEngine, scene_merge, path);
  792. if (idcode == ID_ME) {
  793. /* Convert all new meshes into BGE meshes */
  794. ID *mesh;
  795. for (mesh = (ID *)main_newlib->mesh.first; mesh; mesh = (ID *)mesh->next ) {
  796. if (options & LIB_LOAD_VERBOSE)
  797. printf("MeshName: %s\n", mesh->name + 2);
  798. RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)mesh, NULL, scene_merge, this, false); // For now only use the libloading option for scenes, which need to handle materials/shaders
  799. scene_merge->GetLogicManager()->RegisterMeshName(meshobj->GetName(), meshobj);
  800. }
  801. }
  802. else if (idcode == ID_AC) {
  803. /* Convert all actions */
  804. ID *action;
  805. for (action= (ID *)main_newlib->action.first; action; action = (ID *)action->next) {
  806. if (options & LIB_LOAD_VERBOSE)
  807. printf("ActionName: %s\n", action->name + 2);
  808. scene_merge->GetLogicManager()->RegisterActionName(action->name + 2, action);
  809. }
  810. }
  811. else if (idcode == ID_SCE) {
  812. /* Merge all new linked in scene into the existing one */
  813. ID *scene;
  814. // scenes gets deleted by the thread when it's done using it (look in async_convert())
  815. vector<Scene *> *scenes = (options & LIB_LOAD_ASYNC) ? new vector<Scene *>() : NULL;
  816. for (scene = (ID *)main_newlib->scene.first; scene; scene = (ID *)scene->next ) {
  817. if (options & LIB_LOAD_VERBOSE)
  818. printf("SceneName: %s\n", scene->name + 2);
  819. if (options & LIB_LOAD_ASYNC) {
  820. scenes->push_back((Scene *)scene);
  821. }
  822. else {
  823. /* merge into the base scene */
  824. KX_Scene* other = m_ketsjiEngine->CreateScene((Scene *)scene, true);
  825. scene_merge->MergeScene(other);
  826. // RemoveScene(other); // Don't run this, it frees the entire scene converter data, just delete the scene
  827. delete other;
  828. }
  829. }
  830. if (options & LIB_LOAD_ASYNC) {
  831. status->SetData(scenes);
  832. BLI_task_pool_push(m_threadinfo->m_pool, async_convert, (void *)status, false, TASK_PRIORITY_LOW);
  833. }
  834. #ifdef WITH_PYTHON
  835. /* Handle any text datablocks */
  836. if (options & LIB_LOAD_LOAD_SCRIPTS)
  837. addImportMain(main_newlib);
  838. #endif
  839. /* Now handle all the actions */
  840. if (options & LIB_LOAD_LOAD_ACTIONS) {
  841. ID *action;
  842. for (action = (ID *)main_newlib->action.first; action; action = (ID *)action->next) {
  843. if (options & LIB_LOAD_VERBOSE)
  844. printf("ActionName: %s\n", action->name + 2);
  845. scene_merge->GetLogicManager()->RegisterActionName(action->name + 2, action);
  846. }
  847. }
  848. }
  849. if (!(options & LIB_LOAD_ASYNC))
  850. status->Finish();
  851. // TIMEIT_END(bge_link_blend_file);
  852. m_status_map[main_newlib->name] = status;
  853. return status;
  854. }
  855. /* Note m_map_*** are all ok and don't need to be freed
  856. * most are temp and NewRemoveObject frees m_map_gameobject_to_blender */
  857. bool KX_BlenderSceneConverter::FreeBlendFile(Main *maggie)
  858. {
  859. int maggie_index = -1;
  860. int i = 0;
  861. if (maggie == NULL)
  862. return false;
  863. // If the given library is currently in loading, we do nothing.
  864. if (m_status_map.count(maggie->name)) {
  865. BLI_mutex_lock(&m_threadinfo->m_mutex);
  866. const bool finished = m_status_map[maggie->name]->IsFinished();
  867. BLI_mutex_unlock(&m_threadinfo->m_mutex);
  868. if (!finished) {
  869. printf("Library (%s) is currently being loaded asynchronously, and cannot be freed until this process is done\n", maggie->name);
  870. return false;
  871. }
  872. }
  873. /* tag all false except the one we remove */
  874. for (vector<Main *>::iterator it = m_DynamicMaggie.begin(); !(it == m_DynamicMaggie.end()); it++) {
  875. Main *main = *it;
  876. if (main != maggie) {
  877. BKE_main_id_tag_all(main, LIB_TAG_DOIT, false);
  878. }
  879. else {
  880. maggie_index = i;
  881. }
  882. i++;
  883. }
  884. /* should never happen but just to be safe */
  885. if (maggie_index == -1)
  886. return false;
  887. m_DynamicMaggie.erase(m_DynamicMaggie.begin() + maggie_index);
  888. BKE_main_id_tag_all(maggie, LIB_TAG_DOIT, true);
  889. /* free all tagged objects */
  890. KX_SceneList *scenes = m_ketsjiEngine->CurrentScenes();
  891. int numScenes = scenes->size();
  892. for (int scene_idx = 0; scene_idx < numScenes; scene_idx++) {
  893. KX_Scene *scene = scenes->at(scene_idx);
  894. if (IS_TAGGED(scene->GetBlenderScene())) {
  895. m_ketsjiEngine->RemoveScene(scene->GetName());
  896. m_mat_cache.erase(scene);
  897. m_polymat_cache.erase(scene);
  898. scene_idx--;
  899. numScenes--;
  900. }
  901. else {
  902. /* in case the mesh might be refered to later */
  903. {
  904. CTR_Map<STR_HashedString, void *> &mapStringToMeshes = scene->GetLogicManager()->GetMeshMap();
  905. for (int i = 0; i < mapStringToMeshes.size(); i++) {
  906. RAS_MeshObject *meshobj = (RAS_MeshObject *) *mapStringToMeshes.at(i);
  907. if (meshobj && IS_TAGGED(meshobj->GetMesh())) {
  908. STR_HashedString mn = meshobj->GetName();
  909. mapStringToMeshes.remove(mn);
  910. m_map_mesh_to_gamemesh.remove(CHashedPtr(meshobj->GetMesh()));
  911. i--;
  912. }
  913. }
  914. }
  915. /* Now unregister actions */
  916. {
  917. CTR_Map<STR_HashedString, void *> &mapStringToActions = scene->GetLogicManager()->GetActionMap();
  918. for (int i = 0; i < mapStringToActions.size(); i++) {
  919. ID *action = (ID*) *mapStringToActions.at(i);
  920. if (IS_TAGGED(action)) {
  921. STR_HashedString an = action->name + 2;
  922. mapStringToActions.remove(an);
  923. m_map_blender_to_gameAdtList.remove(CHashedPtr(action));
  924. i--;
  925. }
  926. }
  927. }
  928. //scene->FreeTagged(); /* removed tagged objects and meshes*/
  929. CListValue *obj_lists[] = {scene->GetObjectList(), scene->GetInactiveList(), NULL};
  930. for (int ob_ls_idx = 0; obj_lists[ob_ls_idx]; ob_ls_idx++) {
  931. CListValue *obs = obj_lists[ob_ls_idx];
  932. RAS_MeshObject *mesh;
  933. for (int ob_idx = 0; ob_idx < obs->GetCount(); ob_idx++) {
  934. KX_GameObject *gameobj = (KX_GameObject*)obs->GetValue(ob_idx);
  935. if (IS_TAGGED(gameobj->GetBlenderObject())) {
  936. int size_before = obs->GetCount();
  937. /* Eventually calls RemoveNodeDestructObject
  938. * frees m_map_gameobject_to_blender from UnregisterGameObject */
  939. scene->RemoveObject(gameobj);
  940. if (size_before != obs->GetCount())
  941. ob_idx--;
  942. else {
  943. printf("ERROR COULD NOT REMOVE \"%s\"\n", gameobj->GetName().ReadPtr());
  944. }
  945. }
  946. else {
  947. gameobj->RemoveTaggedActions();
  948. /* free the mesh, we could be referecing a linked one! */
  949. int mesh_index = gameobj->GetMeshCount();
  950. while (mesh_index--) {
  951. mesh = gameobj->GetMesh(mesh_index);
  952. if (IS_TAGGED(mesh->GetMesh())) {
  953. gameobj->RemoveMeshes(); /* XXX - slack, should only remove meshes that are library items but mostly objects only have 1 mesh */
  954. break;
  955. }
  956. else {
  957. /* also free the mesh if it's using a tagged material */
  958. int mat_index = mesh->NumMaterials();
  959. while (mat_index--) {
  960. if (IS_TAGGED(mesh->GetMeshMaterial(mat_index)->m_bucket->GetPolyMaterial()->GetBlenderMaterial())) {
  961. gameobj->RemoveMeshes(); /* XXX - slack, same as above */
  962. break;
  963. }
  964. }
  965. }
  966. }
  967. /* make sure action actuators are not referencing tagged actions */
  968. for (unsigned int act_idx = 0; act_idx < gameobj->GetActuators().size(); act_idx++) {
  969. if (gameobj->GetActuators()[act_idx]->IsType(SCA_IActuator::KX_ACT_ACTION)) {
  970. BL_ActionActuator *act = (BL_ActionActuator *)gameobj->GetActuators()[act_idx];
  971. if (IS_TAGGED(act->GetAction()))
  972. act->SetAction(NULL);
  973. }
  974. }
  975. }
  976. }
  977. }
  978. }
  979. }
  980. int size;
  981. // delete the entities of this scene
  982. /* TODO - */
  983. #if 0
  984. vector<pair<KX_Scene*,KX_WorldInfo*> >::iterator worldit;
  985. size = m_worldinfos.size();
  986. for (i=0, worldit=m_worldinfos.begin(); i<size; ) {
  987. if ((*worldit).second) {
  988. delete (*worldit).second;
  989. *worldit = m_worldinfos.back();
  990. m_worldinfos.pop_back();
  991. size--;
  992. } else {
  993. i++;
  994. worldit++;
  995. }
  996. }
  997. #endif
  998. /* Worlds don't reference original blender data so we need to make a set from them */
  999. typedef std::set<KX_WorldInfo *> KX_WorldInfoSet;
  1000. KX_WorldInfoSet worldset;
  1001. for (int scene_idx = 0; scene_idx < numScenes; scene_idx++) {
  1002. KX_Scene *scene = scenes->at(scene_idx);
  1003. if (scene->GetWorldInfo())
  1004. worldset.insert(scene->GetWorldInfo());
  1005. }
  1006. vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator worldit;
  1007. size = m_worldinfos.size();
  1008. for (i = 0, worldit = m_worldinfos.begin(); i < size;) {
  1009. if (worldit->second && (worldset.count(worldit->second)) == 0) {
  1010. delete worldit->second;
  1011. *worldit = m_worldinfos.back();
  1012. m_worldinfos.pop_back();
  1013. size--;
  1014. }
  1015. else {
  1016. i++;
  1017. worldit++;
  1018. }
  1019. }
  1020. worldset.clear();
  1021. /* done freeing the worlds */
  1022. vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator polymit;
  1023. size = m_polymaterials.size();
  1024. for (i = 0, polymit = m_polymaterials.begin(); i < size; ) {
  1025. RAS_IPolyMaterial *mat = polymit->second;
  1026. Material *bmat = NULL;
  1027. KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial *>(mat);
  1028. bmat = bl_mat->GetBlenderMaterial();
  1029. if (IS_TAGGED(bmat)) {
  1030. /* only remove from bucket */
  1031. polymit->first->GetBucketManager()->RemoveMaterial(mat);
  1032. }
  1033. i++;
  1034. polymit++;
  1035. }
  1036. for (i = 0, polymit = m_polymaterials.begin(); i < size; ) {
  1037. RAS_IPolyMaterial *mat = polymit->second;
  1038. Material *bmat = NULL;
  1039. KX_BlenderMaterial *bl_mat = static_cast<KX_BlenderMaterial*>(mat);
  1040. bmat = bl_mat->GetBlenderMaterial();
  1041. if (IS_TAGGED(bmat)) {
  1042. // Remove the poly material coresponding to this Blender Material.
  1043. m_polymat_cache[polymit->first].erase(bmat);
  1044. delete polymit->second;
  1045. *polymit = m_polymaterials.back();
  1046. m_polymaterials.pop_back();
  1047. size--;
  1048. } else {
  1049. i++;
  1050. polymit++;
  1051. }
  1052. }
  1053. vector<pair<KX_Scene *, BL_Material *> >::iterator matit;
  1054. size = m_materials.size();
  1055. for (i = 0, matit = m_materials.begin(); i < size; ) {
  1056. BL_Material *mat = matit->second;
  1057. if (IS_TAGGED(mat->material)) {
  1058. // Remove the bl material coresponding to this Blender Material.
  1059. m_mat_cache[matit->first].erase(mat->material);
  1060. delete matit->second;
  1061. *matit = m_materials.back();
  1062. m_materials.pop_back();
  1063. size--;
  1064. }
  1065. else {
  1066. i++;
  1067. matit++;
  1068. }
  1069. }
  1070. vector<pair<KX_Scene *, RAS_MeshObject *> >::iterator meshit;
  1071. RAS_BucketManager::BucketList::iterator bit;
  1072. list<RAS_MeshSlot>::iterator msit;
  1073. RAS_BucketManager::BucketList buckets;
  1074. size = m_meshobjects.size();
  1075. for (i = 0, meshit = m_meshobjects.begin(); i < size;) {
  1076. RAS_MeshObject *me = meshit->second;
  1077. if (IS_TAGGED(me->GetMesh())) {
  1078. // Before deleting the mesh object, make sure the rasterizer is
  1079. // no longer referencing it.
  1080. buckets = meshit->first->GetBucketManager()->GetSolidBuckets();
  1081. for (bit = buckets.begin(); bit != buckets.end(); bit++) {
  1082. msit = (*bit)->msBegin();
  1083. while (msit != (*bit)->msEnd()) {
  1084. if (msit->m_mesh == meshit->second)
  1085. (*bit)->RemoveMesh(&(*msit++));
  1086. else
  1087. msit++;
  1088. }
  1089. }
  1090. // And now the alpha buckets
  1091. buckets = meshit->first->GetBucketManager()->GetAlphaBuckets();
  1092. for (bit = buckets.begin(); bit != buckets.end(); bit++) {
  1093. msit = (*bit)->msBegin();
  1094. while (msit != (*bit)->msEnd()) {
  1095. if (msit->m_mesh == meshit->second)
  1096. (*bit)->RemoveMesh(&(*msit++));
  1097. else
  1098. msit++;
  1099. }
  1100. }
  1101. // Now it should be safe to delete
  1102. delete meshit->second;
  1103. *meshit = m_meshobjects.back();
  1104. m_meshobjects.pop_back();
  1105. size--;
  1106. }
  1107. else {
  1108. i++;
  1109. meshit++;
  1110. }
  1111. }
  1112. #ifdef WITH_PYTHON
  1113. /* make sure this maggie is removed from the import list if it's there
  1114. * (this operation is safe if it isn't in the list) */
  1115. removeImportMain(maggie);
  1116. #endif
  1117. delete m_status_map[maggie->name];
  1118. m_status_map.erase(maggie->name);
  1119. BKE_main_free(maggie);
  1120. return true;
  1121. }
  1122. bool KX_BlenderSceneConverter::FreeBlendFile(const char *path)
  1123. {
  1124. return FreeBlendFile(GetMainDynamicPath(path));
  1125. }
  1126. bool KX_BlenderSceneConverter::MergeScene(KX_Scene *to, KX_Scene *from)
  1127. {
  1128. {
  1129. vector<pair<KX_Scene *, KX_WorldInfo *> >::iterator itp = m_worldinfos.begin();
  1130. while (itp != m_worldinfos.end()) {
  1131. if (itp->first == from)
  1132. itp->first = to;
  1133. itp++;
  1134. }
  1135. }
  1136. {
  1137. vector<pair<KX_Scene *, RAS_IPolyMaterial *> >::iterator itp = m_polymaterials.begin();
  1138. while (itp != m_polymaterials.end()) {
  1139. if (itp->first == from) {
  1140. itp->first = to;
  1141. /* also switch internal data */
  1142. RAS_IPolyMaterial *mat = itp->second;
  1143. mat->Replace_IScene(to);
  1144. }
  1145. itp++;
  1146. }
  1147. }
  1148. {
  1149. vector<pair<KX_Scene *, RAS_MeshObject *> >::iterator itp = m_meshobjects.begin();
  1150. while (itp != m_meshobjects.end()) {
  1151. if (itp->first == from)
  1152. itp->first = to;
  1153. itp++;
  1154. }
  1155. }
  1156. {
  1157. vector<pair<KX_Scene *, BL_Material *> >::iterator itp = m_materials.begin();
  1158. while (itp != m_materials.end()) {
  1159. if (itp->first == from)
  1160. itp->first = to;
  1161. itp++;
  1162. }
  1163. }
  1164. MaterialCache::iterator matcacheit = m_mat_cache.find(from);
  1165. if (matcacheit != m_mat_cache.end()) {
  1166. // Merge cached BL_Material map.
  1167. m_mat_cache[to].insert(matcacheit->second.begin(), matcacheit->second.end());
  1168. m_mat_cache.erase(matcacheit);
  1169. }
  1170. PolyMaterialCache::iterator polymatcacheit = m_polymat_cache.find(from);
  1171. if (polymatcacheit != m_polymat_cache.end()) {
  1172. // Merge cached RAS_IPolyMaterial map.
  1173. m_polymat_cache[to].insert(polymatcacheit->second.begin(), polymatcacheit->second.end());
  1174. m_polymat_cache.erase(polymatcacheit);
  1175. }
  1176. return true;
  1177. }
  1178. /* This function merges a mesh from the current scene into another main
  1179. * it does not convert */
  1180. RAS_MeshObject *KX_BlenderSceneConverter::ConvertMeshSpecial(KX_Scene *kx_scene, Main *maggie, const char *name)
  1181. {
  1182. /* Find a mesh in the current main */
  1183. ID *me= static_cast<ID *>(BLI_findstring(&m_maggie->mesh, name, offsetof(ID, name) + 2));
  1184. Main *from_maggie = m_maggie;
  1185. if (me == NULL) {
  1186. // The mesh wasn't in the current main, try any dynamic (i.e., LibLoaded) ones
  1187. vector<Main *>::iterator it;
  1188. for (it = GetMainDynamic().begin(); it != GetMainDynamic().end(); it++) {
  1189. me = static_cast<ID *>(BLI_findstring(&(*it)->mesh, name, offsetof(ID, name) + 2));
  1190. from_maggie = *it;
  1191. if (me)
  1192. break;
  1193. }
  1194. }
  1195. if (me == NULL) {
  1196. printf("Could not be found \"%s\"\n", name);
  1197. return NULL;
  1198. }
  1199. /* Watch this!, if its used in the original scene can cause big troubles */
  1200. if (me->us > 0) {
  1201. #ifdef DEBUG
  1202. printf("Mesh has a user \"%s\"\n", name);
  1203. #endif
  1204. me = (ID*)BKE_mesh_copy(from_maggie, (Mesh*)me);
  1205. id_us_min(me);
  1206. }
  1207. BLI_remlink(&from_maggie->mesh, me); /* even if we made the copy it needs to be removed */
  1208. BLI_addtail(&maggie->mesh, me);
  1209. /* Must copy the materials this uses else we cant free them */
  1210. {
  1211. Mesh *mesh = (Mesh *)me;
  1212. /* ensure all materials are tagged */
  1213. for (int i = 0; i < mesh->totcol; i++) {
  1214. if (mesh->mat[i])
  1215. mesh->mat[i]->id.tag &= ~LIB_TAG_DOIT;
  1216. }
  1217. for (int i = 0; i < mesh->totcol; i++) {
  1218. Material *mat_old = mesh->mat[i];
  1219. /* if its tagged its a replaced material */
  1220. if (mat_old && (mat_old->id.tag & LIB_TAG_DOIT) == 0) {
  1221. Material *mat_old = mesh->mat[i];
  1222. Material *mat_new = BKE_material_copy(from_maggie, mat_old);
  1223. mat_new->id.tag |= LIB_TAG_DOIT;
  1224. id_us_min(&mat_old->id);
  1225. BLI_remlink(&from_maggie->mat, mat_new); // BKE_material_copy uses G.main, and there is no BKE_material_copy_ex
  1226. BLI_addtail(&maggie->mat, mat_new);
  1227. mesh->mat[i] = mat_new;
  1228. /* the same material may be used twice */
  1229. for (int j = i + 1; j < mesh->totcol; j++) {
  1230. if (mesh->mat[j] == mat_old) {
  1231. mesh->mat[j] = mat_new;
  1232. id_us_plus(&mat_new->id);
  1233. id_us_min(&mat_old->id);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. }
  1239. m_currentScene = kx_scene; // This needs to be set in case we LibLoaded earlier
  1240. RAS_MeshObject *meshobj = BL_ConvertMesh((Mesh *)me, NULL, kx_scene, this, false);
  1241. kx_scene->GetLogicManager()->RegisterMeshName(meshobj->GetName(),meshobj);
  1242. m_map_mesh_to_gamemesh.clear(); /* This is at runtime so no need to keep this, BL_ConvertMesh adds */
  1243. return meshobj;
  1244. }