Bot.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Text;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Threading;
  33. using System.Timers;
  34. using log4net;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Assets;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Console;
  40. using pCampBot.Interfaces;
  41. using Timer = System.Timers.Timer;
  42. namespace pCampBot
  43. {
  44. public enum ConnectionState
  45. {
  46. Disconnected,
  47. Connecting,
  48. Connected,
  49. Disconnecting
  50. }
  51. public class Bot
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. public delegate void AnEvent(Bot callbot, EventType someevent); // event delegate for bot events
  55. /// <summary>
  56. /// Bot manager.
  57. /// </summary>
  58. public BotManager Manager { get; private set; }
  59. /// <summary>
  60. /// Bot config, passed from BotManager.
  61. /// </summary>
  62. private IConfig startupConfig;
  63. /// <summary>
  64. /// Behaviours implemented by this bot.
  65. /// </summary>
  66. /// <remarks>
  67. /// Lock this list before manipulating it.
  68. /// </remarks>
  69. public List<IBehaviour> Behaviours { get; private set; }
  70. /// <summary>
  71. /// Objects that the bot has discovered.
  72. /// </summary>
  73. /// <remarks>
  74. /// Returns a list copy. Inserting new objects manually will have no effect.
  75. /// </remarks>
  76. public Dictionary<UUID, Primitive> Objects
  77. {
  78. get
  79. {
  80. lock (m_objects)
  81. return new Dictionary<UUID, Primitive>(m_objects);
  82. }
  83. }
  84. private Dictionary<UUID, Primitive> m_objects = new Dictionary<UUID, Primitive>();
  85. /// <summary>
  86. /// Is this bot connected to the grid?
  87. /// </summary>
  88. public ConnectionState ConnectionState { get; private set; }
  89. public string FirstName { get; private set; }
  90. public string LastName { get; private set; }
  91. public string Name { get; private set; }
  92. public string Password { get; private set; }
  93. public string LoginUri { get; private set; }
  94. public string saveDir;
  95. public string wear;
  96. public event AnEvent OnConnected;
  97. public event AnEvent OnDisconnected;
  98. /// <summary>
  99. /// Keep a track of the continuously acting thread so that we can abort it.
  100. /// </summary>
  101. private Thread m_actionThread;
  102. protected List<uint> objectIDs = new List<uint>();
  103. /// <summary>
  104. /// Random number generator.
  105. /// </summary>
  106. public Random Random { get; private set; }
  107. /// <summary>
  108. /// New instance of a SecondLife client
  109. /// </summary>
  110. public GridClient Client { get; private set; }
  111. /// <summary>
  112. /// Constructor
  113. /// </summary>
  114. /// <param name="bm"></param>
  115. /// <param name="behaviours">Behaviours for this bot to perform</param>
  116. /// <param name="firstName"></param>
  117. /// <param name="lastName"></param>
  118. /// <param name="password"></param>
  119. /// <param name="loginUri"></param>
  120. /// <param name="behaviours"></param>
  121. public Bot(
  122. BotManager bm, List<IBehaviour> behaviours,
  123. string firstName, string lastName, string password, string loginUri)
  124. {
  125. ConnectionState = ConnectionState.Disconnected;
  126. behaviours.ForEach(b => b.Initialize(this));
  127. Client = new GridClient();
  128. Random = new Random(Environment.TickCount);// We do stuff randomly here
  129. FirstName = firstName;
  130. LastName = lastName;
  131. Name = string.Format("{0} {1}", FirstName, LastName);
  132. Password = password;
  133. LoginUri = loginUri;
  134. Manager = bm;
  135. startupConfig = bm.Config;
  136. readconfig();
  137. Behaviours = behaviours;
  138. }
  139. //We do our actions here. This is where one would
  140. //add additional steps and/or things the bot should do
  141. private void Action()
  142. {
  143. while (true)
  144. lock (Behaviours)
  145. Behaviours.ForEach(
  146. b =>
  147. {
  148. Thread.Sleep(Random.Next(3000, 10000));
  149. // m_log.DebugFormat("[pCAMPBOT]: For {0} performing action {1}", Name, b.GetType());
  150. b.Action();
  151. }
  152. );
  153. }
  154. /// <summary>
  155. /// Read the Nini config and initialize
  156. /// </summary>
  157. public void readconfig()
  158. {
  159. wear = startupConfig.GetString("wear", "no");
  160. }
  161. /// <summary>
  162. /// Tells LibSecondLife to logout and disconnect. Raises the disconnect events once it finishes.
  163. /// </summary>
  164. public void shutdown()
  165. {
  166. ConnectionState = ConnectionState.Disconnecting;
  167. if (m_actionThread != null)
  168. m_actionThread.Abort();
  169. Client.Network.Logout();
  170. }
  171. /// <summary>
  172. /// This is the bot startup loop.
  173. /// </summary>
  174. public void startup()
  175. {
  176. Client.Settings.LOGIN_SERVER = LoginUri;
  177. Client.Settings.ALWAYS_DECODE_OBJECTS = false;
  178. Client.Settings.AVATAR_TRACKING = false;
  179. Client.Settings.OBJECT_TRACKING = false;
  180. Client.Settings.SEND_AGENT_THROTTLE = true;
  181. Client.Settings.SEND_PINGS = true;
  182. Client.Settings.STORE_LAND_PATCHES = false;
  183. Client.Settings.USE_ASSET_CACHE = false;
  184. Client.Settings.MULTIPLE_SIMS = true;
  185. Client.Throttle.Asset = 100000;
  186. Client.Throttle.Land = 100000;
  187. Client.Throttle.Task = 100000;
  188. Client.Throttle.Texture = 100000;
  189. Client.Throttle.Wind = 100000;
  190. Client.Throttle.Total = 400000;
  191. Client.Network.LoginProgress += this.Network_LoginProgress;
  192. Client.Network.SimConnected += this.Network_SimConnected;
  193. Client.Network.Disconnected += this.Network_OnDisconnected;
  194. Client.Objects.ObjectUpdate += Objects_NewPrim;
  195. ConnectionState = ConnectionState.Connecting;
  196. if (Client.Network.Login(FirstName, LastName, Password, "pCampBot", "Your name"))
  197. {
  198. ConnectionState = ConnectionState.Connected;
  199. Thread.Sleep(Random.Next(1000, 10000));
  200. m_actionThread = new Thread(Action);
  201. m_actionThread.Start();
  202. // OnConnected(this, EventType.CONNECTED);
  203. if (wear == "save")
  204. {
  205. Client.Appearance.SetPreviousAppearance();
  206. SaveDefaultAppearance();
  207. }
  208. else if (wear != "no")
  209. {
  210. MakeDefaultAppearance(wear);
  211. }
  212. // Extract nearby region information.
  213. Client.Grid.GridRegion += Manager.Grid_GridRegion;
  214. uint xUint, yUint;
  215. Utils.LongToUInts(Client.Network.CurrentSim.Handle, out xUint, out yUint);
  216. ushort minX, minY, maxX, maxY;
  217. minX = (ushort)Math.Min(0, xUint - 5);
  218. minY = (ushort)Math.Min(0, yUint - 5);
  219. maxX = (ushort)(xUint + 5);
  220. maxY = (ushort)(yUint + 5);
  221. Client.Grid.RequestMapBlocks(GridLayerType.Terrain, minX, minY, maxX, maxY, false);
  222. }
  223. else
  224. {
  225. ConnectionState = ConnectionState.Disconnected;
  226. m_log.ErrorFormat(
  227. "{0} {1} cannot login: {2}", FirstName, LastName, Client.Network.LoginMessage);
  228. if (OnDisconnected != null)
  229. {
  230. OnDisconnected(this, EventType.DISCONNECTED);
  231. }
  232. }
  233. }
  234. public void SaveDefaultAppearance()
  235. {
  236. saveDir = "MyAppearance/" + FirstName + "_" + LastName;
  237. if (!Directory.Exists(saveDir))
  238. {
  239. Directory.CreateDirectory(saveDir);
  240. }
  241. Array wtypes = Enum.GetValues(typeof(WearableType));
  242. foreach (WearableType wtype in wtypes)
  243. {
  244. UUID wearable = Client.Appearance.GetWearableAsset(wtype);
  245. if (wearable != UUID.Zero)
  246. {
  247. Client.Assets.RequestAsset(wearable, AssetType.Clothing, false, Asset_ReceivedCallback);
  248. Client.Assets.RequestAsset(wearable, AssetType.Bodypart, false, Asset_ReceivedCallback);
  249. }
  250. }
  251. }
  252. public void SaveAsset(AssetWearable asset)
  253. {
  254. if (asset != null)
  255. {
  256. try
  257. {
  258. if (asset.Decode())
  259. {
  260. File.WriteAllBytes(Path.Combine(saveDir, String.Format("{1}.{0}",
  261. asset.AssetType.ToString().ToLower(),
  262. asset.WearableType)), asset.AssetData);
  263. }
  264. else
  265. {
  266. m_log.WarnFormat("Failed to decode {0} asset {1}", asset.AssetType, asset.AssetID);
  267. }
  268. }
  269. catch (Exception e)
  270. {
  271. m_log.ErrorFormat("Exception: {0}{1}", e.Message, e.StackTrace);
  272. }
  273. }
  274. }
  275. public WearableType GetWearableType(string path)
  276. {
  277. string type = ((((path.Split('/'))[2]).Split('.'))[0]).Trim();
  278. switch (type)
  279. {
  280. case "Eyes":
  281. return WearableType.Eyes;
  282. case "Hair":
  283. return WearableType.Hair;
  284. case "Pants":
  285. return WearableType.Pants;
  286. case "Shape":
  287. return WearableType.Shape;
  288. case "Shirt":
  289. return WearableType.Shirt;
  290. case "Skin":
  291. return WearableType.Skin;
  292. default:
  293. return WearableType.Shape;
  294. }
  295. }
  296. public void MakeDefaultAppearance(string wear)
  297. {
  298. try
  299. {
  300. if (wear == "yes")
  301. {
  302. //TODO: Implement random outfit picking
  303. m_log.DebugFormat("Picks a random outfit. Not yet implemented.");
  304. }
  305. else if (wear != "save")
  306. saveDir = "MyAppearance/" + wear;
  307. saveDir = saveDir + "/";
  308. string[] clothing = Directory.GetFiles(saveDir, "*.clothing", SearchOption.TopDirectoryOnly);
  309. string[] bodyparts = Directory.GetFiles(saveDir, "*.bodypart", SearchOption.TopDirectoryOnly);
  310. InventoryFolder clothfolder = FindClothingFolder();
  311. UUID transid = UUID.Random();
  312. List<InventoryBase> listwearables = new List<InventoryBase>();
  313. for (int i = 0; i < clothing.Length; i++)
  314. {
  315. UUID assetID = UUID.Random();
  316. AssetClothing asset = new AssetClothing(assetID, File.ReadAllBytes(clothing[i]));
  317. asset.Decode();
  318. asset.Owner = Client.Self.AgentID;
  319. asset.WearableType = GetWearableType(clothing[i]);
  320. asset.Encode();
  321. transid = Client.Assets.RequestUpload(asset,true);
  322. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyClothing" + i.ToString(), "MyClothing", AssetType.Clothing,
  323. transid, InventoryType.Wearable, asset.WearableType, PermissionMask.All, delegate(bool success, InventoryItem item)
  324. {
  325. if (success)
  326. {
  327. listwearables.Add(item);
  328. }
  329. else
  330. {
  331. m_log.WarnFormat("Failed to create item {0}", item.Name);
  332. }
  333. }
  334. );
  335. }
  336. for (int i = 0; i < bodyparts.Length; i++)
  337. {
  338. UUID assetID = UUID.Random();
  339. AssetBodypart asset = new AssetBodypart(assetID, File.ReadAllBytes(bodyparts[i]));
  340. asset.Decode();
  341. asset.Owner = Client.Self.AgentID;
  342. asset.WearableType = GetWearableType(bodyparts[i]);
  343. asset.Encode();
  344. transid = Client.Assets.RequestUpload(asset,true);
  345. Client.Inventory.RequestCreateItem(clothfolder.UUID, "MyBodyPart" + i.ToString(), "MyBodyPart", AssetType.Bodypart,
  346. transid, InventoryType.Wearable, asset.WearableType, PermissionMask.All, delegate(bool success, InventoryItem item)
  347. {
  348. if (success)
  349. {
  350. listwearables.Add(item);
  351. }
  352. else
  353. {
  354. m_log.WarnFormat("Failed to create item {0}", item.Name);
  355. }
  356. }
  357. );
  358. }
  359. Thread.Sleep(1000);
  360. if (listwearables == null || listwearables.Count == 0)
  361. {
  362. m_log.DebugFormat("Nothing to send on this folder!");
  363. }
  364. else
  365. {
  366. m_log.DebugFormat("Sending {0} wearables...", listwearables.Count);
  367. Client.Appearance.WearOutfit(listwearables, false);
  368. }
  369. }
  370. catch (Exception ex)
  371. {
  372. Console.WriteLine(ex.ToString());
  373. }
  374. }
  375. public InventoryFolder FindClothingFolder()
  376. {
  377. UUID rootfolder = Client.Inventory.Store.RootFolder.UUID;
  378. List<InventoryBase> listfolders = Client.Inventory.Store.GetContents(rootfolder);
  379. InventoryFolder clothfolder = new InventoryFolder(UUID.Random());
  380. foreach (InventoryBase folder in listfolders)
  381. {
  382. if (folder.Name == "Clothing")
  383. {
  384. clothfolder = (InventoryFolder)folder;
  385. break;
  386. }
  387. }
  388. return clothfolder;
  389. }
  390. public void Network_LoginProgress(object sender, LoginProgressEventArgs args)
  391. {
  392. m_log.DebugFormat("[BOT]: Bot {0} {1} in Network_LoginProcess", Name, args.Status);
  393. if (args.Status == LoginStatus.Success)
  394. {
  395. if (OnConnected != null)
  396. {
  397. OnConnected(this, EventType.CONNECTED);
  398. }
  399. }
  400. }
  401. public void Network_SimConnected(object sender, SimConnectedEventArgs args)
  402. {
  403. m_log.DebugFormat(
  404. "[BOT]: Bot {0} connected to {1} at {2}", Name, args.Simulator.Name, args.Simulator.IPEndPoint);
  405. }
  406. public void Network_OnDisconnected(object sender, DisconnectedEventArgs args)
  407. {
  408. ConnectionState = ConnectionState.Disconnected;
  409. m_log.DebugFormat(
  410. "[BOT]: Bot {0} disconnected reason {1}, message {2}", Name, args.Reason, args.Message);
  411. // m_log.ErrorFormat("Fired Network_OnDisconnected");
  412. // if (
  413. // (args.Reason == NetworkManager.DisconnectType.SimShutdown
  414. // || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  415. // && OnDisconnected != null)
  416. if (
  417. (args.Reason == NetworkManager.DisconnectType.ClientInitiated
  418. || args.Reason == NetworkManager.DisconnectType.ServerInitiated
  419. || args.Reason == NetworkManager.DisconnectType.NetworkTimeout)
  420. && OnDisconnected != null)
  421. // if (OnDisconnected != null)
  422. {
  423. OnDisconnected(this, EventType.DISCONNECTED);
  424. }
  425. }
  426. public void Objects_NewPrim(object sender, PrimEventArgs args)
  427. {
  428. // if (Name.EndsWith("4"))
  429. // throw new Exception("Aaargh");
  430. Primitive prim = args.Prim;
  431. if (prim != null)
  432. {
  433. lock (m_objects)
  434. m_objects[prim.ID] = prim;
  435. if (prim.Textures != null)
  436. {
  437. if (prim.Textures.DefaultTexture.TextureID != UUID.Zero)
  438. {
  439. GetTexture(prim.Textures.DefaultTexture.TextureID);
  440. }
  441. for (int i = 0; i < prim.Textures.FaceTextures.Length; i++)
  442. {
  443. Primitive.TextureEntryFace face = prim.Textures.FaceTextures[i];
  444. if (face != null)
  445. {
  446. UUID textureID = prim.Textures.FaceTextures[i].TextureID;
  447. if (textureID != UUID.Zero)
  448. GetTexture(textureID);
  449. }
  450. }
  451. }
  452. if (prim.Sculpt != null && prim.Sculpt.SculptTexture != UUID.Zero)
  453. GetTexture(prim.Sculpt.SculptTexture);
  454. }
  455. }
  456. private void GetTexture(UUID textureID)
  457. {
  458. lock (Manager.AssetsReceived)
  459. {
  460. // Don't request assets more than once.
  461. if (Manager.AssetsReceived.ContainsKey(textureID))
  462. return;
  463. Manager.AssetsReceived[textureID] = false;
  464. Client.Assets.RequestImage(textureID, ImageType.Normal, Asset_TextureCallback_Texture);
  465. }
  466. }
  467. public void Asset_TextureCallback_Texture(TextureRequestState state, AssetTexture assetTexture)
  468. {
  469. //TODO: Implement texture saving and applying
  470. }
  471. public void Asset_ReceivedCallback(AssetDownload transfer, Asset asset)
  472. {
  473. lock (Manager.AssetsReceived)
  474. Manager.AssetsReceived[asset.AssetID] = true;
  475. // if (wear == "save")
  476. // {
  477. // SaveAsset((AssetWearable) asset);
  478. // }
  479. }
  480. }
  481. }