Oussama Essamadi

Publications

SA:MP after sampctl and open.mp

How sampctl and then open.mp changed the way SA:MP scripts are written, shared and run, from someone who wrote tutorials before either existed.

Publié

Temps de lecture

13 minutes

Article

Hello everyone, it’s been a while (a long while), and this one isn’t a tutorial, it’s more of a look back at how scripting for SA:MP changed since I wrote my first tutorials, and believe me, it changed a lot.

So what got me writing? On the 10th of November, open.mp released v1.1.0.2612 (opens in a new tab), its first release out of the RC phase, and it comes with its own launcher too, so goodbye old SA:MP browser. That’s huge for a mod of a game from 2004, and honestly, it’s the second time in a few years that the way we write SA:MP code got flipped upside down, the first time being sampctl.

This is going to be a long one, so grab a coffee (or tea, I don’t judge).

How it used to be

If you’ve read any of my old tutorials, you already know how they all started, a “Requirements” section full of links, sscanf from a MediaFire link, ZCMD from some file host that doesn’t even exist anymore, YSI from its forum thread… you’d download each one by hand, drop it in your folder and pray it’s the same version the tutorial was written with.

A game mode would usually open with something like this:

#include <a_samp>
#include <sscanf2>
#include <zcmd>
#include <streamer>

Every one of those lines was a file you found somewhere and copied into pawno/include, right next to the compiler that came with the server. And the server itself was set up with a server.cfg, where your plugins had to end with .so on Linux and .dll on Windows (and yes, people mixed those up all the time):

gamemode0 mymode 1
filterscripts admin
plugins sscanf.so streamer.so
rcon_password something-secret
port 7777

No record of what version you had, no way to update everything at once, and good luck sending your project to a friend and having it compile on their machine on the first try. Every server had its own include folder, copied from somewhere, edited sometimes, documented never.

And now even the places those links lived are gone, the certificates for forum.sa-mp.com and wiki.sa-mp.com expired on the 25th of September 2020 (opens in a new tab) and neither of them came back, what’s left is archive copies, and whatever people managed to move somewhere else in time.

sampctl

Then came sampctl (opens in a new tab). Southclaws released 1.0.0 on the 22nd of September 2017, and if you’ve ever touched npm, pip or gem, you already get the idea, it’s a package manager, a build tool and a config manager all in one, written in Go, so it runs the same on Windows, Linux and macOS. Pawn just never had one before that.

pawn.json

Everything starts with a pawn.json (or pawn.yaml if that’s more your thing) at the root of your project, and you don’t even have to write it yourself, sampctl package init asks you a couple of questions and writes it for you, it would look something like this:

{
  "user": "eoussama",
  "repo": "my-gamemode",
  "entry": "gamemodes/main.pwn",
  "output": "gamemodes/main.amx",
  "dependencies": [
    "pawn-lang/samp-stdlib",
    "pawn-lang/YSI-Includes",
    "Southclaws/formatex"
  ]
}

entry is the script to compile, output is where the .amx ends up, and dependencies is basically your old include folder, except it’s written down this time. There’s also dev_dependencies, for stuff you only need while building or testing.

Every dependency is just a GitHub repository, and you can pin it as tight as you want:

user/repo              the repository as it is
user/repo:1.2.3        a tag, ranges like 1.2.x or 2.x work too
user/repo@branch       a branch
user/repo#<sha>        an exact commit (all 40 characters of it)
user/repo/includes     includes kept in a subfolder of the repository

That file alone kills the whole “what version do you have?” conversation, commit it, and whoever clones your project gets the exact same libraries you have.

The commands

These are the ones you’ll be typing the most:

sampctl package init                          # writes pawn.json (and a VS Code tasks.json if you want one)
sampctl package install Southclaws/formatex   # adds a dependency and downloads it
sampctl package ensure                        # downloads everything pawn.json lists
sampctl package build                         # compiles the entry script
sampctl package build --watch                 # rebuilds on every file change
sampctl package run                           # compiles, starts a server and runs the script

The README has a nice little example of how easy it is to try a library out, with formatex installed:

#include <a_samp>
#include <formatex>

main() {
    new str[128];
    formatex(str, sizeof str, "My favourite vehicle is: '%v'!", 400); // should print "Landstalker"
    print(str);
}

Run sampctl package run, and it downloads a server, compiles the script, starts the server and prints My favourite vehicle is: 'Landstalker'!. No going to sa-mp.com, no unzipping server packages, no telling the compiler where your includes are. It can even download the compiler for you, so trying a newer one is a one-line change, and if you’re into Docker, --container runs the whole thing inside a container instead.

The server side

sampctl takes care of the server too, with a samp.json that sampctl server init creates for you, you write this:

{
  "gamemodes": ["rivershell"],
  "plugins": ["maddinat0r/sscanf"],
  "rcon_password": "test",
  "port": 8080
}

and it generates the server.cfg for you, downloads the right sscanf build into plugins/ (.so or .dll, it figures that out on its own), and sampctl server run restarts the server whenever it crashes, which is more than I can say about most of the restart scripts I’ve seen.

Everything around it

The bigger change wasn’t the tool though, it was the culture around it, includes started living in actual repositories, with versions, issues and pull requests, instead of a forum post with a download link at the bottom, and once a library is a repository, contributing to it is just a pull request away.

formatex

Take Slice’s formatex for example, it never had a repository of its own, so in September 2017 Southclaws put it on GitHub (opens in a new tab) as a sampctl package. If you don’t know it, it extends format with extra specifiers, %p for a player’s name, %v for a vehicle model name, %w for a weapon name, and it lets you make your own too.

My first contribution there was fixing its weapon names back in May 2018, then in February 2020 I added custom fallback values (opens in a new tab), basically what those specifiers print when the ID they get is invalid:

#define FORMAT_FALLBACK_p "Unknown player"
#define FORMAT_FALLBACK_v "Unknown vehicle"
#include <formatex>

main() {
    printf("%p", INVALID_PLAYER_ID); // Unknown player
    printf("%v", 10);                // Unknown vehicle
}

Same thing goes for %P, %W and %w.

VS Code

Editors caught up too (rest in peace pawno). Pawn Tools for VS Code (opens in a new tab) gives you syntax highlighting and completions, and with sampctl it gets even easier, sampctl package init writes the .vscode/tasks.json for you and Ctrl+Shift+B just builds. You get four tasks, build only, build watcher, run tests and run tests watcher, and compiler errors show up in the Problems panel with the right file paths, something the plain compiler setup never got right with external includes.

Back in early 2019 I added descriptions for its macros and standard definitions, plus more autocompletion entries, and later the missing strcpy completion, oh and a typo fix in YSI (hey, it counts).

The compiler

The compiler moved on as well, the community-maintained pawn-lang/compiler (opens in a new tab) has been putting out 3.10.x releases since January 2017, 3.10.10 being the one from February 2020, fixing bugs and catching stuff the old one used to just let slide, and since sampctl downloads compilers on demand, upgrading stopped being something you had to do by hand on every machine.

The wiki

When the SA:MP wiki went offline at the end of September 2020, the open.mp team started moving its content over to open.mp/docs (opens in a new tab), and anyone could chip in, so on the 3rd and 4th of October I converted my String manipulation tutorial into a page there, and it still lives there as String Manipulation (opens in a new tab) if you want to check it out.

It might not sound like a big deal, but a lot of us learned Pawn from a forum that doesn’t exist anymore, so moving those tutorials somewhere that’s actually maintained matters.

open.mp

Now to the main event. open.mp isn’t a fork, the team rewrote the server from scratch (opens in a new tab) instead of building on top of the leaked SA:MP source, and kept it a drop-in replacement, SA:MP clients connect to it just fine, and your old .amx loads without even recompiling.

Release Candidate 1 (opens in a new tab) dropped on the 5th of January 2023, with a post that opens with “After four years, two rewrites, arguments and drama, and countless other hurdles; it is finally here!”, and if you followed the project at all, you know that’s not an exaggeration. RC2 came a few days later, mostly fixes and upgrader improvements, and then on the 10th of November, v1.1.0.2612 took it out of RC, with a long list of fixes, a 64-bit build, and the open.mp launcher (opens in a new tab), the first step towards an actual open.mp client.

And the part that matters the most for us scripters, Pawn stays. It’s still the official way to write a game mode and it’s not going anywhere, what changes is pretty much everything around it.

What changes in your code

One include

open.mp ships its own official includes (opens in a new tab), so no more patching the SA:MP ones, your game mode swaps a_samp for one line:

#include <open.mp>

They also come with documentation for three levels, beginner, intermediate (“just tell me how to upgrade”) and expert, where every change is explained with the reasoning behind it, worth a read if you have the time.

const

Some functions only read a string, others write into it, and the includes now actually say which is which:

// Only reads the string, so it's declared const:
native SendRconCommand(const cmd[]);
SendRconCommand("loadfs objects"); // fine

// Writes into the array, so it isn't:
native GetPlayerName(playerid, name[], size = sizeof (name));
GetPlayerName(playerid, "Bob"); // makes no sense, and the compiler now tells you so

Long story short, you can pass string literals straight into any function that only reads them, and the compiler yells at you when you try to write into something you shouldn’t.

Tags, tags everywhere

Parameters that only accept a fixed set of values are enums now, so passing a wrong value gives you a warning instead of a silent bug:

TextDrawAlignment(textid, TEXT_DRAW_ALIGN_LEFT); // fine
TextDrawFont(textid, 7);                         // warning

The docs have an example that shows why this matters, have a look at this:

switch (GetPVarType(playerid, "MY_DATA"))
{
case 0: printf("Unknown type");
case 1: printf("Found an int");
case 2: printf("Found a float");
case 3: printf("Found a string");
case 4: printf("Found a boolean");
}

Looks fine, right? This compiled for years, and it’s wrong twice (take a second and try to spot it), 2 is a string, 3 is a float, and there’s no type 4 at all. GetPVarType now returns a VARTYPE: tag, so those bare numbers give you tag warnings, and once you swap them for VARTYPE_STRING, VARTYPE_FLOAT and friends, both mistakes are right there in front of you, and VARTYPE_BOOL doesn’t even exist, so that last line turns into an error.

The tags are weak by default, meaning an integer where an enum is expected gives you a warning, but not the other way around, and you can change that with a define before the include:

#define STRONG_TAGS   // strict both ways
// or
#define NO_TAGS       // off, for that old codebase you just want running
#include <open.mp>

Callbacks

This is the only breaking change the tags bring, callbacks have tagged parameters too now, and the recommended fix compiles whatever your tag settings are:

#if !defined WEAPON
    #define WEAPON: _:
#endif
public OnPlayerDeath(playerid, killerid, WEAPON:reason)
{
    return 1;
}

Same thing for OnPlayerStateChange (PLAYER_STATE:), OnPlayerKeyStateChange (KEY:), OnPlayerWeaponShot and the rest, and there’s a callback-upgrade tool that does it for a whole folder at once.

Better names

The compiler’s symbol limit went up to 64 characters, so all those cut-short names finally got their full spelling, the old ones still work, but they’re deprecated, and the warning tells you what to use instead:

#pragma deprecated Use `SetPlayer3DTextLabelDrawDistance`
native bool:SetPlayer3DTextLabelDrawDist(playerid, PlayerText3D:textid, Float:drawDistance);

#pragma deprecated Use `TextDrawColour`
native bool:TextDrawColor(Text:textid, textColour);

(yes, TextDrawColour, with a u)

No more format juggling

Natives that take text, like SendClientMessage, now accept format arguments directly, so the good old format-into-a-buffer dance is gone:

// Before
new msg[64];
format(msg, sizeof msg, "Your score is %d", GetPlayerScore(playerid));
SendClientMessage(playerid, -1, msg);

// With open.mp
SendClientMessage(playerid, -1, "Your score is %d", GetPlayerScore(playerid));

I can’t even count how many times I’ve written that “Before” part.

The compiler

open.mp ships with compiler 3.10.11 and an updated VM inside the server, you get __nameof, __addressof, a faster switch, more warnings for things it used to miss, and -O2 optimization that actually works. The only breaking compiler change is include guards, the new compiler doesn’t skip a file it already included anymore, so every include needs its own guard (game modes don’t):

#if defined _INC_my_include
    #endinput
#endif
#define _INC_my_include

The upgrader

Thankfully you don’t have to do all of that by hand, the upgrade (opens in a new tab) tool finds untagged and const-incorrect code and fixes it for you:

./upgrade --report --scans const ./gamemodes   # shows what would change
./upgrade --scans const ./gamemodes            # applies it
./upgrade --scans tags ./gamemodes

It rewrites native declarations, their hooks and the calls, SetTimer("MyFunction", 2000, 0); for example becomes SetTimer("MyFunction", 2000, false);. My advice, run the report first, read it, then apply.

Running it

config.json

The server reads a config.json now, server.cfg still works, but config.json has more settings, and you don’t have to write it from scratch either, omp-server --dump-config converts your existing server.cfg, and omp-server --default-config writes a fresh one. These are the parts you’ll be touching the most:

{
  "name": "My open.mp server",
  "max_players": 50,
  "network": {
    "port": 7777
  },
  "rcon": {
    "password": "something-secret"
  },
  "pawn": {
    "main_scripts": ["mymode 1"],
    "side_scripts": ["filterscripts/admin"],
    "legacy_plugins": ["mysql", "streamer"]
  }
}

Game modes go in main_scripts, filterscripts in side_scripts, and your old plugins in legacy_plugins, without the .so or .dll. Oh, and if you leave the RCON password as changeme, the server refuses to start (as it should).

With sampctl

sampctl and open.mp work together just fine, with one little trick, libraries that depend on samp-stdlib would pull the old includes in next to the new ones, so both stdlib repos got an empty @open.mp branch. Put these three first in your pawn.json, everything else after them, and include <open.mp> in your main file:

{
  "dependencies": [
    "openmultiplayer/omp-stdlib",
    "pawn-lang/samp-stdlib@open.mp",
    "pawn-lang/pawn-stdlib@open.mp"
  ]
}

Remember the branch syntax from earlier? That’s it doing its job.

Where we are now

SA:MP development today looks nothing like it did when I started, projects have a manifest, dependencies are pinned, editors understand the code, the compiler catches mistakes it used to let through, and the server itself is maintained out in the open, by people who clearly care about it.

Not bad for a mod of a game that came out almost twenty years ago.

That’s it for this one, thanks for reading, and see you in the next one!

Suivant

ouLes 21 publicationsouAu hasardouAccueil

ProjetsPublications

Chargement de la liste…

Chargement de la liste…

Raccourcis clavier

Recherche et commandes
Ctrl K⌘K
Passer du clair au sombre
T
Tous les projets
P
Toutes les publications
W
Chercher dans la liste ouverte
S
Accueil
H
M’écrire
C
Afficher ces raccourcis
?
Fermer ce qui est ouvert
esc

Les raccourcis sont activés.