EditorImport.as 18 KB

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