InstanceZone.cs 108 KB

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