EditorImport.as 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. // Urho3D editor import functions
  2. String importOptions = "-t";
  3. class ParentAssignment
  4. {
  5. uint childID;
  6. String parentName;
  7. }
  8. class AssetMapping
  9. {
  10. String assetName;
  11. String fullAssetName;
  12. }
  13. Array<AssetMapping> assetMappings;
  14. String assetImporterPath;
  15. int ExecuteAssetImporter(Array<String>@ args)
  16. {
  17. if (assetImporterPath.empty)
  18. {
  19. String exeSuffix = "";
  20. if (GetPlatform() == "Windows")
  21. exeSuffix = ".exe";
  22. // Try both with and without the tool directory; a packaged build may not have the tool directory
  23. assetImporterPath = fileSystem.programDir + "tool/AssetImporter" + exeSuffix;
  24. if (!fileSystem.FileExists(assetImporterPath))
  25. assetImporterPath = fileSystem.programDir + "AssetImporter" + exeSuffix;
  26. }
  27. return fileSystem.SystemRun(assetImporterPath, args);
  28. }
  29. void ImportModel(const String&in fileName)
  30. {
  31. if (fileName.empty)
  32. return;
  33. ui.cursor.shape = CS_BUSY;
  34. String modelName = "Models/" + GetFileName(fileName) + ".mdl";
  35. String outFileName = sceneResourcePath + modelName;
  36. fileSystem.CreateDir(sceneResourcePath + "Models");
  37. Array<String> args;
  38. args.Push("model");
  39. args.Push("\"" + fileName + "\"");
  40. args.Push("\"" + outFileName + "\"");
  41. args.Push("-p \"" + sceneResourcePath + "\"");
  42. Array<String> options = importOptions.Trimmed().Split(' ');
  43. for (uint i = 0; i < options.length; ++i)
  44. args.Push(options[i]);
  45. // If material lists are to be applied, make sure the option to create them exists
  46. if (applyMaterialList)
  47. args.Push("-l");
  48. if (ExecuteAssetImporter(args) == 0)
  49. {
  50. Node@ newNode = editorScene.CreateChild(GetFileName(fileName));
  51. StaticModel@ newModel = newNode.CreateComponent("StaticModel");
  52. newNode.position = GetNewNodePosition();
  53. newModel.model = cache.GetResource("Model", modelName);
  54. newModel.ApplyMaterialList(); // Setup default materials if possible
  55. // Create an undo action for the create
  56. CreateNodeAction action;
  57. action.Define(newNode);
  58. SaveEditAction(action);
  59. SetSceneModified();
  60. FocusNode(newNode);
  61. }
  62. else
  63. log.Error("Failed to execute AssetImporter to import model");
  64. }
  65. void ImportScene(const String&in fileName)
  66. {
  67. if (fileName.empty)
  68. return;
  69. ui.cursor.shape = CS_BUSY;
  70. // Handle Tundra scene files here in code, otherwise via AssetImporter
  71. if (GetExtension(fileName) == ".txml")
  72. ImportTundraScene(fileName);
  73. else
  74. {
  75. // Export scene to a temp file, then load and delete it if successful
  76. String tempSceneName = sceneResourcePath + TEMP_SCENE_NAME;
  77. Array<String> args;
  78. args.Push("scene");
  79. args.Push("\"" + fileName + "\"");
  80. args.Push("\"" + tempSceneName + "\"");
  81. args.Push("-p \"" + sceneResourcePath + "\"");
  82. Array<String> options = importOptions.Trimmed().Split(' ');
  83. for (uint i = 0; i < options.length; ++i)
  84. args.Push(options[i]);
  85. if (applyMaterialList)
  86. args.Push("-l");
  87. if (ExecuteAssetImporter(args) == 0)
  88. {
  89. skipMruScene = true; // set to avoid adding tempscene to mru
  90. LoadScene(tempSceneName);
  91. fileSystem.Delete(tempSceneName);
  92. UpdateWindowTitle();
  93. }
  94. else
  95. log.Error("Failed to execute AssetImporter to import scene");
  96. }
  97. }
  98. void ImportTundraScene(const String&in fileName)
  99. {
  100. fileSystem.CreateDir(sceneResourcePath + "Materials");
  101. fileSystem.CreateDir(sceneResourcePath + "Models");
  102. fileSystem.CreateDir(sceneResourcePath + "Textures");
  103. XMLFile source;
  104. source.Load(File(fileName, FILE_READ));
  105. String filePath = GetPath(fileName);
  106. XMLElement sceneElem = source.root;
  107. XMLElement entityElem = sceneElem.GetChild("entity");
  108. Array<String> convertedMaterials;
  109. Array<String> convertedMeshes;
  110. Array<ParentAssignment> parentAssignments;
  111. // Read the scene directory structure recursively to get assetname to full assetname mappings
  112. Array<String> fileNames = fileSystem.ScanDir(filePath, "*.*", SCAN_FILES, true);
  113. for (uint i = 0; i < fileNames.length; ++i)
  114. {
  115. AssetMapping mapping;
  116. mapping.assetName = GetFileNameAndExtension(fileNames[i]);
  117. mapping.fullAssetName = fileNames[i];
  118. assetMappings.Push(mapping);
  119. }
  120. // Clear old scene, then create a zone and a directional light first
  121. ResetScene();
  122. // Set standard gravity
  123. editorScene.CreateComponent("PhysicsWorld");
  124. editorScene.physicsWorld.gravity = Vector3(0, -9.81, 0);
  125. // Create zone & global light
  126. Node@ zoneNode = editorScene.CreateChild("Zone");
  127. Zone@ zone = zoneNode.CreateComponent("Zone");
  128. zone.boundingBox = BoundingBox(-1000, 1000);
  129. zone.ambientColor = Color(0.364, 0.364, 0.364);
  130. zone.fogColor = Color(0.707792, 0.770537, 0.831373);
  131. zone.fogStart = 100.0;
  132. zone.fogEnd = 500.0;
  133. Node@ lightNode = editorScene.CreateChild("GlobalLight");
  134. Light@ light = lightNode.CreateComponent("Light");
  135. lightNode.rotation = Quaternion(60, 30, 0);
  136. light.lightType = LIGHT_DIRECTIONAL;
  137. light.color = Color(0.639, 0.639, 0.639);
  138. light.castShadows = true;
  139. light.shadowCascade = CascadeParameters(5, 15.0, 50.0, 0.0, 0.9);
  140. // Loop through scene entities
  141. while (!entityElem.isNull)
  142. {
  143. String nodeName;
  144. String meshName;
  145. String parentName;
  146. Vector3 meshPos;
  147. Vector3 meshRot;
  148. Vector3 meshScale(1, 1, 1);
  149. Vector3 pos;
  150. Vector3 rot;
  151. Vector3 scale(1, 1, 1);
  152. bool castShadows = false;
  153. float drawDistance = 0;
  154. Array<String> materialNames;
  155. int shapeType = -1;
  156. float mass = 0.0f;
  157. Vector3 bodySize;
  158. bool trigger = false;
  159. bool kinematic = false;
  160. uint collisionLayer;
  161. uint collisionMask;
  162. String collisionMeshName;
  163. XMLElement compElem = entityElem.GetChild("component");
  164. while (!compElem.isNull)
  165. {
  166. String compType = compElem.GetAttribute("type");
  167. if (compType == "EC_Mesh" || compType == "Mesh")
  168. {
  169. Array<String> coords = GetComponentAttribute(compElem, "Transform").Split(',');
  170. meshPos = GetVector3FromStrings(coords, 0);
  171. meshPos.z = -meshPos.z; // Convert to lefthanded
  172. meshRot = GetVector3FromStrings(coords, 3);
  173. meshScale = GetVector3FromStrings(coords, 6);
  174. meshName = GetComponentAttribute(compElem, "Mesh ref");
  175. castShadows = GetComponentAttribute(compElem, "Cast shadows").ToBool();
  176. drawDistance = GetComponentAttribute(compElem, "Draw distance").ToFloat();
  177. materialNames = GetComponentAttribute(compElem, "Mesh materials").Split(';');
  178. ProcessRef(meshName);
  179. for (uint i = 0; i < materialNames.length; ++i)
  180. ProcessRef(materialNames[i]);
  181. }
  182. if (compType == "EC_Name" || compType == "Name")
  183. nodeName = GetComponentAttribute(compElem, "name");
  184. if (compType == "EC_Placeable" || compType == "Placeable")
  185. {
  186. Array<String> coords = GetComponentAttribute(compElem, "Transform").Split(',');
  187. pos = GetVector3FromStrings(coords, 0);
  188. pos.z = -pos.z; // Convert to lefthanded
  189. rot = GetVector3FromStrings(coords, 3);
  190. scale = GetVector3FromStrings(coords, 6);
  191. parentName = GetComponentAttribute(compElem, "Parent entity ref");
  192. }
  193. if (compType == "EC_RigidBody" || compType == "RigidBody")
  194. {
  195. shapeType = GetComponentAttribute(compElem, "Shape type").ToInt();
  196. mass = GetComponentAttribute(compElem, "Mass").ToFloat();
  197. bodySize = GetComponentAttribute(compElem, "Size").ToVector3();
  198. collisionMeshName = GetComponentAttribute(compElem, "Collision mesh ref");
  199. trigger = GetComponentAttribute(compElem, "Phantom").ToBool();
  200. kinematic = GetComponentAttribute(compElem, "Kinematic").ToBool();
  201. collisionLayer = GetComponentAttribute(compElem, "Collision Layer").ToInt();
  202. collisionMask = GetComponentAttribute(compElem, "Collision Mask").ToInt();
  203. ProcessRef(collisionMeshName);
  204. }
  205. compElem = compElem.GetNext("component");
  206. }
  207. // If collision mesh not specified for the rigid body, assume same as the visible mesh
  208. if ((shapeType == 4 || shapeType == 6) && collisionMeshName.Trimmed().empty)
  209. collisionMeshName = meshName;
  210. if (!meshName.empty || shapeType >= 0)
  211. {
  212. for (uint i = 0; i < materialNames.length; ++i)
  213. ConvertMaterial(materialNames[i], filePath, convertedMaterials);
  214. ConvertModel(meshName, filePath, convertedMeshes);
  215. ConvertModel(collisionMeshName, filePath, convertedMeshes);
  216. Node@ newNode = editorScene.CreateChild(nodeName);
  217. // Calculate final transform in an Ogre-like fashion
  218. Quaternion quat = GetTransformQuaternion(rot);
  219. Quaternion meshQuat = GetTransformQuaternion(meshRot);
  220. Quaternion finalQuat = quat * meshQuat;
  221. Vector3 finalScale = scale * meshScale;
  222. Vector3 finalPos = pos + quat * (scale * meshPos);
  223. newNode.SetTransform(finalPos, finalQuat, finalScale);
  224. // Create model
  225. if (!meshName.empty)
  226. {
  227. StaticModel@ model = newNode.CreateComponent("StaticModel");
  228. model.model = cache.GetResource("Model", GetOutModelName(meshName));
  229. model.drawDistance = drawDistance;
  230. model.castShadows = castShadows;
  231. // Set default grey material to match Tundra defaults
  232. model.material = cache.GetResource("Material", "Materials/DefaultGrey.xml");
  233. // Then try to assign the actual materials
  234. for (uint i = 0; i < materialNames.length; ++i)
  235. {
  236. Material@ mat = cache.GetResource("Material", GetOutMaterialName(materialNames[i]));
  237. if (mat !is null)
  238. model.materials[i] = mat;
  239. }
  240. }
  241. // Create rigidbody & collision shape
  242. if (shapeType >= 0)
  243. {
  244. RigidBody@ body = newNode.CreateComponent("RigidBody");
  245. // If mesh has scaling, undo it for the collision shape
  246. bodySize.x /= meshScale.x;
  247. bodySize.y /= meshScale.y;
  248. bodySize.z /= meshScale.z;
  249. CollisionShape@ shape = newNode.CreateComponent("CollisionShape");
  250. switch (shapeType)
  251. {
  252. case 0:
  253. shape.SetBox(bodySize);
  254. break;
  255. case 1:
  256. shape.SetSphere(bodySize.x);
  257. break;
  258. case 2:
  259. shape.SetCylinder(bodySize.x, bodySize.y);
  260. break;
  261. case 3:
  262. shape.SetCapsule(bodySize.x, bodySize.y);
  263. break;
  264. case 4:
  265. shape.SetTriangleMesh(cache.GetResource("Model", GetOutModelName(collisionMeshName)), 0, bodySize);
  266. break;
  267. case 6:
  268. shape.SetConvexHull(cache.GetResource("Model", GetOutModelName(collisionMeshName)), 0, bodySize);
  269. break;
  270. }
  271. body.collisionLayer = collisionLayer;
  272. body.collisionMask = collisionMask;
  273. body.trigger = trigger;
  274. body.mass = mass;
  275. }
  276. // Store pending parent assignment if necessary
  277. if (!parentName.empty)
  278. {
  279. ParentAssignment assignment;
  280. assignment.childID = newNode.id;
  281. assignment.parentName = parentName;
  282. parentAssignments.Push(assignment);
  283. }
  284. }
  285. entityElem = entityElem.GetNext("entity");
  286. }
  287. // Process any parent assignments now
  288. for (uint i = 0; i < parentAssignments.length; ++i)
  289. {
  290. Node@ childNode = editorScene.GetNode(parentAssignments[i].childID);
  291. Node@ parentNode = editorScene.GetChild(parentAssignments[i].parentName, true);
  292. if (childNode !is null && parentNode !is null)
  293. childNode.parent = parentNode;
  294. }
  295. UpdateHierarchyItem(editorScene, true);
  296. UpdateWindowTitle();
  297. assetMappings.Clear();
  298. }
  299. String GetFullAssetName(const String& assetName)
  300. {
  301. for (uint i = 0; i < assetMappings.length; ++i)
  302. {
  303. if (assetMappings[i].assetName == assetName)
  304. return assetMappings[i].fullAssetName;
  305. }
  306. return assetName;
  307. }
  308. Quaternion GetTransformQuaternion(Vector3 rotEuler)
  309. {
  310. // Convert rotation to lefthanded
  311. Quaternion rotateX(-rotEuler.x, Vector3(1, 0, 0));
  312. Quaternion rotateY(-rotEuler.y, Vector3(0, 1, 0));
  313. Quaternion rotateZ(-rotEuler.z, Vector3(0, 0, -1));
  314. return rotateZ * rotateY * rotateX;
  315. }
  316. String GetComponentAttribute(XMLElement compElem, const String&in name)
  317. {
  318. XMLElement attrElem = compElem.GetChild("attribute");
  319. while (!attrElem.isNull)
  320. {
  321. if (attrElem.GetAttribute("name") == name)
  322. return attrElem.GetAttribute("value");
  323. attrElem = attrElem.GetNext("attribute");
  324. }
  325. return "";
  326. }
  327. Vector3 GetVector3FromStrings(Array<String>@ coords, uint startIndex)
  328. {
  329. return Vector3(coords[startIndex].ToFloat(), coords[startIndex + 1].ToFloat(), coords[startIndex + 2].ToFloat());
  330. }
  331. void ProcessRef(String& ref)
  332. {
  333. if (ref.StartsWith("local://"))
  334. ref = ref.Substring(8);
  335. if (ref.StartsWith("file://"))
  336. ref = ref.Substring(7);
  337. }
  338. String GetOutModelName(const String&in ref)
  339. {
  340. return "Models/" + GetFullAssetName(ref).Replaced('/', '_').Replaced(".mesh", ".mdl");
  341. }
  342. String GetOutMaterialName(const String&in ref)
  343. {
  344. return "Materials/" + GetFullAssetName(ref).Replaced('/', '_').Replaced(".material", ".xml");
  345. }
  346. String GetOutTextureName(const String&in ref)
  347. {
  348. return "Textures/" + GetFullAssetName(ref).Replaced('/', '_');
  349. }
  350. void ConvertModel(const String&in modelName, const String&in filePath, Array<String>@ convertedModels)
  351. {
  352. if (modelName.Trimmed().empty)
  353. return;
  354. for (uint i = 0; i < convertedModels.length; ++i)
  355. {
  356. if (convertedModels[i] == modelName)
  357. return;
  358. }
  359. String meshFileName = filePath + GetFullAssetName(modelName);
  360. String xmlFileName = filePath + GetFullAssetName(modelName) + ".xml";
  361. String outFileName = sceneResourcePath + GetOutModelName(modelName);
  362. // Convert .mesh to .mesh.xml
  363. String cmdLine = "ogrexmlconverter \"" + meshFileName + "\" \"" + xmlFileName + "\"";
  364. if (!fileSystem.FileExists(xmlFileName))
  365. fileSystem.SystemCommand(cmdLine.Replaced('/', '\\'));
  366. if (!fileSystem.FileExists(outFileName))
  367. {
  368. // Convert .mesh.xml to .mdl
  369. Array<String> args;
  370. args.Push("\"" + xmlFileName + "\"");
  371. args.Push("\"" + outFileName + "\"");
  372. args.Push("-a");
  373. fileSystem.SystemRun(fileSystem.programDir + "tool/OgreImporter", args);
  374. }
  375. convertedModels.Push(modelName);
  376. }
  377. void ConvertMaterial(const String&in materialName, const String&in filePath, Array<String>@ convertedMaterials)
  378. {
  379. if (materialName.Trimmed().empty)
  380. return;
  381. for (uint i = 0; i < convertedMaterials.length; ++i)
  382. {
  383. if (convertedMaterials[i] == materialName)
  384. return;
  385. }
  386. String fileName = filePath + GetFullAssetName(materialName);
  387. String outFileName = sceneResourcePath + GetOutMaterialName(materialName);
  388. if (!fileSystem.FileExists(fileName))
  389. return;
  390. bool mask = false;
  391. bool twoSided = false;
  392. bool uvScaleSet = false;
  393. String textureName;
  394. Vector2 uvScale(1, 1);
  395. Color diffuse(1, 1, 1, 1);
  396. File file(fileName, FILE_READ);
  397. while (!file.eof)
  398. {
  399. String line = file.ReadLine().Trimmed();
  400. if (line.StartsWith("alpha_rejection") || line.StartsWith("scene_blend alpha_blend"))
  401. mask = true;
  402. if (line.StartsWith("cull_hardware none"))
  403. twoSided = true;
  404. // Todo: handle multiple textures per material
  405. if (textureName.empty && line.StartsWith("texture "))
  406. {
  407. textureName = line.Substring(8);
  408. ProcessRef(textureName);
  409. }
  410. if (!uvScaleSet && line.StartsWith("scale "))
  411. {
  412. uvScale = line.Substring(6).ToVector2();
  413. uvScaleSet = true;
  414. }
  415. if (line.StartsWith("diffuse "))
  416. diffuse = line.Substring(8).ToColor();
  417. }
  418. XMLFile outMat;
  419. XMLElement rootElem = outMat.CreateRoot("material");
  420. XMLElement techniqueElem = rootElem.CreateChild("technique");
  421. if (twoSided)
  422. {
  423. XMLElement cullElem = rootElem.CreateChild("cull");
  424. cullElem.SetAttribute("value", "none");
  425. XMLElement shadowCullElem = rootElem.CreateChild("shadowcull");
  426. shadowCullElem.SetAttribute("value", "none");
  427. }
  428. if (!textureName.empty)
  429. {
  430. techniqueElem.SetAttribute("name", mask ? "Techniques/DiffAlphaMask.xml" : "Techniques/Diff.xml");
  431. String outTextureName = GetOutTextureName(textureName);
  432. XMLElement textureElem = rootElem.CreateChild("texture");
  433. textureElem.SetAttribute("unit", "diffuse");
  434. textureElem.SetAttribute("name", outTextureName);
  435. fileSystem.Copy(filePath + GetFullAssetName(textureName), sceneResourcePath + outTextureName);
  436. }
  437. else
  438. techniqueElem.SetAttribute("name", "NoTexture.xml");
  439. if (uvScale != Vector2(1, 1))
  440. {
  441. XMLElement uScaleElem = rootElem.CreateChild("parameter");
  442. uScaleElem.SetAttribute("name", "UOffset");
  443. uScaleElem.SetVector3("value", Vector3(1 / uvScale.x, 0, 0));
  444. XMLElement vScaleElem = rootElem.CreateChild("parameter");
  445. vScaleElem.SetAttribute("name", "VOffset");
  446. vScaleElem.SetVector3("value", Vector3(0, 1 / uvScale.y, 0));
  447. }
  448. if (diffuse != Color(1, 1, 1, 1))
  449. {
  450. XMLElement diffuseElem = rootElem.CreateChild("parameter");
  451. diffuseElem.SetAttribute("name", "MatDiffColor");
  452. diffuseElem.SetColor("value", diffuse);
  453. }
  454. File outFile(outFileName, FILE_WRITE);
  455. outMat.Save(outFile);
  456. outFile.Close();
  457. convertedMaterials.Push(materialName);
  458. }