EditorTemplates.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using CommonAI.Zone.Instance;
  5. using CommonAI.Zone;
  6. using CommonLang.Property;
  7. using System.Globalization;
  8. using CommonAI.Zone.Attributes;
  9. using CommonLang.Xml;
  10. using System.Xml;
  11. using CommonLang.Log;
  12. using CommonLang.IO;
  13. using CommonLang;
  14. using CommonAI.ZoneEditor;
  15. using CommonLang.IO.Attribute;
  16. using System.IO;
  17. using CommonLang.Property.Modeling;
  18. using System.Collections;
  19. using System.Reflection;
  20. using CommonLang.XCSV;
  21. using CommonLang.Concurrent;
  22. using CommonAI.Zone.Helper;
  23. using CommonAI.ZoneServer.JSGModule;
  24. using CommonLang.Vector;
  25. namespace CommonAI.Zone.ZoneEditor
  26. {
  27. public class EditorTemplatesData
  28. {
  29. readonly public TerrainDefinitionMap TerrainDefinitions;
  30. readonly public UnitActionDefinitionMap UnitActionDefinitions;
  31. readonly public HashMap<int, UnitInfo> Units = new HashMap<int, UnitInfo>();
  32. readonly public HashMap<int, SkillTemplate> Skills = new HashMap<int, SkillTemplate>();
  33. readonly public HashMap<int, SpellTemplate> Spells = new HashMap<int, SpellTemplate>();
  34. readonly public HashMap<int, BuffTemplate> Buffs = new HashMap<int, BuffTemplate>();
  35. readonly public HashMap<int, ItemTemplate> Items = new HashMap<int, ItemTemplate>();
  36. readonly public HashMap<int, UnitTriggerTemplate> UnitTriggers = new HashMap<int, UnitTriggerTemplate>();
  37. readonly public HashMap<int, UnitEventTemplate> UnitEvents = new HashMap<int, UnitEventTemplate>();
  38. readonly public HashMap<int, SceneData> Scenes = new HashMap<int, SceneData>();
  39. public EditorTemplatesData(
  40. TerrainDefinitionMap mapDefines,
  41. UnitActionDefinitionMap unitActionDefines,
  42. List<UnitInfo> units,
  43. List<SkillTemplate> skills,
  44. List<SpellTemplate> spells,
  45. List<BuffTemplate> buffs,
  46. List<ItemTemplate> items,
  47. List<UnitTriggerTemplate> triggers,
  48. List<UnitEventTemplate> events,
  49. List<SceneData> scenes)
  50. {
  51. this.TerrainDefinitions = mapDefines;
  52. this.UnitActionDefinitions = unitActionDefines;
  53. PutAll(this.Units, units);
  54. PutAll(this.Skills, skills);
  55. PutAll(this.Spells, spells);
  56. PutAll(this.Buffs, buffs);
  57. PutAll(this.Items, items);
  58. PutAll(this.UnitTriggers, triggers);
  59. PutAll(this.UnitEvents, events);
  60. PutAll(this.Scenes, scenes);
  61. }
  62. public int FileCount
  63. {
  64. get
  65. {
  66. return
  67. this.Units.Count +
  68. this.Skills.Count +
  69. this.Spells.Count +
  70. this.Buffs.Count +
  71. this.Items.Count +
  72. this.UnitTriggers.Count +
  73. this.UnitEvents.Count +
  74. this.Scenes.Count;
  75. }
  76. }
  77. public List<ITemplateData> AllTemplates()
  78. {
  79. ArrayList ret = new ArrayList();
  80. ret.AddRange(Units.Values);
  81. ret.AddRange(Skills.Values);
  82. ret.AddRange(Spells.Values);
  83. ret.AddRange(Buffs.Values);
  84. ret.AddRange(Items.Values);
  85. ret.AddRange(UnitTriggers.Values);
  86. ret.AddRange(UnitEvents.Values);
  87. ret.AddRange(Scenes.Values);
  88. var list = new List<ITemplateData>(ret.Capacity);
  89. foreach (ITemplateData a in ret)
  90. {
  91. list.Add(a);
  92. }
  93. list.Sort(new TemplateDataComparer());
  94. return list;
  95. }
  96. public bool GetObjectByType(Type type, int templateID, out object data)
  97. {
  98. data = null;
  99. if (type.IsAssignableFrom(typeof(UnitInfo)))
  100. {
  101. data = Units[templateID];
  102. }
  103. else if (type.IsAssignableFrom(typeof(SkillTemplate)))
  104. {
  105. data = Skills[templateID];
  106. }
  107. else if (type.IsAssignableFrom(typeof(SpellTemplate)))
  108. {
  109. data = Spells[templateID];
  110. }
  111. else if (type.IsAssignableFrom(typeof(BuffTemplate)))
  112. {
  113. data = Buffs[templateID];
  114. }
  115. else if (type.IsAssignableFrom(typeof(ItemTemplate)))
  116. {
  117. data = Items[templateID];
  118. }
  119. else if (type.IsAssignableFrom(typeof(UnitTriggerTemplate)))
  120. {
  121. data = UnitTriggers[templateID];
  122. }
  123. else if (type.IsAssignableFrom(typeof(UnitEventTemplate)))
  124. {
  125. data = UnitEvents[templateID];
  126. }
  127. else if (type.IsAssignableFrom(typeof(SceneData)))
  128. {
  129. data = Scenes[templateID];
  130. }
  131. return data != null;
  132. }
  133. private static void PutAll<T>(HashMap<int, T> map, List<T> list) where T : ITemplateData
  134. {
  135. foreach (T u in list)
  136. {
  137. map[u.TemplateID] = u;
  138. }
  139. }
  140. public struct TemplateDataComparer : IComparer<ITemplateData>
  141. {
  142. public int Compare(ITemplateData ix, ITemplateData iy)
  143. {
  144. int tr = string.Compare(ix.GetType().FullName, iy.GetType().FullName);
  145. if (tr == 0)
  146. {
  147. return ix.TemplateID - iy.TemplateID;
  148. }
  149. return tr;
  150. }
  151. }
  152. }
  153. public class EditorTemplates
  154. {
  155. public static bool DEFAULT_LOAD_FROM_BIN = true;
  156. public static bool RUNTIME_IN_SERVER = true;
  157. private readonly static Logger log = LoggerFactory.GetLogger("EditorTemplates");
  158. private readonly HashMap<Type, HashMap<int, object>> loaded;
  159. private readonly HashMap<int, SceneData> scenes;
  160. private readonly HashMap<int, SceneData> mCacheScenes;
  161. private readonly string dir;
  162. private IExternalizableFactory factory;
  163. private TemplateManager templates = new TemplateManager();
  164. private bool is_client_mode;
  165. public bool IsClientData { get { return is_client_mode; } }
  166. public string DataRoot { get { return dir; } }
  167. public TemplateManager Templates { get { return templates; } }
  168. public EditorTemplatesData AllTemplatesExcludeScenes
  169. {
  170. get
  171. {
  172. return new EditorTemplatesData(
  173. templates.TerrainDefinition,
  174. templates.UnitActionDefinition,
  175. templates.getAllUnits(),
  176. templates.getAllSkills(),
  177. templates.getAllSpells(),
  178. templates.getAllBuffs(),
  179. templates.getAllItems(),
  180. templates.getAllUnitTriggers(),
  181. templates.getAllUnitEvents(),
  182. new List<SceneData>());
  183. }
  184. }
  185. public EditorTemplates(string dir, IExternalizableFactory factory, bool client_mode = false)
  186. {
  187. this.dir = dir;
  188. this.factory = factory;
  189. this.loaded = new HashMap<Type, HashMap<int, object>>();
  190. this.scenes = new HashMap<int, SceneData>();
  191. this.mCacheScenes = new HashMap<int, SceneData>();
  192. this.is_client_mode = client_mode;
  193. }
  194. /// <summary>
  195. /// 判断当前模板是否加载
  196. /// </summary>
  197. /// <param name="type"></param>
  198. /// <param name="templateID"></param>
  199. /// <param name="template"></param>
  200. /// <returns></returns>
  201. public bool IsTemplateLoaded(Type type, int templateID, out object template)
  202. {
  203. HashMap<int, object> map = loaded.Get(type);
  204. if (map != null && map.TryGetValue(templateID, out template))
  205. {
  206. return true;
  207. }
  208. template = null;
  209. return false;
  210. }
  211. /// <summary>
  212. /// 加载配置
  213. /// </summary>
  214. /// <returns></returns>
  215. public void LoadCFG()
  216. {
  217. this.templates.CFG = LoadXmlAs<Config>(dir + "/config.xml", new Config());
  218. this.templates.ExtConfig = LoadXmlAs<ICommonConfig>(dir + "/config_ext.xml", TemplateManager.Factory.CreateCommonCFG());
  219. this.templates.ExtConfig.init();
  220. }
  221. public string LoadResVersion()
  222. {
  223. string md5 = Resource.LoadAllText(dir + "/ver.md5");
  224. string[] lines = md5.Split('\n');
  225. this.templates.ResourceVersion = lines[0].Trim();
  226. return md5;
  227. }
  228. public void LoadTerrainDefinitionMap()
  229. {
  230. TerrainDefinitionMap td = LoadData<TerrainDefinitionMap>(dir + "/terrain_definition.xml");
  231. if (td != null)
  232. {
  233. this.templates.TerrainDefinition = td;
  234. }
  235. }
  236. public void LoadUnitActionDefinitionMap()
  237. {
  238. UnitActionDefinitionMap td = LoadData<UnitActionDefinitionMap>(dir + "/unit_action_definition.xml");
  239. if (td != null)
  240. {
  241. this.templates.UnitActionDefinition = td;
  242. }
  243. }
  244. public void LoadAllCFG(byte[] dat)
  245. {
  246. LoadAllCFG(new MemoryStream(dat));
  247. }
  248. public void LoadAllCFG(Stream stream)
  249. {
  250. var br = new BinaryReader(stream);
  251. // -- md5
  252. var md5 = br.ReadString();
  253. log.Debug("Eidtor Resource Version = " + md5);
  254. this.templates.ResourceVersion = md5;
  255. // -- config.xml
  256. this.templates.CFG = LoadNextXml<Config>(br, "config.xml", new Config());
  257. // -- config_ext.xml
  258. this.templates.ExtConfig = LoadNextXml<ICommonConfig>(br, "config_ext.xml", TemplateManager.Factory.CreateCommonCFG());
  259. // -- terrain_definition.xml
  260. var td = LoadNextXml<TerrainDefinitionMap>(br, "terrain_definition.xml");
  261. if (td != null)
  262. {
  263. this.templates.TerrainDefinition = td;
  264. }
  265. // -- unit_action_definition
  266. var ud = LoadNextXml<UnitActionDefinitionMap>(br, "unit_action_definition.xml");
  267. if (ud != null)
  268. {
  269. this.templates.UnitActionDefinition = ud;
  270. }
  271. }
  272. T LoadNextXml<T>(BinaryReader br, string srcFileName, T default_value = default(T))
  273. {
  274. try
  275. {
  276. var len = br.ReadInt32();
  277. var dat = br.ReadBytes(len);
  278. XmlDocument xml = XmlUtil.LoadXML(dat);
  279. return (T)XmlUtil.XmlToObject(xml);
  280. }
  281. catch (Exception err)
  282. {
  283. string msg = "LoadXml Error : " + srcFileName + "\n" + err.Message;
  284. if (log != null)
  285. {
  286. log.Error(msg, err);
  287. }
  288. else
  289. {
  290. Console.WriteLine(msg + "\r\n" + err.StackTrace);
  291. }
  292. }
  293. return default_value;
  294. }
  295. public string[] LoadList(string subdir)
  296. {
  297. string base_dir = dir + subdir;
  298. List<string> ret = new List<string>();
  299. string listtxt = Resource.LoadAllText(base_dir + "/.list");
  300. foreach (string line in listtxt.Split('\n'))
  301. {
  302. string[] lv = line.Split(';');
  303. if (lv.Length > 1)
  304. {
  305. ret.Add(base_dir + "/" + lv[lv.Length - 1].Trim() + ".xml");
  306. }
  307. }
  308. return ret.ToArray();
  309. }
  310. /// <summary>
  311. /// 重新读取所有模板
  312. /// </summary>
  313. /// <param name="client"></param>
  314. public void LoadAllTemplates(bool client = false, bool gameEdit = false)
  315. {
  316. try
  317. {
  318. LoadCFG();
  319. LoadResVersion();
  320. LoadTerrainDefinitionMap();
  321. LoadUnitActionDefinitionMap();
  322. if(!client && !gameEdit)
  323. {
  324. this.CacheAllScenes();
  325. }
  326. foreach (string file in LoadList("/units"))
  327. {
  328. LoadTemplate<UnitInfo>(file);
  329. }
  330. foreach (string file in LoadList("/skills"))
  331. {
  332. LoadTemplate<SkillTemplate>(file);
  333. }
  334. foreach (string file in LoadList("/spells"))
  335. {
  336. LoadTemplate<SpellTemplate>(file);
  337. }
  338. foreach (string file in LoadList("/buffs"))
  339. {
  340. LoadTemplate<BuffTemplate>(file);
  341. }
  342. foreach (string file in LoadList("/items"))
  343. {
  344. LoadTemplate<ItemTemplate>(file);
  345. }
  346. if (!client)
  347. {
  348. foreach (string file in LoadList("/unit_triggers"))
  349. {
  350. LoadTemplate<UnitTriggerTemplate>(file);
  351. }
  352. foreach (string file in LoadList("/unit_events"))
  353. {
  354. LoadTemplate<UnitEventTemplate>(file);
  355. }
  356. }
  357. if (TemplateManager.Formula != null)
  358. {
  359. TemplateManager.Formula.InitPluginsData(this);
  360. }
  361. int sncount = templates.RehashAll();
  362. log.Info("RehashAll : " + sncount);
  363. }
  364. catch (Exception err)
  365. {
  366. log.Error(err.Message + "\n" + err.StackTrace);
  367. throw new Exception(err.Message + "\n" + err.StackTrace);
  368. }
  369. }
  370. private object TryLoad(int templateID, Type templateType)
  371. {
  372. if (templateID == 0)
  373. {
  374. return null;
  375. }
  376. object template = null;
  377. if (!IsTemplateLoaded(templateType, templateID, out template))
  378. {
  379. if (templateType.Equals(typeof(UnitInfo)))
  380. {
  381. template = LoadTemplate<UnitInfo>(dir + "/units/" + templateID + ".xml");
  382. }
  383. else if (templateType.Equals(typeof(SkillTemplate)))
  384. {
  385. template = LoadTemplate<SkillTemplate>(dir + "/skills/" + templateID + ".xml");
  386. }
  387. else if (templateType.Equals(typeof(SpellTemplate)))
  388. {
  389. template = LoadTemplate<SpellTemplate>(dir + "/spells/" + templateID + ".xml");
  390. }
  391. else if (templateType.Equals(typeof(BuffTemplate)))
  392. {
  393. template = LoadTemplate<BuffTemplate>(dir + "/buffs/" + templateID + ".xml");
  394. }
  395. else if (templateType.Equals(typeof(ItemTemplate)))
  396. {
  397. template = LoadTemplate<ItemTemplate>(dir + "/items/" + templateID + ".xml");
  398. }
  399. else if (templateType.Equals(typeof(UnitTriggerTemplate)))
  400. {
  401. template = LoadTemplate<UnitTriggerTemplate>(dir + "/unit_triggers/" + templateID + ".xml");
  402. }
  403. else if (templateType.Equals(typeof(UnitEventTemplate)))
  404. {
  405. template = LoadTemplate<UnitEventTemplate>(dir + "/unit_events/" + templateID + ".xml");
  406. }
  407. }
  408. return template;
  409. }
  410. public T LoadTemplate<T>(byte[] binDat) where T : class, ITemplateData
  411. {
  412. T info = LoadDataFromBin<T>(binDat, factory);
  413. if (info != null)
  414. {
  415. TryAddTemplate(info);
  416. }
  417. return info;
  418. }
  419. public T LoadTemplate<T>(Stream stream) where T : class, ITemplateData
  420. {
  421. T info = LoadDataFromBin<T>(stream, factory);
  422. if (info != null)
  423. {
  424. TryAddTemplate(info);
  425. }
  426. return info;
  427. }
  428. public T LoadTemplate<T>(string file) where T : class, ITemplateData
  429. {
  430. try
  431. {
  432. T info = LoadData<T>(file);
  433. if (info != null)
  434. {
  435. TryAddTemplate(info);
  436. return info;
  437. }
  438. else
  439. {
  440. log.Info("LoadTemplate Error : " + file);
  441. }
  442. }
  443. catch (Exception err)
  444. {
  445. throw new Exception("LoadTemplate : " + file + "\n" + err.Message, err);
  446. }
  447. return null;
  448. }
  449. void TryAddTemplate(ITemplateData info)
  450. {
  451. if (info is UnitInfo)
  452. {
  453. templates.addUnit(info as UnitInfo);
  454. }
  455. else if (info is SkillTemplate)
  456. {
  457. templates.addSkill(info as SkillTemplate);
  458. }
  459. else if (info is SpellTemplate)
  460. {
  461. templates.addSpell(info as SpellTemplate);
  462. }
  463. else if (info is BuffTemplate)
  464. {
  465. templates.addBuff(info as BuffTemplate);
  466. }
  467. else if (info is ItemTemplate)
  468. {
  469. templates.addItem(info as ItemTemplate);
  470. }
  471. else if (info is UnitTriggerTemplate)
  472. {
  473. templates.addUnitTrigger(info as UnitTriggerTemplate);
  474. }
  475. else if (info is UnitEventTemplate)
  476. {
  477. templates.addUnitEvent(info as UnitEventTemplate);
  478. }
  479. //log.Debug("LoadTemplate : " + info.GetType() + " : " + info);
  480. HashMap<int, object> map = loaded.Get(info.GetType());
  481. if (map == null)
  482. {
  483. map = new HashMap<int, object>();
  484. loaded.Put(info.GetType(), map);
  485. }
  486. map.Put((info as ITemplateData).TemplateID, info);
  487. }
  488. public ISceneDataLoader sceneDataLoader
  489. {
  490. get;
  491. private set;
  492. }
  493. public void SetSceneDataLoader(ISceneDataLoader sdl)
  494. {
  495. this.sceneDataLoader = sdl;
  496. }
  497. /// <summary>
  498. /// 根据ID加载场景
  499. /// </summary>
  500. /// <param name="id"></param>
  501. /// <param name="cache">是否缓存起来(占用内存,一般服务端用)</param>
  502. /// <param name="client_data">是否是客户端使用</param>
  503. /// <param name="clone">是否克隆(仅cache)</param>
  504. /// <returns></returns>
  505. public SceneData LoadScene(int id, bool cache = true, bool client_data = false, bool clone = true)
  506. {
  507. if (client_data)
  508. {
  509. cache = false;
  510. }
  511. SceneData scene = null;
  512. if (cache)
  513. {
  514. scene = scenes.Get(id);
  515. }
  516. if (scene == null && sceneDataLoader != null)
  517. {
  518. scene = sceneDataLoader.Load(id, client_data , factory);
  519. }
  520. if (scene == null)
  521. {
  522. scene = LoadScene(dir + "/scenes/" + id + ".xml", cache, client_data);
  523. }
  524. if (scene != null)
  525. {
  526. if (cache && clone)
  527. {
  528. scene = IOUtil.CloneIExternalizable<SceneData>(factory, scene);
  529. }
  530. else if (client_data)
  531. {
  532. int sncount = templates.RehashScene(scene.GetSerialDatas());
  533. log.Info("RehashScene : " + sncount);
  534. }
  535. }
  536. return scene;
  537. }
  538. /** 根据ID加载场景 */
  539. public SceneData LoadScene_Server(int id, bool cache = true, bool clone = true)
  540. {
  541. SceneData scene = this.mCacheScenes.Get(id);
  542. if (scene == null)
  543. {
  544. scene = this.LoadScene(id, cache, false, clone);
  545. }
  546. return scene;
  547. }
  548. public SceneData CacheScene_Server(int sceneID)
  549. {
  550. SceneData scene = scenes.Get(sceneID);
  551. if (scene == null && sceneDataLoader != null)
  552. {
  553. scene = sceneDataLoader.Load(sceneID, false, factory);
  554. }
  555. if (scene == null)
  556. {
  557. scene = LoadScene(dir + "/scenes/" + sceneID + ".xml", true, false);
  558. }
  559. if (scene != null)
  560. {
  561. scene = IOUtil.CloneIExternalizable<SceneData>(factory, scene);
  562. }
  563. if(scene == null)
  564. {
  565. log.Error("场景数据不存在:" + sceneID);
  566. }
  567. else if (scene.ZoneData.TotalHeight >= 255 || scene.ZoneData.TotalWidth >= 255)
  568. {
  569. log.Error("场景设置过大,请设置成255*255之内:" + sceneID);
  570. }
  571. return scene;
  572. }
  573. /// <summary>
  574. /// 缓存所有场景数据,一般服务器用。消耗内存较大
  575. /// </summary>
  576. public void CacheAllScenes()
  577. {
  578. // foreach (int scene_id in ListScenes())
  579. // {
  580. // SceneData sceneTemp = this.CacheScene_Server(scene_id);
  581. // if(sceneTemp == null)
  582. // {
  583. // log.Error("缓存场景异常:" + scene_id);
  584. // continue;
  585. // }
  586. // this.mCacheScenes.Put(scene_id, sceneTemp);
  587. //}
  588. //List<SceneData> ret = new List<SceneData>(scenes.Values);
  589. //int sncount = templates.RehashAllScene(ret);
  590. //log.Info("RehashAllScene : " + sncount);
  591. }
  592. //检测场景单位位置合法性. 只允许内部手动调用查看结果,然后关闭
  593. public void CheckScenePosInfo()
  594. {
  595. HashMap < int, UnitInfo > unitsTemp = this.Templates.getUnits();
  596. HashMap<int, UnitInfo> allUnits = new HashMap<int, UnitInfo>();
  597. allUnits.PutAll(unitsTemp);
  598. unitsTemp.Clear();
  599. foreach (SceneData sceneData in mCacheScenes.Values)
  600. {
  601. log.Error("---------------开始检测场景位置信息:" + sceneData.TemplateID + "---------------");
  602. InstanceZone zoneTemp = TemplateManager.Factory.CreateEditorScene(Templates, null, sceneData, null, "1000");
  603. foreach(UnitData unitTemp in sceneData.Units)
  604. {
  605. UnitInfo unitInfo = allUnits.Get(unitTemp.UnitTemplateID);
  606. if(unitInfo == null)
  607. {
  608. log.Warn("场景单位不存在:" + unitTemp.UnitTemplateID);
  609. continue;
  610. }
  611. else if(unitInfo.UType == UnitInfo.UnitType.TYPE_NPC)
  612. {
  613. continue;
  614. }
  615. //if(unitTemp.Name.Equals("小偷"))
  616. //{
  617. // //int i = 0;
  618. //}
  619. if (zoneTemp.TryTouchMap(null, unitTemp.X, unitTemp.Y))
  620. {
  621. log.Error("--场景单位位置非法:" + unitTemp.Name + ", X: " + unitTemp.X + ", Y: " + unitTemp.Y);
  622. }
  623. }
  624. foreach (RegionData regionTemp in sceneData.Regions)
  625. {
  626. bool hasCheckAbility = false;
  627. foreach(RegionAbilityData abilityTemp in regionTemp.Abilities)
  628. {
  629. if(abilityTemp is PlayerStartAbilityData || abilityTemp is SpawnItemAbilityData
  630. || abilityTemp is SpawnUnitAbilityData || abilityTemp is XmdsRebirthAbility)
  631. {
  632. hasCheckAbility = true;
  633. break;
  634. }
  635. }
  636. if (!hasCheckAbility)
  637. {
  638. continue;
  639. }
  640. if(regionTemp.RegionType == RegionData.Shape.STRIP)
  641. {
  642. log.Info("跳过异性区域判定: " + regionTemp.Name);
  643. continue;
  644. }
  645. List<Vector2> checkPos = new List<Vector2>();
  646. if (regionTemp.RegionType == RegionData.Shape.ROUND)
  647. {
  648. checkPos.Add(new Vector2(regionTemp.X - regionTemp.W / 2, regionTemp.Y));
  649. checkPos.Add(new Vector2(regionTemp.X, regionTemp.Y + regionTemp.W / 2));
  650. checkPos.Add(new Vector2(regionTemp.X, regionTemp.Y + regionTemp.W / 2));
  651. checkPos.Add(new Vector2(regionTemp.X - regionTemp.W / 2, regionTemp.Y));
  652. }
  653. else
  654. {
  655. checkPos.Add(new Vector2(regionTemp.X - regionTemp.W / 2, regionTemp.Y - regionTemp.H / 2));
  656. checkPos.Add(new Vector2(regionTemp.X - regionTemp.W / 2, regionTemp.Y + regionTemp.H / 2));
  657. checkPos.Add(new Vector2(regionTemp.X + regionTemp.W / 2, regionTemp.Y - regionTemp.H / 2));
  658. checkPos.Add(new Vector2(regionTemp.X + regionTemp.W / 2, regionTemp.Y + regionTemp.H / 2));
  659. }
  660. foreach (Vector2 posTemp in checkPos)
  661. {
  662. if (zoneTemp.TryTouchMap(null, posTemp.X, posTemp.Y))
  663. {
  664. log.Error("--场景区域位置非法:" + regionTemp.Name + ", X: " + regionTemp.X + ", Y: " + regionTemp.Y);
  665. break;
  666. }
  667. }
  668. }
  669. zoneTemp.Dispose();
  670. }
  671. System.Console.WriteLine("全部场景检测完毕!");
  672. Console.ReadLine();
  673. }
  674. /// <summary>
  675. /// 是否缓存场景
  676. /// </summary>
  677. /// <param name="id"></param>
  678. /// <returns></returns>
  679. public bool ExistSceneInCache(int id)
  680. {
  681. return scenes.ContainsKey(id);
  682. }
  683. public SceneData GetSceneInCache(int id)
  684. {
  685. return scenes.Get(id);
  686. }
  687. public List<int> ListScenes()
  688. {
  689. List<int> ret = new List<int>();
  690. foreach (string file in LoadList("/scenes"))
  691. {
  692. try
  693. {
  694. string sub = file.Replace('\\', '/');
  695. int begin = sub.LastIndexOf('/') + 1;
  696. int end = sub.LastIndexOf('.');
  697. sub = sub.Substring(begin, end - begin);
  698. ret.Add(int.Parse(sub));
  699. }
  700. catch (Exception err)
  701. {
  702. log.Error(err.Message, err);
  703. }
  704. }
  705. return ret;
  706. }
  707. public List<SceneData> LoadAllScenes(bool cache = true, bool client_data = false, bool clone = false)
  708. {
  709. var ret = new List<SceneData>(scenes.Count);
  710. foreach (var id in ListScenes())
  711. {
  712. ret.Add(LoadScene(id, cache, client_data, clone));
  713. }
  714. return ret;
  715. }
  716. //---------------------------------------------------------------------------------------------------
  717. #region Loader
  718. readonly private static Encoding UTF8 = new UTF8Encoding(false);
  719. protected virtual T LoadData<T>(string file) where T : class, IExternalizable
  720. {
  721. T info = null;
  722. if (file.EndsWith(".xml"))
  723. {
  724. if (DEFAULT_LOAD_FROM_BIN)
  725. {
  726. string bin = file + ".bin";
  727. try
  728. {
  729. if (Resource.ExistData(bin))
  730. {
  731. info = LoadDataFromBin<T>(bin, factory);
  732. return info;
  733. }
  734. }
  735. catch (Exception err)
  736. {
  737. log.Error("LoadData Error : " + bin + "\n" + err.Message, err);
  738. }
  739. }
  740. info = LoadXmlAs<T>(file, log);
  741. }
  742. return info;
  743. }
  744. protected virtual SceneData LoadScene(string file, bool cache, bool client_data)
  745. {
  746. try
  747. {
  748. if (client_data)
  749. {
  750. cache = false;
  751. }
  752. SceneData info = null;
  753. string bin_file = file + ".bin";
  754. if (DEFAULT_LOAD_FROM_BIN && Resource.ExistData(bin_file))
  755. {
  756. Stream stream = Resource.LoadDataAsStream(bin_file);
  757. if (stream != null)
  758. {
  759. try
  760. {
  761. InputStream input = new InputStream(stream, factory);
  762. int typeID = input.GetS32();
  763. Type type = factory.GetType(typeID);
  764. if (typeof(SceneData).Equals(type))
  765. {
  766. info = new SceneData();
  767. if (!cache && client_data)
  768. {
  769. info.ReadExternalByClient(input);
  770. }
  771. else
  772. {
  773. info.ReadExternal(input);
  774. }
  775. }
  776. }
  777. finally
  778. {
  779. stream.Dispose();
  780. }
  781. }
  782. }
  783. if (info == null)
  784. {
  785. info = LoadXmlAs<SceneData>(file, log);
  786. }
  787. if (info != null)
  788. {
  789. log.Debug("LoadScene : " + info.GetType() + " : " + info);
  790. if (cache)
  791. {
  792. scenes.Put(info.ID, info);
  793. }
  794. }
  795. else
  796. {
  797. log.Error("LoadScene Error : " + file);
  798. }
  799. return info;
  800. }
  801. catch (Exception err)
  802. {
  803. log.Error("LoadScene : " + file + "\n" + err.Message);
  804. throw new Exception(err.Message, err);
  805. }
  806. }
  807. public static T LoadXmlAs<T>(string path, T default_value = default(T))
  808. {
  809. return LoadXmlAs<T>(path, null, default_value);
  810. }
  811. public static T LoadXmlAs<T>(string path, Logger log, T default_value = default(T))
  812. {
  813. try
  814. {
  815. XmlDocument xml = XmlUtil.LoadXML(path);
  816. return (T)XmlUtil.XmlToObject(xml);
  817. }
  818. catch (Exception err)
  819. {
  820. string msg = "LoadXml Error : " + path + "\n" + err.Message;
  821. if (log != null)
  822. {
  823. log.Error(msg, err);
  824. }
  825. else
  826. {
  827. Console.WriteLine(msg + "\r\n" + err.StackTrace);
  828. }
  829. }
  830. return default_value;
  831. }
  832. public static T LoadDataFromBin<T>(byte[] dat, IExternalizableFactory factory) where T : class, IExternalizable
  833. {
  834. using (var stream = new MemoryStream(dat))
  835. {
  836. LoadDataFromBin<T>(stream, factory);
  837. }
  838. return null;
  839. }
  840. public static T LoadDataFromBin<T>(Stream stream, IExternalizableFactory factory) where T : class, IExternalizable
  841. {
  842. try
  843. {
  844. InputStream input = new InputStream(stream, factory);
  845. int typeID = input.GetS32();
  846. if (typeID != 0)
  847. {
  848. Type type = factory.GetType(typeID);
  849. if (type != null)
  850. {
  851. T any = (T)Activator.CreateInstance(type);
  852. any.ReadExternal(input);
  853. return any;
  854. }
  855. }
  856. }
  857. catch (Exception e)
  858. {
  859. log.Error(e);
  860. }
  861. return null;
  862. }
  863. public static T LoadDataFromBin<T>(string file, IExternalizableFactory factory) where T : IExternalizable
  864. {
  865. var stream = Resource.LoadDataAsStream(file);
  866. if (stream != null)
  867. {
  868. try
  869. {
  870. InputStream input = new InputStream(stream, factory);
  871. int typeID = input.GetS32();
  872. if (typeID != 0)
  873. {
  874. Type type = factory.GetType(typeID);
  875. if (type != null)
  876. {
  877. T any = (T)Activator.CreateInstance(type);
  878. any.ReadExternal(input);
  879. return any;
  880. }
  881. }
  882. }
  883. finally
  884. {
  885. stream.Dispose();
  886. }
  887. }
  888. return default(T);
  889. }
  890. public static string DataToXmlText<T>(T data) where T : IExternalizable
  891. {
  892. StringBuilder output = new StringBuilder();
  893. try
  894. {
  895. XmlDocument doc = XmlUtil.ObjectToXml(data);
  896. XmlWriterSettings settings = new XmlWriterSettings();
  897. settings.Indent = true;
  898. settings.Encoding = UTF8;
  899. using (XmlWriter xml = XmlWriter.Create(output, settings))
  900. {
  901. doc.Save(xml);
  902. xml.Flush();
  903. }
  904. }
  905. catch (Exception err)
  906. {
  907. output.AppendLine(err.Message);
  908. output.AppendLine(err.StackTrace);
  909. }
  910. return output.ToString();
  911. }
  912. public static bool ValidateBin<T>(T data, IExternalizableFactory factory, out string xml, out string retxml) where T : IExternalizable
  913. {
  914. try
  915. {
  916. xml = DataToXmlText<T>(data);
  917. byte[] bin;
  918. using (MemoryStream ms = new MemoryStream(1024 * 1024))
  919. {
  920. OutputStream output = new OutputStream(ms, factory);
  921. output.PutExt(data);
  922. ms.Flush();
  923. bin = new byte[ms.Position];
  924. Array.Copy(ms.GetBuffer(), bin, bin.Length);
  925. }
  926. using (MemoryStream ms = new MemoryStream(bin))
  927. {
  928. InputStream input = new InputStream(ms, factory);
  929. T ret = (T)input.GetExtAny();
  930. retxml = DataToXmlText<T>(ret);
  931. if (xml.Equals(retxml))
  932. {
  933. return true;
  934. }
  935. }
  936. }
  937. catch (Exception err)
  938. {
  939. retxml = xml = (err.Message) + "\r\n" + (err.StackTrace);
  940. }
  941. return false;
  942. }
  943. public static byte[] DataToBin<T>(T data, IExternalizableFactory factory) where T : IExternalizable
  944. {
  945. using (MemoryStream ms = new MemoryStream(1024 * 1024))
  946. {
  947. OutputStream output = new OutputStream(ms, factory);
  948. output.PutExt(data);
  949. ms.Flush();
  950. byte[] bin = new byte[ms.Position];
  951. Array.Copy(ms.GetBuffer(), bin, bin.Length);
  952. return bin;
  953. }
  954. }
  955. public static byte[] SaveDataToBin<T>(FileInfo file, T data, IExternalizableFactory factory) where T : IExternalizable
  956. {
  957. byte[] bin = DataToBin<T>(data, factory);
  958. File.WriteAllBytes(file.FullName, bin);
  959. return bin;
  960. }
  961. public static T DataFromXML<T>(string text) where T : IExternalizable
  962. {
  963. XmlDocument xml = XmlUtil.FromString(text);
  964. if (xml != null)
  965. {
  966. return (T)XmlUtil.XmlToObject(xml);
  967. }
  968. return default(T);
  969. }
  970. #endregion
  971. //---------------------------------------------------------------------------------------------------
  972. #region ResourceID
  973. /// <summary>
  974. /// 有选择的递归读取字段标识的所有相关的模板 [TemplateID] [TemplatesID]
  975. /// 返回资源标记[ResourceID]列表,提供给客户端预加载资源
  976. /// </summary>
  977. /// <param name="dir"></param>
  978. /// <param name="data"></param>
  979. public List<string> SelectTemplates(object data)
  980. {
  981. HashMap<string, FieldAttributeValue> resources = new HashMap<string, FieldAttributeValue>();
  982. HashMap<object, object> exist = new HashMap<object, object>();
  983. SelectAllTemplates(data, resources, exist);
  984. return new List<string>(resources.Keys);
  985. }
  986. public HashMap<string, FieldAttributeValue> SelectTemplatesAsMap(object data)
  987. {
  988. HashMap<string, FieldAttributeValue> resources = new HashMap<string, FieldAttributeValue>();
  989. HashMap<object, object> exist = new HashMap<object, object>();
  990. SelectAllTemplates(data, resources, exist);
  991. return resources;
  992. }
  993. private void SelectAllTemplates(object data, HashMap<string, FieldAttributeValue> resources, HashMap<object, object> exist)
  994. {
  995. if (!exist.ContainsKey(data))
  996. {
  997. exist.Add(data, data);
  998. // 获取所有标识为 TemplateID 字段
  999. List<FieldAttributeValue> templateList = new List<FieldAttributeValue>();
  1000. PropertyUtil.CollectFieldAttributeValues(data, typeof(TemplateIDAttribute), templateList);
  1001. foreach (FieldAttributeValue fa in templateList)
  1002. {
  1003. TemplateIDAttribute t_attr = fa.AttributeData as TemplateIDAttribute;
  1004. object template = TryLoad((int)fa.FieldValue, t_attr.TemplateType);
  1005. if (template != null)
  1006. {
  1007. SelectAllTemplates(template, resources, exist);
  1008. }
  1009. }
  1010. // 获取所有标识为 TemplatesID 字段
  1011. List<FieldAttributeValue> templatesList = new List<FieldAttributeValue>();
  1012. PropertyUtil.CollectFieldAttributeValues(data, typeof(TemplatesIDAttribute), templatesList);
  1013. foreach (FieldAttributeValue fa in templatesList)
  1014. {
  1015. TemplatesIDAttribute t_attr = fa.AttributeData as TemplatesIDAttribute;
  1016. List<int> ids = fa.FieldValue as List<int>;
  1017. foreach (int id in ids)
  1018. {
  1019. object template = TryLoad(id, t_attr.TemplateType);
  1020. if (template != null)
  1021. {
  1022. SelectAllTemplates(template, resources, exist);
  1023. }
  1024. }
  1025. }
  1026. // 获取所有 ResourceID 字段
  1027. List<FieldAttributeValue> resourceList = new List<FieldAttributeValue>();
  1028. PropertyUtil.CollectFieldAttributeValues(data, typeof(ResourceIDAttribute), resourceList);
  1029. foreach (FieldAttributeValue fa in resourceList)
  1030. {
  1031. if (fa.FieldValue != null)
  1032. {
  1033. resources.Put(fa.FieldValue as string, fa);
  1034. }
  1035. }
  1036. }
  1037. }
  1038. #endregion
  1039. //---------------------------------------------------------------------------------------------------
  1040. #region Localization
  1041. public static string GenLocalizationCsv(EditorTemplatesData templates, AtomicFloat percent = null)
  1042. {
  1043. StringBuilder sb = new StringBuilder();
  1044. List<ITemplateData> list = templates.AllTemplates();
  1045. int i = 0;
  1046. foreach (object obj in list)
  1047. {
  1048. GenLocalizationCsv(obj as ITemplateData, sb);
  1049. if (percent != null)
  1050. {
  1051. percent.GetAndSet(((float)i) / list.Count);
  1052. }
  1053. i++;
  1054. }
  1055. return sb.ToString();
  1056. }
  1057. public static void GenLocalizationCsv(ITemplateData data, StringBuilder sb)
  1058. {
  1059. UmlDocument uml = new UmlDocument(data);
  1060. UmlValueNode node = uml.DocumentElement;
  1061. GenLocalizationCsv(data, node, sb);
  1062. }
  1063. public static void GenLocalizationCsv(ITemplateData data, UmlValueNode node, StringBuilder sb)
  1064. {
  1065. if (node.IsLeaf)
  1066. {
  1067. if (node.Value is string && node.OwnerIndexer is FieldInfo)
  1068. {
  1069. FieldInfo field = node.OwnerIndexer as FieldInfo;
  1070. LocalizationTextAttribute tattr = PropertyUtil.GetAttribute<LocalizationTextAttribute>(field);
  1071. if (tattr != null)
  1072. {
  1073. StringBuilder line = new StringBuilder();
  1074. {
  1075. line.Append("\"," + node.Value);
  1076. UmlValueNode it = node;
  1077. while (!it.IsRoot)
  1078. {
  1079. UmlValueNode vt = it as UmlValueNode;
  1080. line.Insert(0, ";");
  1081. line.Insert(0, vt.Name);
  1082. if (it.ParentNode is UmlValueNode)
  1083. {
  1084. it = it.ParentNode as UmlValueNode;
  1085. }
  1086. else
  1087. {
  1088. break;
  1089. }
  1090. }
  1091. line.Insert(0, "\"");
  1092. }
  1093. sb.Append("\"" + data.GetType().FullName + "\",");
  1094. sb.Append("" + data.TemplateID + ",");
  1095. sb.AppendLine(line.ToString());
  1096. }
  1097. }
  1098. }
  1099. else
  1100. {
  1101. foreach (UmlValueNode sub in node.ChildNodes)
  1102. {
  1103. GenLocalizationCsv(data, sub, sb);
  1104. }
  1105. }
  1106. }
  1107. public static void LoadLocalizationCsv(EditorTemplatesData templates, string csv_text, AtomicInteger progress = null)
  1108. {
  1109. CsvTable table = new CsvTable();
  1110. table.LoadFromText(csv_text);
  1111. LoadLocalizationCsv(templates, table, progress);
  1112. }
  1113. public static void LoadLocalizationCsv(EditorTemplatesData templates, CsvTable table, AtomicInteger progress = null)
  1114. {
  1115. for (int r = 0; r < table.MaxRow; r++)
  1116. {
  1117. if (table.Cells[r].Length >= 4)
  1118. {
  1119. string stype = table.GetCell(0, r);
  1120. string stpid = table.GetCell(1, r);
  1121. string sline = table.GetCell(2, r);
  1122. string stext = table.GetCell(3, r);
  1123. Type type = ReflectionUtil.GetType(stype);
  1124. int templateID = int.Parse(stpid);
  1125. object data;
  1126. if (templates.GetObjectByType(type, templateID, out data))
  1127. {
  1128. UmlDocument uml = new UmlDocument(data);
  1129. UmlValueNode node = uml.DocumentElement;
  1130. LoadLocalizationCsv(data as ITemplateData, node, sline, stext);
  1131. }
  1132. }
  1133. if (progress != null) progress.IncrementAndGet();
  1134. }
  1135. }
  1136. public static void LoadLocalizationCsv(ITemplateData data, UmlValueNode node, string line, string value)
  1137. {
  1138. string[] kvs = line.Split(';');
  1139. foreach (string key in kvs)
  1140. {
  1141. node = node.GetChild(key) as UmlValueNode;
  1142. if (node.IsLeaf)
  1143. {
  1144. UmlValueNode owner = node.ParentNode as UmlValueNode;
  1145. owner.SetFieldValue(node, value);
  1146. return;
  1147. }
  1148. }
  1149. }
  1150. #endregion
  1151. //---------------------------------------------------------------------------------------------------
  1152. }
  1153. }