InstanceZone.cs 117 KB

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