Jump to content
  • 0

My script refuses to spawn the NPC. pls help!


Question

Posted (edited)

I have a problem. They just refuse to spawn automatically...


"INFO Spawning phantom Takeshi[268484832] through spawner. Cur/Max 0/35000"

Could someone tell me what's wrong? I think the problem is on row 540. It calls _loc but this location hasnt been set nor linked to an outside source... i think.

Here is the script:

Spoiler

package wp.gameserver.model;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

import org.apache.log4j.Logger;

import com.google.common.io.Files;

import wp.commons.util.Rnd;
import wp.gameserver.Config;
import wp.gameserver.ThreadPoolManager;
import wp.gameserver.ai.PhantomPlayerAI;
import wp.gameserver.dao.CharacterDAO;
import wp.gameserver.dao.PhantomsDAO;
import wp.gameserver.data.xml.holder.PhantomTemplateData;
import wp.gameserver.data.xml.holder.SkillAcquireHolder;
import wp.gameserver.instancemanager.CursedWeaponsManager;
import wp.gameserver.model.base.AcquireType;
import wp.gameserver.model.base.ClassId;
import wp.gameserver.model.base.Experience;
import wp.gameserver.model.base.InvisibleType;
import wp.gameserver.model.base.RestartType;
import wp.gameserver.model.entity.L2Event;
import wp.gameserver.model.items.ItemInstance;
import wp.gameserver.model.phantom.PhantomTemplate;
import wp.gameserver.tables.SkillTable;
import wp.gameserver.templates.item.CreateItem;
import wp.gameserver.templates.item.ItemTemplate;
import wp.gameserver.utils.Location;
import wp.gameserver.utils.Util;

public class PhantomPlayers
{
	private static final Logger _log = Logger.getLogger(PhantomPlayers.class.getName());
	private static List<Integer> _phantoms;
	private static List<String> _phantomNames;
	private static List<PhantomSpawner> _phantomSpawners;
	
	public static void init()
	{
		_log.info("Loading phantom players...");
		
		try
		{
			File file = Config.findNonCustomResource("config/phantom/player_names.txt");
			_phantomNames = Files.readLines(file, StandardCharsets.UTF_8);
		}
		catch (IOException e)
		{
			_log.warn("PhantomPlayers: Unable to load phantom player names.", e);
			_phantomNames = Collections.emptyList();
		}
		
		_phantoms = new ArrayList<>(PhantomsDAO.getInstance().selectAll().keySet());
		_phantomSpawners = new ArrayList<>();
		PhantomSpawner spawner = new PhantomSpawner();
		ThreadPoolManager.getInstance().execute(spawner);
		_phantomSpawners.add(spawner);
		
		_log.info("Loaded " + _phantoms.size() + " phantom players from database with a maximum of " + Config.PHANTOM_MAX_PLAYERS + " phantoms.");
		_log.info("Loaded " + _phantomNames.size() + " possible phantom names.");
		_log.info("Scheduled spawner with " + (Config.PHANTOM_SPAWN_DELAY / 1000) + " seconds delay.");
	}
	
	public static Player createNewPhantom()
	{
		if (_phantomNames == null)
		{
			return null;
		}
		
		for (int i = 0; i < 25; i++) // 25 tries to make a phantom player. Enough tries to avoid name duplicate and other stuff.
		{
			String name = Rnd.get(_phantomNames);
			Player player = createNewPhantom(name);
			if (player != null)
			{
				return player;
			}
		}
		
		return null;
	}
	
	public static Player createNewPhantom(String name)
	{
		return createNewPhantom(name, PhantomTemplateData.getInstance().getRandomTemplate());
	}
	
	public static Player createNewPhantom(String name, PhantomTemplate template)
	{
		boolean female = Rnd.nextBoolean();
		int hairStyle = Rnd.get(3);
		int hairColor = Rnd.get(3);
		int face = Rnd.get(3);
		return createNewPhantom(name, template, female, hairStyle, hairColor, face);
	}
	
	public static Player createNewPhantom(String name, PhantomTemplate template, boolean female, int hairStyle, int hairColor, int face)
	{
		try
		{
			if (!Util.isMatchingRegexp(name, Config.CNAME_TEMPLATE))
			{
				return null;
			}
			if ((CharacterDAO.getInstance().getObjectIdByName(name) > 0) || Util.contains(Config.FORBIDDEN_CHAR_NAMES, name))
			{
				return null;
			}
			
			if (template == null)
			{
				return null;
			}
			
			final ClassId classId = ClassId.VALUES[template.getClassId()];
			Player newChar = Player.create(classId.getId(), female ? 1 : 0, Config.PHANTOM_ACCOUNT, name, hairStyle, hairColor, face);
			if (newChar == null)
			{
				return null;
			}
			
			newChar.setCreateTime(System.currentTimeMillis());
			try
			{
				switch (classId.getLevel())
				{
					case 2:
						newChar.addExpAndSp(Experience.getExpForLevel(20), 835863);
						break;
					case 3:
						newChar.addExpAndSp(Experience.getExpForLevel(40), 15422930);
						break;
					case 4:
						newChar.addExpAndSp(Experience.getExpForLevel(76), 931275829);
						break;
				}
			}
			catch (ArrayIndexOutOfBoundsException | NullPointerException e)
			{
				_log.warn("PhantomPlayers: Failed to set appropreate level for classId " + classId, e);
			}
			
			Player.restoreCharSubClasses(newChar);
			
			if (Config.STARTING_ADENA > 0)
			{
				newChar.addAdena(Config.STARTING_ADENA);
			}
			
			if (Config.STARTING_LVL > newChar.getLevel())
			{
				newChar.addExpAndSp(Experience.LEVEL[Config.STARTING_LVL] - newChar.getExp(), 0, 0, 0, false, false);
			}
			
			if (Config.SPAWN_CHAR)
			{
				newChar.teleToLocation(Config.SPAWN_X, Config.SPAWN_Y, Config.SPAWN_Z);
			}
			else
			{
				newChar.setLoc(Rnd.get(newChar.getTemplate().getSpawnLocs()));
			}
			
			if (Config.CHAR_TITLE)
			{
				newChar.setTitle(Config.ADD_CHAR_TITLE);
			}
			else
			{
				newChar.setTitle("");
			}
			
			for (CreateItem i : newChar.getTemplate().getItems())
			{
				ItemInstance item = new ItemInstance(i.getItemId());
				newChar.getInventory().addItem(item);
				
				if (i.isEquipable() && item.isEquipable() && ((newChar.getActiveWeaponItem() == null) || (item.getTemplate().getType2() != ItemTemplate.TYPE2_WEAPON)))
				{
					newChar.getInventory().equipItem(item);
				}
			}
			
			if (Config.ALLOW_START_ITEMS)
			{
				if (classId.isMage())
				{
					for (int i = 0; i < Config.START_ITEMS_MAGE.length; i++)
					{
						ItemInstance item = new ItemInstance(Config.START_ITEMS_MAGE[i]);
						item.setCount(Config.START_ITEMS_MAGE_COUNT[i]);
						newChar.getInventory().addItem(item);
					}
					
					if (Config.BIND_NEWBIE_START_ITEMS_TO_CHAR)
					{
						for (int i = 0; i < Config.START_ITEMS_MAGE_BIND_TO_CHAR.length; i++)
						{
							ItemInstance item = new ItemInstance(Config.START_ITEMS_MAGE_BIND_TO_CHAR[i]);
							item.setCount(Config.START_ITEMS_MAGE_COUNT_BIND_TO_CHAR[i]);
							item.setCustomFlags(ItemInstance.FLAG_NO_CRYSTALLIZE | ItemInstance.FLAG_NO_TRADE | ItemInstance.FLAG_NO_TRANSFER | ItemInstance.FLAG_NO_DROP | ItemInstance.FLAG_NO_SELL);
							newChar.getInventory().addItem(item);
						}
					}
				}
				else
				{
					for (int i = 0; i < Config.START_ITEMS_FITHER.length; i++)
					{
						ItemInstance item = new ItemInstance(Config.START_ITEMS_FITHER[i]);
						item.setCount(Config.START_ITEMS_FITHER_COUNT[i]);
						newChar.getInventory().addItem(item);
					}
					
					if (Config.BIND_NEWBIE_START_ITEMS_TO_CHAR)
					{
						for (int i = 0; i < Config.START_ITEMS_FITHER_BIND_TO_CHAR.length; i++)
						{
							ItemInstance item = new ItemInstance(Config.START_ITEMS_FITHER_BIND_TO_CHAR[i]);
							item.setCount(Config.START_ITEMS_FITHER_COUNT_BIND_TO_CHAR[i]);
							item.setCustomFlags(ItemInstance.FLAG_NO_CRYSTALLIZE | ItemInstance.FLAG_NO_TRADE | ItemInstance.FLAG_NO_TRANSFER | ItemInstance.FLAG_NO_DROP | ItemInstance.FLAG_NO_SELL);
							newChar.getInventory().addItem(item);
						}
					}
				}
			}
			
			for (SkillLearn skill : SkillAcquireHolder.getInstance().getAvailableSkills(newChar, AcquireType.NORMAL))
			{
				newChar.addSkill(SkillTable.getInstance().getInfo(skill.getId(), skill.getLevel()), true);
			}
			
			newChar.setCurrentHpMp(newChar.getMaxHp(), newChar.getMaxMp());
			newChar.setCurrentCp(0); // retail
			newChar.setOnlineStatus(true);
			
			newChar.store(true);
			newChar.getInventory().store();
			newChar.deleteMe();
			
			PhantomsDAO.getInstance().insert(newChar.getObjectId(), template);
			
			_phantoms.add(newChar.getObjectId());
			return newChar;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static PhantomSpawner spawnPhantoms(int numSpawns, long delayInMilis, boolean generateNewPhantoms, Location loc)
	{
		PhantomSpawner spawner = new PhantomSpawner(numSpawns, delayInMilis, generateNewPhantoms).setLocation(loc);
		ThreadPoolManager.getInstance().execute(spawner);
		_phantomSpawners.add(spawner);
		return spawner;
	}
	
	/**
	 * Gets the next unspawned phantom.
	 * @return random free (unspawned) phantom object id or -1 if all are taken.
	 */
	private static int getUnspawnedPhantomObjId()
	{
		List<Integer> _unspawnedPhantoms = new ArrayList<>();
		_unspawnedPhantoms.addAll(_phantoms);
		
		for (Player player : L2ObjectsStorage.getAllPlayersForIterate())
		{
			if (_unspawnedPhantoms.contains(Integer.valueOf(player.getObjectId())))
			{
				_unspawnedPhantoms.remove(Integer.valueOf(player.getObjectId()));
			}
		}
		
		if (!_unspawnedPhantoms.isEmpty())
		{
			return Rnd.get(_unspawnedPhantoms);
		}
		
		return -1;
	}
	
	public static class PhantomSpawn implements Runnable
	{
		private final int _objId;
		private Location _loc;
		
		public PhantomSpawn()
		{
			_objId = getUnspawnedPhantomObjId();
		}
		
		public PhantomSpawn(int objId)
		{
			_objId = objId;
			_loc = null;
		}
		
		public PhantomSpawn setLocation(Location loc)
		{
			_loc = new Location(loc.getX() + Rnd.get(200), loc.getY() + Rnd.get(200), loc.getZ());
			return this;
		}
		
		@Override
		public void run()
		{
			
			Player player = World.getPlayer(_objId);
			if (player == null)
			{
				player = Player.restore(_objId);
			}
			if (player == null)
			{
				return;
			}
			
			player.setOfflineMode(false);
			player.setIsOnline(true);
			player.updateOnlineStatus();
			
			player.setOnlineStatus(true);
			player.setInvisibleType(InvisibleType.NONE);
			player.setNonAggroTime(Long.MAX_VALUE);
			player.spawnMe();
			
			player.setHero(Config.NEW_CHAR_IS_HERO);
			player.setNoble(Config.NEW_CHAR_IS_NOBLE);
			
			player.getListeners().onEnter();
			
			// Backup to set default name color every time on login.
			if ((player.getNameColor() != 0xFFFFFF) && ((player.getKarma() == 0) || (player.getRecomHave() == 0)) && !player.isGM())
			{
				player.setNameColor(0xFFFFFF);
			}
			
			if ((player.getTitleColor() != Player.DEFAULT_TITLE_COLOR) && !player.isGM())
			{
				player.setTitleColor(Player.DEFAULT_TITLE_COLOR);
			}
			
			// Restore after nocarrier title, title color.
			if (player.getVar("NoCarrierTitle") != null)
			{
				player.setTitle(player.getVar("NoCarrierTitle"));
				
				if (player.getVar("NoCarrierTitleColor") != null)
				{
					player.setTitleColor(Integer.parseInt(player.getVar("NoCarrierTitleColor")));
				}
				
				player.broadcastCharInfo();
				
				player.unsetVar("NoCarrierTitle");
				player.unsetVar("NoCarrierTitleColor");
			}
			
			if (player.isCursedWeaponEquipped())
			{
				CursedWeaponsManager.getInstance().showUsageTime(player, player.getCursedWeaponEquippedId());
			}
			
			player.setCurrentHpMp(player.getMaxHp(), player.getMaxMp());
			player.setCurrentCp(player.getMaxCp());
			
			player.setIsPhantom(true);
			
			if (player.getAI().isPhantomPlayerAI())
			{
				((PhantomPlayerAI) player.getAI()).startAITask();
			}
			
			if (L2Event.isParticipant(player))
			{
				L2Event.restorePlayerEventStatus(player);
			}
			
			player.setRunning();
			player.standUp();
			player.startTimers();
			
			player.broadcastCharInfo();
			player.setHeading(Rnd.get(65535));
			if (player.isDead())
			{
				player.teleToLocation(Location.getRestartLocation(player, RestartType.TO_VILLAGE));
				player.doRevive(100);
			}
			else
			{
				player.teleToLocation(_loc == null ? player.getLoc() : _loc);
			}
		}
	}
	
	/**
	 * Checks if the given player is in the world, then logs out when he is out of combat.
	 */
	private static class PhantomDespawn implements Runnable
	{
		private final int _objId;
		private final boolean _force;
		
		public PhantomDespawn(int objId, boolean force)
		{
			_objId = objId;
			_force = force;
		}
		
		@Override
		public void run()
		{
			Player phantom = L2ObjectsStorage.getPlayer(_objId);
			if (phantom == null)
			{
				return;
			}
			
			if (!_force)
			{
				// Continue when phantom is out of combat.
				if (phantom.isInCombat())
				{
					ThreadPoolManager.getInstance().schedule(this, 1000);
					return;
				}
				
				// When phantom is out of combat, stop moving.
				if (phantom.isMoving)
				{
					phantom.stopMove();
				}
			}
			
			phantom.getAI().stopAITask();
			phantom.kick();
		}
	}
	
	public static class PhantomSpawner implements Runnable
	{
		private final int _numSpawns;
		private final long _delayInMilis;
		private final boolean _generateNewPhantoms;
		private int _curSpawns = 0;
		private Location _loc = null;
		private ScheduledFuture<?> _task = null;
		
		public PhantomSpawner()
		{
			_numSpawns = Config.PHANTOM_SPAWN_MAX;
			_delayInMilis = Config.PHANTOM_SPAWN_DELAY;
			_generateNewPhantoms = true;
		}
		
		public PhantomSpawner(int numSpawns)
		{
			_numSpawns = numSpawns;
			_delayInMilis = Config.PHANTOM_SPAWN_DELAY;
			_generateNewPhantoms = true;
		}
		
		public PhantomSpawner(int numSpawns, long delayInMilis)
		{
			_numSpawns = numSpawns;
			_delayInMilis = delayInMilis;
			_generateNewPhantoms = true;
		}
		
		public PhantomSpawner(int numSpawns, long delayInMilis, boolean generateNewPhantoms)
		{
			_numSpawns = numSpawns;
			_delayInMilis = delayInMilis;
			_generateNewPhantoms = generateNewPhantoms;
		}
		
		public PhantomSpawner setLocation(Location loc)
		{
			_loc = loc;
			return this;
		}
		
		@Override
		public void run()
		{
			if (_numSpawns == 0)
			{
				return;
			}
			
			_task = ThreadPoolManager.getInstance().scheduleAtFixedRate(() ->
			{
				if (_curSpawns < _numSpawns)
				{
					// Do not spawn more than max phantoms.
					if (L2ObjectsStorage.getAllPlayersStream().filter(Player::isPhantom).count() >= Config.PHANTOM_MAX_PLAYERS)
					{
						return;
					}
					
					int objId = getUnspawnedPhantomObjId();
					if (objId > 0)
					{
						if (_generateNewPhantoms)
						{
							try
							{
								Player phantom = createNewPhantom();
								if (phantom != null)
								{
									objId = phantom.getObjectId();
									_log.info("Spawning phantom " + phantom + " through spawner. Cur/Max " + _curSpawns + "/" + _numSpawns);
								}
							}
							catch (Exception e)
							{
								_log.error("ERROR: Spawning phantom  through spawner. Cur/Max " + _curSpawns + "/" + _numSpawns, e);
							}
						}
						else
						{
							return;
						}
					}
					
					ThreadPoolManager.getInstance().execute(new PhantomSpawn(objId).setLocation(_loc));
					_curSpawns++;
				}
			}, 0, _delayInMilis);
		}
		
		public void cancel()
		{
			if (_task != null)
			{
				_task.cancel(true);
				System.out.println("Canceling phantom scheduler");
			}
		}
	}
	
	public static void stopSpawners()
	{
		if (_phantomSpawners != null)
		{
			for (PhantomSpawner thread : _phantomSpawners)
			{
				if (thread != null)
				{
					thread.cancel();
				}
			}
		}
	}
	
	public static void terminatePhantoms(boolean force)
	{
		stopSpawners();
		
		for (int objId : _phantoms)
		{
			new PhantomDespawn(objId, force).run();
		}
	}
	
	public static void terminatePhantom(int objId, boolean disableFromReenter)
	{
		if (disableFromReenter && (_phantoms != null))
		{
			_phantoms.remove(Integer.valueOf(objId));
		}
		
		new PhantomDespawn(objId, true).run();
	}
}

 

 



The following is a row I've taken from the admin commands java and it spawns the Phantoms.
 

ThreadPoolManager.getInstance().execute(new PhantomPlayers.PhantomSpawn(phantom.getObjectId()).setLocation(activeChar.getLoc()));
 

Edited by bru7al

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Posts

    • 12-07-2025 - OUR TOPIC IS RELEVANT! CONTACT US BY THE CONTACTS BELOW
    • Hundreds of players have already jumped into the world of L2Elixir x3, and the server grows bigger every day! A truly international community is forming — EU, NA, LATAM, Asia — all gathering for the same purpose: To relive the L2Elixir era the right way. Join now and be part of the early wave!   Website: https://l2elixir.org/ Discord: https://discord.gg/5ydPHvhbxs   🎄 Christmas Event Activated! 🎄 Craft your Ordinary or Special Christmas Tree, place it outside of a peace zone, and enjoy festive outfits, boosted EXP/SP, Adena, and Drop Rates, plus the Holiday Festival buff  (more HP/MP/CP, higher P.Def/P.Atk/M.Atk, faster movement, reduced MP cost!) every 12-hours! 🎁 Santa’s Hourly Gifts While you’re actively farming, Santa appears worldwide to drop special rewards such as: Special Christmas Tree Christmas Red Sock Santa’s Weapon Exchange Ticket (12h) Gift from Santa Santa Hats & Rudolph accessories Agathion: Rudolph Chest of Experience Shadow Hats Scrolls Event b.soe / b.rez Loot Crates 🔥 Santa’s Weapon Ticket Gives you a D/C/B-grade weapon based on your level, randomly enchanted +4 to +10!  4-hour expiration time. Celebrate, fight, farm — and let Santa upgrade your holidays! 🎅✨
    • what do u mean i want to change the normal weapons some weapons are working perftect some not getting th effect and the arcana has the effect above the weapons as u see ... i dont what is the probkenm
    • Stop paying for files that are already public and free. Here you can download a fully working Interlude server with C4-like gameplay, including source code so you can compile it yourself and verify everything. People will try to convince you that free releases are “broken”, “full of backdoors”, etc. That’s exactly why I’m also providing the SVN with the full source – so you can: Review the code yourself Remove / modify whatever you don’t like Compile your own binaries What’s included GX-EXT Interlude server (C4-style gameplay) – L2Off Client Interlude tweaked for C4 gameplay Public SVN with source code Downloads: Server GX-EXT: https://www.mediafire.com/file/q5ipkjd36tnhfxv/L2OFF_C4_C4_ACU_GXEXT.rar/file Client Interlude C4 Gameplay: https://www.mediafire.com/file/rdkfc8wwau042oh/Cliente_Interlude_Jugabilidad_C4.rar/file SVN (source code, delayed a couple of months to avoid reselling fresh work): https://svn.l2servers.com.ar/!/#GX-EXT_INTERLUDE User: gx Pass: gx How to compile To compile the source you will need: Visual Studio 2005 (x64 toolset) (Classic L2Off toolchain – yes, it’s old, but that’s what the original server uses.) Use this as you want: learn, test, open your own server, or just audit the code. But please, stop buying the same leaked/resold files over and over when you can get them here for free, with source, and actually know what you’re running.  
    • @GX-Ext Please reupload the pack+web+client because all the links inside that post or in the https://l2servers.com.ar/ are dead
  • Topics

×
×
  • Create New...

AdBlock Extension Detected!

Our website is made possible by displaying online advertisements to our members.

Please disable AdBlock browser extension first, to be able to use our community.

I've Disabled AdBlock