Skip to content

Commit

Permalink
cleaning up net/ code
Browse files Browse the repository at this point in the history
  • Loading branch information
Squeakrats committed Feb 28, 2016
1 parent e5b0847 commit e50117a
Show file tree
Hide file tree
Showing 5 changed files with 128 additions and 141 deletions.
69 changes: 33 additions & 36 deletions cruft/engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,58 +16,55 @@ export class Engine extends Emitter {
}
}

var initialize;
var initialized = new Promise((resolve, reject) => {
initialize = (config) => {
var promises = [];

scheduler.addChild(new Script((now, deltaMs) => {
engine.scene.update(now, deltaMs);
}));
var engine = new Engine();
var cache = new Cache();
var factory = new Factory();
var network = new Network();
var scheduler = new Scheduler();
var memory = new MemoryManager();

if(config.factory) {
let creators = config.factory;
for(let name in creators){
factory.register(name, creators[name]);
}
}

engine.scene = instantiate(config.scene || null);
var initialize = (config) => {

var promises = [];

Promise.all(promises).then(()=>{
engine.scene.initialize();
scheduler.start(config.scheduler || 17);
resolve();
});
scheduler.addChild(new Script((now, deltaMs) => {
engine.scene.update(now, deltaMs);
}));

if(config.factory) {
let creators = config.factory;
for(let name in creators){
factory.register(name, creators[name]);
}
}

if(config.network){
promises.push(network.initialize(config.network.name, config.network.options));
if(config.network.peer){
promises.push(network.createSession(config.network.peer))
}
}
});

engine.scene = instantiate(config.scene || null);

return Promise.all(promises).then(()=>{
engine.scene.initialize();
scheduler.start(config.scheduler || 17);
});

}

var instantiate = (type, config) => {
var actor = factory.create(type, config);
return actor;
}

var engine = new Engine();
var cache = new Cache();
var factory = new Factory();
var network = new Network();
var scheduler = new Scheduler();
var memory = new MemoryManager();


export default engine;//for now export raw factory. prob wont do that always.
export {cache, factory, network, scheduler, memory, initialize, initialized, instantiate };
export default engine;
export {cache, factory, network, scheduler, memory, initialize, instantiate };

//****DEBUG****//
window.engine = engine;
window.kill = function () { scheduler.kill(); }
window.onbeforeonload = function () { network.peer.destroy(); }


/*
*/
7 changes: 6 additions & 1 deletion cruft/graphics/renderables/Sprite.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ import Renderable from "../Renderable";

export default class Sprite extends Renderable {

constructor() {
constructor(url, width, height) {
super();
this.dirt = 0;
this._width = null;
this._height = null;
this._url = null;
this._image = null;
this.loaded = false;

if(url) this.url = url;
if(width !== undefined) this.width = width;
if(height !== undefined) this.height = height;

}

dirty () {
Expand Down
47 changes: 21 additions & 26 deletions cruft/net/Connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,53 +6,48 @@ export default class Connection extends Emitter { //wrapper for peer connection.

this.connection = connection;

this.connection.on("data", (data) => {
this.emit("data", data);
this.emit(data.event, data);//for now assume its always json
this.connection.on("data", (e) => {
this.emit(e.event, e.data);//for now assume its always json
this.emit("data", e);
})

this.on("ping_request", () => {
this.connection.send({
event : "ping_response",
timestamp : Date.now()
})
this.emit("ping_response");
})
}



send(data) {
this.connection.send(data);
emit(event, data) {
this.connection.send({event, data});
}

//assume no other ping_requests durring this time :I
ping() { //tfw no timeout. Lol. Prob should do that cause if connection drops infinite hang. RIP.
ping() { //never have more than one pending ping.
return new Promise((resolve, reject) => {
var timeout = 10000//TODO make reject if ping hasnt been answered by then.
this.connection.send({
event : "ping_request"
});

this.once("ping_response", (message) => {
resolve(message);
})
var resolved = false;
this.emit("ping_request");
this.once("ping_response", resolve);
setTimeout(() => {
if(!resolved) reject();
}, 5000)
})

}

latency() {
//calculate da latency :O :O
return new Promise((resolve, reject) => {
//for now do 1 RTT. DO a bunch of averages for a real test.
var last = Date.now();
this.ping().then((data) => {
var now = Date.now();
var latency = now - last;
resolve({timestamp : data.timestamp, latency : latency});
})
resolve(now - last);
}, reject);

})
}
}

destroy() {
this.connection.close();
this.connection = null;
}


}
Expand Down
111 changes: 49 additions & 62 deletions cruft/net/Network.js
Original file line number Diff line number Diff line change
@@ -1,87 +1,68 @@
import Emitter from "../core/Emitter"
import Session from "./Session"
import Emitter from "../core/Emitter";
import Session from "./Session";
import Connection from "./Connection";

export default class Network extends Emitter {

constructor(name, key) {
super();
this.peerId = null;
this.id = null;
this.peer = null;
this.sessions = null;
}

initialize() {
this.peerId = null;
this.peer = new Peer(name, { key });
initialize(id, options) {//@TODO someway to detect if it failed.
this.id = null;
this.peer = new Peer(id, options);
this.sessions = {};
var builder = {};


this.peer.on("open", (id) => {
console.info("Peerjs ID : " + id );
this.peerId = id;
this.emit("open", id);
})
this.id = id;
console.info(`PeerJS id : ${id}`)
});

var builder = {};

//try to build sessions
this.peer.on("connection", (conn) => {
var peer = conn.peer;
if(!builder[peer]) builder[peer] = {};
var built = builder[peer];
conn.once("data", (data) => {
built[data.connectionType] = conn;

var peerId = conn.peer;
if(!builder[peerId]) builder[peerId] = {};
var built = builder[peerId];

conn.once("data", (type) => {
built[type] = conn; //maybe not alow them to do that cause they can prob do spooky setter/getter mod
if(built.reliable && built.unreliable){
var session = new Session( peer, built.reliable, built.unreliable );
var session = new Session( peerId, new Connection(built.reliable), new Connection(built.unreliable) );
delete builder[peerId];
this.addSession(session);
this.emit("connection", session);
}

})

conn.on("close", () => {
var session = this.sessions[peer];
delete this.sessions[peer];
if(session) {
session.reliable.close();
session.unreliable.close();
this.emit("close", session);
}
if(builder[peerId]){
if(built.reliable) built.reliable.destroy();
if(built.unreliable) built.unreliable.destroy();
}else{
this.removeSession(this.sessions[peerId]);
}
})
})
}

//change how many listeners we add here,.
addSession(session) {
this.sessions[session.key] = session;
session.on("data", (data) => {
this.emit(data.event, {
session : session,
packet : data
});
});
return new Promise((resolve, reject) => {
this.peer.on("open", resolve);//@TODO reject
})
}

//temp util functions @TODO figure out how to do binary stuff.
emitReliable(event, data) {

var packet = {
event : event,
timestamp : Date.now(),
data : data
}

for(var key in this.sessions){
this.sessions[key].reliable.send(packet);
}
addSession(session) {
this.sessions[session.peer] = session;
}

emitUnreliable(event, data) {
var packet = {
event : event,
timestamp : Date.now(),
data : data
}

for(var key in this.sessions){
this.sessions[key].unreliable.send(packet);
}
removeSession(session) {
session.destroy();
delete this.sessions[session.peer];
}

createSession(name) { //we need some kind of timeout for this stuff. It will just hang forever if it fails. TODO failing
Expand All @@ -95,7 +76,7 @@ export default class Network extends Emitter {
var tryResolve = () => {
loaded++;
if(loaded == 2){
var session = new Session( peer, reliable, unreliable )
var session = new Session( name, reliable, unreliable )
this.addSession(session);
resolve(session)
}
Expand All @@ -106,12 +87,12 @@ export default class Network extends Emitter {
}

reliable.once("open", () => {
reliable.send({connectionType:"reliable"});
reliable.send("reliable");
tryResolve();
});

unreliable.once("open", () => {
unreliable.send({connectionType:"unreliable"});
unreliable.send("unreliable");
tryResolve();
});

Expand All @@ -120,7 +101,13 @@ export default class Network extends Emitter {
})
}

emit(event, data) {
var sessions = this.sessions;

for(var peer in sessions){
sessions[peer].emit(event, data);
}
}

}

//NetworkManager
}
Loading

0 comments on commit e50117a

Please sign in to comment.