Difference between revisions of "User:AVS/Scripting"

From VCMI Project Wiki
Jump to: navigation, search
(Low level events API)
 
(29 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Roadmap ==
+
= Configuration =
# {{done}} make "hellow world" works
 
# add new test objects
 
# implement WoG henchman script ''(just as an example)''
 
# WoG 3.59 creature abilities (from new towns)
 
# (*) WoG objects ''(if will not be already written in ERM)''
 
# (*) WoG artifacts ''(if will not be already written in ERM)''
 
  
== Implementation details ==
+
<syntaxhighlight lang="javascript">
* Lua 5.2.1 static + SLB
+
{
 +
//general purpose script, Lua or ERM, runs on server
 +
"myScript":
 +
{
 +
"source":"path/to/script/with/ext",
 +
"implements":"ANYTHING"
 +
},
  
  
== Directory structure ==
+
//custom battle spell effect, Lua only, runs on both client and server
 +
//script ID will be used as effect 'type' (with mod prefix)
 +
"mySpellEffect":
 +
{
 +
"source":"path/to/script/with/ext",
 +
"implements":"BATTLE_EFFECT"
 +
},
  
* {{done}} "ALL/Scripts" - autoloading scripts. Independent of each other.
+
//TODO: object|building type
* {{todo}} "ALL/ScriptLib" - script library, load on demand.
+
//custom map object or building, Lua only, runs on both client and server
* recomended to put scripts in mod subfolder
+
//script ID will be used as 'handler' (with mod prefix)
 +
"myObjectType":
 +
{
 +
"source":"path/to/script/with/ext",
 +
"implements":"MAP_OBJECT"
 +
},
 +
//TODO: server query
 +
//TODO: client query
  
== Persistence ==
+
}
 +
</syntaxhighlight>
 +
 
 +
= Lua =
 +
== API Reference ==
 +
{{todo}} '''In near future Lua API may change drastically several times. Information here may be outdated'''
 +
=== Globals ===
 +
* DATA - persistent table
 +
** DATA.ERM contains ERM state, anything else is free to use.
 +
* GAME - IGameInfoCallback API
 +
* BATTLE - IBattleInfoCallback API
 +
* EVENT_BUS - opaque handle, for use with events API
 +
* SERVICES - root "raw" access to all static game objects
 +
** SERVICES:artifacts()
 +
** SERVICES:creatures()
 +
** SERVICES:factions()
 +
** SERVICES:heroClasses()
 +
** SERVICES:heroTypes()
 +
** SERVICES:spells()
 +
** SERVICES:skills()
 +
* require(URI)
 +
** works similar to usual Lua require
 +
** require("ClassName") - loads additional API and returns it as table (for C++ classes)
 +
** require("core:relative.path.to.module") - loads module from "SCRIPTS/LIB"
 +
** {{todo}} require("modName:relative.path.to.module") - loads module from dependent mod
 +
** {{todo}} require(":relative.path.to.module") - loads module from same mod
 +
* logError(text) - backup error log function
 +
=== Low level events API ===
 +
 
 +
<syntaxhighlight lang="Lua">
 +
 
 +
-- Each event type must be loaded first
 +
local PlayerGotTurn = require("events.PlayerGotTurn")
 +
 
 +
-- in this example subscription handles made global, do so if there is no better place
 +
-- !!! do not store them in local variables
 +
sub1 = PlayerGotTurn.subscribeAfter(EVENT_BUS, function(event)
 +
--do smth
 +
end)
 +
 
 +
sub2 = PlayerGotTurn.subscribeBefore(EVENT_BUS, function(event)
 +
--do smth
 +
end)
 +
 
 +
</syntaxhighlight>
 +
 
 +
=== Lua standard library ===
 +
VCMI uses LuaJIT, which is Lua 5.1 API, see [https://www.lua.org/manual/5.1/manual.html upstream documentation]
 +
 
 +
Following libraries are supported
 +
* base
 +
* table
 +
* string
 +
* math
 +
* bit
 +
 
 +
= ERM =
 +
== Features ==
 +
* no strict limit on function/variable numbers (technical limit 32 bit integer except 0))
 +
* {{todo}} semi compare
 +
* {{done}} macros
 +
 
 +
== Bugs ==
 +
* {{todo}} Broken XOR support (clashes with `X` option)
 +
 
 +
== Triggers ==
 +
* {{todo}} '''!?AE''' Equip/Unequip artifact
 +
* {{wip}} '''!?BA''' when any battle occurs
 +
* {{wip}} '''!?BF'''  when a battlefield is prepared for a battle
 +
* {{todo}} '''!?BG''' at every action taken by any stack or by the hero
 +
* {{todo}} '''!?BR''' at every turn of a battle
 +
*  ''!?CM (client only)  click the mouse button.''
 +
* {{todo}} '''!?CO''' Commander triggers 
 +
* {{todo}} '''!?DL''' Custom dialogs
 +
* {{done}} '''!?FU''' function
 +
* {{todo}} '''!?GE''' "global" event 
 +
* {{todo}} '''!?GM''' Saving/Loading
 +
* {{todo}} '''!?HE''' when the hero # is attacked by an enemy hero or visited by an allied hero 
 +
* {{todo}} '''!?HL''' hero gains a level
 +
* {{todo}} '''!?HM''' every step a hero # takes
 +
* ''!?IP Multiplayer support. ''
 +
* {{todo}} '''!?LE''' (!$LE) An Event on the map
 +
* {{wip}} '''!?MF''' stack taking physical damage(before an action)
 +
* {{todo}} '''!?MG''' casting on the adventure map 
 +
* ''!?MM scroll text during a battle ''
 +
* {{todo}} '''!?MR''' Magic resistance
 +
* {{todo}} '''!?MW''' Wandering Monsters
 +
* {{wip}} '''!?OB''' (!$OB) visiting objects
 +
* {{done}} '''!?PI'''  Post Instruction.
 +
* {{todo}} '''!?SN''' Sound and ERA extensions
 +
*  ''!?TH town hall''
 +
* {{todo}} '''!?TL''' Real-Time Timer
 +
* {{todo}} '''!?TM''' timed events
  
* {{todo}} JsonNode`s in Advmap objects.
+
== Receivers ==
* (*) global state of scripts and scripts itself. + reloading scripts (Era like)
+
=== VCMI ===
 +
* '''!!MC:S@varName@''' - declare new "normal" variable (technically v-var with string key)
 +
* {{todo}} Identifier resolver
 +
* {{wip}} Bonus system
  
== Engine interaction ==
+
=== ERA ===
 +
* {{done}} !!if !!el !!en
 +
* {{todo}} !!br !!co
 +
* {{todo}} !!SN:X
  
* read only through callbacks
+
=== WoG ===
* '''ALL''' changes through NetPacks
+
* {{todo}} !!AR Артефакт (ресурс) в определенной позиции
 +
* {{todo}} !!BA Битва
 +
** !!BA:A$ return 1 for battle evaluation
 +
* {{todo}} !!BF Препятствия на поле боя
 +
* {{todo}} !!BG Действий монстров в бою
 +
* {{todo}} !!BH Действия героя в бою
 +
* {{todo}} !!BM Монстр в битве
 +
* {{wip}} !!BU Универсальные параметры битвы
 +
* {{todo}} !!CA Замок
 +
* {{todo}} !!CD Разрушения замков
 +
* {{todo}} !!CE События в замке
 +
* {{todo}} !!CM Клика мышью
 +
* {{todo}} !!DL Нестандартный диалог (только ТЕ или выше)
 +
* {{todo}} !!CO Командиры
 +
* {{wip}} !!DO Многократный вызов функции
 +
* {{todo}} !!EA Бонусы опыта существ
 +
* {{todo}} !!EX Опыт стека
 +
* {{done}} !!FU Однократный вызов функции
 +
* {{todo}} !!GE Глобальное событие
 +
* {{wip}} !!HE Герой
 +
* {{todo}} !!HL Новый уровень героя
 +
* {{todo}} !!HO Взаимодействия героев
 +
* {{todo}} !!HT Подсказки по правому клику
 +
* {{wip}} !!IF Диалоги и флагов
 +
* {{todo}} !!IP Сетевой сервис битвы
 +
* {{todo}} !!LE Локальное события
 +
* {{wip}} !!MA Общие параметры монстров
 +
* {{done}} !!MC Макросы
 +
* {{wip}} !!MF Получение физ. урона в бою
 +
* {{todo}} !!MM Текст в битве
 +
* {{wip}} !!MO Монстр в определенной позиции
 +
* {{todo}} !!MP Контроль MP3
 +
* {{todo}} !!MR Сопротивления магии
 +
* {{todo}} !!MW Бродячих монстров
 +
* {{wip}} !!OB Объект в определенной позиции
 +
* {{todo}} !!OW Параметры игрока
 +
* {{todo}} !!PM Пирамиды или новые объекты
 +
* {{todo}} !!PO Информация квадрата карты
 +
* {{todo}} (???) !!QW Журнала
 +
* {{todo}} !!SN Проигрываемые звуков
 +
* {{todo}} !!SS Настройка заклинаний (только ТЕ или выше)
 +
* {{todo}} !!TL Контроль времени хода (только ТЕ или выше)
 +
* {{todo}} !!TM Временный таймер
 +
* {{todo}} !!TR Квадрата карты (почва, проходимость, т.п.)
 +
* {{todo}} !!UN Универсальная команда
 +
''!#VC Контроль переменных''  
 +
* {{wip}} !!VR Установка переменных
  
== Problems ==
+
== Persistence ==
* How to override server logic when script acts at client side?
 

Latest revision as of 21:55, 11 May 2020

Configuration

{
 	//general purpose script, Lua or ERM, runs on server
 	"myScript":
	{
		"source":"path/to/script/with/ext",
		"implements":"ANYTHING"
	},


 	//custom battle spell effect, Lua only, runs on both client and server
 	//script ID will be used as effect 'type' (with mod prefix)
 	"mySpellEffect":
	{
		"source":"path/to/script/with/ext",
		"implements":"BATTLE_EFFECT"
	},

	//TODO: object|building type
 	//custom map object or building, Lua only, runs on both client and server
 	//script ID will be used as 'handler' (with mod prefix)
 	"myObjectType":
	{
		"source":"path/to/script/with/ext",
		"implements":"MAP_OBJECT"
	},
	//TODO: server query
	//TODO: client query

}

Lua

API Reference

[Todo] In near future Lua API may change drastically several times. Information here may be outdated

Globals

  • DATA - persistent table
    • DATA.ERM contains ERM state, anything else is free to use.
  • GAME - IGameInfoCallback API
  • BATTLE - IBattleInfoCallback API
  • EVENT_BUS - opaque handle, for use with events API
  • SERVICES - root "raw" access to all static game objects
    • SERVICES:artifacts()
    • SERVICES:creatures()
    • SERVICES:factions()
    • SERVICES:heroClasses()
    • SERVICES:heroTypes()
    • SERVICES:spells()
    • SERVICES:skills()
  • require(URI)
    • works similar to usual Lua require
    • require("ClassName") - loads additional API and returns it as table (for C++ classes)
    • require("core:relative.path.to.module") - loads module from "SCRIPTS/LIB"
    • [Todo] require("modName:relative.path.to.module") - loads module from dependent mod
    • [Todo] require(":relative.path.to.module") - loads module from same mod
  • logError(text) - backup error log function

Low level events API

-- Each event type must be loaded first
local PlayerGotTurn = require("events.PlayerGotTurn")

-- in this example subscription handles made global, do so if there is no better place
-- !!! do not store them in local variables
sub1 = 	PlayerGotTurn.subscribeAfter(EVENT_BUS, function(event)
		--do smth
	end)

sub2 = 	PlayerGotTurn.subscribeBefore(EVENT_BUS, function(event)
		--do smth
	end)

Lua standard library

VCMI uses LuaJIT, which is Lua 5.1 API, see upstream documentation

Following libraries are supported

  • base
  • table
  • string
  • math
  • bit

ERM

Features

  • no strict limit on function/variable numbers (technical limit 32 bit integer except 0))
  • [Todo] semi compare
  • [Done] macros

Bugs

  • [Todo] Broken XOR support (clashes with `X` option)

Triggers

  • [Todo] !?AE Equip/Unequip artifact
  • [WiP] !?BA when any battle occurs
  • [WiP] !?BF when a battlefield is prepared for a battle
  • [Todo] !?BG at every action taken by any stack or by the hero
  • [Todo] !?BR at every turn of a battle
  • !?CM (client only) click the mouse button.
  • [Todo] !?CO Commander triggers
  • [Todo] !?DL Custom dialogs
  • [Done] !?FU function
  • [Todo] !?GE "global" event
  • [Todo] !?GM Saving/Loading
  • [Todo] !?HE when the hero # is attacked by an enemy hero or visited by an allied hero
  • [Todo] !?HL hero gains a level
  • [Todo] !?HM every step a hero # takes
  • !?IP Multiplayer support.
  • [Todo] !?LE (!$LE) An Event on the map
  • [WiP] !?MF stack taking physical damage(before an action)
  • [Todo] !?MG casting on the adventure map
  • !?MM scroll text during a battle
  • [Todo] !?MR Magic resistance
  • [Todo] !?MW Wandering Monsters
  • [WiP] !?OB (!$OB) visiting objects
  • [Done] !?PI Post Instruction.
  • [Todo] !?SN Sound and ERA extensions
  • !?TH town hall
  • [Todo] !?TL Real-Time Timer
  • [Todo] !?TM timed events

Receivers

VCMI

  • !!MC:S@varName@ - declare new "normal" variable (technically v-var with string key)
  • [Todo] Identifier resolver
  • [WiP] Bonus system

ERA

  • [Done] !!if !!el !!en
  • [Todo] !!br !!co
  • [Todo] !!SN:X

WoG

  • [Todo] !!AR Артефакт (ресурс) в определенной позиции
  • [Todo] !!BA Битва
    •  !!BA:A$ return 1 for battle evaluation
  • [Todo] !!BF Препятствия на поле боя
  • [Todo] !!BG Действий монстров в бою
  • [Todo] !!BH Действия героя в бою
  • [Todo] !!BM Монстр в битве
  • [WiP] !!BU Универсальные параметры битвы
  • [Todo] !!CA Замок
  • [Todo] !!CD Разрушения замков
  • [Todo] !!CE События в замке
  • [Todo] !!CM Клика мышью
  • [Todo] !!DL Нестандартный диалог (только ТЕ или выше)
  • [Todo] !!CO Командиры
  • [WiP] !!DO Многократный вызов функции
  • [Todo] !!EA Бонусы опыта существ
  • [Todo] !!EX Опыт стека
  • [Done] !!FU Однократный вызов функции
  • [Todo] !!GE Глобальное событие
  • [WiP] !!HE Герой
  • [Todo] !!HL Новый уровень героя
  • [Todo] !!HO Взаимодействия героев
  • [Todo] !!HT Подсказки по правому клику
  • [WiP] !!IF Диалоги и флагов
  • [Todo] !!IP Сетевой сервис битвы
  • [Todo] !!LE Локальное события
  • [WiP] !!MA Общие параметры монстров
  • [Done] !!MC Макросы
  • [WiP] !!MF Получение физ. урона в бою
  • [Todo] !!MM Текст в битве
  • [WiP] !!MO Монстр в определенной позиции
  • [Todo] !!MP Контроль MP3
  • [Todo] !!MR Сопротивления магии
  • [Todo] !!MW Бродячих монстров
  • [WiP] !!OB Объект в определенной позиции
  • [Todo] !!OW Параметры игрока
  • [Todo] !!PM Пирамиды или новые объекты
  • [Todo] !!PO Информация квадрата карты
  • [Todo] (???) !!QW Журнала
  • [Todo] !!SN Проигрываемые звуков
  • [Todo] !!SS Настройка заклинаний (только ТЕ или выше)
  • [Todo] !!TL Контроль времени хода (только ТЕ или выше)
  • [Todo] !!TM Временный таймер
  • [Todo] !!TR Квадрата карты (почва, проходимость, т.п.)
  • [Todo] !!UN Универсальная команда
  • !#VC Контроль переменных
  • [WiP] !!VR Установка переменных

Persistence