GithubHelp home page GithubHelp logo

sleitnick / rbxts-proton Goto Github PK

View Code? Open in Web Editor NEW
24.0 2.0 3.0 174 KB

Experimental framework for Roblox game development

Home Page: https://www.npmjs.com/package/@rbxts/proton

License: MIT License

TypeScript 100.00%
framework roblox roblox-ts typescript

rbxts-proton's Introduction

Proton

Lint Release

Proton is an easy-to-use framework for Roblox game development.

Like the proton of an atom, Proton aims at adding stability to your game development, all while only remaining a portion of the whole. Use Proton to structure and connect the top-level design of your game.

Warning Proton is early in development. Due to currently limitations with roblox-ts, Proton does not yet support dependency injection, which is a necessary feature to make Proton production-ready. Other portions of Proton may also change, as the overall API is not solidified.

Providers

Providers are the core of Proton. A provider provides a specific service or utility to your game. For example, a game might have a DataProvider (or DataService/DataManager/etc.) that provides the logic for handling data for players in the game.

Structure

The minimum structure of a provider looks like the following:

import { Provider } from "@rbxts/proton";

@Provider()
export class MyProvider {}

That's it. The @Provider() decorator communicates data about the class to Proton, but does not mutate the given provider at all. Proton will create a singleton of the provider once Proton is started.

Extensible

Providers can have any number of methods or fields added to them. They're just plain classes. Add anything to them.

@Provider()
export class MyProvider {
	private message = "hello!";

	// Optional constructor method
	constructor() {
		// Use the constructor to set up any necessary functionality
		// for the provider (e.g. hooking up network connections).
	}

	// Custom method
	helloWorld() {
		print(this.message);
	}
}

Built-in Start Lifecycle

Proton includes an optional built-in lifecycle method ProtonStart, which is fired when Proton is started. All ProtonStart lifecycle methods are called at the same time using task.spawn, which means that these methods can yield without blocking other providers from starting. It is common practice to use ProtonStart as a place to have long-running loops (e.g. a system that drives map loading and rotation every round).

import { Lifecycle, ProtonStart, Provider } from "@rbxts/proton";

@Provider()
export class MyProvider {
	constructor() {
		print("MyProvider initialized");
	}

	@Lifecycle(ProtonStart)
	onStart() {
		print("MyProvider started");
	}
}

Starting Proton

From both a server and client script, call the Proton.start() method.

import { Proton } from "@rbxts/proton";

Proton.start();

If another script requires Proton to be started, Proton.awaitStart() can be used, which will yield until Proton is fully started.

import { Proton } from "@rbxts/proton";

Proton.awaitStart();

Loading Providers

Modules are not magically loaded. Thus, if your providers exist in their own modules but are never imported by any running code, then Proton will never see them and they will not start. This is common for top-level providers that no other code relies on. In such cases, they must be explicitly imported:

import { Proton } from "@rbxts/proton";

// e.g.
import "./providers/my-provider.ts"

Proton.start();

Getting a Provider

Once Proton is started, use Proton.get() to get a provider:

const myProvider = Proton.get(MyProvider);
myProvider.helloWorld();

Providers can also access other providers:

@Provider()
export class AnotherProvider {
	private readonly myProvider = Proton.get(MyProvider);

	constructor() {
		myProvider.helloWorld();
	}
}

Network

The recommended way to do networking in Proton is to create a network.ts file in a shared directory (e.g. accessible from both the server and the client), and then create a Network namespace with the desired NetEvent and NetFunction objects. Optionally, multiple different namespaces can be created to separate between network functionality.

// shared/network.ts
import { NetEvent, NetEventType, NetFunction } from "@rbxts/proton";

export namespace Network {
	// Send a message to a player
	export const sendMessageToPlayer = new NetEvent<[message: string], NetEventType.ServerToClient>();

	// Get fireBullet from player
	export const fireBullet = new NetEvent<[pos: Vector3, dir: Vector3], NetEventType.ClientToServer>();

	// Allow client to fetch some data
	export const getData = new NetFunction<void, [data: string]>();

	// Client sends request to buy something
	export const buy = new NetFunction<[item: string, category: string], [bought: boolean]>();

	// Client gets sent multiple variables
	export const getMultiple = new NetFunction<void, {msg1: string, msg2: string, msg3: string}>();
}

Example of the above Network setup being consumed:

// server

Network.sendMessageToPlayer.server.fire(somePlayer, "hello world!");
Network.fireBullet.server.connect((pos, dir) => {
	// Handle bullet being fired
});
Network.getData.server.handle((player) => {
	return "Some data";
});
Network.buy.server.handle((player, item, category) => {
	// Buy item
	return false;
});
Network.getMultiple.handle((player) => {
	return { msg1: "hello", msg2: "world", msg3: "how are you" };
});
// client

Network.sendMessageToPlayer.client.connect((message) => {
	print(message);
});
Network.fireBullet.client.fire(new Vector3(), Vector3.zAxis);
const data = Network.getData.client.fire();
const { msg1, msg2, msg3 } = Network.getMultiple.client.fire();

Lifecycles

Custom lifecycles can be added. At their core, lifecycles are just special event dispatchers that can hook onto a class method. For example, here is a lifecycle that is fired every Heartbeat.

// shared/lifecycles.ts
import { ProtonLifecycle } from "@rbxts/proton";

export interface OnHeartbeat {
	onHeartbeat(dt: number): void;
}

export const HeartbeatLifecycle = new ProtonLifecycle<OnHeartbeat["onHeartbeat"]>();

RunService.Heartbeat.Connect((dt) => HeartbeatLifecycle.fire(dt));

A provider can then hook into the lifecycle:

import { Provider, Lifecycle } from "@rbxts/proton";

@Provider()
export class MyProvider implements OnHeartbeat {
	@Lifecycle(HeartbeatLifecycle)
	onHeartbeat(dt: number) {
		print("Update", dt);
	}
}

Here is a more complex lifecycle that is fired when a player enters the game.

// shared/lifecycles.ts
export interface OnPlayerAdded {
	onPlayerAdded(player: Player): void;
}

export const PlayerAddedLifecycle = new ProtonLifecycle<OnPlayerAdded["onPlayerAdded"]>();

// Trigger lifecycle for all current players and all future players:
Players.PlayerAdded.Connect((player) => PlayerAddedLifecycle.fire(player));
for (const player of Players.GetPlayers()) {
	PlayerAddedLifecycle.fire(player);
}

// Trigger lifecycle for all players for any new callbacks that get registered later on during runtime:
PlayerAddedLifecycle.onRegistered((callback) => {
	for (const player of Players.GetPlayers()) {
		task.spawn(callback, player);
	}
});
@Provider()
export class MyProvider implements OnPlayerAdded {
	@Lifecycle(PlayerAddedLifecycle)
	onPlayerAdded(player: Player) {
		print(`Player entered the game: ${player}`);
	}
}

Having the OnPlayerAdded interface just helps to keep explicit typings across consumers of the lifecycle. However, it is not entirely necessary. The above example could also have a lifecycle definition and consumer look like such:

export const PlayerAddedLifecycle = new ProtonLifecycle<(player: Player) => void>();

@Provider()
export class MyProvider {
	@Lifecycle(PlayerAddedLifecycle)
	onPlayerAdded(player: Player) {}
}

Components

Bind components to Roblox instances using the Component class and CollectionService tags.

import { BaseComponent, Component } from "@rbxts/proton";

@Component({ tag: "MyComponent" })
class MyComponent extends BaseComponent<BasePart> {
	onStart() {}
	onStop() {}
}

In initialization file:

import { Proton } from "@rbxts/proton";

import "./wherever/my-component";

Proton.start();

rbxts-proton's People

Contributors

chainreactionist avatar djboy08 avatar sleitnick avatar tomgie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

rbxts-proton's Issues

Cannot invoke Remote Function from Server

Hi, I am not sure if this was intentional or not, but here is the Typings for NetFunctionServer and NetFunctionClient.

declare class NetFunctionServer<TX extends unknown[] | unknown, RX extends unknown[] | unknown> {
    private readonly rf;
    constructor(rf: RemoteFunction);
    /**
     * Handle invocations to this remote function coming from clients.
     * @param handler Handler
     */
    handle(handler: (player: Player, ...args: NetworkParams<TX>) => NetworkReturn<RX>): void;
}
declare class NetFunctionClient<TX extends unknown[] | unknown, RX extends unknown[] | unknown> {
    private readonly rf;
    constructor(rf: RemoteFunction);
    /**
     * Invoke the remote function, sending the arguments to the server.
     * @param args TX
     * @returns RX
     */
    invoke(...args: NetworkParams<TX>): Promise<NetworkReturn<RX>>;
}

Their is no invokeClient as there should be per https://create.roblox.com/docs/reference/engine/classes/RemoteFunction#InvokeClient

Is there a reason behind this?

Network tuple fails due to runtime `TS.async` not allowing tuples returned from callback

If a network function returns a tuple, only the first item in the tuple will go through. This is because the NetFunctionClient.invoke method uses built-in async functionality. Doing so uses the runtime TS.async function, which wraps the method in a promise that only resolves the first returned item from the function.

This limitation means that native tuples probably can't be used in this context. Not entirely sure what the solution is. Perhaps remove the async and explicitly return promise instead? Or just use arrays of return arguments instead of tuple?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.