Skip to content

Commit

Permalink
refactor(frontend): fix signal graph
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryex committed Aug 24, 2024
1 parent b1c9db2 commit 6e503f9
Show file tree
Hide file tree
Showing 22 changed files with 1,765 additions and 1,711 deletions.
26 changes: 7 additions & 19 deletions ic10emu/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl VM {
obj_ids.push(obj_id)
}

transaction.finialize()?;
transaction.finalize()?;

let transaction_ids = transaction.id_space.in_use_ids();
self.id_space.borrow_mut().use_new_ids(&transaction_ids);
Expand Down Expand Up @@ -200,15 +200,12 @@ impl VM {
/// current database.
/// Errors if the object can not be built do to a template error
/// Returns the built object's ID
pub fn add_object_frozen(
self: &Rc<Self>,
frozen: FrozenObject,
) -> Result<ObjectID, VMError> {
pub fn add_object_frozen(self: &Rc<Self>, frozen: FrozenObject) -> Result<ObjectID, VMError> {
let mut transaction = VMTransaction::new(self);

let obj_id = transaction.add_object_from_frozen(frozen)?;

transaction.finialize()?;
transaction.finalize()?;

let transaction_ids = transaction.id_space.in_use_ids();
self.id_space.borrow_mut().use_new_ids(&transaction_ids);
Expand Down Expand Up @@ -1351,17 +1348,7 @@ impl VM {
.objects
.borrow()
.iter()
.filter_map(|(_obj_id, obj)| {
if obj
.borrow()
.as_item()
.is_some_and(|item| item.get_parent_slot().is_some())
{
None
} else {
Some(FrozenObject::freeze_object_sparse(obj, self))
}
})
.map(|(_obj_id, obj)| FrozenObject::freeze_object_sparse(obj, self))
.collect::<Result<Vec<_>, _>>()?,
networks: self
.networks
Expand Down Expand Up @@ -1406,7 +1393,7 @@ impl VM {
for frozen in state.objects {
let _ = transaction.add_object_from_frozen(frozen)?;
}
transaction.finialize()?;
transaction.finalize()?;

self.circuit_holders.borrow_mut().clear();
self.program_holders.borrow_mut().clear();
Expand All @@ -1423,6 +1410,7 @@ impl VM {
let transaction_ids = transaction.id_space.in_use_ids();
self.id_space.borrow_mut().use_ids(&transaction_ids)?;

self.objects.borrow_mut().extend(transaction.objects);
self.circuit_holders
.borrow_mut()
.extend(transaction.circuit_holders);
Expand Down Expand Up @@ -1557,7 +1545,7 @@ impl VMTransaction {
Ok(obj_id)
}

pub fn finialize(&mut self) -> Result<(), VMError> {
pub fn finalize(&mut self) -> Result<(), VMError> {
for (child, (slot, parent)) in &self.object_parents {
let child_obj = self
.objects
Expand Down
2 changes: 2 additions & 0 deletions stationeers_data/src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,11 @@ pub struct SlotInfo {
#[cfg_attr(feature = "tsify", derive(Tsify), tsify(into_wasm_abi, from_wasm_abi))]
pub struct LogicInfo {
#[serde_as( as = "BTreeMap<DisplayFromStr, _>")]
#[cfg_attr(feature = "tsify", tsify(type = "Map<string, Map<LogicSlotType, MemoryAccess>>"))]
pub logic_slot_types: BTreeMap<u32, BTreeMap<LogicSlotType, MemoryAccess>>,
pub logic_types: BTreeMap<LogicType, MemoryAccess>,
#[serde_as( as = "Option<BTreeMap<DisplayFromStr, _>>")]
#[cfg_attr(feature = "tsify", tsify(type = "Map<string, string> | undefined"))]
pub modes: Option<BTreeMap<u32, String>>,
pub transmission_receiver: bool,
pub wireless_logic: bool,
Expand Down
1 change: 1 addition & 0 deletions www/cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@
"trunc",
"ufuzzy",
"VMIC",
"VMUI",
"vstack",
"whos"
],
Expand Down
4 changes: 2 additions & 2 deletions www/src/ts/editor/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ export class IC10Editor extends BaseElement {
app.session.onLoad((_e) => {
const session = app.session;
const updated_ids: number[] = [];
for (const [id, code] of session.programs) {
for (const [id, code] of session.programs.value) {
updated_ids.push(id);
that.createOrSetSession(id, code);
}
Expand Down Expand Up @@ -271,7 +271,7 @@ export class IC10Editor extends BaseElement {
that.activeLineMarkers.set(
id,
session.addMarker(
new Range(active_line, 0, active_line, 1),
new Range(active_line.value, 0, active_line.value, 1),
"vm_ic_active_line",
"fullLine",
true,
Expand Down
12 changes: 6 additions & 6 deletions www/src/ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import "@shoelace-style/shoelace/dist/components/relative-time/relative-time.js"
import "ace-builds";
import "ace-builds/esm-resolver";

class DeferedApp {
class DeferredApp {

app: App;
private resolvers: ((value: App) => void)[];
Expand Down Expand Up @@ -69,7 +69,7 @@ class DeferedApp {

}

class DeferedVM {
class DeferredVM {

vm: VirtualMachine;
private resolvers: ((value: VirtualMachine) => void)[];
Expand Down Expand Up @@ -102,13 +102,13 @@ class DeferedVM {
declare global {
interface Window
{
App: DeferedApp;
VM: DeferedVM;
App: DeferredApp;
VM: DeferredVM;
}
}

window.App = new DeferedApp();
window.VM = new DeferedVM();
window.App = new DeferredApp();
window.VM = new DeferredVM();

import type { App } from "./app";
import type { VirtualMachine } from "./virtualMachine";
Expand Down
95 changes: 49 additions & 46 deletions www/src/ts/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from "./utils";

import * as presets from "./presets";
import { batch, computed, effect, signal, Signal } from "@lit-labs/preact-signals";
const { demoVMState } = presets;

export interface SessionEventMap {
Expand All @@ -37,100 +38,101 @@ export interface SessionEventMap {
}

export class Session extends TypedEventTarget<SessionEventMap>() {
private _programs: Map<number, string>;
private _errors: Map<number, ICError[]>;
private _activeIC: number;
private _activeLines: Map<number, number>;
private _programs: Signal<Map<ObjectID, string>>;
private _errors: Signal<Map<ObjectID, ICError[]>>;
private _activeIC: Signal<ObjectID>;
private _activeLines: Signal<Map<ObjectID, number>>;
private _save_timeout?: ReturnType<typeof setTimeout>;
private _vm_state: FrozenVM;

private app: App;

constructor(app: App) {
super();
this.app = app;
this._programs = new Map();
this._errors = new Map();
this._programs = signal(new Map());
this._errors = signal(new Map());
this._save_timeout = undefined;
this._activeIC = 1;
this._activeLines = new Map();
this._vm_state = undefined;
this._activeIC = signal(null);
this._activeLines = signal(new Map());
this.loadFromFragment();

const that = this;
window.addEventListener("hashchange", (_event) => {
that.loadFromFragment();
});

this._programs.subscribe((_) => {this._fireOnLoad()});
}

get programs(): Map<number, string> {
get programs(): Signal<Map<number, string>> {
return this._programs;
}

set programs(programs: Iterable<[number, string]>) {
this._programs = new Map([...programs]);
this._fireOnLoad();
this._programs.value = new Map(programs);
}

get activeIC() {
get activeIC(): Signal<ObjectID> {
return this._activeIC;
}

set activeIC(val: number) {
this._activeIC = val;
this.dispatchCustomEvent("session-active-ic", this.activeIC);
set activeIC(val: ObjectID) {
this._activeIC.value = val;
this.dispatchCustomEvent("session-active-ic", this.activeIC.peek());
}

changeID(oldID: number, newID: number) {
if (this.programs.has(oldID)) {
this.programs.set(newID, this.programs.get(oldID));
this.programs.delete(oldID);
changeID(oldID: ObjectID, newID: ObjectID) {
if (this.programs.peek().has(oldID)) {
const newVal = new Map(this.programs.value);
newVal.set(newID, newVal.get(oldID));
newVal.delete(oldID);
this.programs.value = newVal;
}
this.dispatchCustomEvent("session-id-change", { old: oldID, new: newID });
}

onIDChange(callback: (e: CustomEvent<{ old: number; new: number }>) => any) {
onIDChange(callback: (e: CustomEvent<{ old: ObjectID; new: ObjectID}>) => any) {
this.addEventListener("session-id-change", callback);
}

onActiveIc(callback: (e: CustomEvent<number>) => any) {
onActiveIc(callback: (e: CustomEvent<ObjectID>) => any) {
this.addEventListener("session-active-ic", callback);
}

get errors() {
return this._errors;
}

getActiveLine(id: number) {
return this._activeLines.get(id);
getActiveLine(id: ObjectID) {
return computed(() => this._activeLines.value.get(id));
}

setActiveLine(id: number, line: number) {
const last = this._activeLines.get(id);
setActiveLine(id: ObjectID, line: number) {
const last = this._activeLines.peek().get(id);
if (last !== line) {
this._activeLines.set(id, line);
this._activeLines.value = new Map([ ... this._activeLines.value.entries(), [id, line]]);
this._fireOnActiveLine(id);
}
}

setProgramCode(id: number, code: string) {
this._programs.set(id, code);
setProgramCode(id: ObjectID, code: string) {
this._programs.value = new Map([ ...this._programs.value.entries(), [id, code]]);
if (this.app.vm) {
this.app.vm.updateCode();
}
this.save();
}

setProgramErrors(id: number, errors: ICError[]) {
this._errors.set(id, errors);
setProgramErrors(id: ObjectID, errors: ICError[]) {
this._errors.value = new Map([ ...this._errors.value.entries(), [id, errors]]);
this._fireOnErrors([id]);
}

_fireOnErrors(ids: number[]) {
_fireOnErrors(ids: ObjectID[]) {
this.dispatchCustomEvent("session-errors", ids);
}

onErrors(callback: (e: CustomEvent<number[]>) => any) {
onErrors(callback: (e: CustomEvent<ObjectID[]>) => any) {
this.addEventListener("session-errors", callback);
}

Expand All @@ -142,7 +144,7 @@ export class Session extends TypedEventTarget<SessionEventMap>() {
this.dispatchCustomEvent("session-load", this);
}

onActiveLine(callback: (e: CustomEvent<number>) => any) {
onActiveLine(callback: (e: CustomEvent<ObjectID>) => any) {
this.addEventListener("active-line", callback);
}

Expand All @@ -159,7 +161,8 @@ export class Session extends TypedEventTarget<SessionEventMap>() {
}

async saveToFragment() {
const toSave = { vm: this.app.vm.saveVMState(), activeIC: this.activeIC };
const vm = await window.VM.get()
const toSave = { vm: vm.state.vm.value, activeIC: this.activeIC };
const bytes = new TextEncoder().encode(toJson(toSave));
try {
const c_bytes = await compress(bytes, defaultCompression);
Expand All @@ -172,21 +175,21 @@ export class Session extends TypedEventTarget<SessionEventMap>() {
}

async load(data: SessionDB.CurrentDBVmState | OldPrograms | string) {
const vm = await window.VM.get()
if (typeof data === "string") {
this._activeIC = 1;
this.app.vm.restoreVMState(demoVMState.vm);
this._programs = new Map([[1, data]]);
this.activeIC = 1;
await vm.restoreVMState(demoVMState.vm);
this.programs = [[1, data]];
} else if ("programs" in data) {
this._activeIC = 1;
this.app.vm.restoreVMState(demoVMState.vm);
this._programs = new Map(data.programs);
this.activeIC = 1;
await vm.restoreVMState(demoVMState.vm);
this.programs = data.programs;
} else if ("vm" in data) {
this._programs = new Map();
this.programs = [];
const state = data.vm;
// assign first so it's present when the
// vm fires events
this._activeIC = data.activeIC;
const vm = await window.VM.get()
this._activeIC.value = data.activeIC;
await vm.restoreVMState(state);
this.programs = vm.getPrograms();
// assign again to fire event
Expand Down Expand Up @@ -259,7 +262,7 @@ export class Session extends TypedEventTarget<SessionEventMap>() {
async saveLocal(name: string) {
const state: SessionDB.CurrentDBVmState = {
vm: await (await window.VM.get()).ic10vm.saveVMState(),
activeIC: this.activeIC,
activeIC: this.activeIC.peek(),
};
const db = await this.openIndexDB();
const transaction = db.transaction(
Expand Down
12 changes: 12 additions & 0 deletions www/src/ts/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import { Ace } from "ace-builds";
import { TransferHandler } from "comlink";

export function isSome<T>(object: T | null | undefined): object is T {
return typeof object !== "undefined" && object !== null;
}

export function range(size: number, start: number = 0): number[] {
const base = [...Array(size ?? 0).keys()]
if (start != 0) {
return base.map(i => i + start);
}
return base
}

export function docReady(fn: () => void) {
// see if DOM is already available
if (
Expand Down
Loading

0 comments on commit 6e503f9

Please sign in to comment.