InstanceZone.cs 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934
  1. using CommonAI.Data;
  2. using CommonAI.RTS;
  3. using CommonAI.Zone.EventTrigger;
  4. using CommonAI.Zone.Formula;
  5. using CommonAI.Zone.Helper;
  6. using CommonAI.ZoneClient;
  7. using CommonAI.ZoneEditor;
  8. using CommonAI.ZoneServer.JSGModule;
  9. using CommonLang;
  10. using CommonLang.Concurrent;
  11. using CommonLang.IO;
  12. using CommonLang.Log;
  13. using CommonLang.Property;
  14. using CommonLang.Vector;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Diagnostics;
  18. using static CommonAI.Zone.SpellTemplate;
  19. using static CommonAI.Zone.UnitInfo;
  20. namespace CommonAI.Zone.Instance
  21. {
  22. /// <summary>
  23. /// 服务端场景
  24. /// </summary>
  25. public partial class InstanceZone : GameEntity
  26. {
  27. private static AtomicInteger s_alloc_zone_count = new AtomicInteger(0);
  28. private static AtomicInteger s_active_zone_count = new AtomicInteger(0);
  29. /// <summary>
  30. /// 分配实例数量
  31. /// </summary>
  32. public static int AllocZoneCount { get { return s_alloc_zone_count.Value; } }
  33. /// <summary>
  34. /// 未释放实例数量
  35. /// </summary>
  36. public static int ActiveZoneCount { get { return s_active_zone_count.Value; } }
  37. //------------------------------------------------------------------------
  38. // 基础数据
  39. private InstanceZoneListener mListener;
  40. private TemplateManager mTemplates;
  41. private IFormula mFormula = TemplateManager.Factory.Formula;
  42. private IQuestAdapter mQuestAdapter;
  43. private SyncMessageQueue<Action> mSyncActionQueue = new SyncMessageQueue<Action>();
  44. private Queue<Event> mSendingEvents = new Queue<Event>();
  45. private InstanceZoneObjectMap mObjects;
  46. public TemplateManager Templates { get { return mTemplates; } }
  47. public IQuestAdapter QuestAdapter { get { return mQuestAdapter; } }
  48. public int UpdateIntervalMS { get { return mLastInterval; } }
  49. private readonly int mMaxUnitCount;
  50. private int mLastInterval = 0;
  51. private ulong mTimer = 0;
  52. private long mCurPassTimeMS = 0;
  53. private long mQueryPassTimeMS = 0;
  54. private int mQueryPassTimeSEC = 0;
  55. private bool mHalfSync = false;
  56. readonly private Random random;
  57. readonly private Logger log;
  58. public string UUID { get; set; }
  59. //------------------------------------------------------------------------
  60. readonly private ZoneInfo m_TerrainSrc;
  61. readonly private SpaceDivision mSpaceDiv;
  62. public ZoneInfo TerrainSrc { get { return m_TerrainSrc; } }
  63. public ZoneInfo Terrain { get { return path_terrain_data.Data; } }
  64. public int SpaceDivSize { get; private set; }
  65. [Desc("单位当前帧位移的最小距离")]
  66. public float MinStep { get; private set; }
  67. [Desc("最大单位数量")]
  68. public int MaxUnitCount { get { return mMaxUnitCount; } }
  69. [Desc("场景中是否存在Area")]
  70. public bool HasArea { get { return mHasArea; } }
  71. //山大王id
  72. protected int mKingID;
  73. //绑定服务器
  74. protected string mBindGameSrvId;
  75. //------------------------------------------------------------------------
  76. /// <summary>
  77. ///
  78. /// </summary>
  79. /// <param name="templates"></param>
  80. /// <param name="listener">消息接收者</param>
  81. /// <param name="data">场景数据</param>
  82. /// <param name="spaceDivSize">空间分割参数</param>
  83. /// <param name="maxUnitCount">最大单位数</param>
  84. /// <param name="randomSeed">随机种子</param>
  85. internal InstanceZone(TemplateManager templates, InstanceZoneListener listener, ZoneEditor.SceneData data, GSCreateAreaData gsData,
  86. int spaceDivSize, int maxUnitCount, int randomSeed)
  87. {
  88. InstanceZone.s_alloc_zone_count++;
  89. InstanceZone.s_active_zone_count++;
  90. var info = data.ZoneData;
  91. this.log = LoggerFactory.GetLogger(string.Format("InstanceZone({0})", info.TemplateID));
  92. this.random = TemplateManager.Factory.CreateRandom(randomSeed);// new Random(randomSeed);
  93. this.mTemplates = templates;
  94. this.IsSyncZ = false;
  95. this.MinStep = MoveHelper.GetDistance(1000 / templates.CFG.SYSTEM_FPS, templates.CFG.OBJECT_MOVE_TO_MIN_STEP_SEC);
  96. if (spaceDivSize < 1)
  97. {
  98. throw new Exception("SpaceDivSize must large than map 1 !");
  99. }
  100. this.mMaxUnitCount = maxUnitCount;
  101. this.mListener = listener;
  102. this.m_TerrainSrc = info;
  103. this.SpaceDivSize = spaceDivSize;
  104. this.mSpaceDiv = new SpaceDivision(
  105. m_TerrainSrc.TotalWidth,
  106. m_TerrainSrc.TotalHeight,
  107. spaceDivSize * m_TerrainSrc.GridCellW,
  108. spaceDivSize * m_TerrainSrc.GridCellH);
  109. this.mObjects = new InstanceZoneObjectMap("zoneId:" + this.GetSceneID());
  110. // this.path_terrain_data = new InstanceZoneManhattanMap(templates, info.Clone() as ZoneInfo);
  111. // this.path_finder = new AstarManhattan(path_terrain_data, true, spaceDivSize);
  112. // this.path_terrain_area_gen = new ManhattanMapAreaGenerator(path_terrain_data.Data);
  113. this.InitTerrain(data, spaceDivSize, out this.path_terrain_data, out this.path_finder, out this.path_terrain_area_gen);
  114. this.mQuestAdapter = TemplateManager.Factory.CreateQuestAdapter(this);
  115. this.baseInit(data, gsData);
  116. }
  117. protected virtual void baseInit(ZoneEditor.SceneData data, GSCreateAreaData gsData)
  118. {
  119. }
  120. // -----------------------------------------------------------------------------------
  121. ~InstanceZone()
  122. {
  123. InstanceZone.s_alloc_zone_count--;
  124. }
  125. protected override void Disposing()
  126. {
  127. base.Disposing();
  128. this.ClearEvents();
  129. foreach (var obj in mObjects.Objects)
  130. {
  131. obj.Dispose();
  132. }
  133. this.mObjects.Dispose();
  134. this.mObjects = null;
  135. foreach (var flg in mFlags.Values)
  136. {
  137. flg.Dispose();
  138. }
  139. this.mFlags.Clear();
  140. this.DisposeTerrain();
  141. this.mSpaceDiv.Dispose();
  142. this.mQuestAdapter.Dispose();
  143. this.mQuestAdapter = null;
  144. this.mListener = null;
  145. this.mTemplates = null;
  146. this.mFormula = null;
  147. this.mSyncActionQueue = null;
  148. this.mSendingEvents = null;
  149. this.mTasks.Clear();
  150. this.mTasks = null;
  151. this.mTimeTasks.Dispose();
  152. this.mTimeTasks = null;
  153. this.EnvironmentVarMap.Clear();
  154. this.mFlags.Clear();
  155. this.m_UnitsPos.Clear();
  156. this.m_UnitsStates.Clear();
  157. InstanceZone.s_active_zone_count--;
  158. }
  159. // -----------------------------------------------------------------------------------
  160. protected Logger Log { get { return log; } }
  161. public int TotalWidth { get { return m_TerrainSrc.TotalWidth; } }
  162. public int TotalHeight { get { return m_TerrainSrc.TotalHeight; } }
  163. public int GridCellW { get { return m_TerrainSrc.GridCellW; } }
  164. public int GridCellH { get { return m_TerrainSrc.GridCellH; } }
  165. public int XCount { get { return m_TerrainSrc.XCount; } }
  166. public int YCount { get { return m_TerrainSrc.YCount; } }
  167. public ulong Tick { get { return mTimer; } }
  168. /// <summary>
  169. /// 是否发 SyncPosEvent 包
  170. /// </summary>
  171. public bool SyncPos
  172. {
  173. get { return sync_pos_list.Enable; }
  174. set { sync_pos_list.Enable = value; }
  175. }
  176. /// <summary>
  177. /// 是否为低速率网络同步(将优化为半字通信)
  178. /// </summary>
  179. public bool IsHalfSync
  180. {
  181. get { return mHalfSync; }
  182. set
  183. {
  184. if (value && TotalWidth <= 255 && TotalHeight <= 255)
  185. {
  186. mHalfSync = value;
  187. }
  188. else
  189. {
  190. mHalfSync = false;
  191. }
  192. }
  193. }
  194. /// <summary>
  195. /// 同步包是否包含Z
  196. /// </summary>
  197. public bool IsSyncZ
  198. {
  199. get;
  200. set;
  201. }
  202. public long PassTimeMS { get { return mQueryPassTimeMS; } }
  203. public int PassTimeSEC { get { return mQueryPassTimeSEC; } }
  204. public Random RandomN { get { return random; } }
  205. // public void Trace(string text)
  206. // {
  207. // log.Info(text);
  208. // }
  209. // -----------------------------------------------------------------------------------
  210. //------------------------------------------------------------------------------------
  211. #region TIMING_AND_TASK
  212. private SyncMessageQueue<Action<InstanceZone>> mTasks = new SyncMessageQueue<Action<InstanceZone>>();
  213. private TimeTaskQueue mTimeTasks = new TimeTaskQueue();
  214. private void doTask(Action<InstanceZone> task)
  215. {
  216. task(this);
  217. }
  218. /// <summary>
  219. /// 【线程安全】向主线程排一个任务
  220. /// </summary>
  221. /// <param name="task"></param>
  222. public void queueTask(Action<InstanceZone> task)
  223. {
  224. mTasks.Enqueue(task);
  225. }
  226. public string GetInfo()
  227. {
  228. if(this.mObjects == null)
  229. {
  230. return "对象:-1";
  231. }
  232. return "对象:" + AllObjectsCount + ", 单位:" + AllUnitsCount + ", 法术:" + AllSpellsCount + ", 道具:" + AllItemsCount + ", 玩家:" + AllPlayersCount;
  233. }
  234. /// <summary>
  235. /// 【线程安全】增加时间任务
  236. /// </summary>
  237. /// <param name="intervalMS"></param>
  238. /// <param name="delayMS"></param>
  239. /// <param name="repeat"></param>
  240. /// <param name="handler"></param>
  241. public TimeTaskMS AddTimeTask(int intervalMS, int delayMS, int repeat, TickHandler handler)
  242. {
  243. return mTimeTasks.AddTimeTask(intervalMS, delayMS, repeat, handler);
  244. }
  245. /// <summary>
  246. /// 【线程安全】增加延时回调方法
  247. /// </summary>
  248. /// <param name="delayMS"></param>
  249. /// <param name="handler"></param>
  250. public TimeTaskMS AddTimeDelayMS(int delayMS, TickHandler handler)
  251. {
  252. return mTimeTasks.AddTimeDelayMS(delayMS, handler);
  253. }
  254. /// <summary>
  255. /// 【线程安全】增加定时回调方法
  256. /// </summary>
  257. /// <param name="intervalMS"></param>
  258. /// <param name="handler"></param>
  259. public TimeTaskMS AddTimePeriodicMS(int intervalMS, TickHandler handler)
  260. {
  261. if(intervalMS <= 0)
  262. {
  263. log.Error("增加定时任务异常:" + intervalMS);
  264. return null;
  265. }
  266. return mTimeTasks.AddTimePeriodicMS(intervalMS, handler);
  267. }
  268. #endregion
  269. //-----------------------------------------------------------------------------------
  270. /// <summary>
  271. /// 【线程安全】向当前场景输入指令
  272. /// </summary>
  273. /// <param name="act"></param>
  274. public void pushAction(Action act)
  275. {
  276. mSyncActionQueue.Enqueue(act);
  277. }
  278. protected internal void queueEventInternal(Event evt)
  279. {
  280. mSendingEvents.Enqueue(evt);
  281. }
  282. /// <summary>
  283. /// 【内部调用】输出消息
  284. /// </summary>
  285. public void queueEvent(ZoneEvent evt, GameEntity sender = null)
  286. {
  287. if (sender != null) { evt.sender = sender; }
  288. this.queueEventInternal(evt);
  289. }
  290. /// <summary>
  291. /// 【内部调用】输出消息
  292. /// </summary>
  293. /// <param name="obj"></param>
  294. /// <param name="evt"></param>
  295. public void queueObjectEvent(InstanceZoneObject obj, ObjectEvent evt, bool force = false)
  296. {
  297. if(mSendingEvents == null)
  298. {
  299. if(mObjects == null)
  300. {
  301. log.Warn("queueObjectEvent exception1: " + this.GetSceneID() + ", mObjects null, " + this.UUID + ", " + evt.GetType()
  302. + ", " + new StackTrace().ToString());
  303. }
  304. else
  305. {
  306. log.Warn("queueObjectEvent exception2: " + this.GetSceneID() + ", Players: " + this.AllPlayersCount + ", Items: "
  307. + this.AllItemsCount + ", Units: " + this.AllUnitsCount + ", " + this.UUID + ", " + evt.GetType() + ", " + new StackTrace().ToString());
  308. }
  309. return;
  310. }
  311. if (obj.ID == 0)
  312. return;
  313. if (!force && !obj.IsInZone)
  314. return;
  315. obj.onSendingEvent(ref evt);
  316. if (evt != null)
  317. {
  318. evt.object_id = obj.ID;
  319. evt.sender = obj;
  320. mSendingEvents.Enqueue(evt);
  321. }
  322. }
  323. /// <summary>
  324. /// 立即发送指令
  325. /// </summary>
  326. /// <param name="obj"></param>
  327. /// <param name="req"></param>
  328. /// <param name="rsp"></param>
  329. public void sendActorResponse(InstanceZoneObject obj, ActorRequest req, ActorResponse rsp)
  330. {
  331. if (obj.ID == 0)
  332. return;
  333. if (!obj.IsInZone)
  334. return;
  335. rsp.MessageID = req.MessageID;
  336. rsp.object_id = obj.ID;
  337. rsp.sender = obj;
  338. mSendingEvents.Enqueue(rsp);
  339. }
  340. public void sendMessageBox(string msg)
  341. {
  342. queueEventInternal(new TestMessageBox(msg));
  343. }
  344. public virtual int GetSceneID() { return 0; }
  345. //-----------------------------------------------------------------------------------
  346. public void RecvMessageFromGameServer(ZoneServer.SendMessageR2B msg)
  347. {
  348. LastRecvMessageR2B = msg;
  349. if (mOnRecvFromGS != null)
  350. {
  351. mOnRecvFromGS.Invoke(this, msg);
  352. }
  353. }
  354. public void SendMessageToGameServer(string msg)
  355. {
  356. ZoneServer.SendMessageB2R b2r = new ZoneServer.SendMessageB2R();
  357. b2r.Message = msg;
  358. LastSentMessageB2R = b2r;
  359. if (mOnSendToGS != null)
  360. {
  361. mOnSendToGS.Invoke(this, b2r);
  362. }
  363. }
  364. public void SendEventToGameServer(IExternalizable evt)
  365. {
  366. ZoneServer.SendEventB2R b2r = new ZoneServer.SendEventB2R();
  367. b2r.evt = evt;
  368. if (mOnSendMessageB2REvent != null)
  369. {
  370. mOnSendMessageB2REvent.Invoke(this, b2r);
  371. }
  372. }
  373. public bool CheckAutoDropItem()
  374. {
  375. return this.mListener.CheckDropItem();
  376. }
  377. //-----------------------------------------------------------------------------------
  378. public virtual void Update(int intervalMS, bool slowRefresh)
  379. {
  380. beginEventsRecord();
  381. this.mLastInterval = intervalMS;
  382. this.MinStep = MoveHelper.GetDistance(intervalMS, Templates.CFG.OBJECT_MOVE_TO_MIN_STEP_SEC);
  383. if (mTimer == 0)
  384. {
  385. mCurPassTimeMS = 0;
  386. mQueryPassTimeMS = 0;
  387. mQueryPassTimeSEC = 0;
  388. foreach (InstanceFlag f in mFlags.Values)
  389. {
  390. f.OnStart();
  391. }
  392. if (mOnInit != null)
  393. mOnInit.Invoke(this);
  394. }
  395. mTasks.ProcessMessages(doTask);
  396. mSyncActionQueue.ProcessMessages(updateAction);
  397. mObjects.Refresh();
  398. var objetes = mObjects.Objects;
  399. {
  400. // clean space div state
  401. foreach (InstanceZoneObject u in objetes)
  402. {
  403. u.onUpdate(this, slowRefresh);
  404. }
  405. mSpaceDiv.ClearSpaceNearChanges();
  406. bool dirty = false;
  407. foreach (InstanceZoneObject u in objetes)
  408. {
  409. if (u.Enable)
  410. {
  411. dirty = u.updatePos(this);
  412. u.mCurCellNode.MarkPosDirty(dirty);
  413. if (dirty && u.ClientVisible && u.SyncPos)
  414. {
  415. if (mOnObjectPosChanged != null)
  416. {
  417. mOnObjectPosChanged.Invoke(this, u);
  418. }
  419. sync_pos_list.Add(u);
  420. }
  421. }
  422. }
  423. }
  424. foreach (InstanceFlag f in mFlags.Values)
  425. {
  426. f.update();
  427. }
  428. if (mOnUpdate != null)
  429. {
  430. mOnUpdate.Invoke(this);
  431. }
  432. updateEvents();
  433. mTimeTasks.Update(intervalMS);
  434. mCurPassTimeMS += intervalMS;
  435. mQueryPassTimeMS = mCurPassTimeMS;
  436. mQueryPassTimeSEC = (int)(mCurPassTimeMS / 1000);
  437. mTimer++;
  438. }
  439. private void updateAction(Action act)
  440. {
  441. if (act is SystemMessage)
  442. {
  443. processSystemMessage(act as SystemMessage);
  444. }
  445. else if (act is ObjectAction)
  446. {
  447. ObjectAction oa = (ObjectAction)act;
  448. InstanceUnit unit = act.sender as InstanceUnit;
  449. if (unit == null)
  450. {
  451. unit = mObjects.GetObject<InstanceUnit>(oa.object_id);
  452. }
  453. if (unit != null)
  454. {
  455. unit.doAction(oa);
  456. if (mOnHandleObjectAction != null)
  457. {
  458. mOnHandleObjectAction.Invoke(unit, oa);
  459. }
  460. mFormula.OnUnitHandleNetMessage(unit, oa);
  461. }
  462. else
  463. {
  464. log.Info("Drop message : " + oa);
  465. }
  466. }
  467. else
  468. {
  469. if (mOnHandleAction != null)
  470. {
  471. mOnHandleAction.Invoke(this, act);
  472. }
  473. mFormula.OnZoneHandleNetMessage(this, act);
  474. }
  475. }
  476. private void updateEvents()
  477. {
  478. if (sync_pos_list.Enable)
  479. {
  480. queueEvent(sync_pos_list.AsEvent(this));
  481. }
  482. sync_pos_list.Clear();
  483. while (mSendingEvents.Count > 0)
  484. {
  485. Event evt = mSendingEvents.Dequeue();
  486. //log.Info("---->onEvent:" + evt.ToString());
  487. mListener.onEventHandler(evt);
  488. if (mOnPostEvent != null)
  489. {
  490. mOnPostEvent.Invoke(this, evt);
  491. }
  492. if (evt is GameOverEvent && mOnGameOver != null)
  493. {
  494. mOnGameOver.Invoke(this, evt as GameOverEvent);
  495. }
  496. }
  497. }
  498. virtual protected void processSystemMessage(SystemMessage msg)
  499. {
  500. if (msg is Ping)
  501. {
  502. queueEventInternal(new Pong(msg as Ping));
  503. }
  504. }
  505. //-------------------------------------------------------------------------------------------
  506. #region OBJECTS
  507. private uint mObjectIDIndexer = 0;
  508. internal uint genObjectID()
  509. {
  510. mObjectIDIndexer++;
  511. return mObjectIDIndexer;
  512. }
  513. // 获取一个单位
  514. public T getObject<T>(uint obj_id) where T : InstanceZoneObject
  515. {
  516. if (obj_id == 0) return null;
  517. T go = mObjects.GetObject<T>(obj_id);
  518. if (go != null)
  519. {
  520. return go;
  521. }
  522. return null;
  523. }
  524. public InstanceUnit getUnit(uint obj_id)
  525. {
  526. if (obj_id == 0) return null;
  527. return mObjects.GetObject<InstanceUnit>(obj_id);
  528. }
  529. public InstanceUnit getUnitByTemplateID(int templateId)
  530. {
  531. if (templateId == 0) return null;
  532. foreach (InstanceUnit u in mObjects.Units)
  533. {
  534. if (u.Info.TemplateID == templateId)
  535. {
  536. return u;
  537. }
  538. }
  539. return null;
  540. }
  541. public InstanceUnit getUnitByName(string name)
  542. {
  543. if (string.IsNullOrEmpty(name))
  544. {
  545. return null;
  546. }
  547. foreach (InstanceUnit u in mObjects.Units)
  548. {
  549. if (name.Equals(u.Name))
  550. {
  551. return u;
  552. }
  553. }
  554. return null;
  555. }
  556. public InstancePlayer getPlayerByUUID(string playerUUID)
  557. {
  558. if (string.IsNullOrEmpty(playerUUID))
  559. {
  560. return null;
  561. }
  562. return mObjects.GetPlayer(playerUUID);
  563. }
  564. public InstanceItem getItemByName(string name)
  565. {
  566. if (string.IsNullOrEmpty(name))
  567. {
  568. return null;
  569. }
  570. foreach (InstanceItem u in mObjects.Items)
  571. {
  572. if (name.Equals(u.Name))
  573. {
  574. return u;
  575. }
  576. }
  577. return null;
  578. }
  579. public InstanceUnit getUnitByID(int UnitID)
  580. {
  581. foreach (InstanceUnit obj in mObjects.Units)
  582. {
  583. if (obj.ID == UnitID)
  584. {
  585. return obj;
  586. }
  587. }
  588. return null;
  589. }
  590. public IEnumerable<InstancePlayer> AllPlayers { get { return mObjects.Players; } }
  591. public int AllPlayersCount { get { return mObjects.PlayersCount; } }
  592. public IEnumerable<InstanceUnit> AllUnits { get { return mObjects.Units; } }
  593. public int AllUnitsCount { get { return mObjects.UnitsCount; } }
  594. public IEnumerable<InstanceSpell> AllSpells { get { return mObjects.Spells; } }
  595. public int AllSpellsCount { get { return mObjects.SpellsCount; } }
  596. public IEnumerable<InstanceItem> AllItems { get { return mObjects.Items; } }
  597. public int AllItemsCount { get { return mObjects.ItemsCount; } }
  598. public IEnumerable<InstanceZoneObject> AllObjects { get { return mObjects.Objects; } }
  599. public int AllObjectsCount { get { return mObjects.ObjectsCount; } }
  600. [Obsolete("use {@link #AllUnits} {@link #AllSpells} {@link #AllItems} for best performance!")]
  601. public IEnumerable<InstanceZoneObject> allObjs()
  602. {
  603. return mObjects.Objects;
  604. }
  605. [Obsolete("use {@link #AllUnitsCount} {@link #AllSpellsCount} {@link #AllItemsCount} for best performance!")]
  606. public int allObjsCount()
  607. {
  608. return mObjects.ObjectsCount;
  609. }
  610. [Obsolete]
  611. public List<T> selectUnits<T>(Predicate<T> select) where T : InstanceUnit
  612. {
  613. List<T> ret = new List<T>(mObjects.UnitsCount);
  614. foreach (InstanceUnit obj in mObjects.Units)
  615. {
  616. if (select(obj as T))
  617. {
  618. ret.Add(obj as T);
  619. }
  620. }
  621. return ret;
  622. }
  623. public void selectUnits<T>(Predicate<T> select, List<T> ret) where T : InstanceUnit
  624. {
  625. foreach (InstanceUnit obj in mObjects.Units)
  626. {
  627. if (select(obj as T))
  628. {
  629. ret.Add(obj as T);
  630. }
  631. }
  632. }
  633. public T selectRandomUnit<T>(Predicate<T> select) where T : InstanceUnit
  634. {
  635. T ret = null;
  636. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  637. {
  638. foreach (InstanceUnit obj in mObjects.Units)
  639. {
  640. if (obj is T && select(obj as T))
  641. {
  642. list.Add(obj as T);
  643. }
  644. }
  645. if (list.Count > 0)
  646. {
  647. ret = CUtils.GetRandomInArray<InstanceUnit>(list, random) as T;
  648. }
  649. }
  650. return ret;
  651. }
  652. public T selectUnit<T>(Predicate<T> select) where T : InstanceUnit
  653. {
  654. foreach (InstanceUnit obj in mObjects.Units)
  655. {
  656. if (select(obj as T))
  657. {
  658. return obj as T;
  659. }
  660. }
  661. return null;
  662. }
  663. //-------------------------------------------------------------------------------------------
  664. /// <summary>
  665. /// 创建一个单位实体
  666. /// </summary>
  667. virtual public InstanceZoneObject CreateUnit(UnitInfo info, string name, int force, int alliesForce, int level)
  668. {
  669. InstanceUnit unit = TemplateManager.Factory.CreateUnit(this, info, name, force, alliesForce, level);
  670. if (unit != null)
  671. {
  672. return unit;
  673. }
  674. switch (info.UType)
  675. {
  676. case UnitInfo.UnitType.TYPE_PLAYER:
  677. return new InstancePlayer(this, info, name, force, level, alliesForce);
  678. case UnitInfo.UnitType.TYPE_MANUAL:
  679. return new InstanceManual(this, info, name, force, level);
  680. case UnitInfo.UnitType.TYPE_PET:
  681. return new InstancePet(this, info, name, force, level);
  682. case UnitInfo.UnitType.TYPE_SUMMON:
  683. return new InstanceSummon(this, info, name, force, level);
  684. case UnitInfo.UnitType.TYPE_BUILDING:
  685. return new InstanceBuilding(this, info, name, force, level);
  686. case UnitInfo.UnitType.TYPE_MONSTER:
  687. return new InstanceGuard(this, info, name, force, level);
  688. case UnitInfo.UnitType.TYPE_NPC:
  689. return new InstanceGuard(this, info, name, force, level);
  690. default:
  691. return new InstanceGuard(this, info, name, force, level);
  692. }
  693. }
  694. //-------------------------------------------------------------------------------------------
  695. public InstanceUnit AddUnit(int unitTemplateID, string name, int force, int level, float x, float y, float direction, bool pointLv = false)
  696. {
  697. UnitInfo info = Templates.getUnit(unitTemplateID);
  698. if (info != null)
  699. {
  700. return AddUnit(info, name, force, level, x, y, direction, null, "", 0, pointLv);
  701. }
  702. return null;
  703. }
  704. /// <summary>
  705. /// 添加一个单位
  706. /// </summary>
  707. /// <param name="info">单位模板</param>
  708. /// <param name="name">场景中名字(Key)</param>
  709. /// <param name="force">单位阵营</param>
  710. /// <param name="level">单位等级</param>
  711. /// <param name="x">坐标</param>
  712. /// <param name="y">坐标</param>
  713. /// <param name="direction">方向</param>
  714. /// <param name="summoner">召唤者</param>
  715. /// <returns></returns>
  716. public InstanceUnit AddUnit(UnitInfo info, string name, int force, int level, float x, float y, float direction,
  717. InstanceUnit summoner = null, String clientShowName = "", int gsFlag = 0, bool pointLv = false)
  718. {
  719. AddUnitEvent add;
  720. return AddUnit(info, name, force, level, x, y, direction, out add, summoner, clientShowName, gsFlag, 0, pointLv);
  721. }
  722. /// <summary>
  723. /// 添加一个单位
  724. /// </summary>
  725. /// <param name="info">单位模板</param>
  726. /// <param name="name">场景中名字(Key)</param>
  727. /// <param name="force">单位阵营</param>
  728. /// <param name="level">单位等级</param>
  729. /// <param name="x">坐标</param>
  730. /// <param name="y">坐标</param>
  731. /// <param name="direction">方向</param>
  732. /// <param name="add">输出事件</param>
  733. /// <param name="summoner">召唤者</param>
  734. /// <returns></returns>
  735. ///
  736. private long mAddUnitPrintTime = 0;
  737. public InstanceUnit AddUnit(UnitInfo info, string name, int force, int level, float x, float y, float direction,
  738. out AddUnitEvent add, InstanceUnit summoner = null, String clientShowName = "", int gsFlag = 0, int alliesForce = 0, bool pointLv = false)
  739. {
  740. add = null;
  741. if (mObjects.UnitsCount >= mMaxUnitCount)
  742. {
  743. if(mAddUnitPrintTime < CommonLang.CUtils.localTimeMS)
  744. {
  745. mAddUnitPrintTime = CommonLang.CUtils.localTimeMS + 3000;
  746. log.Warn(string.Format("--Zone AddUnit to max: {0}, UUID: {1}, ID: {2} 单位数量:{3}", this.GetSceneID(), this.UUID, info.TemplateID, GetZoneUnitInfo()));
  747. }
  748. return null;
  749. }
  750. if (mTryAddUnit != null && !mTryAddUnit.Invoke(info))
  751. {
  752. //log.Info(string.Format("Zone Unit TryAdd max: {0}, {1}, 单位数量:{2}", this.TerrainSrc.ID, info.TemplateID, mObjects.UnitsCount));
  753. return null;
  754. }
  755. // 创建实体单位
  756. InstanceZoneObject ret = CreateUnit(info, name, force, alliesForce, level);
  757. // 存入单位列表
  758. if (ret is InstanceUnit)
  759. {
  760. InstanceUnit unit = ret as InstanceUnit;
  761. //unit.Name = name;
  762. unit.gameServerFlag = gsFlag;
  763. // 存入单位列表
  764. if (unit.tryAdd(x, y, direction))
  765. {
  766. mObjects.AddObject(unit);
  767. this.LastAddedUnit = unit;
  768. if (unit is ISummonedUnit)
  769. {
  770. ((ISummonedUnit)unit).SummonerUnit = summoner;
  771. }
  772. try
  773. {
  774. unit.onAdded(this, pointLv);
  775. if (mOnUnitAdded != null)
  776. mOnUnitAdded.Invoke(this, unit);
  777. add = new AddUnitEvent();
  778. add.sender = unit;
  779. if (unit.ClientVisible)
  780. {
  781. if (clientShowName != null && !unit.IsPlayer && clientShowName.Length > 0)
  782. {
  783. unit.SetDiaplayerName(clientShowName);
  784. }
  785. //// 阵营判断
  786. //if(info.UType == UnitType.TYPE_MONSTER && force > 1)
  787. //{
  788. // add.flag = 1;
  789. //}
  790. queueEvent(add);
  791. }
  792. }
  793. catch (Exception err)
  794. {
  795. log.Warn("AddUnit catch :" + name + ", e:" + err);
  796. add.ErrorMessage = err.Message;
  797. return null;
  798. }
  799. finally
  800. {
  801. add.Sync = unit.GenSyncUnitInfo(true);
  802. }
  803. return unit;
  804. }
  805. }
  806. return null;
  807. }
  808. /** 获取场景单位异常信息 */
  809. private string GetZoneUnitInfo(int nMinNums = 50)
  810. {
  811. HashMap<int, int> mInfo = new HashMap<int, int>();
  812. foreach (InstanceUnit obj in mObjects.Units)
  813. {
  814. mInfo.Put(obj.Info.ID, mInfo.Get(obj.Info.ID) + 1);
  815. }
  816. string finalStr = "";
  817. foreach(int unitID in mInfo.Keys)
  818. {
  819. int count = mInfo.Get(unitID);
  820. if (count < nMinNums)
  821. {
  822. continue;
  823. }
  824. finalStr = finalStr + (unitID) + "-" + count + ", ";
  825. }
  826. return finalStr;
  827. }
  828. public InstanceItem AddItem(ItemTemplate template, string name, float x, float y, float direction, int force, string disPlayName,
  829. out AddItemEvent add, InstanceUnit creater,int from)
  830. {
  831. add = null;
  832. if (mTryAddItem != null && !mTryAddItem.Invoke(template))
  833. {
  834. //log.Info(string.Format("Zone item TryAdd max: {0}, {1}", this.mSceneType, template.TemplateID));
  835. return null;
  836. }
  837. InstanceItem ret = TemplateManager.Factory.CreateItem(this, template, name, force, creater, disPlayName,from);
  838. ret.setPos(x, y);
  839. if (ret.tryAdd(x, y, direction))
  840. {
  841. mObjects.AddObject(ret);
  842. this.LastCreatedInstanceItem = ret;
  843. add = new AddItemEvent();
  844. add.sender = ret;
  845. if (ret.ClientVisible)
  846. {
  847. queueEvent(add);
  848. }
  849. try
  850. {
  851. ret.onAdded(this);
  852. if (mItemAdded != null)
  853. mItemAdded.Invoke(this, ret, creater);
  854. }
  855. catch (Exception err)
  856. {
  857. log.Warn("AddItem: " + template.ID + ", catch: " + err);
  858. add.ErrorMessage = err.Message;
  859. return null;
  860. }
  861. finally
  862. {
  863. add.Sync = ret.GenSyncItemInfo(true, null);
  864. }
  865. return ret;
  866. }
  867. return null;
  868. }
  869. public InstanceItem AddItem(ItemTemplate template, string name, float x, float y, float direction, int force, string disPlayName, InstanceUnit creater,int from=0)
  870. {
  871. AddItemEvent add;
  872. return AddItem(template, name, x, y, direction, force, disPlayName, out add, creater,from);
  873. }
  874. /// <summary>
  875. /// 添加一个法术或飞行道具
  876. /// </summary>
  877. /// <param name="template"></param>
  878. /// <param name="launch"></param>
  879. /// <param name="sender"></param>
  880. /// <param name="launcher">此法术的最初发起者</param>
  881. /// <param name="target_obj_id"></param>
  882. /// <param name="targetPos"></param>
  883. /// <param name="startX"></param>
  884. /// <param name="startY"></param>
  885. /// <param name="direction"></param>
  886. /// <param name="chain"></param>
  887. /// <returns></returns>
  888. public InstanceSpell AddSpell(
  889. XmdsSkillType fromSkillType,
  890. SpellTemplate template,
  891. LaunchSpell launch,
  892. InstanceZoneObject sender,
  893. InstanceUnit launcher,
  894. uint target_obj_id,
  895. Vector2 targetPos,
  896. float startX,
  897. float startY,
  898. float direction,
  899. SpellChainLevelInfo chain = null,
  900. int actionIndex = -1,
  901. int maxAffectUnit = 0,
  902. Dictionary<uint, InstanceUnit> damageList = null,
  903. int spellIndex = 0,
  904. JSGCreateSpellData createData = null)
  905. {
  906. if (template != null && sender != null)
  907. {
  908. InstanceUnit target = getUnit(target_obj_id);
  909. switch (template.MType)
  910. {
  911. // case SpellTemplate.MotionType.Missile:
  912. // if (target == null)
  913. // {
  914. // return null;
  915. // }
  916. // break;
  917. case SpellTemplate.MotionType.BindingTarget:
  918. if (target == null)
  919. {
  920. return null;
  921. }
  922. startX = target.X;
  923. startY = target.Y;
  924. break;
  925. case SpellTemplate.MotionType.SelectTarget:
  926. if (targetPos != null)
  927. {
  928. startX = targetPos.X;
  929. startY = targetPos.Y;
  930. }
  931. break;
  932. case SpellTemplate.MotionType.SeekerMissile:
  933. case SpellTemplate.MotionType.SeekerSelectTarget:
  934. {
  935. target = null;
  936. target_obj_id = 0;
  937. }
  938. break;
  939. case SpellTemplate.MotionType.Chain:
  940. if (target == null)
  941. {
  942. return null;
  943. }
  944. break;
  945. case SpellTemplate.MotionType.Cannon:
  946. if (target == null && targetPos == null)
  947. {
  948. targetPos = new Vector2(startX, startY);
  949. }
  950. break;
  951. }
  952. // 创建实体单位
  953. //InstanceSpell ret = new InstanceSpell(this, template, launch, launcher, sender, chainLevel);
  954. InstanceSpell ret = TemplateManager.Factory.CreateSpell(this, template, launch, launcher, sender, fromSkillType, damageList, spellIndex, createData);
  955. //ret.Direction = direction;
  956. ret.BindActionIndex = actionIndex;
  957. ret.MaxAffectUnit = (maxAffectUnit == 0) ? ret.Info.MaxAffectUnit : maxAffectUnit;
  958. ret.faceTo(direction);
  959. ret.setChainInfo(chain);
  960. ret.setTargetPos(targetPos);
  961. ret.setTarget(target);
  962. // 存入单位列表
  963. float xChanage, yChange;
  964. launch.GetXModify(launcher, out xChanage, out yChange);
  965. if (ret.tryAdd(startX + xChanage, startY + yChange, direction))
  966. {
  967. //System.Console.WriteLine("--AddSpell: " + ret.Info.ID + ", " + ret.ID);
  968. launcher.Virtual.DispatchSendSpellOverEvent(launch, template, ret.X, ret.Y);
  969. mObjects.AddObject(ret);
  970. this.LastLaunchSpell = ret.Info;
  971. ret.onAdded(this);
  972. if (ret.ClientVisible)
  973. {
  974. // 产生事件
  975. AddSpellEvent evt = new AddSpellEvent(ret);
  976. evt.sender = ret;
  977. queueEvent(evt);
  978. }
  979. return ret;
  980. }
  981. }
  982. return null;
  983. }
  984. // 移除一个单位
  985. public bool RemoveObject(InstanceZoneObject obj)
  986. {
  987. //Console.WriteLine("RemoveObject : " + obj.ID);
  988. if (mObjects.RemoveObject(obj))
  989. {
  990. obj.onRemoved(this);
  991. if (obj is InstanceUnit)
  992. {
  993. InstanceUnit unit = obj as InstanceUnit;
  994. mFormula.OnUnitRemoved(unit);
  995. if (mOnUnitRemoved != null)
  996. mOnUnitRemoved.Invoke(this, unit);
  997. }
  998. else if(obj is InstanceItem)
  999. {
  1000. if (this.mOnItemRemoved != null)
  1001. this.mOnItemRemoved.Invoke(this, (InstanceItem)obj);
  1002. }
  1003. if (obj.ClientVisible)
  1004. {
  1005. RemoveObjectEvent remove = new RemoveObjectEvent(obj.ID);
  1006. remove.sender = obj;
  1007. queueEvent(remove);
  1008. }
  1009. obj.Dispose();
  1010. return true;
  1011. }
  1012. return false;
  1013. }
  1014. public InstanceZoneObject RemoveObjectByID(uint oid)
  1015. {
  1016. var obj = mObjects.GetObject<InstanceZoneObject>(oid);
  1017. if (obj != null && RemoveObject(obj))
  1018. {
  1019. return obj;
  1020. }
  1021. return null;
  1022. }
  1023. public InstanceZoneObject RemoveUnitByID(uint unitTemplateId)
  1024. {
  1025. InstanceUnit obj = mObjects.GetUnit(unitTemplateId);
  1026. if (obj != null && RemoveObject(obj))
  1027. {
  1028. return obj;
  1029. }
  1030. return null;
  1031. }
  1032. public InstanceZoneObject RemoveSpellByLaunchIDAndSpellID(int launchId, int spellId)
  1033. {
  1034. InstanceSpell spell = mObjects.GetSpllByLanuchAndSpellId(launchId, spellId);
  1035. if(spell != null && RemoveObject(spell))
  1036. {
  1037. return spell;
  1038. }
  1039. return null;
  1040. }
  1041. public InstanceZoneObject RemoveItemByID(uint unitTemplateId)
  1042. {
  1043. InstanceItem obj = mObjects.GetItem(unitTemplateId);
  1044. if (obj != null && RemoveObject(obj))
  1045. {
  1046. Console.WriteLine("成功移除单位:" + unitTemplateId);
  1047. return obj;
  1048. }
  1049. return null;
  1050. }
  1051. public int GetZoneKingID()
  1052. {
  1053. return this.mKingID;
  1054. }
  1055. public string GetBindGameSrvID()
  1056. {
  1057. return this.mBindGameSrvId;
  1058. }
  1059. //----------------------------------------------------------------------------------------------------------------------------------------
  1060. private class InstanceZoneObjectMap
  1061. {
  1062. private class DirtyList<K, T> where T : InstanceZoneObject
  1063. {
  1064. private static Logger log = LoggerFactory.GetLogger("DirtyList");
  1065. private bool dirty = true;
  1066. private List<T> mObjectsCollection = new List<T>();
  1067. private HashMap<K, T> mObjects = new HashMap<K, T>();
  1068. public int Count { get { return mObjects.Count; } }
  1069. public void Add(K key, T obj)
  1070. {
  1071. dirty = true;
  1072. mObjects.Add(key, obj);
  1073. }
  1074. public void Put(K key, T obj)
  1075. {
  1076. dirty = true;
  1077. mObjects.Put(key, obj);
  1078. }
  1079. public bool Remove(K key)
  1080. {
  1081. if (mObjects.Remove(key))
  1082. {
  1083. dirty = true;
  1084. return true;
  1085. }
  1086. return false;
  1087. }
  1088. public void Dispose()
  1089. {
  1090. mObjectsCollection.Clear();
  1091. mObjects.Clear();
  1092. }
  1093. public T Get(K key)
  1094. {
  1095. return mObjects.Get(key);
  1096. }
  1097. public bool ContainsKey(K key)
  1098. {
  1099. return mObjects.ContainsKey(key);
  1100. }
  1101. public IEnumerable<T> GetCollection(string logFlag)
  1102. {
  1103. try
  1104. {
  1105. if (dirty)
  1106. {
  1107. dirty = false;
  1108. mObjectsCollection.Clear();
  1109. mObjectsCollection.AddRange(mObjects.Values);
  1110. }
  1111. return mObjectsCollection;
  1112. }
  1113. catch (Exception err)
  1114. {
  1115. log.Warn("GetCollectioncatch:" + logFlag + ", CollectCnt: " + mObjectsCollection.Count +
  1116. ", mObjectsCnt: " + mObjects.Count + ", e:" + err);
  1117. }
  1118. return mObjects.Values;
  1119. }
  1120. }
  1121. private DirtyList<uint, InstanceZoneObject> mObjects = new DirtyList<uint, InstanceZoneObject>();
  1122. private DirtyList<uint, InstanceUnit> mObjects_MirrorUnits = new DirtyList<uint, InstanceUnit>();
  1123. private DirtyList<uint, InstanceSpell> mObjects_MirrorSpells = new DirtyList<uint, InstanceSpell>();
  1124. private DirtyList<uint, InstanceItem> mObjects_MirrorItems = new DirtyList<uint, InstanceItem>();
  1125. private DirtyList<string, InstancePlayer> mObjects_MirrorPlayers = new DirtyList<string, InstancePlayer>();
  1126. private string logFlag = "";
  1127. public InstanceZoneObjectMap(string logFlag)
  1128. {
  1129. this.logFlag = logFlag;
  1130. }
  1131. internal void Refresh()
  1132. {
  1133. //mObjects.Refresh();
  1134. //mObjects_MirrorUnits.Refresh();
  1135. //mObjects_MirrorSpells.Refresh();
  1136. //mObjects_MirrorItems.Refresh();
  1137. //mObjects_MirrorPlayers.Refresh();
  1138. }
  1139. public void AddObject(InstanceZoneObject obj)
  1140. {
  1141. mObjects.Add(obj.ID, obj);
  1142. if (obj is InstanceUnit)
  1143. {
  1144. mObjects_MirrorUnits.Add(obj.ID, obj as InstanceUnit);
  1145. }
  1146. else if (obj is InstanceSpell)
  1147. {
  1148. mObjects_MirrorSpells.Add(obj.ID, obj as InstanceSpell);
  1149. }
  1150. else if (obj is InstanceItem)
  1151. {
  1152. mObjects_MirrorItems.Add(obj.ID, obj as InstanceItem);
  1153. }
  1154. if (obj is InstancePlayer)
  1155. {
  1156. var p = obj as InstancePlayer;
  1157. mObjects_MirrorPlayers.Put(p.PlayerUUID, p);
  1158. }
  1159. }
  1160. public bool RemoveObject(InstanceZoneObject obj)
  1161. {
  1162. if (mObjects.Remove(obj.ID))
  1163. {
  1164. if (obj is InstanceUnit)
  1165. {
  1166. mObjects_MirrorUnits.Remove(obj.ID);
  1167. }
  1168. else if (obj is InstanceSpell)
  1169. {
  1170. mObjects_MirrorSpells.Remove(obj.ID);
  1171. }
  1172. else if (obj is InstanceItem)
  1173. {
  1174. mObjects_MirrorItems.Remove(obj.ID);
  1175. }
  1176. if (obj is InstancePlayer)
  1177. {
  1178. var p = obj as InstancePlayer;
  1179. mObjects_MirrorPlayers.Remove(p.PlayerUUID);
  1180. }
  1181. return true;
  1182. }
  1183. return false;
  1184. }
  1185. private InstanceZoneObject GetObject(uint id)
  1186. {
  1187. return mObjects.Get(id);
  1188. }
  1189. public bool ContainsObject(InstanceZoneObject obj)
  1190. {
  1191. return mObjects.ContainsKey(obj.ID);
  1192. }
  1193. public bool ContainsObjectByKey(uint id)
  1194. {
  1195. return mObjects.ContainsKey(id);
  1196. }
  1197. public void Dispose()
  1198. {
  1199. mObjects.Dispose();
  1200. mObjects_MirrorUnits.Dispose();
  1201. mObjects_MirrorSpells.Dispose();
  1202. mObjects_MirrorItems.Dispose();
  1203. mObjects_MirrorPlayers.Dispose();
  1204. }
  1205. public T GetObject<T>(uint id) where T : InstanceZoneObject
  1206. {
  1207. Type type = typeof(T);
  1208. if (type.IsSubclassOf(typeof(InstanceUnit)))
  1209. {
  1210. return mObjects_MirrorUnits.Get(id) as T;
  1211. }
  1212. else if (type.IsSubclassOf(typeof(InstanceSpell)))
  1213. {
  1214. return mObjects_MirrorSpells.Get(id) as T;
  1215. }
  1216. else if (type.IsSubclassOf(typeof(InstanceItem)))
  1217. {
  1218. return mObjects_MirrorItems.Get(id) as T;
  1219. }
  1220. else
  1221. {
  1222. return mObjects.Get(id) as T;
  1223. }
  1224. }
  1225. public InstanceUnit GetUnit(uint unitTemplateId)
  1226. {
  1227. foreach (InstanceUnit obj in mObjects_MirrorUnits.GetCollection(logFlag))
  1228. {
  1229. if (obj.Info.ID == unitTemplateId)
  1230. {
  1231. return obj;
  1232. }
  1233. }
  1234. return null;
  1235. }
  1236. public InstanceSpell GetSpllByLanuchAndSpellId(int launchId, int spellId)
  1237. {
  1238. foreach (InstanceSpell obj in mObjects_MirrorSpells.GetCollection(logFlag))
  1239. {
  1240. if (obj.Info.ID == spellId && obj.LauncherID == launchId)
  1241. {
  1242. return obj;
  1243. }
  1244. }
  1245. return null;
  1246. }
  1247. public InstanceItem GetItem(uint itemId)
  1248. {
  1249. return mObjects_MirrorItems.Get(itemId);
  1250. }
  1251. public InstancePlayer GetPlayer(string uuid)
  1252. {
  1253. return mObjects_MirrorPlayers.Get(uuid);
  1254. }
  1255. public int ObjectsCount { get { return mObjects.Count; } }
  1256. public IEnumerable<InstanceZoneObject> Objects { get { return mObjects.GetCollection(logFlag); } }
  1257. public int UnitsCount { get { return mObjects_MirrorUnits.Count; } }
  1258. public IEnumerable<InstanceUnit> Units { get { return mObjects_MirrorUnits.GetCollection(logFlag); } }
  1259. public int SpellsCount { get { return mObjects_MirrorSpells.Count; } }
  1260. public IEnumerable<InstanceSpell> Spells { get { return mObjects_MirrorSpells.GetCollection(logFlag); } }
  1261. public int ItemsCount { get { return mObjects_MirrorItems.Count; } }
  1262. public IEnumerable<InstanceItem> Items { get { return mObjects_MirrorItems.GetCollection(logFlag); } }
  1263. public int PlayersCount { get { return mObjects_MirrorPlayers.Count; } }
  1264. public IEnumerable<InstancePlayer> Players { get { return mObjects_MirrorPlayers.GetCollection(logFlag); } }
  1265. }
  1266. #endregion
  1267. //------------------------------------------------------------------------------------
  1268. #region CALL_BACK
  1269. internal void cb_unitDamageCallBack(InstanceUnit target, InstanceUnit attacker, int reduceHP, AttackSource source)
  1270. {
  1271. LastHittedUnit = target;
  1272. LastAttackUnit = attacker;
  1273. if (attacker != null)
  1274. attacker.callback_onAttack(this, target, reduceHP, source);
  1275. if (target != null)
  1276. target.callback_onDamage(this, attacker, reduceHP, source);
  1277. if (mOnUnitDamage != null)
  1278. mOnUnitDamage.Invoke(this, target, attacker, reduceHP, source);
  1279. }
  1280. internal void cb_unitDeadCallBack(InstanceUnit obj, InstanceUnit attacker)
  1281. {
  1282. statisticForceDead(obj);
  1283. LastHittedUnit = obj;
  1284. LastKilledUnit = obj;
  1285. //if (attacker == null)
  1286. // attacker = obj;
  1287. LastAttackUnit = attacker;
  1288. obj.doDead(attacker);
  1289. if(attacker != null)
  1290. {
  1291. obj.deadDropItems(attacker.Force);
  1292. attacker.CurrentMoney += obj.Info.DropMoney;
  1293. }
  1294. mFormula.OnUnitDead(obj, attacker);
  1295. obj.callback_onDead(this, attacker);
  1296. if (mOnUnitDead != null)
  1297. mOnUnitDead.Invoke(this, obj, attacker);
  1298. obj.mProcessDeadCallbackTime = CommonLang.CUtils.localTimeMS + 1000;
  1299. }
  1300. internal void cb_unitActivatedCallBack(InstanceUnit obj)
  1301. {
  1302. nearChange(obj);
  1303. LastActivatedUnit = obj;
  1304. obj.callback_onActivated(this);
  1305. if (mOnUnitActivated != null)
  1306. mOnUnitActivated.Invoke(this, obj);
  1307. }
  1308. internal void cb_unitRebirthCallBack(InstanceUnit obj)
  1309. {
  1310. LastRebirthUnit = obj;
  1311. obj.callback_onRebirth(this);
  1312. if (mOnUnitRebirth != null)
  1313. mOnUnitRebirth.Invoke(this, obj);
  1314. }
  1315. internal void cb_unitGotInventoryItemCallBack(InstanceUnit obj, ItemTemplate item, int count)
  1316. {
  1317. LastUnitGotInventoryItem = item;
  1318. obj.callback_onGotInventoryItem(this, item);
  1319. if (mOnUnitGotInventoryItem != null)
  1320. mOnUnitGotInventoryItem.Invoke(this, obj, item, count);
  1321. }
  1322. internal void cb_unitLostInventoryItemCallBack(InstanceUnit obj, ItemTemplate item, int count)
  1323. {
  1324. LastUnitLostInventoryItem = item;
  1325. obj.callback_onLostInventoryItem(this, item);
  1326. if (mOnUnitLostInventoryItem != null)
  1327. mOnUnitLostInventoryItem.Invoke(this, obj, item, count);
  1328. }
  1329. internal int cb_unitGotInstanceItemCallBack(InstanceUnit obj, InstanceItem item)
  1330. {
  1331. LastUnitGotInstanceItem = item;
  1332. obj.callback_onGotInstanceItem(this, item);
  1333. short times = 0;
  1334. if (mOnUnitGotInstanceItem != null)
  1335. {
  1336. InstancePlayer player = (obj as InstancePlayer);
  1337. if (player == null)
  1338. {
  1339. return 0;
  1340. }
  1341. if (item.unitPickInfo != null)
  1342. {
  1343. if (item.Info.maxPickTimes > 0)
  1344. {
  1345. times = item.unitPickInfo.Get(player.PlayerUUID);
  1346. if (times >= item.Info.maxPickTimes)
  1347. {
  1348. player.Virtual.SendMsgToClient(XmdsConstConfig.TIPS_PICK_MAX);
  1349. return item.Info.maxPickTimes;
  1350. }
  1351. }
  1352. item.unitPickInfo.Put(player.PlayerUUID, ++times);
  1353. item.TotalPickTimes++;
  1354. }
  1355. mOnUnitGotInstanceItem.Invoke(this, obj, item);
  1356. }
  1357. return times;
  1358. }
  1359. internal void cb_unitUseItemCallBack(InstanceUnit obj, ItemTemplate item, InstanceUnit item_creater)
  1360. {
  1361. LastUnitUseItem = item;
  1362. obj.callback_onUseItem(this, item, item_creater);
  1363. if (mOnUnitUseItem != null)
  1364. mOnUnitUseItem.Invoke(this, obj, item, item_creater);
  1365. }
  1366. internal void cb_unitGotBuffCallBack(InstanceUnit obj, InstanceUnit.BuffState buff)
  1367. {
  1368. LastUnitGotBuff = buff.Data;
  1369. obj.callback_onGotBuff(this, buff);
  1370. if (mOnUnitGotBuff != null)
  1371. mOnUnitGotBuff.Invoke(this, obj, buff);
  1372. }
  1373. internal void cb_unitLostBuffCallBack(InstanceUnit obj, InstanceUnit.BuffState buff)
  1374. {
  1375. obj.callback_onLostBuff(this, buff);
  1376. if (mOnUnitLostBuff != null)
  1377. mOnUnitLostBuff.Invoke(this, obj, buff);
  1378. }
  1379. internal void cb_unitGotMoneyCallBack(InstanceUnit obj, int add_money)
  1380. {
  1381. if (mOnUnitGotMoney != null)
  1382. {
  1383. mOnUnitGotMoney.Invoke(obj, add_money);
  1384. }
  1385. }
  1386. internal void cb_unitPickUnitCallBack(InstanceUnit src, InstanceUnit pickable)
  1387. {
  1388. LastPickableUnit = pickable;
  1389. if (mOnUnitPickUnit != null)
  1390. {
  1391. mOnUnitPickUnit.Invoke(this, src, pickable);
  1392. }
  1393. }
  1394. public void cb_unitOutBattleCallBack(InstanceUnit obj)
  1395. {
  1396. if (mOnUnitOutBattle != null)
  1397. {
  1398. mOnUnitOutBattle.Invoke(this, obj);
  1399. }
  1400. }
  1401. internal bool cb_unitTryPickItem(InstanceUnit unit, InstanceItem item)
  1402. {
  1403. LastPickingItem = item;
  1404. LastPickingItemUnit = unit;
  1405. bool ret = true;
  1406. if (mTryPickItem != null)
  1407. {
  1408. foreach (TryPickItemHandler trypick in mTryPickItem.GetInvocationList())
  1409. {
  1410. if (!trypick.Invoke(this, unit, item))
  1411. {
  1412. ret = false;
  1413. }
  1414. }
  1415. }
  1416. return ret;
  1417. }
  1418. internal void cb_unitFinishPickItem(InstanceUnit unit, InstanceItem item)
  1419. {
  1420. if (mFinishPickItem != null)
  1421. {
  1422. mFinishPickItem.Invoke(this, unit, item);
  1423. }
  1424. }
  1425. internal void cb_unitLaunchSkill(InstanceUnit unit, CommonAI.Zone.Instance.InstanceUnit.SkillState ss)
  1426. {
  1427. LastLaunchSkill = ss.Data;
  1428. LastLaunchSkillUnit = unit;
  1429. if (mOnUnitLaunchSkill != null)
  1430. {
  1431. mOnUnitLaunchSkill.Invoke(this, unit, ss);
  1432. }
  1433. }
  1434. internal void cb_playerReady(InstancePlayer player)
  1435. {
  1436. if (mPlayerReady != null)
  1437. {
  1438. mPlayerReady.Invoke(player);
  1439. }
  1440. }
  1441. #endregion
  1442. //-------------------------------------------------------------------------------------------
  1443. #region UNIT_ATTACK
  1444. /// <summary>
  1445. /// 获得两个对象是否是队友
  1446. /// </summary>
  1447. /// <param name="src"></param>
  1448. /// <param name="dst"></param>
  1449. /// <returns></returns>
  1450. public virtual bool IsTeammates(InstanceUnit src, InstanceUnit dst)
  1451. {
  1452. return false;
  1453. }
  1454. /// <summary>
  1455. /// 测试是否可见,单位间可交互(AOI)
  1456. /// </summary>
  1457. /// <param name="src"></param>
  1458. /// <param name="dst"></param>
  1459. /// <returns></returns>
  1460. public virtual bool IsVisibleAOI(InstanceZoneObject src, InstanceZoneObject dst)
  1461. {
  1462. if (src.AoiStatus == dst.AoiStatus)
  1463. {
  1464. if (dst is InstanceUnit)
  1465. {
  1466. return (dst as InstanceUnit).IsVisible;
  1467. }
  1468. return true;
  1469. }
  1470. else if (src.AoiStatus != null)
  1471. {
  1472. return src.AoiStatus.CanSeeOther;
  1473. }
  1474. else if (dst.AoiStatus != null)
  1475. {
  1476. return dst.AoiStatus.CanSeeMe;
  1477. }
  1478. return false;
  1479. }
  1480. /// <summary>
  1481. /// 测试是否可攻击
  1482. /// </summary>
  1483. /// <param name="src"></param>
  1484. /// <param name="target"></param>
  1485. /// <param name="expectTarget"></param>
  1486. /// <param name="reason"></param>
  1487. /// <param name="weapon"></param>
  1488. /// <returns></returns>
  1489. public virtual bool IsAttackable(InstanceUnit src, InstanceUnit target, SkillTemplate.CastTarget expectTarget, AttackReason reason, ITemplateData weapon)
  1490. {
  1491. if(src == null || target == null)
  1492. {
  1493. return false;
  1494. }
  1495. if (!IsVisibleAOI(src, target))
  1496. {
  1497. return false;
  1498. }
  1499. if (target.CanWhiplashDeadBody)
  1500. {
  1501. if (!target.IsAttackable)
  1502. return false;
  1503. if (!target.IsVisible)
  1504. return false;
  1505. if (target.IsInvincible)
  1506. return false;
  1507. }
  1508. else
  1509. {
  1510. if (!target.IsActive)
  1511. return false;
  1512. if (!target.IsVisible)
  1513. return false;
  1514. if (target.IsInvincible)
  1515. return false;
  1516. }
  1517. switch (expectTarget)
  1518. {
  1519. case SkillTemplate.CastTarget.Enemy:
  1520. return src.Force != target.Force;
  1521. case SkillTemplate.CastTarget.PetForMaster:
  1522. if (src is InstancePet)
  1523. {
  1524. return (src as InstancePet).Master == target;
  1525. }
  1526. return false;
  1527. case SkillTemplate.CastTarget.Alias:
  1528. return (src != target) && (src.Force == target.Force);
  1529. case SkillTemplate.CastTarget.AlliesIncludeSelf:
  1530. return (src.Force == target.Force);
  1531. case SkillTemplate.CastTarget.AlliesExcludeSelf:
  1532. return (src != target) && (src.Force == target.Force);
  1533. case SkillTemplate.CastTarget.EveryOne:
  1534. return true;
  1535. case SkillTemplate.CastTarget.EveryOneExcludeSelf:
  1536. return (src != target);
  1537. case SkillTemplate.CastTarget.Self:
  1538. return src == target;
  1539. case SkillTemplate.CastTarget.EnemyAndSelf:
  1540. return src.Force != target.Force || src == target;
  1541. case SkillTemplate.CastTarget.NA:
  1542. default:
  1543. return false;
  1544. }
  1545. }
  1546. /// <summary>
  1547. /// 扫描所有可攻击对象
  1548. /// </summary>
  1549. /// <param name="src"></param>
  1550. /// <param name="list"></param>
  1551. /// <param name="expectTarget"></param>
  1552. /// <param name="reason"></param>
  1553. /// <param name="weapon"></param>
  1554. public void getAttackableUnits(InstanceUnit src, List<InstanceUnit> list, SkillTemplate.CastTarget expectTarget, AttackReason reason, ITemplateData weapon)
  1555. {
  1556. for (int i = list.Count - 1; i >= 0; --i)
  1557. {
  1558. InstanceUnit o = list[i];
  1559. if (!IsAttackable(src, o, expectTarget, reason, weapon))
  1560. {
  1561. list.RemoveAt(i);
  1562. }
  1563. }
  1564. }
  1565. /// <summary>
  1566. /// 对单个单位攻击。
  1567. /// </summary>
  1568. /// <param name="src"></param>
  1569. /// <param name="attack"></param>
  1570. /// <param name="target"></param>
  1571. /// <param name="expectTarget">判断IsAttackable</param>
  1572. /// <returns></returns>
  1573. public bool unitAttackSingle(
  1574. InstanceUnit src,
  1575. AttackSource attack,
  1576. InstanceUnit target,
  1577. SkillTemplate.CastTarget expectTarget)
  1578. {
  1579. if (IsAttackable(src, target, expectTarget, AttackReason.Attack, attack.Weapon))
  1580. {
  1581. target.doHitAttack(src, attack);
  1582. return true;
  1583. }
  1584. return false;
  1585. }
  1586. /// <summary>
  1587. /// 某个单位对指定列表里的 IsAttackable 单位发起攻击。
  1588. /// 此操作会修改List
  1589. /// </summary>
  1590. /// <param name="src"></param>
  1591. /// <param name="attack"></param>
  1592. /// <param name="list">调用完成后,列表中未命中单位会自动移除。</param>
  1593. /// <param name="expectTarget">判断IsAttackable</param>
  1594. /// <returns></returns>
  1595. public int unitAttack(
  1596. InstanceUnit src,
  1597. AttackSource attack,
  1598. List<InstanceUnit> list,
  1599. SkillTemplate.CastTarget expectTarget)
  1600. {
  1601. int count = 0;
  1602. for (int i = list.Count - 1; i >= 0; --i)
  1603. {
  1604. InstanceUnit o = list[i];
  1605. if (IsAttackable(src, o, expectTarget, AttackReason.Attack, attack.Weapon))
  1606. {
  1607. o.doHitAttack(src, attack);
  1608. count++;
  1609. }
  1610. else
  1611. {
  1612. list.RemoveAt(i);
  1613. }
  1614. }
  1615. return count;
  1616. }
  1617. /// <summary>
  1618. /// 直接对列表中的单位攻击,不做任何判断。
  1619. /// </summary>
  1620. /// <param name="src"></param>
  1621. /// <param name="attack"></param>
  1622. /// <param name="list"></param>
  1623. public int unitAttackDirect(
  1624. InstanceUnit src,
  1625. AttackSource attack,
  1626. List<InstanceUnit> list)
  1627. {
  1628. int count = 0;
  1629. for (int i = list.Count - 1; i >= 0; --i)
  1630. {
  1631. InstanceUnit o = list[i];
  1632. o.doHitAttack(src, attack);
  1633. count++;
  1634. }
  1635. return count;
  1636. }
  1637. /// <summary>
  1638. /// 某个单位发起周身攻击
  1639. /// </summary>
  1640. /// <param name="src"></param>
  1641. /// <param name="attack"></param>
  1642. /// <param name="range"></param>
  1643. /// <param name="expectTarget"></param>
  1644. /// <returns></returns>
  1645. public int unitAttackRound(
  1646. InstanceUnit src,
  1647. AttackSource attack,
  1648. float range,
  1649. SkillTemplate.CastTarget expectTarget)
  1650. {
  1651. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1652. {
  1653. getObjectsRoundRange<InstanceUnit>(
  1654. Collider.Object_HitBody_TouchRound,
  1655. src.X, src.Y, range,
  1656. list, src.AoiStatus);
  1657. return unitAttack(src, attack, list, expectTarget);
  1658. }
  1659. }
  1660. /// <summary>
  1661. /// 某个单位发起扇形范围攻击
  1662. /// </summary>
  1663. /// <param name="src"></param>
  1664. /// <param name="attack"></param>
  1665. /// <param name="direction"></param>
  1666. /// <param name="range"></param>
  1667. /// <param name="angle"></param>
  1668. /// <param name="expectTarget"></param>
  1669. /// <returns></returns>
  1670. public int unitAttackFan(
  1671. InstanceUnit src,
  1672. AttackSource attack,
  1673. float direction,
  1674. float range,
  1675. float angle,
  1676. SkillTemplate.CastTarget expectTarget)
  1677. {
  1678. float dr = angle / 2;
  1679. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1680. {
  1681. getObjectsFanRange<InstanceUnit>(
  1682. Collider.Object_HitBody_TouchFan,
  1683. src.X, src.Y, range,
  1684. direction - dr,
  1685. direction + dr,
  1686. list, src.AoiStatus);
  1687. return unitAttack(src, attack, list, expectTarget);
  1688. }
  1689. }
  1690. //-------------------------------------------------------------------------------------------------------
  1691. // 单位释放法术
  1692. //-------------------------------------------------------------------------------------------------------
  1693. public void unitLaunchSpell(
  1694. XmdsSkillType fromSkillType,
  1695. InstanceUnit launcher,
  1696. LaunchSpell launch,
  1697. float startX,
  1698. float startY,
  1699. uint targetUnitID = 0,
  1700. Vector2 targetPos = null, int actionIndex = -1, int maxAffectUnit = 0, float pointDir = 0)
  1701. {
  1702. if(launch == null)
  1703. {
  1704. log.Error("单位释放技能异常: " + launcher.Info.ID + ", " + new StackTrace().ToString());
  1705. return;
  1706. }
  1707. if (CUtils.RandomPercent(RandomN, launch.LaunchPercent))
  1708. {
  1709. float direction = pointDir == 0 ? launcher.Direction : pointDir;
  1710. if (targetPos != null)
  1711. {
  1712. //direction = MathVector.getDegree(startX, startY, targetPos.x, targetPos.y);
  1713. targetPos = (Vector2)targetPos.Clone();
  1714. }
  1715. SpellTemplate spell = Templates.getSpell(launch.SpellID);
  1716. if(spell == null)
  1717. {
  1718. log.Error("unitLaunchSpell找不到法术模板:" + launcher.PlayerUUID + ", " + launch.SpellID + ", SN: " + launch.SerialNumber);
  1719. return;
  1720. }
  1721. JSGCreateSpellData createData;
  1722. if (spell != null && launch.Count > 0 && mFormula.TryLaunchSpell(launcher, launch, ref spell, out createData, ref startX, ref startY))
  1723. {
  1724. SpellChainLevelInfo chain = null;
  1725. if (launch.ChainLevel > 0)
  1726. {
  1727. chain = new SpellChainLevelInfo(launch);
  1728. }
  1729. switch (launch.PType)
  1730. {
  1731. case LaunchSpell.PosType.POS_TYPE_FAN:
  1732. {
  1733. float startAngle = direction - launch.Angle / 2f;// + launch.StartAngle;
  1734. float interAngle = launch.Count > 0 ? launch.Angle / (launch.Count - 1) : 0;
  1735. for (int i = 0; i < launch.Count; i++)
  1736. {
  1737. AddSpell(fromSkillType, spell, launch, launcher, launcher,
  1738. targetUnitID, targetPos, startX, startY,
  1739. startAngle + interAngle * i, chain, actionIndex, maxAffectUnit);
  1740. }
  1741. }
  1742. break;
  1743. case LaunchSpell.PosType.POS_TYPE_TOSAMETARGET:
  1744. {
  1745. InstanceUnit target = SeekSpellAttackable(launcher, spell, launcher.AoiStatus, startX, startY, launch.SeekingTargetRange,
  1746. spell.ExpectTarget, SeekingExpect.Nearest, null);
  1747. if (target != null)
  1748. {
  1749. launcher.faceTo(target.X, target.Y);
  1750. launcher.SendForceSync();
  1751. targetPos = new Vector2(target.X, target.Y);
  1752. //Console.WriteLine("-------------targetPos 1 - " + target.X + ", " + target.Y);
  1753. //Console.WriteLine("-------------targetPos 2 - " + targetPos);
  1754. int[] index = { 0, -1, 1 };
  1755. float testAngle = (float)Math.Atan2(targetPos.Y - launcher.Y, targetPos.X - launcher.X);
  1756. float xBase = 3.0f;
  1757. float xAdd = (float)(xBase * Math.Sin(testAngle)); //角Dir的对边
  1758. float yAdd = (float)(xBase * Math.Cos(testAngle)); //Dir的邻边
  1759. for (int i = 0; i < launch.Count; i++)
  1760. {
  1761. float tempX = startX - xAdd * index[i];
  1762. float tempY = startY + yAdd * index[i];
  1763. float angle = (float)Math.Atan2(targetPos.Y - tempY, targetPos.X - tempX);
  1764. AddSpell(fromSkillType, spell, launch, launcher, launcher,
  1765. targetUnitID, targetPos, tempX, tempY,
  1766. angle, chain, actionIndex, maxAffectUnit);
  1767. }
  1768. }
  1769. else
  1770. {
  1771. int[] index = { 0, -1, 1 };
  1772. float xBase = 3.0f;
  1773. float xAdd = (float)(xBase * Math.Sin(direction)); //角Dir的对边
  1774. float yAdd = (float)(xBase * Math.Cos(direction)); //Dir的邻边
  1775. float[] startAngleTemp = { 0, launch.Angle, launch.Angle * 1.2f, launch.Angle * 1.4f, launch.Angle * 1.5f };
  1776. for (int i = 0; i < launch.Count; i++)
  1777. {
  1778. float tempX = startX - xAdd * index[i];
  1779. float tempY = startY + yAdd * index[i];
  1780. AddSpell(fromSkillType, spell, launch, launcher, launcher,
  1781. targetUnitID, targetPos, tempX, tempY,
  1782. direction - startAngleTemp[i] * index[i], chain, actionIndex, maxAffectUnit);
  1783. }
  1784. }
  1785. }
  1786. break;
  1787. case LaunchSpell.PosType.POS_TYPE_CYCLE:
  1788. {
  1789. float startAngle = direction + launch.StartAngle;
  1790. float interAngle = CMath.PI_MUL_2 / launch.Count;
  1791. InstanceSpell[] spellBrothers = null;
  1792. if (launch.Count > 1 && spell.MType == SpellTemplate.MotionType.Foxfire)
  1793. {
  1794. spellBrothers = new InstanceSpell[launch.Count];
  1795. }
  1796. for (int i = 0; i < launch.Count; i++)
  1797. {
  1798. var sb = AddSpell(fromSkillType, spell, launch, launcher, launcher,
  1799. targetUnitID, targetPos, startX, startY,
  1800. startAngle + interAngle * i, chain, actionIndex, maxAffectUnit);
  1801. if (spellBrothers != null)
  1802. {
  1803. spellBrothers[i] = sb;
  1804. sb.brothers = spellBrothers;
  1805. }
  1806. }
  1807. }
  1808. break;
  1809. case LaunchSpell.PosType.POS_TYPE_X:
  1810. {
  1811. float startAngle = direction + launch.StartAngle;
  1812. float[] interAngle = { launch.Angle, CMath.PI_F - launch.Angle, CMath.PI_F + launch.Angle, CMath.PI_F * 2 - launch.Angle };
  1813. Dictionary<uint, InstanceUnit> damageList = (spell.HitIntervalMS <= 0 ? new Dictionary<uint, InstanceUnit>() : null);
  1814. for (int i = 0; i < 4; i++)
  1815. {
  1816. AddSpell(fromSkillType, spell, launch, launcher, launcher, targetUnitID, targetPos,
  1817. startX, startY, startAngle + interAngle[i], chain, actionIndex, maxAffectUnit, damageList);
  1818. }
  1819. }
  1820. break;
  1821. case LaunchSpell.PosType.POS_TYPE_RANDOM_DIRECTION:
  1822. {
  1823. for (int i = 0; i < launch.Count; i++)
  1824. {
  1825. float d = (float)(random.NextDouble() * CMath.PI_MUL_2);
  1826. AddSpell(fromSkillType, spell, launch, launcher,
  1827. launcher, targetUnitID, targetPos, startX,
  1828. startY, d, chain, actionIndex, maxAffectUnit);
  1829. }
  1830. }
  1831. break;
  1832. case LaunchSpell.PosType.POS_TYPE_AREA:
  1833. using (var enemy_list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1834. {
  1835. SeekSpellAttackable(enemy_list, startX, startY, launcher, spell, launch, chain);
  1836. for (int i = 0; i < launch.Count && i < enemy_list.Count; i++)
  1837. {
  1838. AddSpell(fromSkillType, spell, launch, launcher, launcher, enemy_list[i].ID, null,
  1839. startX, startY, direction, chain, actionIndex, maxAffectUnit);
  1840. }
  1841. }
  1842. break;
  1843. case LaunchSpell.PosType.POS_TYPE_RANDOM_FOR_SPELL:
  1844. launch_randomTypeSpell(fromSkillType, spell, launcher, launch, chain, launcher, actionIndex);
  1845. break;
  1846. case LaunchSpell.PosType.POS_TYPE_RANDOM_POS:
  1847. launch_randomPosSpell(fromSkillType, spell, launcher, launch, chain, launcher, actionIndex);
  1848. break;
  1849. case LaunchSpell.PosType.POS_TYPE_MANY_CANNON:
  1850. launch_ManyCannon(fromSkillType, spell, launcher, launch, chain, launcher, targetUnitID, actionIndex, createData);
  1851. break;
  1852. case LaunchSpell.PosType.POS_TYPE_DEFAULT_SINGLE:
  1853. default:
  1854. {
  1855. AddSpell(fromSkillType, spell, launch, launcher, launcher,
  1856. targetUnitID, targetPos, startX, startY,
  1857. direction + launch.StartAngle, chain, actionIndex, maxAffectUnit);
  1858. }
  1859. break;
  1860. }
  1861. }
  1862. }
  1863. }
  1864. // 单位释放法术
  1865. public void spellLaunchSpell(
  1866. XmdsSkillType fromSkillType,
  1867. InstanceSpell sender,
  1868. LaunchSpell launch,
  1869. float startX,
  1870. float startY,
  1871. uint targetUnitID = 0,
  1872. Vector2 targetPos = null, int actionIndex = -1, int maxAffectUnit = 0)
  1873. {
  1874. switch (launch.SenderUnit)
  1875. {
  1876. case LaunchSpell.LaunchSpllSenderUnit.Launcher:
  1877. this.unitLaunchSpell(fromSkillType, sender.Launcher, launch, startX, startY, targetUnitID, targetPos);
  1878. return;
  1879. }
  1880. if (CUtils.RandomPercent(RandomN, launch.LaunchPercent))
  1881. {
  1882. SpellChainLevelInfo chain = sender.ChainInfo;
  1883. if (chain != null)
  1884. {
  1885. if (!chain.TryLaunch(launch.SpellID))
  1886. {
  1887. // chain is end //
  1888. return;
  1889. }
  1890. }
  1891. SpellTemplate spell = Templates.getSpell(launch.SpellID);
  1892. JSGCreateSpellData createData;
  1893. if (spell != null && launch.Count > 0 && mFormula.TryLaunchSpell(sender.Launcher, launch, ref spell, out createData, ref startX, ref startY))
  1894. {
  1895. float direction = sender.Direction;
  1896. if (targetPos != null)
  1897. {
  1898. direction = MathVector.getDegree(startX, startY, targetPos.X, targetPos.Y);
  1899. targetPos = (Vector2)targetPos.Clone();
  1900. }
  1901. switch (launch.PType)
  1902. {
  1903. case LaunchSpell.PosType.POS_TYPE_FAN:
  1904. {
  1905. float startAngle = direction - launch.Angle / 2f + launch.StartAngle;
  1906. float interAngle = launch.Count > 0 ? launch.Angle / (launch.Count - 1) : 0;
  1907. for (int i = 0; i < launch.Count; i++)
  1908. {
  1909. AddSpell(fromSkillType, spell, launch, sender, sender.Launcher,
  1910. targetUnitID, targetPos, startX, startY,
  1911. startAngle + interAngle * i, chain, actionIndex, maxAffectUnit);
  1912. }
  1913. }
  1914. break;
  1915. case LaunchSpell.PosType.POS_TYPE_CYCLE:
  1916. {
  1917. float startAngle = direction + launch.StartAngle;
  1918. float interAngle = CMath.PI_MUL_2 / launch.Count;
  1919. for (int i = 0; i < launch.Count; i++)
  1920. {
  1921. AddSpell(fromSkillType, spell, launch, sender, sender.Launcher,
  1922. targetUnitID, targetPos, startX, startY,
  1923. startAngle + interAngle * i, chain, actionIndex, maxAffectUnit);
  1924. }
  1925. }
  1926. break;
  1927. case LaunchSpell.PosType.POS_TYPE_X:
  1928. {
  1929. float startAngle = direction + launch.StartAngle;
  1930. float[] interAngle = { launch.Angle, CMath.PI_F - launch.Angle, CMath.PI_F + launch.Angle, CMath.PI_F * 2 - launch.Angle };
  1931. Dictionary<uint, InstanceUnit> damageList = (spell.HitIntervalMS <= 0 ? new Dictionary<uint, InstanceUnit>() : null);
  1932. for (int i = 0; i < launch.Count; i++)
  1933. {
  1934. AddSpell(fromSkillType, spell, launch, sender, sender.Launcher, targetUnitID,
  1935. targetPos, startX, startY, startAngle + interAngle[i], chain, actionIndex, maxAffectUnit, damageList);
  1936. }
  1937. }
  1938. break;
  1939. case LaunchSpell.PosType.POS_TYPE_RANDOM_FOR_SPELL:
  1940. launch_randomTypeSpell(fromSkillType, spell, sender, launch, chain, sender.Launcher, actionIndex);
  1941. break;
  1942. case LaunchSpell.PosType.POS_TYPE_MANY_CANNON:
  1943. launch_ManyCannon(fromSkillType, spell, sender, launch, chain, sender.Launcher, targetUnitID, actionIndex, createData);
  1944. break;
  1945. case LaunchSpell.PosType.POS_TYPE_RANDOM_POS:
  1946. launch_randomPosSpell(fromSkillType, spell, sender, launch, chain, sender.Launcher, actionIndex);
  1947. break;
  1948. case LaunchSpell.PosType.POS_TYPE_RANDOM_DIRECTION:
  1949. {
  1950. for (int i = 0; i < launch.Count; i++)
  1951. {
  1952. float d = (float)(random.NextDouble() * CMath.PI_MUL_2);
  1953. AddSpell(fromSkillType, spell, launch, sender, sender.Launcher,
  1954. targetUnitID, targetPos, startX, startY, d, chain, actionIndex, maxAffectUnit);
  1955. }
  1956. }
  1957. break;
  1958. case LaunchSpell.PosType.POS_TYPE_AREA:
  1959. using (var enemy_list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  1960. {
  1961. SeekSpellAttackable(enemy_list, startX, startY, sender.Launcher, spell, launch, chain);
  1962. for (int i = 0; i < launch.Count && i < enemy_list.Count; i++)
  1963. {
  1964. AddSpell(fromSkillType, spell, launch, sender, sender.Launcher,
  1965. enemy_list[i].ID, targetPos, startX, startY, direction, chain, actionIndex, maxAffectUnit);
  1966. }
  1967. }
  1968. break;
  1969. case LaunchSpell.PosType.POS_TYPE_DEFAULT_SINGLE:
  1970. default:
  1971. {
  1972. AddSpell(fromSkillType, spell, launch, sender, sender.Launcher,
  1973. targetUnitID, targetPos, startX, startY, direction, chain, actionIndex, maxAffectUnit);
  1974. }
  1975. break;
  1976. }
  1977. }
  1978. }
  1979. }
  1980. public void attackLaunchSpell(
  1981. XmdsSkillType fromSkillType,
  1982. InstanceUnit attacker,
  1983. InstanceUnit damage,
  1984. AttackSource source,
  1985. int serverExt = 0)
  1986. {
  1987. LaunchSpell launch = source.Attack.Spell;
  1988. if (launch == null)
  1989. return;
  1990. InstanceZoneObject sender;
  1991. if (source.FromSpellUnit != null)
  1992. {
  1993. sender = source.FromSpellUnit;
  1994. }
  1995. else
  1996. {
  1997. sender = attacker;
  1998. }
  1999. switch (launch.SenderUnit)
  2000. {
  2001. case LaunchSpell.LaunchSpllSenderUnit.Launcher:
  2002. sender = attacker;
  2003. break;
  2004. case LaunchSpell.LaunchSpllSenderUnit.DamagedUnit:
  2005. sender = damage;
  2006. break;
  2007. }
  2008. if (CUtils.RandomPercent(RandomN, launch.LaunchPercent))
  2009. {
  2010. float startX = damage.X;
  2011. float startY = damage.Y;
  2012. SpellTemplate spell = Templates.getSpell(launch.SpellID);
  2013. JSGCreateSpellData createData;
  2014. if (spell != null && launch.Count > 0 && mFormula.TryLaunchSpell(attacker, launch, ref spell, out createData, ref startX, ref startY))
  2015. {
  2016. SpellChainLevelInfo chain = null;
  2017. if (source.FromSpellUnit != null && source.FromSpellUnit.ChainInfo != null)
  2018. {
  2019. chain = source.FromSpellUnit.ChainInfo;
  2020. if (!chain.TryLaunch(launch.SpellID))
  2021. {
  2022. // chain is end //
  2023. return;
  2024. }
  2025. }
  2026. switch (launch.PType)
  2027. {
  2028. case LaunchSpell.PosType.POS_TYPE_FAN:
  2029. {
  2030. float startAngle = sender.Direction - launch.Angle / 2f + launch.StartAngle;
  2031. float interAngle = launch.Count > 0 ? launch.Angle / (launch.Count - 1) : 0;
  2032. for (int i = 0; i < launch.Count; i++)
  2033. {
  2034. AddSpell(fromSkillType, spell, launch, sender, attacker, damage.ID, null,
  2035. startX, startY, startAngle + interAngle * i, chain, serverExt);
  2036. }
  2037. }
  2038. break;
  2039. case LaunchSpell.PosType.POS_TYPE_CYCLE:
  2040. {
  2041. float startAngle = sender.Direction + launch.StartAngle;
  2042. float interAngle = CMath.PI_MUL_2 / launch.Count;
  2043. for (int i = 0; i < launch.Count; i++)
  2044. {
  2045. AddSpell(fromSkillType, spell, launch, sender, attacker, damage.ID, null,
  2046. startX, startY, startAngle + interAngle * i, chain, serverExt);
  2047. }
  2048. }
  2049. break;
  2050. case LaunchSpell.PosType.POS_TYPE_X:
  2051. {
  2052. float startAngle = sender.Direction + launch.StartAngle;
  2053. float[] interAngle = { launch.Angle, CMath.PI_F - launch.Angle, CMath.PI_F + launch.Angle, CMath.PI_F * 2 - launch.Angle };
  2054. Dictionary<uint, InstanceUnit> damageList = (spell.HitIntervalMS <= 0 ? new Dictionary<uint, InstanceUnit>() : null);
  2055. for (int i = 0; i < launch.Count; i++)
  2056. {
  2057. AddSpell(fromSkillType, spell, launch, sender, attacker, damage.ID, null,
  2058. startX, startY, startAngle + interAngle[i], chain, serverExt, 0, damageList);
  2059. }
  2060. }
  2061. break;
  2062. case LaunchSpell.PosType.POS_TYPE_RANDOM_FOR_SPELL:
  2063. launch_randomTypeSpell(fromSkillType, spell, sender, launch, chain, attacker, serverExt);
  2064. break;
  2065. case LaunchSpell.PosType.POS_TYPE_MANY_CANNON:
  2066. launch_ManyCannon(fromSkillType, spell, sender, launch, chain, attacker, damage.ID, serverExt, createData);
  2067. break;
  2068. case LaunchSpell.PosType.POS_TYPE_RANDOM_POS:
  2069. launch_randomPosSpell(fromSkillType, spell, sender, launch, chain, attacker, serverExt);
  2070. break;
  2071. case LaunchSpell.PosType.POS_TYPE_RANDOM_DIRECTION:
  2072. {
  2073. for (int i = 0; i < launch.Count; i++)
  2074. {
  2075. float d = (float)(random.NextDouble() * CMath.PI_MUL_2);
  2076. AddSpell(fromSkillType, spell, launch, sender, attacker, damage.ID, null,
  2077. startX, startY, d, chain, serverExt);
  2078. }
  2079. }
  2080. break;
  2081. case LaunchSpell.PosType.POS_TYPE_AREA:
  2082. using (var enemy_list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  2083. {
  2084. SeekSpellAttackable(enemy_list, startX, startY, attacker, spell, launch, chain);
  2085. for (int i = 0; i < launch.Count && i < enemy_list.Count; i++)
  2086. {
  2087. AddSpell(fromSkillType, spell, launch, sender, attacker, enemy_list[i].ID, null,
  2088. startX, startY, 0, chain, serverExt);
  2089. }
  2090. }
  2091. break;
  2092. case LaunchSpell.PosType.POS_TYPE_DEFAULT_SINGLE:
  2093. default:
  2094. {
  2095. AddSpell(fromSkillType, spell, launch, sender, attacker, damage.ID, null,
  2096. startX, startY, sender.Direction, chain, serverExt);
  2097. }
  2098. break;
  2099. }
  2100. }
  2101. }
  2102. }
  2103. private void launch_randomTypeSpell(XmdsSkillType fromSkillType, SpellTemplate spell, InstanceZoneObject sender,
  2104. LaunchSpell launch, SpellChainLevelInfo chain, InstanceUnit attacker, int serverExt = 0)
  2105. {
  2106. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  2107. {
  2108. attacker.Parent.getObjectsRoundRange<InstanceUnit>(
  2109. (obj, dx, dy, dr) =>
  2110. {
  2111. var u = obj as InstanceUnit;
  2112. //己方单位.
  2113. if ((attacker.IsPlayer && !u.IsPlayer) || (!attacker.IsPlayer && u.IsPlayer))
  2114. {
  2115. return CMath.includeRoundPoint(dx, dy, dr, u.X, u.Y);
  2116. }
  2117. return false;
  2118. },
  2119. attacker.X,
  2120. attacker.Y,
  2121. launch.SeekingTargetRange,
  2122. list, attacker.AoiStatus);
  2123. int maxCount = launch.Count == 0 ? list.Count : Math.Min(launch.Count, list.Count);
  2124. for (int i = 0; i < maxCount; i++)
  2125. {
  2126. float r = (float)(random.NextDouble() * spell.BodySize);
  2127. float a = (float)(random.NextDouble() * CMath.PI_MUL_2);
  2128. float x = (float)(list[i].X + Math.Cos(a) * r);
  2129. float y = (float)(list[i].Y + Math.Sin(a) * r);
  2130. float d = (float)(random.NextDouble() * CMath.PI_MUL_2);
  2131. AddSpell(fromSkillType, spell, launch, sender, attacker, 0, null,
  2132. x, y, d, chain, serverExt);
  2133. }
  2134. }
  2135. }
  2136. private void launch_randomPosSpell(XmdsSkillType fromSkillType, SpellTemplate spell, InstanceZoneObject sender,
  2137. LaunchSpell launch, SpellChainLevelInfo chain, InstanceUnit attacker, int serverExt = 0)
  2138. {
  2139. for (int i = 0; i < launch.Count; i++)
  2140. {
  2141. float x = (float)(random.NextDouble() * launch.SpellRange/2);
  2142. float y = (float)(random.NextDouble() * launch.SpellRange/2);
  2143. float d = (float)(random.NextDouble() * CMath.PI_MUL_2);
  2144. int randX = random.Next() % 2 == 0 ? 1 : -1;
  2145. int randY = random.Next() % 2 == 0 ? 1 : -1;
  2146. AddSpell(fromSkillType, spell, launch, sender, attacker, 0, null,
  2147. sender.X + x * randX, sender.Y + y * randY, d, chain, serverExt);
  2148. }
  2149. }
  2150. public InstanceSpell launch_ManyCannon(XmdsSkillType fromSkillType, SpellTemplate spell, InstanceZoneObject sender,
  2151. LaunchSpell launch, SpellChainLevelInfo chain, InstanceUnit attacker, uint targetUnitID, int serverExt, JSGCreateSpellData createData)
  2152. {
  2153. //float angleOffset = targetUnitID == 0 ? launch.StartAngle / 3 : launch.StartAngle;
  2154. float angleOffset = JSGModule.GetCurveStartAngleOffect(attacker, getUnit(targetUnitID), launch.StartAngle, spell.SeekingRange);
  2155. float startAngle = CMath.OpitimizeRadians(attacker.Direction) + angleOffset;
  2156. float launchX = attacker.X - (float)(1.0f * Math.Cos(attacker.Direction));
  2157. float launchY = attacker.Y - (float)(1.0f * Math.Sin(attacker.Direction));
  2158. Vector2 targetPos = JSGModule.GetCurveDefaultTargetPos(attacker, spell.SeekingRange);
  2159. //System.Console.WriteLine("targetPos: " + targetPos.X + ", " + targetPos.Y);
  2160. int totalCount = createData == null ? launch.Count : createData.mMaxSpellCount;
  2161. return AddSpell(fromSkillType, spell, launch, sender, attacker, targetUnitID, targetPos,
  2162. launchX, launchY, startAngle, chain, serverExt, 0, null, totalCount-1, createData);
  2163. }
  2164. public void spellSummonUnit(InstanceSpell summoner, SummonUnit summon)
  2165. {
  2166. float x = summoner.X;
  2167. float y = summoner.Y;
  2168. float radius = summoner.BodyBlockSize;
  2169. UnitInfo info = Templates.getUnit(summon.UnitTemplateID);
  2170. if (info.UType != UnitType.TYPE_SUMMON || info.LifeTimeMS <= 0)
  2171. {
  2172. log.Warn("召唤非召唤类单位1:" + summoner.ID + ", 召唤id: " + summon.UnitTemplateID);
  2173. return;
  2174. }
  2175. //UnitInfo un = (UnitInfo)info.Clone();
  2176. //un.UType = UnitInfo.UnitType.TYPE_SUMMON;
  2177. string name = null;
  2178. if (TemplateManager.Formula.TrySummonUnit(summoner.Launcher, summon, ref info, ref name))
  2179. {
  2180. for (int i = 0; i < summon.Count; i++)
  2181. {
  2182. float dx, dy, dr;
  2183. //float angle = (float)RandomN.NextDouble() * CMath.PI_MUL_2;
  2184. //float lengt = (float)RandomN.NextDouble() * radius;
  2185. //dx = x + (float)Math.Cos(angle) * lengt;
  2186. //dy = y + (float)Math.Sin(angle) * lengt;
  2187. //dr = (float)RandomN.NextDouble() * CMath.PI_MUL_2;
  2188. //召唤单位时判断当前位置能否行走,防止被召唤单位卡在地图里.Editor by Alex.
  2189. var pos = PathFinder.FindNearRandomMoveableNode(RandomN, x, y, radius, true);
  2190. if (pos == null)
  2191. {
  2192. dx = summoner.Launcher.X;
  2193. dy = summoner.Launcher.Y;
  2194. }
  2195. else
  2196. {
  2197. dx = pos.PosX;
  2198. dy = pos.PosY;
  2199. }
  2200. dr = summoner.Direction;
  2201. InstanceUnit unit = null;
  2202. if (!summoner.Launcher.IsActive)
  2203. {
  2204. unit = AddUnit(info, name, summoner.Launcher.Force, summon.UnitLevel, dx, dy, dr, null);
  2205. }
  2206. else
  2207. {
  2208. unit = AddUnit(info, name, summoner.Launcher.Force, summon.UnitLevel, dx, dy, dr, summoner.Launcher);
  2209. }
  2210. if (unit != null)
  2211. {
  2212. if (info.LifeTimeMS > 0)
  2213. {
  2214. AddTimeDelayMS(info.LifeTimeMS, (task) =>
  2215. {
  2216. unit.kill();
  2217. });
  2218. }
  2219. if (summon.Effect != null)
  2220. {
  2221. queueEvent(new AddEffectEvent(unit.ID, dx, dy, dr, summon.Effect));
  2222. }
  2223. }
  2224. }
  2225. }
  2226. }
  2227. public void unitSummonUnit(InstanceUnit summoner, SummonUnit summon)
  2228. {
  2229. float x = summoner.X;
  2230. float y = summoner.Y;
  2231. MathVector.movePolar(ref x, ref y, summoner.Direction, summoner.BodyBlockSize * 4);
  2232. float radius = summoner.BodyBlockSize * 2;
  2233. UnitInfo info = Templates.getUnit(summon.UnitTemplateID);
  2234. if (info.UType != UnitType.TYPE_SUMMON || info.LifeTimeMS <= 0)
  2235. {
  2236. log.Warn("召唤非召唤类单位2:" + summoner.ID + ", 召唤id: " + summon.UnitTemplateID);
  2237. return;
  2238. }
  2239. //UnitInfo un = (UnitInfo)info.Clone();
  2240. //un.UType = UnitInfo.UnitType.TYPE_SUMMON;
  2241. string name = null;
  2242. if (TemplateManager.Formula.TrySummonUnit(summoner, summon, ref info, ref name))
  2243. {
  2244. for (int i = 0; i < summon.Count; i++)
  2245. {
  2246. float angle = (float)RandomN.NextDouble() * CMath.PI_MUL_2;
  2247. float lengt = (float)RandomN.NextDouble() * radius;
  2248. float dx = x + (float)Math.Cos(angle) * lengt;
  2249. float dy = y + (float)Math.Sin(angle) * lengt;
  2250. float dr = (float)RandomN.NextDouble() * CMath.PI_MUL_2;
  2251. InstanceUnit unit = AddUnit(info, name, summoner.Force, summon.UnitLevel, dx, dy, dr, summoner);
  2252. if (unit != null)
  2253. {
  2254. if (info.LifeTimeMS > 0)
  2255. {
  2256. AddTimeDelayMS(info.LifeTimeMS, (task) =>
  2257. {
  2258. unit.kill();
  2259. });
  2260. }
  2261. if (summon.Effect != null)
  2262. {
  2263. queueEvent(new AddEffectEvent(unit.ID, dx, dy, dr, summon.Effect));
  2264. }
  2265. }
  2266. }
  2267. }
  2268. }
  2269. public InstanceUnit summonUnit(InstanceUnit summoner, UnitInfo info, string name, int level, float x, float y, float direction)
  2270. {
  2271. if (info.UType != UnitType.TYPE_SUMMON || info.LifeTimeMS <= 0)
  2272. {
  2273. log.Warn("召唤非召唤类单位3:" + summoner.ID + ", 召唤id: " + info.ID);
  2274. return null;
  2275. }
  2276. InstanceUnit unit = AddUnit(info, name, summoner.Force, level, x, y, direction, summoner);
  2277. if (unit != null)
  2278. {
  2279. if (info.LifeTimeMS > 0)
  2280. {
  2281. AddTimeDelayMS(info.LifeTimeMS, (task) =>
  2282. {
  2283. unit.kill();
  2284. });
  2285. }
  2286. }
  2287. return unit;
  2288. }
  2289. /// <summary>
  2290. /// 锁定范围内指定目标
  2291. /// </summary>
  2292. /// <param name="spell"></param>
  2293. /// <param name="X"></param>
  2294. /// <param name="Y"></param>
  2295. /// <param name="range"></param>
  2296. /// <param name="expectTarget"></param>
  2297. /// <param name="expectSeeking"></param>
  2298. /// <param name="chain"></param>
  2299. /// <returns></returns>
  2300. public virtual InstanceUnit SeekSpellAttackable(
  2301. InstanceUnit launcher,
  2302. SpellTemplate spellData,
  2303. ObjectAoiStatus aoiStatus,
  2304. float X, float Y, float range,
  2305. SkillTemplate.CastTarget expectTarget,
  2306. SpellTemplate.SeekingExpect expectSeeking,
  2307. SpellChainLevelInfo chain)
  2308. {
  2309. using (var list = ListObjectPool<InstanceUnit>.AllocAutoRelease())
  2310. {
  2311. getObjectsRoundRange<InstanceUnit>((InstanceZoneObject o, float x, float y, float r) =>
  2312. {
  2313. InstanceUnit u = o as InstanceUnit;
  2314. if (chain != null)
  2315. {
  2316. switch (expectSeeking)
  2317. {
  2318. case SpellTemplate.SeekingExpect.RandomIgnoreInChain:
  2319. case SpellTemplate.SeekingExpect.NearestIgnoreInChain:
  2320. case SpellTemplate.SeekingExpect.FarthestIgnoreInChain:
  2321. if (chain.ContainsTarget(u))
  2322. {
  2323. return false;
  2324. }
  2325. break;
  2326. default:
  2327. if (chain.LastTarget == u)
  2328. {
  2329. return false;
  2330. }
  2331. break;
  2332. }
  2333. }
  2334. if (IsAttackable(launcher, u, expectTarget, AttackReason.Look, spellData))
  2335. {
  2336. return CMath.intersectRound(x, y, r, o.X, o.Y, o.BodyHitSize);
  2337. }
  2338. return false;
  2339. }, X, Y, range, list, aoiStatus);
  2340. switch (expectSeeking)
  2341. {
  2342. case SpellTemplate.SeekingExpect.Random:
  2343. case SpellTemplate.SeekingExpect.RandomIgnoreInChain:
  2344. CUtils.RandomList(RandomN, list);
  2345. break;
  2346. case SpellTemplate.SeekingExpect.Nearest:
  2347. case SpellTemplate.SeekingExpect.NearestIgnoreInChain:
  2348. list.Sort(new ObjectSorterNearest<InstanceUnit>(X, Y));
  2349. break;
  2350. case SpellTemplate.SeekingExpect.Farthest:
  2351. case SpellTemplate.SeekingExpect.FarthestIgnoreInChain:
  2352. list.Sort(new ObjectSorterFarthest<InstanceUnit>(X, Y));
  2353. break;
  2354. }
  2355. if (list.Count > 0)
  2356. {
  2357. return list[0];
  2358. }
  2359. }
  2360. return null;
  2361. }
  2362. public virtual void SeekSpellAttackable(List<InstanceUnit> ret, float X, float Y,
  2363. InstanceUnit Launcher,
  2364. SpellTemplate spell,
  2365. LaunchSpell launch,
  2366. SpellChainLevelInfo chain)
  2367. {
  2368. getObjectsRoundRange<InstanceUnit>((InstanceZoneObject o, float x, float y, float r) =>
  2369. {
  2370. InstanceUnit u = o as InstanceUnit;
  2371. if (chain != null)
  2372. {
  2373. switch (launch.SeekingTargetExpect)
  2374. {
  2375. case SpellTemplate.SeekingExpect.RandomIgnoreInChain:
  2376. case SpellTemplate.SeekingExpect.NearestIgnoreInChain:
  2377. case SpellTemplate.SeekingExpect.FarthestIgnoreInChain:
  2378. if (chain.ContainsTarget(u))
  2379. {
  2380. return false;
  2381. }
  2382. break;
  2383. default:
  2384. if (chain.LastTarget == u)
  2385. {
  2386. return false;
  2387. }
  2388. break;
  2389. }
  2390. }
  2391. if (IsAttackable(Launcher, u, spell.ExpectTarget, AttackReason.Look, spell))
  2392. {
  2393. return CMath.intersectRound(x, y, r, o.X, o.Y, o.BodyHitSize);
  2394. }
  2395. return false;
  2396. }, X, Y, launch.SeekingTargetRange, ret, Launcher.AoiStatus);
  2397. switch (launch.SeekingTargetExpect)
  2398. {
  2399. case SpellTemplate.SeekingExpect.Random:
  2400. case SpellTemplate.SeekingExpect.RandomIgnoreInChain:
  2401. CUtils.RandomList(RandomN, ret);
  2402. break;
  2403. case SpellTemplate.SeekingExpect.Nearest:
  2404. case SpellTemplate.SeekingExpect.NearestIgnoreInChain:
  2405. ret.Sort(new ObjectSorterNearest<InstanceUnit>(X, Y));
  2406. break;
  2407. case SpellTemplate.SeekingExpect.Farthest:
  2408. case SpellTemplate.SeekingExpect.FarthestIgnoreInChain:
  2409. ret.Sort(new ObjectSorterFarthest<InstanceUnit>(X, Y));
  2410. break;
  2411. }
  2412. }
  2413. /**游戏服场景标识通知*/
  2414. public virtual void GSZoneFlagNotifyMsg(int value1)
  2415. {
  2416. }
  2417. #endregion
  2418. //-------------------------------------------------------------------------------------------------------//
  2419. #region EDITOR_AND_SCRIPT
  2420. readonly private HashMap<string, InstanceFlag> mFlags = new HashMap<string, InstanceFlag>();
  2421. private bool mHasArea = false;
  2422. protected bool addFlag(InstanceFlag flag)
  2423. {
  2424. if (!mFlags.ContainsKey(flag.Name))
  2425. {
  2426. mFlags.Add(flag.Name, flag);
  2427. flag.onAdded();
  2428. if (flag is ZoneArea)
  2429. {
  2430. mHasArea = true;
  2431. }
  2432. return true;
  2433. }
  2434. return false;
  2435. }
  2436. public InstanceFlag getFlag(string name)
  2437. {
  2438. if(string.IsNullOrEmpty(name))
  2439. {
  2440. return null;
  2441. }
  2442. return mFlags.Get(name);
  2443. }
  2444. public T getFlagAs<T>(string name) where T : InstanceFlag
  2445. {
  2446. return mFlags.Get(name) as T;
  2447. }
  2448. public bool setFlag(string name, bool enable)
  2449. {
  2450. InstanceFlag flag = getFlag(name);
  2451. if (flag != null)
  2452. {
  2453. flag.Enable = enable;
  2454. return true;
  2455. }
  2456. return false;
  2457. }
  2458. #endregion
  2459. //-------------------------------------------------------------------------------------------------------//
  2460. #region Environment
  2461. private HashMap<string, EnvironmentVar> EnvironmentVarMap = new HashMap<string, EnvironmentVar>();
  2462. public void AddEnvironmentVar(string key, object value, bool syncToClient)
  2463. {
  2464. if (!string.IsNullOrEmpty(key))
  2465. {
  2466. EnvironmentVar var = EnvironmentVarMap.Get(key);
  2467. if (var != null)
  2468. {
  2469. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || (var.SyncToClient && var.Value != value))
  2470. {
  2471. queueEvent(new SyncEnvironmentVarEvent(key, value));
  2472. }
  2473. var.Value = value;
  2474. }
  2475. else
  2476. {
  2477. var = new EnvironmentVar(key, syncToClient, value);
  2478. EnvironmentVarMap.Add(key, var);
  2479. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || var.SyncToClient)
  2480. {
  2481. queueEvent(new SyncEnvironmentVarEvent(key, value));
  2482. }
  2483. }
  2484. }
  2485. }
  2486. public void SetEnvironmentVar(string key, object value)
  2487. {
  2488. if (!string.IsNullOrEmpty(key))
  2489. {
  2490. EnvironmentVar var = EnvironmentVarMap.Get(key);
  2491. if (var != null)
  2492. {
  2493. if (EnvironmentVar.ALWAYS_SYNC_ENVIRONMENT_VAR || (var.SyncToClient && var.Value != value))
  2494. {
  2495. queueEvent(new SyncEnvironmentVarEvent(key, value));
  2496. }
  2497. var.Value = value;
  2498. }
  2499. }
  2500. }
  2501. public T GetEnvironmentVarAs<T>(string key)
  2502. {
  2503. if (!string.IsNullOrEmpty(key))
  2504. {
  2505. EnvironmentVar var = EnvironmentVarMap.Get(key);
  2506. if (var != null)
  2507. {
  2508. try
  2509. {
  2510. return (T)var.Value;
  2511. }
  2512. catch (Exception err)
  2513. {
  2514. log.Warn("GetEnvironmentVarAs : " + key + ", catch: " + err);
  2515. }
  2516. }
  2517. }
  2518. return default(T);
  2519. }
  2520. public int ListEnvironmentVars(List<EnvironmentVar> list)
  2521. {
  2522. list.AddRange(EnvironmentVarMap.Values);
  2523. return EnvironmentVarMap.Count;
  2524. }
  2525. public ClientStruct.ZoneEnvironmentVar[] GetCurrentZoneVars()
  2526. {
  2527. ClientStruct.ZoneEnvironmentVar[] ret = new ClientStruct.ZoneEnvironmentVar[EnvironmentVarMap.Count];
  2528. int i = 0;
  2529. foreach (EnvironmentVar var in EnvironmentVarMap.Values)
  2530. {
  2531. ret[i] = new ClientStruct.ZoneEnvironmentVar();
  2532. ret[i].Key = var.Key;
  2533. ret[i].Value = var.Value;
  2534. ret[i].SyncToClient = var.SyncToClient;
  2535. i++;
  2536. }
  2537. return ret;
  2538. }
  2539. protected void BindZoneVar(ZoneVar var, BindValuesAdapter api)
  2540. {
  2541. if (string.IsNullOrEmpty(var.Key))
  2542. {
  2543. // Error
  2544. return;
  2545. }
  2546. if (var.Value is IEditorValue)
  2547. {
  2548. IEditorValue evalue = (var.Value as IEditorValue);
  2549. AddEnvironmentVar(var.Key, evalue.GetEnvValue(api), var.SyncToClient);
  2550. }
  2551. else if (var.Value is Array)
  2552. {
  2553. Array array = var.Value as Array;
  2554. for (int i = 0; i < array.Length; i++)
  2555. {
  2556. object e = array.GetValue(i);
  2557. if (e is IEditorValue)
  2558. {
  2559. string key = string.Format(var.Key + "[{0}]", i);
  2560. IEditorValue evalue = (e as IEditorValue);
  2561. AddEnvironmentVar(key, evalue.GetEnvValue(api), var.SyncToClient);
  2562. }
  2563. }
  2564. }
  2565. }
  2566. #endregion
  2567. //-------------------------------------------------------------------------------------------------------//
  2568. #region QUEST
  2569. /// <summary>
  2570. /// 【第三方系统通知】任务已接受
  2571. /// </summary>
  2572. /// <param name="playerUUID"></param>
  2573. /// <param name="quest"></param>
  2574. internal void gs_OnQuestAccepted(string playerUUID, string quest)
  2575. {
  2576. queueTask((InstanceZone zone) =>
  2577. {
  2578. InstancePlayer p = getPlayerByUUID(playerUUID);
  2579. if (p != null)
  2580. {
  2581. p.doQuestAccepted(quest);
  2582. if (mOnQuestAccepted != null)
  2583. mOnQuestAccepted.Invoke(p, quest);
  2584. }
  2585. });
  2586. }
  2587. /// <summary>
  2588. /// 【第三方系统通知】任务已完成
  2589. /// </summary>
  2590. /// <param name="playerUUID"></param>
  2591. /// <param name="quest"></param>
  2592. internal void gs_OnQuestCommitted(string playerUUID, string quest)
  2593. {
  2594. queueTask((InstanceZone zone) =>
  2595. {
  2596. InstancePlayer p = getPlayerByUUID(playerUUID);
  2597. if (p != null)
  2598. {
  2599. if (mOnQuestCommitted != null)
  2600. mOnQuestCommitted.Invoke(p, quest);
  2601. p.doQuestCommitted(quest);
  2602. }
  2603. });
  2604. }
  2605. /// <summary>
  2606. /// 【第三方系统通知】任务已放弃
  2607. /// </summary>
  2608. /// <param name="playerUUID"></param>
  2609. /// <param name="quest"></param>
  2610. internal void gs_OnQuestDropped(string playerUUID, string quest)
  2611. {
  2612. queueTask((InstanceZone zone) =>
  2613. {
  2614. InstancePlayer p = getPlayerByUUID(playerUUID);
  2615. if (p != null)
  2616. {
  2617. if (mOnQuestDropped != null)
  2618. mOnQuestDropped.Invoke(p, quest);
  2619. p.doQuestDropped(quest);
  2620. }
  2621. });
  2622. }
  2623. /// <summary>
  2624. /// 【第三方系统通知】任务状态已改变
  2625. /// </summary>
  2626. /// <param name="playerUUID"></param>
  2627. /// <param name="quest"></param>
  2628. /// <param name="key"></param>
  2629. /// <param name="value"></param>
  2630. internal void gs_OnQuestStatusChanged(string playerUUID, string quest, string key, string value)
  2631. {
  2632. queueTask((InstanceZone zone) =>
  2633. {
  2634. InstancePlayer p = getPlayerByUUID(playerUUID);
  2635. if (p != null)
  2636. {
  2637. p.doQuestStatusChanged(quest, key, value);
  2638. if (mOnQuestStatusChanged != null)
  2639. mOnQuestStatusChanged.Invoke(p, quest, key, value);
  2640. }
  2641. });
  2642. }
  2643. //给单个玩家发送消息
  2644. internal void doSendMsgToPlayer(InstancePlayer player, CommonLang.Protocol.IMessage msg)
  2645. {
  2646. mQuestAdapter.DoSendMsgToPlayer(player.PlayerUUID, msg);
  2647. }
  2648. /// <summary>
  2649. /// 本地通知游戏服
  2650. /// </summary>
  2651. /// <param name="player"></param>
  2652. /// <param name="quest"></param>
  2653. /// <param name="args"></param>
  2654. internal void doAcceptQuest(InstancePlayer player, string quest, string args)
  2655. {
  2656. mQuestAdapter.DoAcceptQuest(player.PlayerUUID, quest, args);
  2657. }
  2658. /// <summary>
  2659. /// 本地通知游戏服
  2660. /// </summary>
  2661. /// <param name="player"></param>
  2662. /// <param name="quest"></param>
  2663. /// <param name="args"></param>
  2664. internal void doCommitQuest(InstancePlayer player, string quest, string args)
  2665. {
  2666. mQuestAdapter.DoCommitQuest(player.PlayerUUID, quest, args);
  2667. }
  2668. /// <summary>
  2669. /// 本地通知游戏服
  2670. /// </summary>
  2671. /// <param name="player"></param>
  2672. /// <param name="quest"></param>
  2673. /// <param name="args"></param>
  2674. internal void doDropQuest(InstancePlayer player, string quest, string args)
  2675. {
  2676. mQuestAdapter.DoDropQuest(player.PlayerUUID, quest, args);
  2677. }
  2678. /// <summary>
  2679. /// 本地通知游戏服
  2680. /// </summary>
  2681. /// <param name="player"></param>
  2682. /// <param name="quest"></param>
  2683. /// <param name="key"></param>
  2684. /// <param name="value"></param>
  2685. internal void doUpdateQuestStatus(InstancePlayer player, string quest, string key, string value)
  2686. {
  2687. mQuestAdapter.DoUpdateQuestStatus(player.PlayerUUID, quest, key, value);
  2688. }
  2689. #endregion
  2690. //-------------------------------------------------------------------------------------------------------//
  2691. }
  2692. }