feat: some shut

This commit is contained in:
max_richter 2024-04-20 04:08:30 +02:00
parent 78c88e4d66
commit 4c7c4cac2c
21 changed files with 172 additions and 171 deletions

2
Cargo.lock generated
View File

@ -302,7 +302,7 @@ dependencies = [
] ]
[[package]] [[package]]
name = "triangle" name = "template"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",

View File

@ -8,6 +8,8 @@ import type { NodeInput } from "@nodes/types";
const logger = createLogger("graph-manager"); const logger = createLogger("graph-manager");
logger.mute();
function areSocketsCompatible(output: string | undefined, inputs: string | string[] | undefined) { function areSocketsCompatible(output: string | undefined, inputs: string | string[] | undefined) {
if (Array.isArray(inputs) && output) { if (Array.isArray(inputs) && output) {
return inputs.includes(output); return inputs.includes(output);
@ -225,6 +227,32 @@ export class GraphManager extends EventEmitter<{ "save": Graph, "result": any, "
return this.registry.getNode(id); return this.registry.getNode(id);
} }
async loadNode(id: string) {
await this.registry.load([id]);
const nodeType = this.registry.getNode(id);
if (!nodeType) return;
const settingTypes = this.settingTypes;
const settingValues = this.settings;
if (nodeType.inputs) {
for (const key in nodeType.inputs) {
let settingId = nodeType.inputs[key].setting;
if (settingId) {
settingTypes[settingId] = nodeType.inputs[key];
if (settingValues[settingId] === undefined && "value" in type.inputs[key]) {
settingValues[settingId] = nodeType.inputs[key].value;
}
}
}
}
this.settings = settingValues;
this.settingTypes = settingTypes;
this.emit("settings", { types: settingTypes, values: settingValues });
}
getChildrenOfNode(node: Node) { getChildrenOfNode(node: Node) {
const children = []; const children = [];
const stack = node.tmp?.children?.slice(0); const stack = node.tmp?.children?.slice(0);
@ -349,6 +377,8 @@ export class GraphManager extends EventEmitter<{ "save": Graph, "result": any, "
return; return;
} }
const node: Node = { id: this.createNodeId(), type, position, tmp: { type: nodeType }, props }; const node: Node = { id: this.createNodeId(), type, position, tmp: { type: nodeType }, props };
this.nodes.update((nodes) => { this.nodes.update((nodes) => {

View File

@ -773,14 +773,13 @@
} }
const pos = projectScreenToWorld(mx, my); const pos = projectScreenToWorld(mx, my);
graph.registry.load([nodeId]).then(() => { graph.loadNode(nodeId).then(() => {
graph.createNode({ graph.createNode({
type: nodeId, type: nodeId,
props: {}, props: {},
position: pos, position: pos,
}); });
}); });
console.log({ nodeId });
} }
function handlerDragOver(e: DragEvent) { function handlerDragOver(e: DragEvent) {

View File

@ -10,7 +10,7 @@ export class RemoteNodeRegistry implements NodeRegistry {
constructor(private url: string) { } constructor(private url: string) { }
private async loadNode(id: `${string}/${string}/${string}`) { async loadNode(id: `${string}/${string}/${string}`) {
const wasmResponse = await this.fetchNode(id); const wasmResponse = await this.fetchNode(id);
// Setup Wasm wrapper // Setup Wasm wrapper
@ -81,6 +81,8 @@ export class RemoteNodeRegistry implements NodeRegistry {
log.log("loaded nodes in", duration, "ms"); log.log("loaded nodes in", duration, "ms");
this.status = "ready"; this.status = "ready";
return nodes
} }
getNode(id: string) { getNode(id: string) {

View File

@ -1,19 +1,15 @@
<script lang="ts"> <script lang="ts">
import { Select } from "@nodes/ui";
import type { Writable } from "svelte/store"; import type { Writable } from "svelte/store";
let activeStore = 0;
export let activeId: Writable<string>; export let activeId: Writable<string>;
$: [activeUser, activeCollection, activeNode] = $activeId.split(`/`); $: [activeUser, activeCollection, activeNode] = $activeId.split(`/`);
</script> </script>
<div class="breadcrumbs"> <div class="breadcrumbs">
{#if activeUser} {#if activeUser}
<button <Select id="root" options={["root"]} bind:value={activeStore}></Select>
on:click={() => {
$activeId = "";
}}
>
root
</button>
{#if activeCollection} {#if activeCollection}
<button <button
on:click={() => { on:click={() => {
@ -38,7 +34,7 @@
<span>{activeUser}</span> <span>{activeUser}</span>
{/if} {/if}
{:else} {:else}
<span>root</span> <Select id="root" options={["root"]} bind:value={activeStore}></Select>
{/if} {/if}
</div> </div>
@ -61,7 +57,8 @@
cursor: pointer; cursor: pointer;
} }
.breadcrumbs > button::after { .breadcrumbs > button::after,
.breadcrumbs :global(select)::after {
content: "/"; content: "/";
position: absolute; position: absolute;
right: -11px; right: -11px;
@ -78,4 +75,9 @@
font-size: 1em; font-size: 1em;
opacity: 0.5; opacity: 0.5;
} }
.breadcrumbs :global(select) {
padding: 3px 5px;
outline: none;
}
</style> </style>

View File

@ -26,7 +26,9 @@
<div class="wrapper"> <div class="wrapper">
{#if !activeUser} {#if !activeUser}
<div class="header">
<h3>Users</h3> <h3>Users</h3>
</div>
{#await nodeRegistry.fetchUsers()} {#await nodeRegistry.fetchUsers()}
<div>Loading...</div> <div>Loading...</div>
{:then users} {:then users}
@ -44,7 +46,15 @@
{#await nodeRegistry.fetchUser(activeUser)} {#await nodeRegistry.fetchUser(activeUser)}
<div>Loading...</div> <div>Loading...</div>
{:then user} {:then user}
<div class="header">
<button
on:click={() => {
$activeId = "";
}}
class="i-tabler-arrow-back"
></button>
<h3>Collections</h3> <h3>Collections</h3>
</div>
{#each user.collections as collection} {#each user.collections as collection}
<button <button
on:click={() => { on:click={() => {
@ -58,35 +68,47 @@
<div>{error.message}</div> <div>{error.message}</div>
{/await} {/await}
{:else if !activeNode} {:else if !activeNode}
<div class="header">
<button
on:click={() => {
$activeId = activeUser;
}}
class="i-tabler-arrow-back"
></button>
<h3>Nodes</h3> <h3>Nodes</h3>
</div>
{#await nodeRegistry.fetchCollection(`${activeUser}/${activeCollection}`)} {#await nodeRegistry.fetchCollection(`${activeUser}/${activeCollection}`)}
<div>Loading...</div> <div>Loading...</div>
{:then collection} {:then collection}
{#each collection.nodes as node} {#each collection.nodes as node}
<button {#await nodeRegistry.fetchNodeDefinition(node.id)}
on:click={() => {
$activeId = node.id;
}}
>
{node.id.split(`/`)[2]}
</button>
{/each}
{:catch error}
<div>{error.message}</div>
{/await}
{:else}
{#await nodeRegistry.fetchNodeDefinition(`${activeUser}/${activeCollection}/${activeNode}`)}
<div>Loading...</div> <div>Loading...</div>
{:then node} {:then node}
<DraggableNode {node} /> <DraggableNode {node} />
{:catch error} {:catch error}
<div>{error.message}</div> <div>{error.message}</div>
{/await} {/await}
{/each}
{:catch error}
<div>{error.message}</div>
{/await}
{/if} {/if}
</div> </div>
<style> <style>
.wrapper { .wrapper {
padding: 1em; padding: 0.8em;
max-height: calc(100vh - 170px);
overflow-y: auto;
}
.header {
display: flex;
align-items: center;
gap: 0.5em;
margin-bottom: 0.5em;
}
h3 {
margin: 0;
} }
</style> </style>

View File

@ -111,6 +111,8 @@ export class MemoryRuntimeExecutor implements RuntimeExecutor {
// here we store the intermediate results of the nodes // here we store the intermediate results of the nodes
const results: Record<string, string | boolean | number> = {}; const results: Record<string, string | boolean | number> = {};
const runSeed = settings["randomSeed"] === true ? Math.floor(Math.random() * 100000000) : 5120983;
for (const node of sortedNodes) { for (const node of sortedNodes) {
const node_type = this.typeMap.get(node.type)!; const node_type = this.typeMap.get(node.type)!;
@ -120,7 +122,7 @@ export class MemoryRuntimeExecutor implements RuntimeExecutor {
for (const [key, input] of Object.entries(node_type.inputs || {})) { for (const [key, input] of Object.entries(node_type.inputs || {})) {
if (input.type === "seed") { if (input.type === "seed") {
inputs[key] = Math.floor(Math.random() * 100000000); inputs[key] = runSeed;
continue; continue;
} }

View File

@ -93,8 +93,16 @@
icon: "i-tabler-chart-bar", icon: "i-tabler-chart-bar",
id: "graph", id: "graph",
settings: writable(ev.detail.values), settings: writable(ev.detail.values),
definition: ev.detail.types, definition: {
randomSeed: {
type: "boolean",
label: "Random Seed",
value: true,
},
...ev.detail.types,
},
}; };
settings = settings; settings = settings;
} }
</script> </script>

View File

@ -1,5 +1,5 @@
[package] [package]
name = "triangle" name = "template"
version = "0.1.0" version = "0.1.0"
authors = ["Max Richter <jim-x@web.de>"] authors = ["Max Richter <jim-x@web.de>"]
edition = "2018" edition = "2018"

View File

@ -1,6 +1,6 @@
{ {
"scripts": { "scripts": {
"build": "wasm-pack build --release --out-name index --no-default-features", "build": "wasm-pack build --release --out-name index --no-default-features",
"dev": "cargo watch -s 'pnpm build'" "dev": "cargo watch -s 'wasm-pack build --dev --out-name index --no-default-features'"
} }
} }

View File

@ -0,0 +1,18 @@
{
"outputs": [
"float"
],
"inputs": {
"min": {
"type": "float",
"value": 2
},
"max": {
"type": "float",
"value": 2
},
"seed": {
"type": "seed"
}
}
}

View File

@ -1,48 +1,22 @@
use macros::define_node; use macros::include_definition_file;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
define_node!( include_definition_file!("src/definition.json");
r#"{
"outputs": ["float"],
"inputs": {
"min": { "type": "float", "value": 2 },
"max": { "type": "float", "value": 2 },
"seed": { "type": "seed" }
}
}"#
);
#[wasm_bindgen] #[wasm_bindgen]
pub fn execute(args: &[i32]) -> Vec<i32> { pub fn execute(args: &[i32]) -> Vec<i32> {
// let min: String; let mut result = Vec::with_capacity(args.len() + 7);
// if var_min.is_string() { result.push(0);
// min = unwrap_string(var_min); result.push(1);
// } else { result.push(0); // encoding the [ bracket
// min = unwrap_int(var_min).to_string(); result.push(args[1] + 1);
// }
//
// let max: String;
// if var_max.is_string() {
// max = unwrap_string(var_max);
// } else {
// max = unwrap_int(var_max).to_string();
// }
//
// let seed: String;
// if var_seed.is_string() {
// seed = unwrap_string(var_seed);
// } else {
// seed = unwrap_int(var_seed).to_string();
// }
//
// log(&format!("min: {}, max: {}, seed: {}", min, max, seed));
//
// // Interpolate strings into JSON format
// let json_string = format!(
// r#"{{"__type": "random", "min": {}, "max": {}, "seed": {}}}"#,
// min, max, seed
// );
// json_string result.push(1); // adding the node-type, random: 0
vec![1, args[0]] result.extend_from_slice(&args[2..]);
result.push(1);
result.push(1); // closing bracket
result.push(1);
result.push(1); // closing bracket
result
} }

View File

@ -33,7 +33,7 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
let a = i as f32 / (res_curve - 1) as f32; let a = i as f32 / (res_curve - 1) as f32;
path_p[i * 4] = origin[0] + (a * 8.0).sin() * 0.2; path_p[i * 4] = origin[0] + (a * 8.0).sin() * 0.2;
path_p[i * 4 + 1] = origin[1] + a * length; path_p[i * 4 + 1] = origin[1] + a * length;
path_p[i * 4 + 2] = origin[2] + 0.0; path_p[i * 4 + 2] = origin[2] + ((a + 2.0) * 8.0).sin() * 0.2;
path_p[i * 4 + 3] = thickness * (1.0 - a); path_p[i * 4 + 3] = thickness * (1.0 - a);
} }

View File

@ -1,6 +1,6 @@
{ {
"scripts": { "scripts": {
"build": "wasm-pack build --release --out-name index --no-default-features", "build": "wasm-pack build --release --out-name index --no-default-features",
"dev": "cargo watch -s 'pnpm build'" "dev": "cargo watch -s 'wasm-pack build --dev --out-name index --no-default-features'"
} }
} }

View File

@ -1,5 +1,5 @@
use macros::include_definition_file; use macros::include_definition_file;
use utils::{decode_float, encode_float, wrap_arg}; use utils::{decode_float, encode_float, evaluate_arg, evaluate_float, get_args, wrap_arg};
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use web_sys::console; use web_sys::console;
@ -9,11 +9,15 @@ include_definition_file!("src/input.json");
#[wasm_bindgen] #[wasm_bindgen]
pub fn execute(input: &[i32]) -> Vec<i32> { pub fn execute(input: &[i32]) -> Vec<i32> {
let size = input[2]; utils::set_panic_hook();
let decoded = decode_float(input[2]);
let args = get_args(input);
let size = evaluate_arg(args[0]);
let decoded = decode_float(size);
let negative_size = encode_float(-decoded); let negative_size = encode_float(-decoded);
console::log_1(&format!("WASM(triangle): input: {:?} -> {}", input, decoded).into()); console::log_1(&format!("WASM(triangle): input: {:?} -> {}", args[0],decoded).into());
// [[1,3, x, y, z, x, y,z,x,y,z]]; // [[1,3, x, y, z, x, y,z,x,y,z]];
wrap_arg(&[ wrap_arg(&[
@ -22,8 +26,6 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
1, // 1 face 1, // 1 face
// this are the indeces for the face // this are the indeces for the face
0, 2, 1, 0, 2, 1,
// this is the normal for the single face 1065353216 == 1.0f encoded is i32
0, 1065353216, 0,
// //
negative_size, // x -> point 1 negative_size, // x -> point 1
0, // y 0, // y
@ -36,6 +38,10 @@ pub fn execute(input: &[i32]) -> Vec<i32> {
0, // x -> point 3 0, // x -> point 3
0, // y 0, // y
size, // z size, // z
// this is the normal for the single face 1065353216 == 1.0f encoded is i32
0, 1065353216, 0,
0, 1065353216, 0,
0, 1065353216, 0,
]) ])
} }

View File

@ -1,6 +1,6 @@
{ {
"scripts": { "scripts": {
"build": "wasm-pack build --release --out-name index --no-default-features", "build": "wasm-pack build --release --out-name index --no-default-features",
"dev": "cargo watch -s 'pnpm build'" "dev": "cargo watch -s 'wasm-pack build --dev --out-name index --no-default-features'"
} }
} }

View File

@ -53,11 +53,11 @@ pub fn extrude_path(input_path: &[i32], res_x: usize) -> Vec<i32> {
}; };
v = v.normalize(); v = v.normalize();
let n = Vec3::new(0.0, 1.0, 0.0); // Assuming 'n' is the up vector or similar let n = Vec3::new(0.0, -1.0, 0.0); // Assuming 'n' is the up vector or similar
let axis = n.cross(v); let axis = n.cross(v);
let angle = n.dot(v).acos(); let angle = n.dot(v).acos();
let quat = Quat::from_axis_angle(axis, angle); let quat = Quat::from_axis_angle(axis, angle).normalize();
let mat = Mat4::IDENTITY * Mat4::from_quat(quat); let mat = Mat4::IDENTITY * Mat4::from_quat(quat);
for j in 0..res_x { for j in 0..res_x {
@ -98,7 +98,7 @@ pub fn extrude_path(input_path: &[i32], res_x: usize) -> Vec<i32> {
point[2] + circle_y, point[2] + circle_y,
); );
let pt = Mat4::transform_point3(&mat, _pt) + point; let pt = Mat4::transform_vector3(&mat, _pt) + point;
normals[idx ] = circle_x; normals[idx ] = circle_x;
normals[idx + 1] = 0.0; normals[idx + 1] = 0.0;

View File

@ -1,78 +0,0 @@
use std::cell::RefCell;
use serde_json::Value;
use wasm_bindgen::prelude::*;
pub fn unwrap_int(val: JsValue) -> i32 {
if val.is_undefined() || val.is_null() {
panic!("Value is undefined");
}
return val.as_f64().unwrap() as i32;
}
pub fn unwrap_float(val: JsValue) -> f64 {
if val.is_undefined() || val.is_null() {
panic!("Value is undefined");
}
return val.as_f64().unwrap();
}
pub fn unwrap_string(val: JsValue) -> String {
if val.is_undefined() || val.is_null() {
panic!("Value is undefined");
}
return val.as_string().unwrap();
}
pub fn evaluate_parameters(val: JsValue) -> f64 {
let str = unwrap_string(val);
let v: Value = serde_json::from_str(&str).unwrap();
let index = RefCell::new(0.0);
return walk_json(&v, &index);
}
fn walk_json(value: &Value, depth: &RefCell<f64>) -> f64 {
*depth.borrow_mut() += 1.0;
match value {
// If it's an object, recursively walk through its fields
Value::Object(obj) => {
let obj_type = obj.get("__type").unwrap();
if obj_type == "random" {
let min = walk_json(obj.get("min").unwrap(), depth);
let max = walk_json(obj.get("max").unwrap(), depth);
let seed = (obj.get("seed").unwrap().as_f64().unwrap() + *depth.borrow() * 2000.0)
/ 1000000.0;
let range = max - min;
let seed = seed % range;
return seed - min;
} else if obj_type == "math" {
let a = walk_json(obj.get("a").unwrap(), depth);
let b = walk_json(obj.get("b").unwrap(), depth);
let op_type = obj.get("op_type").unwrap();
if op_type == 0 {
return a + b;
} else if op_type == 1 {
return a - b;
} else if op_type == 2 {
return a * b;
} else if op_type == 3 {
return a / b;
}
}
return 0.0;
}
Value::Array(arr) => {
for val in arr {
walk_json(val, depth);
}
return 0.0;
}
Value::Number(num) => {
return num.as_f64().unwrap();
}
// If it's a primitive value, print it
_ => {
return 0.0;
}
}
}

View File

@ -1,9 +1,7 @@
mod encoding; mod encoding;
mod helpers;
mod nodes; mod nodes;
mod tree; mod tree;
pub use encoding::*; pub use encoding::*;
pub use helpers::*;
pub use tree::*; pub use tree::*;
pub mod geometry; pub mod geometry;

View File

@ -1,4 +1,4 @@
use crate::encoding; use crate::{encoding, log};
pub fn math_node(args: &[i32]) -> i32 { pub fn math_node(args: &[i32]) -> i32 {
let math_type = args[0]; let math_type = args[0];
@ -16,3 +16,20 @@ pub fn math_node(args: &[i32]) -> i32 {
encoding::encode_float(result) encoding::encode_float(result)
} }
static mut CALL_COUNT: i32 = 0;
pub fn random_node(args: &[i32]) -> i32 {
let min = encoding::decode_float(args[0]);
let max = encoding::decode_float(args[1]);
let seed = (args[2] + unsafe { CALL_COUNT } * 2312312) % 100_000;
let v = seed as f32 / 100_000.0;
log!("Random node: min: {}, max: {}, seed: {}", min, max, seed);
let result = min + v * (max - min);
unsafe {
CALL_COUNT += 1;
}
encoding::encode_float(result)
}

View File

@ -1,4 +1,4 @@
use crate::decode_float; use crate::{decode_float, log};
pub fn get_args(args: &[i32]) -> Vec<&[i32]> { pub fn get_args(args: &[i32]) -> Vec<&[i32]> {
let mut idx: usize = 0; let mut idx: usize = 0;
@ -103,6 +103,7 @@ pub fn evaluate_node(input_args: &[i32]) -> i32 {
match node_type { match node_type {
0 => crate::nodes::math_node(&input_args[1..]), 0 => crate::nodes::math_node(&input_args[1..]),
1 => crate::nodes::random_node(&input_args[1..]),
_ => 0, _ => 0,
} }
} }