tnsc4502
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    A report about Script System in Wvs project and OdinMS === (You can refer [3ad5fc5](https://github.com/tnsc4502/mnwvs196/tree/3ad5fc5494b65aa4ec997da3a78ecfae604a9987) as the one with old script system and [8793fce](https://github.com/tnsc4502/mnwvs196/tree/8793fceed8440dd936881e901234b02118f98f21) as the latest one with updated script system.) An experiment about using std::thread to execute a script asynchronously showed that it may causes frequently D.C. To begin with, I will briefly describe the pipeline of script execution, and in this report we only consider two scenarios to start up a script, the first one is by User_OnSelectNpc packet, and the other one, in this report, is by FieldSet. The packet "User_OnSelectNpc" is received when players click NPCs, then the server side invokes a corresponding script by calling pScript->Run() where lua_pcall is called to execute the lua script file. ```graphviz digraph User_OnSelectNpc_pipleline { rankdir=LR; node [shape=record]; { "User::OnPacket"->"Script::Run"->"lua_pcall"; } } ``` Invoking a lua script by lua_pcall is similar to call a function, the caller keep waiting until finish the whole script. Moreover, the conversation between the player and the Npc continues only when the player respond. For example, the following simple lua code(self represents the script system itself, askNumber shows a conversation with a textbox requires the player input an integer and onSay shows a simple conversation with an OK button): ``` lua= inputNum = self.askNumber("Input an arbitrary number (0 ~ 1000):", 0, 0, 1000) self.onSay("You input:" . inputNum) ``` Obviously, without player's response (inputNum), the script SHOULD NOT execute line2 since inputNum is undefined. Let's see what happens in askNumber(and other functions that are used to make the conversation): ```graphviz digraph askNumber_example { rankdir=LR; node [shape=record]; { "self.askNumber" ->"Script::SelfAskNumber" ->"User::SendPacket(MessageInfo)" ->"Script::Wait" ->"Return user's input"; } } ``` where Script::Wait will enter some kind of infinite loop(e.g, while(1) in C++) and only be woken up by User_OnScriptMessageAnswer packet. In consideration of the CPU utilization, we don't actually use while(1) to wait the response but conditional_variable instead. To wake up the suspended script, it sets the user input according to the packet information(we skip the details here) and calls m_pScript->Notify() at User::OnScriptMessageAnswer; therefore the Script::SelfAskNumber is now able to return a valid value. ```graphviz digraph wait_and_notify { { rankdir=LR; node [shape=record style=filled]; a [label="1. Script::Wait"] b [fillcolor=yellow label="2. m_cndVariable.wait"] c [label="3. Script::Notify"] d [label="4. m_cndVariable.notify_one"] e [label="5. lua_pushinteger(return user's input)"] } a->b->e c->d } ``` In original OdinMS, it uses state-machine mechanism to handle the conversation, every Npc script have function action(mode, type, selection) which is used to indicate current state and user's response (except askText and askNumber), each time the User_OnScriptMessageAnswer packet is received, the server invoke it again and pass different parameters to distinguish the state. The main reason, I guess, why the developer of OD adopted this way is simplicity, especially when making the conversation with prev/next button. When clicking the prev button, it requires the script system roll back to the previous line and perform the instruction again; however, the built-in script system in Java doesn't support such manipulation like "rewind", and lua neither. The OD simply solved this problem(It's not a problem technically) by increasing/decreasing the state(In [3ad5fc5](https://github.com/tnsc4502/mnwvs196/tree/3ad5fc5494b65aa4ec997da3a78ecfae604a9987), we solve the problem by using a for-loop with a page indicator which is controlled by user's response, for more details, please refer to Script::SelfSayNextGroup, in [8793fce](https://github.com/tnsc4502/mnwvs196/tree/8793fceed8440dd936881e901234b02118f98f21) we use message-based mechanism instead, please refer to ScriptNPCConversation::SelfSayNext); however, it somehow brings itself inconvenience to write the script. For example, the following nested askMenu in OD style: ``` javascript= if(state == 0) { cm.sendSimple("Select an option:#L1#Buy something#l\r\n#L2#Job Selection(For beginner)#l"); } else if(state == 1) { if(selection == 1) { cm.sendSimple("Which item you want to buy?...."); nextState = 2 } else if(selection == 2) { cm.sendSimple("Which job you want to be?..."); nextState = 3 } } else if(state == 2) { cm.sendYesNo("You really want this item? It costs..."); nextState = 4 } else if(state == 3) { cm.sendYesNo("You really want to be this job? You can't change the job once you've decided."); nextState = 5 } else if(state == 4) { if(selection == 1) cm.gainItem(...); else cm.sendOk("Don't waste my time!"); } else if(state == 5) { if(selection == 1) cm.changeJob(...); else cm.sendOk("Take some time to consider carefully..."); } ``` Comparing to the reformed one below, the latter one seems better: ``` javascript= if(state == BEGIN) { cm.sendSimple("Select an option:#L1#Buy something#l\r\n#L2#Job Selection(For beginner)#l"); } else if(state == MENU_SELECTION_1) { if(selection == 1) { cm.sendSimple("Which item you want to buy?...."); nextState = ITEM_SELECTION } else if(selection == 2) { cm.sendSimple("Which job you want to be?..."); nextState = JOB_SELECTION } } else if(state == ITEM_SELECTION) { cm.sendYesNo("You really want this item? It costs..."); nextState = ITEM_SELECTION_CONFIRM } else if(state == JOB_SELECTION) { cm.sendYesNo("You really want to be this job? You can't change the job once you've decided."); nextState = JOB_SELECTION_CONFIRM } else if(state == ITEM_SELECTION_CONFIRM) { ... } else if(state == JOB_SELECTION_CONFIRM) { ... } ``` It now at least have descriptions of states not only strange numbers, but it still requires lots efforts to trace and read the whole script, the more complex the script is, the more pain you will feel. The elegant way to implement this script in our project may like this(I've re-implemented some OD-based servers, they are now able to execute scripts in this way too): ``` javascript= selection = self.askMenu("Select an option:#L1#Buy something#l\r\n#L2#Job Selection(For beginner)#l"); if(selection == 1) { selection = self.askMenu("Which item you want to buy?...."); if(self.askYesNo("You really want this item? It costs...")) self.exchange(0, selection, 1) else self.onSay("Don't waste my time!") } else if(selection == 2) { selection = self.askMenu("Which job you want to be?..."); if(self.askYesNo("You really want to be this job? You can't change the job once you've decided.")) self.setJob(selection) else self.onSay("Take some time to consider carefully...") } ``` For me and NEXON, it just resembles to write a C/C++ code. The story of OD is now over, we should back to Script::Wait. Imagine that a player clicks a Npc and suddenly leave his seat, as mentioned before, the server invokes the script via lua_pcall and keeps waiting the response to the conversation, and finally the server is blocked consequently. The whole server, at least for that player(if every socket has it's own thread, then the thread will be blocked rather than the whole server), can no longer receive/send any packets since the server is blocked by Script::Wait, that is a disaster because it should still be able to receive/send packets even when talking to Npc(e.g, the party or buddy notification). To prevent the server from being blocked by scripts, we first use std::thread to perform pScript->run() concurrently. Yet we quickly discovered that it has high probability(3/5) to cause the client to disconnect from server and return to Login Section every time the player clicks the Npc. Honestly, I haven't figured out the real reason, but since D.C. usually caused by asymmetric IV between client and server(the encryption code didn't take thread-safety into design consideration), and I think the conditional waiting caused somewhere being unsynchronized, the clue is probably around there. Fortunately, lua provides another lightweight method "coroutine" to do things like "concurrently", we don't discuss the difference between coroutine and other concurrent models here. There are two important functions related to our script system: lua_resume which resumes to run the script and lua_yield which enables us the ability to pause the execution of the script. Our new pipeline of how the script system work is like below: ```graphviz digraph User_OnSelectNpc_pipleline { rankdir=LR; node [shape=record]; { "User::OnPacket"->"Script::Run"->"lua_resume"; } } ``` The difference between lua_resume and lua_pcall is that the former just invoke the script asynchronously and return a state immediately(if the value is LUA_OK or value not LUA_YIELD, we abort the script) unlike the latter one which wait the whole script being run through. Now we don't need std::thread and conditional variables anymore, the new Script::Wait simply calls lua_yield to pause the execution, and Script::Notify just calls Script::Run to resume the execution. For implementation details, please refer to [8793fce](https://github.com/tnsc4502/mnwvs196/tree/8793fceed8440dd936881e901234b02118f98f21), we divided the script system into core, conversation-related and others. Using coroutine doesn't cause any D.C. problem, and the overall performance seems better than using std::thread and conditional variables. In the other scenario, the FieldSet may invoke an arbitrary function in scripts(like events in OD). For example, when reaching the time limit, we may want to call onTimedOut in the script to do some stuffs. To call lua a function from C++ side, it requires first calling lua_getglobal(lua state obj, "func name"), and then calling lua_resume. But luaL_loadfile won't get all symbols in the script since it doesn't run through the whole script, we need to call lua_pcall after initializing the script. To conclude, the script system in wvs project is adaptable to any scenarios in MapleStory and is stable enough though most helper functions like transerFieldRequest haven't implemented yet LEL.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully