// PlayerTwo for Unity WebGL (2021.3 or later, Unity 6 included): PlayerTwo's game SDK from C# (the owner, 2026-12-03:
// "Build these: ... Unity and Godot bridges in the browser"). A WebGL build hosted on PlayerTwo has the SDK in its page
// (https://playertwo.plus/sdk/v1.js); PlayerTwo.jslib calls it, and this file is its C# side.
//
// Put P2.cs and P2Runner.cs in Assets/PlayerTwo/ and PlayerTwo.jslib in Assets/Plugins/WebGL/ (or unzip
// https://playertwo.plus/sdk/playertwo-unity.zip into your project's folder). Then, once, early:
//
// P2.Init(r => {
// if (!r.Ok) { Debug.Log("Playing without PlayerTwo: " + r.Code); return; } // "not-on-player-two"
// Debug.Log("Hello " + P2.Player.Name);
// });
// P2.Trophies.Unlock("first-win");
// P2.Scores.Submit("time-attack", 83.4, r => Debug.Log("Rank " + r["rank"].Int));
// P2.Saves.Put("slot-1", JsonUtility.ToJson(state));
// P2.Store.Buy("blaze-ball", r => { if (r.Ok && r["ok"].Bool) Equip(r["product"]["key"].Str); });
//
// Every call answers once, by its callback, in Update on the main thread (never inside the call that asked): a P2Result
// with Ok, and Data (the SDK's own answer as JSON: r["rank"].Int, r.Data["trophy"]["name"].Str), or Code, Message and
// Status when it was refused. In the Unity editor, and in any build but WebGL, every call answers Ok = false with code
// "not-on-player-two" and nothing else happens; in a WebGL build anywhere but PlayerTwo (or localhost) the same.
// Docs: https://playertwo.plus/docs/sdk/engines
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using AOT;
using UnityEngine;
namespace PlayerTwoSdk
{
/// A call's answer: Ok and Data, or Code, Message and Status when it was refused (Data then holds the
/// refusal, with anything else it carries: a save's "version", a sale's "from").
public sealed class P2Result
{
public bool Ok;
/// "not-on-player-two", "offline", "timeout", "unknown-trophy", "version", "no-store", "guest", ...
public string Code;
public string Message;
/// The HTTP status behind a refusal, or 0.
public int Status;
/// The answer as JSON text, to read with JsonUtility.FromJson if you like.
public string Json;
public P2Json Data = P2Json.Null;
/// The room, for P2.Rooms' calls.
public P2Room Room;
public P2Json this[string key] { get { return Data[key]; } }
/// A save read back (P2.Saves.Get) as its bytes, or as text.
public byte[] SaveBytes() { var b64 = Data["data"].Str; return string.IsNullOrEmpty(b64) ? new byte[0] : Convert.FromBase64String(b64); }
public string SaveText() { return Encoding.UTF8.GetString(SaveBytes()); }
public override string ToString() { return Ok ? Json : Code + " (" + Status + "): " + Message; }
internal static P2Result From(bool ok, string json)
{
var r = new P2Result { Ok = ok, Json = json };
try { r.Data = P2Json.Parse(json); }
catch (Exception e) { return Refused("bad-answer", "PlayerTwo's answer wasn't JSON: " + e.Message); }
if (!ok)
{
r.Code = r.Data["code"].Str ?? "failed";
r.Message = r.Data["message"].Str ?? r.Code;
r.Status = r.Data["status"].Int;
}
return r;
}
internal static P2Result Refused(string code, string message)
{
var d = new Dictionary { { "code", code }, { "message", message }, { "status", 0 }, { "env", "disabled" } };
return From(false, P2Json.Write(d));
}
}
/// The player: Id is theirs for your game only.
public sealed class P2Player
{
public string Id, Handle, Name, Picture, Creature;
public int Level;
internal static P2Player From(P2Json j)
{
if (j.Type != P2Json.Kind.Object) return null;
return new P2Player { Id = j["id"].Str, Handle = j["handle"].Str, Name = j["name"].Str, Picture = j["picture"].Str, Creature = j["creature"].Str, Level = j["level"].Int };
}
}
/// P2.Init's options.
public sealed class P2Options
{
/// How long to wait for PlayerTwo's page to answer, in ms (1500 when 0).
public int Timeout;
/// Outside PlayerTwo the page says "Play this on PlayerTwo" and Init never answers.
public bool Required;
/// The localhost stand-in's trophies, add-ons, products and params, as a JSON object
/// ({"trophies":[{"key":"first-win","name":"First win","tier":1}]}), or "true" to use the stand-in anywhere.
public string Local;
/// Where the page loads PlayerTwo's SDK from when it hasn't it (https://playertwo.plus/sdk/v1.js).
public string Sdk;
}
/// What P2.Rooms.Join, Create and Party take (leave out what you don't need).
public sealed class P2RoomOptions
{
/// A name you choose ("duel", "coop-hard").
public string Mode;
/// 1 to 64 players.
public int Size;
/// How many teams (2 to 16), the size split evenly between them.
public int Teams;
/// A private room's six-letter code.
public string Code;
/// The room you were in (its Id), to come back to it.
public string Room;
/// A match by skill: players rated near you first.
public bool Skill;
/// A match for your whole party, on one team.
public bool Together;
/// Keep the room as a replay.
public bool Record;
/// Keep the room where it opened (by default it moves between far-apart players).
public bool StayPut;
/// Your own version of what your pages say to each other.
public string Net;
/// Milliseconds (1000 to 600000): the room says OnAlone once if nobody else came by then.
public int Alone;
internal Dictionary Json()
{
var o = new Dictionary();
if (!string.IsNullOrEmpty(Mode)) o["mode"] = Mode;
if (Size > 0) o["size"] = Size;
if (Teams > 0) o["teams"] = Teams;
if (!string.IsNullOrEmpty(Code)) o["code"] = Code;
if (!string.IsNullOrEmpty(Room)) o["room"] = Room;
if (Skill) o["skill"] = true;
if (Together) o["together"] = true;
if (Record) o["record"] = true;
if (StayPut) o["between"] = false;
if (!string.IsNullOrEmpty(Net)) o["net"] = Net;
if (Alone > 0) o["alone"] = Alone;
return o;
}
}
/// P2Room.SyncStart's options.
public sealed class P2SyncOptions
{
/// Sends a second (30 when 0; 15 in a match of more than 16).
public int Rate;
/// How far behind (ms) others are drawn; 0: each player's own ("auto").
public int Delay;
/// How far this player sees, in the units of the fields named x and z (or y); 0: no limit.
public float Near;
/// A jump longer than this between two updates is a teleport (0: never).
public float Snap;
/// Fields that are angles in radians, which turn the short way round.
public string[] Angles;
/// "replay" (the default) or "snap": how a scripted room's correction is applied.
public string Fix;
internal Dictionary Json()
{
var o = new Dictionary();
if (Rate > 0) o["rate"] = Rate;
if (Delay > 0) o["delay"] = Delay;
if (Near > 0) o["near"] = Near;
if (Snap > 0) o["snap"] = Snap;
if (Angles != null) o["angles"] = Angles;
if (!string.IsNullOrEmpty(Fix)) o["fix"] = Fix;
return o;
}
}
/// PlayerTwo's SDK. Call P2.Init once, early; every other call waits for it.
public static class P2
{
/// Where the game is: "p2" on PlayerTwo, "local" on localhost (the stand-in), "disabled" anywhere else
/// (the editor too); "" until Init has answered.
public static string Env { get; private set; }
/// Init answered Ok: PlayerTwo (or its stand-in) is there.
public static bool Ready { get; private set; }
public static P2Player Player { get; private set; }
public static string GameSlug { get; private set; }
public static string GameTitle { get; private set; }
/// True while its developer (or an admin) plays: see Test mode in the docs.
public static bool Test { get; private set; }
/// True in a demo: demos earn no trophies.
public static bool Demo { get; private set; }
/// A guest, playing without a PlayerTwo account: nothing is sold to a guest; ask with P2.SignUp.
public static bool Guest { get; private set; }
/// A small live picture of the game goes to the Plaza's screens.
public static bool OnAir { get; private set; }
/// The invite params the player came with (a join link, a friend's Join, a door), or null.
public static Dictionary Params { get; private set; }
/// PlayerTwo's own layer over the game opened (true: pause) or closed.
public static event Action OnOverlay;
/// The player is about to close the game: what you keep should go now. Heard at once (not in Update), and
/// every call you make while you hear it (a last P2.Saves.Put) is waited for, a moment and a half at most.
public static event Action OnFlush;
/// The party's leader in your game picked something (their "join" params), or left it (null).
public static event Action OnLead;
/// PlayerTwo's shop screen (P2.Store.Open) shows a product to try on ({ key, kind, name, about, picture?,
/// price, qty?, contents?, owned }), or null (IsNull) when the look ends. P2.Store.TryOn() turns it on.
public static event Action OnTryOn;
static P2() { Env = ""; }
/* ---------- starting ---------- */
public static void Init(Action done) { Init(null, done); }
public static void Init(P2Options options, Action done)
{
var o = new Dictionary();
if (options != null)
{
if (options.Timeout > 0) o["timeout"] = options.Timeout;
if (options.Required) o["required"] = true;
if (!string.IsNullOrEmpty(options.Local)) o["local"] = P2Json.Parse(options.Local);
if (!string.IsNullOrEmpty(options.Sdk)) o["sdk"] = options.Sdk;
}
Go("init", new object[] { o }, r =>
{
Ready = r.Ok;
Env = r["env"].Str ?? "disabled";
if (r.Ok)
{
Player = P2Player.From(r["player"]);
GameSlug = r["game"]["slug"].Str;
GameTitle = r["game"]["title"].Str;
Test = r["test"].Bool; Demo = r["demo"].Bool; Guest = r["guest"].Bool; OnAir = r["onAir"].Bool;
Params = r["params"].StringMap();
}
if (done != null) done(r);
});
}
/// Any call as a Task: var r = await P2.Async(cb => P2.Trophies.Unlock("first-win", cb));
public static Task Async(Action> start)
{
var t = new TaskCompletionSource();
start(r => t.TrySetResult(r));
return t.Task;
}
/* ---------- the calls (docs: https://playertwo.plus/docs/sdk, the same calls in JavaScript) ---------- */
/// { player, game, session, test, demo, from, params }
public static void Me(Action done) { Go("me", None, done); }
/// Who is playing, for your own servers: Data.Str is a JWT signed by PlayerTwo, ten minutes.
public static void Identity(Action done) { Go("identity", None, done); }
/// A link to your game that opens it with these params: Data.Str.
public static void Invite(Dictionary invite, Action done) { Go("invite", new object[] { invite }, done); }
/// The player's critter (pixels and a 3D model), name, level and what they wear.
public static void Avatar(Action done) { Go("avatar", None, done); }
/// Asks a guest to sign up, with your reason (up to 80 characters).
public static void SignUp(string why, Action done = null) { Go("signUp", new object[] { why }, done); }
/// A moment your game names itself (a lowercase letter, then up to 31 lowercase letters, digits and _),
/// with up to 12 values: in your studio's analytics. Fire and forget.
public static void Track(string name, Dictionary data = null) { Tell("track", new object[] { name, data }); }
/// Any call of the SDK by its name, with its arguments as a list (what this file doesn't wrap).
public static void Call(string method, IList args, Action done) { Go("call", new object[] { method, args }, done); }
public static class Trophies
{
/// { trophies: [{ key, name, how, tier, xp, hidden, art, share, rarity, earned }], xp, level }
public static void List(Action done) { Go("trophies.list", None, done); }
/// The player sees the toast. { trophy, new, n, xp: { gained, total }, level, complete? }
public static void Unlock(string key, Action done = null) { Go("trophies.unlock", new object[] { key }, done); }
}
public static class Addons
{
/// Each add-on on sale: [{ key, name, about, price, owned }]
public static void List(Action done) { Go("addons.list", None, done); }
/// Data.Bool: whether the player has it.
public static void Has(string key, Action done) { Go("addons.has", new object[] { key }, done); }
}
/// In-game purchases: your studio's products, or charges your server makes.
public static class Store
{
/// [{ key, kind, name, about, picture?, price, qty?, owned, count?, owners, onSaleFrom, onSaleUntil }]
public static void List(Action done, bool coming = false) { Go("store.list", new object[] { coming }, done); }
/// What the player has: [{ key, kind, count? }]
public static void Owned(Action done) { Go("store.owned", None, done); }
/// { state: "owned" | "free-game" | "free-period" | "test" | "none", until, left?, via? }
public static void Access(Action done) { Go("store.access", None, done); }
/// How many of your charges were paid with each ref: { ref: n }.
public static void Sold(string[] refs, Action done) { Go("store.sold", new object[] { refs }, done); }
/// PlayerTwo's own sheet sells it. { ok: true, product: { key, kind, n }, count?, receipt, exp, test }
/// or { ok: false, reason: "cancelled" }.
public static void Buy(string key, Action done) { Go("store.buy", new object[] { key }, done); }
/// A charge your server made, paid on PlayerTwo's card. { ok: true, charge, amount, receipt, exp, test }
public static void Pay(string charge, Action done) { Go("store.pay", new object[] { charge }, done); }
/// PlayerTwo's ready-made shop screen over the game: your products in tabs by kind, the daily deal and
/// the first-purchase pack, bought on PlayerTwo's card. Answers when the player closes it: { ok: true, bought:
/// [...] }. kind: open on a kind's tab ("skin"); key: with a product chosen.
public static void Open(Action done = null, string kind = null, string key = null)
{
var o = new Dictionary();
if (!string.IsNullOrEmpty(kind)) o["kind"] = kind;
if (!string.IsNullOrEmpty(key)) o["key"] = key;
Go("store.open", new object[] { o }, done);
}
/// The daily deal: { product, percent, price, was, ends }, or null (Data.IsNull).
public static void Deal(Action done) { Go("store.deal", None, done); }
/// Try-on, once (false turns it off): while the shop screen is open, P2.OnTryOn hears the product the
/// player looks at, and null when the look ends.
public static void TryOn(bool on = true, Action done = null) { Go("store.tryOn", new object[] { on }, done); }
}
/// Donations to you, when your studio put them inside the game.
public static class Donate
{
/// Data.Bool: whether the game takes donations inside itself now.
public static void Available(Action done) { Go("donate.available", None, done); }
/// PlayerTwo's donation sheet, from the player's press on your own button: { shown, reason? }
public static void Open(Action done = null) { Go("donate.open", None, done); }
/// PlayerTwo's own Donate button in a corner ("bottom-right", "bottom-left", "top-right", "top-left"):
/// { shown }.
public static void Button(string corner = "bottom-right", Action done = null) { Go("donate.button", new object[] { corner }, done); }
public static void RemoveButton(Action done = null) { Go("donate.remove", None, done); }
}
public static class Moments
{
/// Once your results screen shows: { offered, shared }. Never refused.
public static void Offer(Action done = null) { Go("moments.offer", None, done); }
}
/// Notifications from your game's server, to players who said yes.
public static class Notify
{
/// PlayerTwo's card asks, with your reason (up to 120 characters): { allowed, asked }.
public static void Ask(string why, Action done) { Go("notify.ask", new object[] { why }, done); }
/// Data.Bool
public static void Allowed(Action done) { Go("notify.allowed", None, done); }
}
public static class Device
{
/// { tier: "low" | "mid" | "high", phone, touch, memory, cores, gpu, software, screen: { w, h, dpr },
/// saveData, reducedMotion, fps }
public static void Get(Action done) { Go("device.get", None, done); }
}
public static class Stats
{
/// { stats: { key: value } }
public static void All(Action done) { Go("stats.get", None, done); }
/// Data.Num: one stat (0 if it was never set).
public static void Get(string key, Action done) { Go("stats.get", new object[] { key }, done); }
/// { stats, unlocked }: trophies waiting on a stat are earned by themselves.
public static void Set(string key, double value, Action done = null) { Go("stats.set", new object[] { key, value }, done); }
public static void Add(string key, double amount = 1, Action done = null) { Go("stats.add", new object[] { key, amount }, done); }
}
/// Leaderboards.
public static class Scores
{
/// { board, value, best, new, previous, rank, total }
public static void Submit(string board, double value, Action done = null) { Go("scores.submit", new object[] { board, value }, done); }
/// around: "top" or "me". { board, rows: [{ rank, value, at, player, me? }], total, me }
public static void List(string board, Action done, string around = "top", bool friends = false, int limit = 10)
{
Go("scores.list", new object[] { board, new Dictionary { { "around", around }, { "friends", friends }, { "limit", limit } } }, done);
}
}
/// Cloud saves: named slots, up to 1 MB each.
public static class Saves
{
/// { slots: [{ slot, size, version, at }], max, maxBytes }
public static void List(Action done) { Go("saves.list", None, done); }
/// { slot, size, version, at, data }: r.SaveText() or r.SaveBytes().
public static void Get(string slot, Action done) { Go("saves.get", new object[] { slot }, done); }
/// Text (JsonUtility.ToJson(state)), refused with code "version" when another device saved since
/// the version you name (r["version"] is the one there now).
public static void Put(string slot, string text, Action done = null, int version = -1) { Go("saves.put", new object[] { slot, text, "text", Version(version) }, done); }
public static void Put(string slot, byte[] bytes, Action done = null, int version = -1) { Go("saves.put", new object[] { slot, Convert.ToBase64String(bytes ?? new byte[0]), "base64", Version(version) }, done); }
public static void Delete(string slot, Action done = null) { Go("saves.delete", new object[] { slot }, done); }
static Dictionary Version(int v) { var o = new Dictionary(); if (v >= 0) o["version"] = v; return o; }
}
public static class Presence
{
/// The line friends see ("Chapter 3, The Docks"; null clears it), and what they join you with.
public static void Set(string status, Dictionary join = null, Action done = null) { Go("presence.set", new object[] { status, join }, done); }
}
public static class Loading
{
public static void Done(Action done = null) { Go("loading.done", None, done); }
}
public static class Gameplay
{
public static void Start(Action done = null) { Go("gameplay.start", None, done); }
public static void Stop(Action done = null) { Go("gameplay.stop", None, done); }
}
/// Your game's errors, in your studio's analytics.
public static class Errors
{
static bool catching;
/// One by hand: its message, where in your game (up to 40 characters), and its stack if you have it.
public static void Report(string message, string where = null, string stack = null) { Tell("errors.report", new object[] { message, where, stack }); }
/// Stop catching them for this page (Report still sends).
public static void Off() { CatchExceptions(false); Tell("errors.off", None); }
/// Report every exception Unity logs (Application.logMessageReceived), with its stack.
public static void CatchExceptions(bool on = true)
{
if (on == catching) return;
catching = on;
if (on) Application.logMessageReceived += Logged;
else Application.logMessageReceived -= Logged;
}
static void Logged(string message, string stack, LogType type) { if (type == LogType.Exception) Report(message, "Unity", stack); }
}
/// Outside data PlayerTwo fetches for your game.
public static class Feeds
{
/// { at, status, body } or { at, items: [{ item, sig }] }
public static void Get(string name, Action done) { Go("feeds.get", new object[] { name }, done); }
}
/// What the player has from PlayerTwo's shop in the Plaza.
public static class Items
{
public static void List(Action done) { Go("items.list", None, done); }
}
/// Doors to other games on PlayerTwo, the party with them.
public static class Travel
{
public static void To(string slug, Dictionary invite = null, string place = null, Action done = null)
{
var o = new Dictionary { { "params", invite ?? new Dictionary() } };
if (!string.IsNullOrEmpty(place)) o["place"] = place;
Go("travel.to", new object[] { slug, o }, done);
}
public static void Home(Action done = null) { Go("travel.home", None, done); }
/// { home: { title, url }, links: [{ slug, title, tagline, art, players, friends, why, free, owned }] }
public static void Links(Action done) { Go("travel.links", None, done); }
}
/// The player's PlayerTwo party: the leader decides.
public static class Party
{
/// { id, me: { id, leader }, leader, members } or null (Data.IsNull).
public static void Get(Action done) { Go("party.get", None, done); }
/// The leader in your game now and what they join with ({ leader, join, at }), or null.
public static P2Json Lead() { return Peek("party.lead", None); }
}
/// Multiplayer with no server of your own. Each answers with r.Room once you are in.
public static class Rooms
{
public static void Join(P2RoomOptions options, Action done) { Make("rooms.join", new object[] { (options ?? new P2RoomOptions()).Json() }, done); }
public static void Create(P2RoomOptions options, Action done) { Make("rooms.create", new object[] { (options ?? new P2RoomOptions()).Json() }, done); }
public static void Party(P2RoomOptions options, Action done) { Make("rooms.party", new object[] { (options ?? new P2RoomOptions()).Json() }, done); }
/// A world kept for good ("main" when null), or an area of it; region: "na", "europe", "asia", "oceania".
public static void World(string name, Action done, string area = null, string region = null)
{
var o = new Dictionary();
if (!string.IsNullOrEmpty(area)) o["area"] = area;
if (!string.IsNullOrEmpty(region)) o["region"] = region;
Make("rooms.world", new object[] { name, o }, done);
}
/// Watch a room by its Id: you hear everything and can say nothing.
public static void Watch(string roomId, Action done) { Make("rooms.watch", new object[] { roomId }, done); }
/// The game's public rooms open now: [{ id, mode, size, players, watchers, ... }]
public static void Live(string mode, Action done) { Go("rooms.live", new object[] { mode }, done); }
/// A bad connection, on purpose, for this page's rooms from now on (on localhost too).
public static void Simulate(int lag, int jitter = 0, double loss = 0) { Tell("rooms.simulate", new object[] { new Dictionary { { "lag", lag }, { "jitter", jitter }, { "loss", loss } } }); }
public static void StopSimulating() { Tell("rooms.simulate", new object[] { null }); }
static void Make(string method, object[] args, Action done)
{
Go(method, args, r =>
{
if (r.Ok) { r.Room = new P2Room(r.Data); open[r.Room.Handle] = r.Room; }
if (done != null) done(r);
});
}
}
/* ---------- underneath: the jslib's four functions, and answers handed over in Update ---------- */
static readonly object[] None = new object[0];
static readonly Dictionary> waiting = new Dictionary>();
static readonly Queue queue = new Queue();
internal static readonly Dictionary open = new Dictionary();
static int nextId = 1;
static bool started;
delegate void AnswerFn(int id, int ok, IntPtr json);
delegate void EventFn(IntPtr kind, IntPtr json);
#if UNITY_WEBGL && !UNITY_EDITOR
static readonly bool Web = true;
[DllImport("__Internal")] static extern void P2_Start(AnswerFn answer, EventFn heard);
[DllImport("__Internal")] static extern void P2_Ask(int id, string method, string args);
[DllImport("__Internal")] static extern void P2_Fire(string what, string args);
[DllImport("__Internal")] static extern string P2_Read(string what, string args);
#else
static readonly bool Web = false;
static void P2_Start(AnswerFn answer, EventFn heard) { }
static void P2_Ask(int id, string method, string args) { }
static void P2_Fire(string what, string args) { }
static string P2_Read(string what, string args) { return null; }
#endif
static void Begin()
{
if (started) return;
started = true;
P2Runner.Make();
if (Web) P2_Start(Answered, Heard);
}
/// A call by its name, answered once (later) through done.
internal static void Go(string method, object[] args, Action done)
{
Begin();
if (!Web)
{
var no = P2Result.Refused("not-on-player-two", Application.isEditor ? "PlayerTwo isn't in the Unity editor: build for WebGL, and play it on PlayerTwo or localhost." : "PlayerTwo is in a WebGL build only.");
if (done != null) Later(() => done(no));
return;
}
int id = nextId++;
if (done != null) waiting[id] = done;
P2_Ask(id, method, P2Json.Write(args));
}
/// Fire and forget.
internal static void Tell(string what, object[] args)
{
Begin();
if (Web) P2_Fire(what, P2Json.Write(args));
}
/// A read answered at once (P2Json.Null when it can't be).
internal static P2Json Peek(string what, object[] args)
{
Begin();
if (!Web) return P2Json.Null;
P2Json got;
try { got = P2Json.Parse(P2_Read(what, P2Json.Write(args))); }
catch (Exception e) { Debug.LogWarning("PlayerTwo: " + what + ": " + e.Message); return P2Json.Null; }
if (got["ok"].Bool) return got["data"];
Debug.LogWarning("PlayerTwo: " + what + ": " + got["error"]["message"].Str);
return P2Json.Null;
}
[MonoPInvokeCallback(typeof(AnswerFn))]
static void Answered(int id, int ok, IntPtr json)
{
Action done;
if (!waiting.TryGetValue(id, out done)) return;
waiting.Remove(id);
var r = P2Result.From(ok != 0, Utf8(json));
Later(() => done(r));
}
[MonoPInvokeCallback(typeof(EventFn))]
static void Heard(IntPtr kindPtr, IntPtr jsonPtr)
{
string kind = Utf8(kindPtr);
/* closing: at once, so the calls the game makes now are waited for */
if (kind == "flush")
{
var f = OnFlush;
if (f != null) foreach (Action a in f.GetInvocationList()) Run(a);
return;
}
P2Json e;
try { e = P2Json.Parse(Utf8(jsonPtr)); } catch (Exception x) { Debug.LogWarning("PlayerTwo: " + kind + ": " + x.Message); return; }
Later(() =>
{
if (kind == "overlay") { if (OnOverlay != null) OnOverlay(e.Bool); }
else if (kind == "lead") { if (OnLead != null) OnLead(e); }
else if (kind == "tryon") { if (OnTryOn != null) OnTryOn(e); }
else if (kind == "room") { P2Room room; if (open.TryGetValue(e["room"].Int, out room)) room.Heard(e); }
});
}
static void Later(Action job)
{
if (P2Runner.Made) queue.Enqueue(job);
else Run(job);
}
static void Run(Action job)
{
try { job(); }
catch (Exception e) { Debug.LogException(e); }
}
/// P2Runner's Update: everything heard since the last frame, in order.
internal static void Drain()
{
int n = queue.Count;
while (n-- > 0 && queue.Count > 0) Run(queue.Dequeue());
}
/* a UTF-8 buffer the jslib made, copied before it is freed */
static string Utf8(IntPtr p)
{
if (p == IntPtr.Zero) return null;
int n = 0;
while (Marshal.ReadByte(p, n) != 0) n++;
var bytes = new byte[n];
Marshal.Copy(p, bytes, 0, n);
return Encoding.UTF8.GetString(bytes);
}
}
/// A room you are in (r.Room from P2.Rooms). Its events come in Update, as the SDK's room.on.
public sealed class P2Room
{
public readonly int Handle;
/// Its name, to come back to it with (P2RoomOptions.Room).
public readonly string Id;
/// A private room's code, or null.
public readonly string Code;
public readonly string Mode;
public readonly int Size;
public readonly int Teams;
/// Your id in the room (the same as P2.Player.Id).
public readonly string Me;
/// Its build has a room.js on PlayerTwo's servers: only that writes the shared state.
public readonly bool Scripted;
public readonly bool World;
public readonly bool Watching;
public readonly bool Gated;
/// Messages a second you may send it (bursts of twice that).
public readonly int Rate;
/// False once it closed (OnClose).
public bool Open { get; private set; }
public string ClosedWhy { get; private set; }
public event Action OnJoin, OnAway, OnBack;
/// Someone left: the player, and why ("left", "dropped", "kicked", ...).
public event Action OnLeave;
public event Action OnHost;
public event Action OnTeam;
/// A key of the shared state changed: key, value (null: taken away), who wrote it.
public event Action OnState;
/// A message: its type, its data, who sent it (null: the room's own code).
public event Action OnMessage;
public event Action OnReconnecting, OnReconnected;
/// The room opened again between far-apart players: its new id.
public event Action OnMoved;
public event Action OnVoice, OnSpeaking;
/// Nobody else came within P2RoomOptions.Alone ms.
public event Action OnAlone;
public event Action OnError;
/// You're out: "left", "closed", "lost", "replaced", "stopped", "time", "empty", "update", ...
public event Action OnClose;
/// Another player's first synced values (SyncStart): make their object.
public event Action OnSyncJoin;
public event Action OnSyncLeave;
/// A scripted room's code put your synced values right: the values, and the room time of the move it
/// corrected (NaN when none). Copy them into your own object.
public event Action OnSyncFix;
/// The room's code made an object (ObjectsStart): its key and values by name.
public event Action OnObjectAdd;
public event Action OnObjectRemove;
internal P2Room(P2Json j)
{
Handle = j["room"].Int; Id = j["id"].Str; Code = j["code"].Str; Mode = j["mode"].Str; Size = j["size"].Int; Teams = j["teams"].Int;
Me = j["me"].Str; Scripted = j["scripted"].Bool; World = j["world"].Bool; Watching = j["watching"].Bool; Gated = j["gated"].Bool; Rate = j["rate"].Int;
Open = true;
}
/// The room now: { id, code, mode, size, teams, me, host, isHost, players, state, owners, voice: { who,
/// muted, speaking } }.
public P2Json Info() { return P2.Peek("room", new object[] { Handle }); }
/// Who is here, you too: [{ id, handle, name, picture, face, level, kind, away, rating?, team? }]
public P2Json Players { get { return Info()["players"]; } }
public P2Json State { get { return Info()["state"]; } }
/// The host's id: whoever has been here longest.
public string Host { get { return Info()["host"].Str; } }
public bool IsHost { get { return Info()["isHost"].Bool; } }
public P2Json Get(string key) { return P2.Peek("room.get", new object[] { Handle, key }); }
/// A message of `type` to everyone else, or to one player; data is anything JSON carries (a Dictionary,
/// a list, a number, a string, or P2Json.Parse(JsonUtility.ToJson(x))). fast: the lossy fast lane.
public void Send(string type, object data = null, string to = null, bool fast = false)
{
var o = new Dictionary();
if (to != null) o["to"] = to;
if (fast) o["fast"] = true;
P2.Tell("room.send", new object[] { Handle, type, data, o });
}
public void SendTo(string type, object data, string[] to, bool fast = false)
{
var o = new Dictionary { { "to", to } };
if (fast) o["fast"] = true;
P2.Tell("room.send", new object[] { Handle, type, data, o });
}
/// A key of the shared state (null takes it away); refused (OnError, not-yours) if it isn't yours.
public void Set(string key, object value) { P2.Tell("room.set", new object[] { Handle, key, value }); }
/// Leave for good.
public void Leave() { P2.Tell("room.leave", new object[] { Handle }); }
/// There and back in ms (Data.Num).
public void Ping(Action done) { P2.Go("room.ping", new object[] { Handle }, done); }
/// The room's clock, the same for every player in it (ms).
public double Now() { return P2.Peek("room.now", new object[] { Handle }).Num; }
/// { ping, jitter, lane, up, down, peers, lanePing, stalls, stall }
public P2Json Stats() { return P2.Peek("room.stats", new object[] { Handle }); }
/// Smooth movement: name your numbers ("x", "y", "z", "ry"), then call SyncStep with them every frame.
public bool SyncStart(string[] fields, P2SyncOptions options = null)
{
return P2.Peek("room.sync.start", new object[] { Handle, fields, (options ?? new P2SyncOptions()).Json() }).Bool;
}
/// Each frame: your values (in the order you named them) go out at the sync's rate, and everyone else's
/// come back smoothed: { "<player id>": [x, y, z, ry], ... }.
public P2Json SyncStep(params double[] values) { return P2.Peek("room.sync.step", new object[] { Handle, values }); }
public void SyncStop() { P2.Tell("room.sync.stop", new object[] { Handle }); }
/// A scripted room's objects (room.objects in room.js): OnObjectAdd and OnObjectRemove, and each frame
/// ObjectsStep's { key: { name: value } }.
public bool ObjectsStart(int delay = 0, float snap = 0, string[] angles = null)
{
var o = new Dictionary();
if (delay > 0) o["delay"] = delay;
if (snap > 0) o["snap"] = snap;
if (angles != null) o["angles"] = angles;
return P2.Peek("room.objects.start", new object[] { Handle, o }).Bool;
}
public P2Json ObjectsStep() { return P2.Peek("room.objects.step", new object[] { Handle }); }
public void ObjectsStop() { P2.Tell("room.objects.stop", new object[] { Handle }); }
/// Voice chat: the browser asks for the microphone first. Refused "no-mic", "voice-full" or "no-voice".
public void VoiceJoin(bool muted = false, Action done = null) { P2.Go("room.voice.join", new object[] { Handle, muted }, done); }
public void VoiceLeave() { P2.Tell("room.voice.leave", new object[] { Handle }); }
/// Your microphone off or on, the other way: says whether it is off.
public bool VoiceMute() { return P2.Peek("room.voice.mute", new object[] { Handle, null }).Bool; }
public bool VoiceMute(bool off) { return P2.Peek("room.voice.mute", new object[] { Handle, off }).Bool; }
/// How loud a player is to you, 0 to 1.
public void VoiceVolume(string id, float volume) { P2.Tell("room.voice.volume", new object[] { Handle, id, volume }); }
internal void Heard(P2Json e)
{
switch (e["type"].Str)
{
case "join": if (OnJoin != null) OnJoin(e["player"]); break;
case "away": if (OnAway != null) OnAway(e["player"]); break;
case "back": if (OnBack != null) OnBack(e["player"]); break;
case "leave": if (OnLeave != null) OnLeave(e["player"], e["why"].Str); break;
case "host": if (OnHost != null) OnHost(e["id"].Str); break;
case "team": if (OnTeam != null) OnTeam(e["id"].Str, e["team"].Int); break;
case "state": if (OnState != null) OnState(e["key"].Str, e["value"], e["by"].Str); break;
case "message": if (OnMessage != null) OnMessage(e["name"].Str, e["data"], e["from"].Str); break;
case "reconnecting": if (OnReconnecting != null) OnReconnecting(); break;
case "reconnected": if (OnReconnected != null) OnReconnected(); break;
case "moved": if (OnMoved != null) OnMoved(e["id"].Str); break;
case "voice": if (OnVoice != null) OnVoice(e["id"].Str, e["on"].Bool); break;
case "speaking": if (OnSpeaking != null) OnSpeaking(e["id"].Str, e["on"].Bool); break;
case "alone": if (OnAlone != null) OnAlone(e["ms"].Num); break;
case "error": if (OnError != null) OnError(P2Result.From(false, e["error"].ToString())); break;
case "sync.join": if (OnSyncJoin != null) OnSyncJoin(e["id"].Str, e["values"]); break;
case "sync.leave": if (OnSyncLeave != null) OnSyncLeave(e["id"].Str); break;
case "sync.fix": if (OnSyncFix != null) OnSyncFix(e["values"], e["at"].IsNull ? double.NaN : e["at"].Num); break;
case "object.add": if (OnObjectAdd != null) OnObjectAdd(e["key"].Str, e["values"]); break;
case "object.remove": if (OnObjectRemove != null) OnObjectRemove(e["key"].Str); break;
case "close":
Open = false;
ClosedWhy = e["why"].Str;
P2.open.Remove(Handle);
if (OnClose != null) OnClose(ClosedWhy);
break;
}
}
}
/// A JSON value as PlayerTwo answered it: j["key"], j[0], .Str, .Num, .Int, .Bool, .IsNull; a missing key or
/// index reads as P2Json.Null, so j["a"]["b"].Str never throws. ToString() is its JSON.
public sealed class P2Json : IEnumerable
{
public enum Kind { Null, Bool, Number, String, Array, Object }
public static readonly P2Json Null = new P2Json(Kind.Null);
static readonly P2Json True = new P2Json(true), False = new P2Json(false);
public readonly Kind Type;
readonly bool b;
readonly double n;
readonly string s;
readonly List items;
readonly List keys;
readonly Dictionary map;
P2Json(Kind type) { Type = type; }
P2Json(bool value) { Type = Kind.Bool; b = value; }
P2Json(double value) { Type = Kind.Number; n = value; }
P2Json(string value) { Type = Kind.String; s = value; }
P2Json(List list) { Type = Kind.Array; items = list; }
P2Json(List names, Dictionary values) { Type = Kind.Object; keys = names; map = values; }
public P2Json this[string key] { get { P2Json v; return map != null && key != null && map.TryGetValue(key, out v) ? v : Null; } }
public P2Json this[int index] { get { return items != null && index >= 0 && index < items.Count ? items[index] : Null; } }
public bool IsNull { get { return Type == Kind.Null; } }
public bool Has(string key) { return map != null && key != null && map.ContainsKey(key); }
/// An array's length, or an object's number of keys.
public int Count { get { return items != null ? items.Count : keys != null ? keys.Count : 0; } }
public IList Keys { get { return keys != null ? (IList)keys.AsReadOnly() : new string[0]; } }
public string Str { get { return Type == Kind.String ? s : null; } }
public double Num { get { return Type == Kind.Number ? n : 0; } }
public int Int { get { return Type == Kind.Number && n >= int.MinValue && n <= int.MaxValue ? (int)Math.Round(n) : 0; } }
public long Long { get { return Type == Kind.Number && Math.Abs(n) < 9.2e18 ? (long)Math.Round(n) : 0; } }
public float Float { get { return (float)Num; } }
public bool Bool { get { return Type == Kind.Bool && b; } }
/// An object of strings as a Dictionary (null if it isn't an object).
public Dictionary StringMap()
{
if (keys == null) return null;
var d = new Dictionary();
foreach (var k in keys) { var v = map[k]; d[k] = v.Type == Kind.String ? v.s : v.ToString(); }
return d;
}
/// An array of numbers (SyncStep's values) as doubles.
public double[] Numbers()
{
var d = new double[items != null ? items.Count : 0];
for (int i = 0; i < d.Length; i++) d[i] = items[i].Num;
return d;
}
public IEnumerator GetEnumerator()
{
if (items != null) foreach (var x in items) yield return x;
else if (keys != null) foreach (var k in keys) yield return map[k];
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public override string ToString() { var sb = new StringBuilder(); WriteTo(sb); return sb.ToString(); }
/* ---------- reading ---------- */
public static P2Json Parse(string text)
{
if (string.IsNullOrEmpty(text)) return Null;
int i = 0;
var v = Read(text, ref i);
Skip(text, ref i);
if (i != text.Length) throw new FormatException("more after the JSON, at " + i);
return v;
}
static void Skip(string t, ref int i) { while (i < t.Length && (t[i] == ' ' || t[i] == '\t' || t[i] == '\n' || t[i] == '\r')) i++; }
static void Expect(string t, ref int i, char c)
{
if (i >= t.Length || t[i] != c) throw new FormatException("expected '" + c + "' at " + i);
i++;
}
static bool Word(string t, ref int i, string w)
{
if (string.CompareOrdinal(t, i, w, 0, w.Length) != 0) return false;
i += w.Length;
return true;
}
static P2Json Read(string t, ref int i)
{
Skip(t, ref i);
if (i >= t.Length) throw new FormatException("the JSON ended early");
char c = t[i];
if (c == '{')
{
i++;
var names = new List();
var values = new Dictionary();
Skip(t, ref i);
if (i < t.Length && t[i] == '}') { i++; return new P2Json(names, values); }
while (true)
{
Skip(t, ref i);
string k = ReadString(t, ref i);
Skip(t, ref i);
Expect(t, ref i, ':');
var v = Read(t, ref i);
if (!values.ContainsKey(k)) names.Add(k);
values[k] = v;
Skip(t, ref i);
if (i < t.Length && t[i] == ',') { i++; continue; }
Expect(t, ref i, '}');
return new P2Json(names, values);
}
}
if (c == '[')
{
i++;
var list = new List();
Skip(t, ref i);
if (i < t.Length && t[i] == ']') { i++; return new P2Json(list); }
while (true)
{
list.Add(Read(t, ref i));
Skip(t, ref i);
if (i < t.Length && t[i] == ',') { i++; continue; }
Expect(t, ref i, ']');
return new P2Json(list);
}
}
if (c == '"') return new P2Json(ReadString(t, ref i));
if (Word(t, ref i, "true")) return True;
if (Word(t, ref i, "false")) return False;
if (Word(t, ref i, "null")) return Null;
int start = i;
while (i < t.Length && "+-0123456789.eE".IndexOf(t[i]) >= 0) i++;
double d;
if (start == i || !double.TryParse(t.Substring(start, i - start), NumberStyles.Float, CultureInfo.InvariantCulture, out d)) throw new FormatException("not JSON at " + start);
return new P2Json(d);
}
static string ReadString(string t, ref int i)
{
Expect(t, ref i, '"');
var sb = new StringBuilder();
while (i < t.Length)
{
char c = t[i++];
if (c == '"') return sb.ToString();
if (c != '\\') { sb.Append(c); continue; }
if (i >= t.Length) break;
char e = t[i++];
switch (e)
{
case '"': sb.Append('"'); break;
case '\\': sb.Append('\\'); break;
case '/': sb.Append('/'); break;
case 'b': sb.Append('\b'); break;
case 'f': sb.Append('\f'); break;
case 'n': sb.Append('\n'); break;
case 'r': sb.Append('\r'); break;
case 't': sb.Append('\t'); break;
case 'u':
if (i + 4 > t.Length) throw new FormatException("a \\u escape ended early");
sb.Append((char)int.Parse(t.Substring(i, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture));
i += 4;
break;
default: throw new FormatException("a bad escape at " + (i - 1));
}
}
throw new FormatException("a string in the JSON never ended");
}
/* ---------- writing: C# values (null, strings, bools, numbers, dictionaries, lists, arrays, P2Json) as JSON ---------- */
internal static string Write(object value) { var sb = new StringBuilder(); Write(sb, value); return sb.ToString(); }
static void Write(StringBuilder sb, object v)
{
if (v == null) { sb.Append("null"); return; }
var j = v as P2Json;
if (j != null) { j.WriteTo(sb); return; }
var str = v as string;
if (str != null) { Quote(sb, str); return; }
if (v is bool) { sb.Append((bool)v ? "true" : "false"); return; }
if (v is float) { float f = (float)v; if (float.IsNaN(f) || float.IsInfinity(f)) sb.Append("null"); else sb.Append(f.ToString("R", CultureInfo.InvariantCulture)); return; }
if (v is double || v is decimal) { Number(sb, Convert.ToDouble(v, CultureInfo.InvariantCulture)); return; }
if (v is int || v is long || v is short || v is byte || v is uint || v is ulong || v is ushort || v is sbyte) { sb.Append(Convert.ToString(v, CultureInfo.InvariantCulture)); return; }
if (v is char || v is Enum) { Quote(sb, v.ToString()); return; }
var dict = v as IDictionary;
if (dict != null)
{
sb.Append('{');
bool first = true;
foreach (DictionaryEntry e in dict)
{
if (!first) sb.Append(',');
first = false;
Quote(sb, Convert.ToString(e.Key, CultureInfo.InvariantCulture));
sb.Append(':');
Write(sb, e.Value);
}
sb.Append('}');
return;
}
var list = v as IEnumerable;
if (list != null)
{
sb.Append('[');
bool first = true;
foreach (var x in list) { if (!first) sb.Append(','); first = false; Write(sb, x); }
sb.Append(']');
return;
}
Quote(sb, v.ToString());
}
static void Number(StringBuilder sb, double d)
{
if (double.IsNaN(d) || double.IsInfinity(d)) sb.Append("null");
else sb.Append(d.ToString("R", CultureInfo.InvariantCulture));
}
static void Quote(StringBuilder sb, string s)
{
sb.Append('"');
foreach (char c in s)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < ' ' || c == '
' || c == '
') sb.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
else sb.Append(c);
break;
}
}
sb.Append('"');
}
void WriteTo(StringBuilder sb)
{
switch (Type)
{
case Kind.Null: sb.Append("null"); break;
case Kind.Bool: sb.Append(b ? "true" : "false"); break;
case Kind.Number: Number(sb, n); break;
case Kind.String: Quote(sb, s); break;
case Kind.Array:
sb.Append('[');
for (int i = 0; i < items.Count; i++) { if (i > 0) sb.Append(','); items[i].WriteTo(sb); }
sb.Append(']');
break;
default:
sb.Append('{');
for (int i = 0; i < keys.Count; i++) { if (i > 0) sb.Append(','); Quote(sb, keys[i]); sb.Append(':'); map[keys[i]].WriteTo(sb); }
sb.Append('}');
break;
}
}
}
}