SceneScriptManager.java 10 KB
Newer Older
1
2
package emu.grasscutter.scripts;

Melledy's avatar
Melledy committed
3
import java.util.ArrayList;
4
5
6
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
7
import java.util.Map;
8
import java.util.Set;
Melledy's avatar
Melledy committed
9
import java.util.stream.Collectors;
10
11
12
13
14
15
16
17
18
19

import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptException;

import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.CoerceJavaToLua;

import emu.grasscutter.Grasscutter;
Melledy's avatar
Melledy committed
20
21
22
import emu.grasscutter.data.GameData;
import emu.grasscutter.data.def.MonsterData;
import emu.grasscutter.data.def.WorldLevelData;
23
24
25
26
import emu.grasscutter.game.entity.EntityGadget;
import emu.grasscutter.game.entity.EntityMonster;
import emu.grasscutter.game.entity.GameEntity;
import emu.grasscutter.game.world.Scene;
Melledy's avatar
Melledy committed
27
import emu.grasscutter.scripts.constants.EventType;
28
29
30
31
32
33
34
35
36
37
import emu.grasscutter.scripts.constants.ScriptGadgetState;
import emu.grasscutter.scripts.constants.ScriptRegionShape;
import emu.grasscutter.scripts.data.SceneBlock;
import emu.grasscutter.scripts.data.SceneConfig;
import emu.grasscutter.scripts.data.SceneGadget;
import emu.grasscutter.scripts.data.SceneGroup;
import emu.grasscutter.scripts.data.SceneInitConfig;
import emu.grasscutter.scripts.data.SceneMonster;
import emu.grasscutter.scripts.data.SceneSuite;
import emu.grasscutter.scripts.data.SceneTrigger;
38
import emu.grasscutter.scripts.data.SceneVar;
Melledy's avatar
Melledy committed
39
import emu.grasscutter.scripts.data.ScriptArgs;
40
41
42
43
44
45
46
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;

public class SceneScriptManager {
	private final Scene scene;
	private final ScriptLib scriptLib;
	private final LuaValue scriptLibLua;
Melledy's avatar
Melledy committed
47
	private final Map<String, Integer> variables;
48
	
49
	private Bindings bindings;
50
51
52
53
54
55
56
57
58
59
	private SceneConfig config;
	private List<SceneBlock> blocks;
	private Int2ObjectOpenHashMap<Set<SceneTrigger>> triggers;
	private boolean isInit;
	
	public SceneScriptManager(Scene scene) {
		this.scene = scene;
		this.scriptLib = new ScriptLib(this);
		this.scriptLibLua = CoerceJavaToLua.coerce(this.scriptLib);
		this.triggers = new Int2ObjectOpenHashMap<>();
60
		this.variables = new HashMap<>();
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
		
		// TEMPORARY
		if (this.getScene().getId() < 10) {
			return;
		}
		
		// Create
		this.init();
	}
	
	public Scene getScene() {
		return scene;
	}

	public ScriptLib getScriptLib() {
		return scriptLib;
	}
	
	public LuaValue getScriptLibLua() {
		return scriptLibLua;
	}

	public Bindings getBindings() {
		return bindings;
	}

	public SceneConfig getConfig() {
		return config;
	}

	public List<SceneBlock> getBlocks() {
		return blocks;
	}

Melledy's avatar
Melledy committed
95
	public Map<String, Integer> getVariables() {
96
97
98
		return variables;
	}

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
	public Set<SceneTrigger> getTriggersByEvent(int eventId) {
		return triggers.computeIfAbsent(eventId, e -> new HashSet<>());
	}
	
	public void registerTrigger(SceneTrigger trigger) {
		getTriggersByEvent(trigger.event).add(trigger);
	}
	
	public void deregisterTrigger(SceneTrigger trigger) {
		getTriggersByEvent(trigger.event).remove(trigger);
	}
	
	// TODO optimize
	public SceneGroup getGroupById(int groupId) {
		for (SceneBlock block : this.getScene().getLoadedBlocks()) {
			for (SceneGroup group : block.groups) {
				if (group.id == groupId) {
					return group;
				}
			}
		}
		return null;
	}

	private void init() {
		// Get compiled script if cached
		CompiledScript cs = ScriptLoader.getScriptByPath(
			Grasscutter.getConfig().SCRIPTS_FOLDER + "Scene/" + getScene().getId() + "/scene" + getScene().getId() + "." + ScriptLoader.getScriptType());
		
		if (cs == null) {
			Grasscutter.getLogger().warn("No script found for scene " + getScene().getId());
			return;
		}
		
		// Create bindings
		bindings = ScriptLoader.getEngine().createBindings();
		
		// Set variables
Melledy's avatar
Melledy committed
137
		bindings.put("EventType", new EventType()); // TODO - make static class to avoid instantiating a new class every scene
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
		bindings.put("GadgetState", new ScriptGadgetState());
		bindings.put("RegionShape", new ScriptRegionShape());
		bindings.put("ScriptLib", getScriptLib());
		
		// Eval script
		try {
			cs.eval(getBindings());
			
			this.config = ScriptLoader.getSerializer().toObject(SceneConfig.class, bindings.get("scene_config"));
			
			// TODO optimize later
			// Create blocks
			List<Integer> blockIds = ScriptLoader.getSerializer().toList(Integer.class, bindings.get("blocks"));
			List<SceneBlock> blocks = ScriptLoader.getSerializer().toList(SceneBlock.class, bindings.get("block_rects"));
			
			for (int i = 0; i < blocks.size(); i++) {
				SceneBlock block = blocks.get(0);
				block.id = blockIds.get(i);
				
157
				loadBlockFromScript(block);
158
159
160
161
162
			}
			
			this.blocks = blocks;
		} catch (ScriptException e) {
			Grasscutter.getLogger().error("Error running script", e);
163
			return;
164
		}
165
		
166
167
168
169
170
171
172
173
		// TEMP
		this.isInit = true;
	}

	public boolean isInit() {
		return isInit;
	}
	
174
	private void loadBlockFromScript(SceneBlock block) {
175
176
177
178
179
180
181
182
183
184
185
186
187
		CompiledScript cs = ScriptLoader.getScriptByPath(
			Grasscutter.getConfig().SCRIPTS_FOLDER + "Scene/" + getScene().getId() + "/scene" + getScene().getId() + "_block" + block.id + "." + ScriptLoader.getScriptType());
	
		if (cs == null) {
			return;
		}
		
		// Eval script
		try {
			cs.eval(getBindings());
			
			// Set groups
			block.groups = ScriptLoader.getSerializer().toList(SceneGroup.class, bindings.get("groups"));
188
			block.groups.forEach(g -> g.block_id = block.id);
189
190
191
192
193
		} catch (ScriptException e) {
			Grasscutter.getLogger().error("Error loading block " + block.id + " in scene " + getScene().getId(), e);
		}
	}
	
194
195
196
197
	public void loadGroupFromScript(SceneGroup group) {
		// Set flag here so if there is no script, we dont call this function over and over again.
		group.setLoaded(true);
		
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
		CompiledScript cs = ScriptLoader.getScriptByPath(
			Grasscutter.getConfig().SCRIPTS_FOLDER + "Scene/" + getScene().getId() + "/scene" + getScene().getId() + "_group" + group.id + "." + ScriptLoader.getScriptType());
	
		if (cs == null) {
			return;
		}
		
		// Eval script
		try {
			cs.eval(getBindings());

			// Set
			group.monsters = ScriptLoader.getSerializer().toList(SceneMonster.class, bindings.get("monsters"));
			group.gadgets = ScriptLoader.getSerializer().toList(SceneGadget.class, bindings.get("gadgets"));
			group.triggers = ScriptLoader.getSerializer().toList(SceneTrigger.class, bindings.get("triggers"));
			group.suites = ScriptLoader.getSerializer().toList(SceneSuite.class, bindings.get("suites"));
			group.init_config = ScriptLoader.getSerializer().toObject(SceneInitConfig.class, bindings.get("init_config"));
215
			
Melledy's avatar
Melledy committed
216
			// Add variables to suite
217
			List<SceneVar> variables = ScriptLoader.getSerializer().toList(SceneVar.class, bindings.get("variables"));
Melledy's avatar
Melledy committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
			variables.forEach(var -> this.getVariables().put(var.name, var.value));
			
			// Add monsters to suite TODO optimize
			HashMap<Integer, SceneMonster> map = (HashMap<Integer, SceneMonster>) group.monsters.stream().collect(Collectors.toMap(m -> m.config_id, m -> m));
			
			for (SceneSuite suite : group.suites) {
				suite.sceneMonsters = new ArrayList<>(suite.monsters.size());
				for (int id : suite.monsters) {
					SceneMonster monster = map.get(id);
					if (monster != null) {
						suite.sceneMonsters.add(monster);
					}
				}
			}
232
233
234
235
236
237
238
239
240
241
242
243
244
		} catch (ScriptException e) {
			Grasscutter.getLogger().error("Error loading group " + group.id + " in scene " + getScene().getId(), e);
		}
	}

	public void onTick() {
		checkTriggers();
	}
	
	public void checkTriggers() {

	}
	
245
	public void spawnGadgetsInGroup(SceneGroup group) {
Melledy's avatar
Melledy committed
246
247
248
249
250
		for (SceneGadget g : group.gadgets) {
			EntityGadget entity = new EntityGadget(getScene(), g.gadget_id, g.pos);
			
			if (entity.getGadgetData() == null) continue;
			
251
			entity.setBlockId(group.block_id);
Melledy's avatar
Melledy committed
252
253
254
255
256
257
258
259
260
261
			entity.setConfigId(g.config_id);
			entity.setGroupId(group.id);
			entity.getRotation().set(g.rot);
			entity.setState(g.state);
			
			getScene().addEntity(entity);
			this.callEvent(EventType.EVENT_GADGET_CREATE, new ScriptArgs(entity.getConfigId()));
		}
	}
	
Melledy's avatar
Melledy committed
262
263
264
265
	public void spawnMonstersInGroup(SceneGroup group, int suiteIndex) {
		spawnMonstersInGroup(group, group.getSuiteByIndex(suiteIndex));
	}
	
Melledy's avatar
Melledy committed
266
	public void spawnMonstersInGroup(SceneGroup group) {
Melledy's avatar
Melledy committed
267
268
269
270
271
272
273
274
275
276
		spawnMonstersInGroup(group, null);
	}
	
	public void spawnMonstersInGroup(SceneGroup group, SceneSuite suite) {
		List<SceneMonster> monsters = group.monsters;
		
		if (suite != null) {
			monsters = suite.sceneMonsters;
		}

Melledy's avatar
Melledy committed
277
278
		List<GameEntity> toAdd = new ArrayList<>();
		
Melledy's avatar
Melledy committed
279
		for (SceneMonster monster : monsters) {
Melledy's avatar
Melledy committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
			MonsterData data = GameData.getMonsterDataMap().get(monster.monster_id);
			
			if (data == null) {
				continue;
			}
			
			// Calculate level
			int level = monster.level;
			
			if (getScene().getDungeonData() != null) {
				level = getScene().getDungeonData().getShowLevel();
			} else if (getScene().getWorld().getWorldLevel() > 0) {
				WorldLevelData worldLevelData = GameData.getWorldLevelDataMap().get(getScene().getWorld().getWorldLevel());
				
				if (worldLevelData != null) {
					level = worldLevelData.getMonsterLevel();
				}
			}
			
			// Spawn mob
			EntityMonster entity = new EntityMonster(getScene(), data, monster.pos, level);
			entity.getRotation().set(monster.rot);
			entity.setGroupId(group.id);
			entity.setConfigId(monster.config_id);
			
			toAdd.add(entity);
		}
		
		if (toAdd.size() > 0) {
			getScene().addEntities(toAdd);
			
			for (GameEntity entity : toAdd) {
				callEvent(EventType.EVENT_ANY_MONSTER_LIVE, new ScriptArgs(entity.getConfigId()));
			}
		}
	}
	
317
318
	// Events
	
Melledy's avatar
Melledy committed
319
320
321
	public void callEvent(int eventType, ScriptArgs params) {
		for (SceneTrigger trigger : this.getTriggersByEvent(eventType)) {
			LuaValue condition = null;
322
			
Melledy's avatar
Melledy committed
323
324
			if (trigger.condition != null && !trigger.condition.isEmpty()) {
				condition = (LuaValue) this.getBindings().get(trigger.condition);
325
326
			}
			
Melledy's avatar
Melledy committed
327
328
329
330
331
332
333
334
335
336
			LuaValue ret = LuaValue.TRUE;
			
			if (condition != null) {
				LuaValue args = LuaValue.NIL;
				
				if (params != null) {
					args = CoerceJavaToLua.coerce(params);
				}
				
				ret = condition.call(this.getScriptLibLua(), args);
337
338
339
			}
			
			if (ret.checkboolean() == true) {
Melledy's avatar
Melledy committed
340
				LuaValue action = (LuaValue) this.getBindings().get(trigger.action);
341
342
343
344
345
				action.call(this.getScriptLibLua(), LuaValue.NIL);
			}
		}
	}
}