Skip to content

Commit

Permalink
Use the bench namespace functions
Browse files Browse the repository at this point in the history
Signed-off-by: Dimitris Zervas <[email protected]>
  • Loading branch information
dzervas committed Jun 26, 2024
1 parent 5dfe59f commit e2c4e82
Show file tree
Hide file tree
Showing 13 changed files with 32 additions and 143 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions applications/web/src/components/AppBar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import Sun from "phosphor-svelte/lib/Sun"
import type {WithTarget} from "shared/types"
import {base} from "../base"
import {renameProject} from "shared/projectUtils"
import {bench} from "shared/projectUtils"
const log = (function () { const context = "[AppBar.svelte]"; const color="gray"; return Function.prototype.bind.call(console.log, console, `%c${context}`, `font-weight:bold;color:${color};`)})() // prettier-ignore
Expand Down Expand Up @@ -62,7 +62,7 @@
on:keydown={e => {
if (e.key === "Enter") {
log("Renaming project")
renameProject(newProjectName)
bench.projectRename(newProjectName)
project.name = newProjectName
renaming = false
}
Expand Down
4 changes: 2 additions & 2 deletions applications/web/src/components/BottomBar.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script>
import {project, workbenchIndex, workbenchIsStale} from "shared/stores"
import {renameWorkbench} from "shared/projectUtils"
import {bench} from "shared/projectUtils"
// prettier-ignore
const log = (function () { const context = "[BottomBar.svelte]"; const color="gray"; return Function.prototype.bind.call(console.log, console, `%c${context}`, `font-weight:bold;color:${color};`)})()
Expand All @@ -23,7 +23,7 @@
on:keydown={e => {
if (e.key === "Enter") {
log("Renaming workbench index:", i)
renameWorkbench(new_workbench_name)
bench.workbenchRename(new_workbench_name)
wb.name = new_workbench_name
workbenchIsStale.set(true)
wb.renaming = false
Expand Down
5 changes: 3 additions & 2 deletions applications/web/src/components/ToolBar.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script>
import {currentlySelected, currentlyMousedOver, selectingFor, featureIndex, sketchBeingEdited, sketchTool, workbench, hiddenSketches} from "shared/stores"
import {newExtrusion, newSketchOnPlane} from "shared/projectUtils"
import {bench, newExtrusion} from "shared/projectUtils"
import {base} from "../base"
const log = (function () { const context = "[ToolBar.svelte]"; const color="gray"; return Function.prototype.bind.call(console.log, console, `%c${context}`, `font-weight:bold;color:${color};`)})() // prettier-ignore
Expand All @@ -14,7 +14,8 @@
}
const createNewSketch = () => {
// log('Create new sketch')
newSketchOnPlane()
// TODO: This is wrong
bench.workbenchSketchAdd({PlaneId: "0"})
$featureIndex = $workbench.history.length - 1
}
const debugging = false
Expand Down
6 changes: 3 additions & 3 deletions applications/web/src/components/features/Extrusion.svelte
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<script lang="ts">
import {slide} from "svelte/transition"
import {quintOut} from "svelte/easing"
import {arraysEqual, renameStep, updateExtrusion} from "shared/projectUtils"
import {arraysEqual, bench, updateExtrusion} from "shared/projectUtils"
import {selectingFor, workbenchIsStale, featureIndex, currentlySelected, hiddenSketches} from "shared/stores"
import X from "phosphor-svelte/lib/X"
import {base} from "../../base"
import type {FeatureExtrusionAdd} from "shared/cadmium-api"
import type { StepHash } from "cadmium"
import type {StepHash} from "cadmium"
// @ts-ignore
const log = (function () { const context = "[ExtrusionFeature.svelte]"; const color="gray"; return Function.prototype.bind.call(console.log, console, `%c${context}`, `font-weight:bold;color:${color};`)})() // prettier-ignore
Expand Down Expand Up @@ -153,7 +153,7 @@
<button
class="flex-grow bg-sky-500 hover:bg-sky-700 text-white font-bold py-1.5 px-1 shadow"
on:click={() => {
renameStep(hash, name)
bench.stepRename(hash, name)
}}>Done</button
>

Expand Down
4 changes: 2 additions & 2 deletions applications/web/src/components/features/Plane.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import {slide} from "svelte/transition"
import {quintOut} from "svelte/easing"
import {renameStep} from "shared/projectUtils"
import {bench} from "shared/projectUtils"
import {workbenchIsStale, featureIndex} from "shared/stores"
import MagnifyingGlass from "phosphor-svelte/lib/MagnifyingGlass"
import type {Plane, SetCameraFocus} from "shared/types"
Expand Down Expand Up @@ -78,7 +78,7 @@
<button
class="flex-grow bg-sky-500 hover:bg-sky-700 text-white font-bold py-1.5 px-1 shadow"
on:click={() => {
renameStep(index, name)
bench.stepRename(index, name)
}}>Done</button
>

Expand Down
4 changes: 2 additions & 2 deletions applications/web/src/components/features/Point.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import {slide} from "svelte/transition"
import {quintOut} from "svelte/easing"
import {renameStep} from "shared/projectUtils"
import {bench} from "shared/projectUtils"
import {workbenchIsStale, featureIndex} from "shared/stores"
import {base} from "../../base"
Expand Down Expand Up @@ -56,7 +56,7 @@
<button
class="flex-grow bg-sky-500 hover:bg-sky-700 text-white font-bold py-1.5 px-1 shadow"
on:click={() => {
renameStep(index, name)
bench.stepRename(index, name)
}}>Done</button
>

Expand Down
8 changes: 4 additions & 4 deletions applications/web/src/components/features/Sketch.svelte
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts">
import {slide} from "svelte/transition"
import {quintOut} from "svelte/easing"
import {renameStep, setSketchPlane} from "shared/projectUtils"
import {bench} from "shared/projectUtils"
import {
hiddenSketches,
featureIndex,
Expand Down Expand Up @@ -98,11 +98,11 @@
let thingSelected = $currentlySelected[0]
if (thingSelected.type === "plane") {
setSketchPlane(hash, parseInt(thingSelected.id))
bench.workbenchSketchSetPlane(hash, thingSelected.id)
} else if (thingSelected.type === "meshFace") {
log("HOW DO I HANDLE THIS?")
log(thingSelected)
// setSketchPlane(id, $currentlySelected[0].id)
// bench.workbenchSketchSetPlane(hash, $currentlySelected[0].id)
}
disengageSearchForPlane()
Expand Down Expand Up @@ -201,7 +201,7 @@
class="flex-grow bg-sky-500 hover:bg-sky-700 text-white font-bold py-1.5 px-1 shadow"
on:click={() => {
// This is a form button so remember that it triggers the form's on:submit
renameStep(hash, name)
bench.stepRename(hash, name)
}}>Done</button
>

Expand Down
4 changes: 2 additions & 2 deletions applications/web/src/components/tools/NewLine.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
// - twoD: an object with x and y properties representing the point in 2D space
// - threeD: an object with x, y, and z properties representing the point in 3D space
// - id: a string representing the id of the point in the sketch
// If the id is nullish we call addPointToSketch to create a new point in the sketch.
// If the id is nullish we call sketchAddPoint to create a new point in the sketch.
if (!point) return
point.id = point.id ?? bench.sketchAddPoint(sketchIndex, point.x, point.y).data
stack.push(point)
Expand Down Expand Up @@ -59,7 +59,7 @@
if (geom.type === "point3D") {
if (geom.x && geom.y && geom.z) {
const twoD = projectToPlane(new Vector3(geom.x, geom.y, geom.z))
snappedTo = { x: twoD.x, y: twoD.y, hidden: false } as Point2WithID
snappedTo = {x: twoD.x, y: twoD.y, hidden: false} as Point2WithID
}
}
if (geom.type === "point") {
Expand Down
8 changes: 4 additions & 4 deletions applications/web/src/components/tools/NewRectangle.svelte
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<script lang="ts">
import {snapPoints, sketchTool, previewGeometry, currentlyMousedOver} from "shared/stores"
import {addRectangleBetweenPoints, addPointToSketch} from "shared/projectUtils"
import {bench} from "shared/projectUtils"
import {Vector3} from "three"
import type {IDictionary, PointLikeById, ProjectToPlane} from "shared/types"
import type { Point2 } from "cadmium"
import type {Point2} from "cadmium"
// @ts-ignore
const log = (function () { const context = "[NewRectangleTool.svelte]"; const color="gray"; return Function.prototype.bind.call(console.log, console, `%c${context}`, `font-weight:bold;color:${color};`)})() // prettier-ignore
Expand All @@ -18,7 +18,7 @@
function pushToStack(point: PointLikeById) {
if (!point) return
point.id = point.id ?? addPointToSketch(sketchIndex, point.twoD, false)
point.id = point.id ?? bench.sketchAddPoint(sketchIndex, point.twoD, false)
stack.push(point)
}
Expand All @@ -34,7 +34,7 @@
default:
const endPoint = popFromStack()
const anchor = popFromStack()
addRectangleBetweenPoints(sketchIndex, +anchor!.id!, +endPoint!.id!)
bench.sketchAddRectangle(sketchIndex, +anchor!.id!, +endPoint!.id!)
clearStack()
break
}
Expand Down
1 change: 1 addition & 0 deletions packages/cadmium/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ convert_case = "0.6"
xxhash-rust = { version = "0.8", features = ["xxh3"] }
js-sys = "0.3"
loro = "0.16"
chrono = { version = "0.4.38", features = ["js-sys", "serde", "wasm-bindgen"], default-features = false }

[lib]
crate-type = ["cdylib", "rlib"]
Expand Down
11 changes: 5 additions & 6 deletions packages/cadmium/src/step/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use chrono::{DateTime, Utc};
use std::cell::RefCell;
use std::fmt::Display;
use std::rc::Rc;
use std::time::SystemTime;

use serde::{Deserialize, Serialize};
use tsify_next::Tsify;
Expand Down Expand Up @@ -40,18 +40,17 @@ pub struct Step {
suppressed: bool,
data: Message,
pub result: StepResult,
timestamp: SystemTime,
timestamp: DateTime<Utc>,
author: String,
}

impl Step {
pub fn new(data: Message, result: StepResult) -> Self {
let timestamp = SystemTime::now();
let timestamp = Utc::now();
let author = "Anonymous".to_string();

let message_data = serde_json::to_string(&data).unwrap();
let timestamp_str = serde_json::to_string(&timestamp).unwrap();
let author = serde_json::to_string(&author).unwrap();
let timestamp_str = timestamp.to_string();
let hash_data = [
message_data.as_bytes(),
timestamp_str.as_bytes(),
Expand Down Expand Up @@ -95,7 +94,7 @@ impl Step {
self.suppressed
}

pub fn timestamp(&self) -> SystemTime {
pub fn timestamp(&self) -> DateTime<Utc> {
self.timestamp
}
}
Expand Down
115 changes: 1 addition & 114 deletions packages/shared/projectUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {Vector2, Vector3, type Vector2Like} from "three"
import type {Entity, MessageHistory, WithTarget} from "./types"
import type {Workbench, MessageResult, Solid, Step, Point3, Plane, ISketch, StepHash} from "cadmium"
import {isSketchActionStep} from "./stepTypeGuards"
import {isMessage} from "./typeGuards"

import * as cad from "./cadmium-api"
(window as any).cad = cad
Expand Down Expand Up @@ -34,27 +33,6 @@ export namespace bench {
}
(window as any).bench = bench

export function getWorkbenchSolids(): Solid[] {
let wp = get(wasmProject)
return wp.get_workbench_solids(get(workbenchIndex))
}

export function isPoint(node: Node): node is Node & Point3 {
// const typedObj = node as Point3
// return typedObj.x !== undefined && typedObj.y !== undefined && typedObj.z !== undefined
return "Point" in node
}
export function isPlane(node: Node): node is Node & Plane {
return "Plane" in node
}
export type SketchStep = Step & {result: ISketch, data: cad.WorkbenchSketchAdd }
export function isSketchStep(step: Step): step is SketchStep {
return "WorkbenchSketchAdd" in step.data && "Sketch" in step.result
}
export function isSolid(node: Node): node is Node & Solid[] {
return "Solid" in node
}

export function arraysEqual(a: any[], b: any[]) {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) {
Expand Down Expand Up @@ -97,30 +75,8 @@ export function updateExtrusion(extrusionId: number, sketchId: number, length: n
extrusion_id: extrusionId,
},
}
const isValid = checkWasmMessage(message)
const hasFaceIds = notEmpty(message.UpdateExtrusion.face_ids)
if (isValid) {
sendWasmMessage(message)
workbenchIsStale.set(true)
if (hasFaceIds) {
log("[updateExtrusion]", "[checkWasmMessage]", "is valid,", "sending message...", message)
// sendWasmMessage(message)
} else log("[updateExtrusion]", "[checkWasmMessage]", "is valid,", "but face_ids is empty,", "NOT sending message:", message)
} else log("[updateExtrusion]", "[checkWasmMessage]", "is bogus,", "abort message send!", message)

// sendWasmMessage(message)

// should this be set stale when not sending the wasm message? todo
// workbenchIsStale.set(true)
}

export function setSketchPlane(sketchId: number, planeId: number) {
return cad.workbenchSketchSetPlane(get(workbenchIndex).toString(), sketchId, {PlaneId: planeId})
}

export function newSketchOnPlane() {
// TODO: Why are we defaulting to plane 0?
cad.workbenchSketchAdd(get(workbenchIndex).toString(), {PlaneId: 0})
sendWasmMessage(message)
}

export function newExtrusion() {
Expand Down Expand Up @@ -150,34 +106,6 @@ export function deleteEntities(sketchIdx: string, selection: Entity[]) {
}
}

export function addRectangleBetweenPoints(sketchIdx: string, point1: string, point2: string) {
return cad.sketchAddRectangle(get(workbenchIndex).toString(), sketchIdx, point1, point2)
}

export function addCircleBetweenPoints(sketchIdx: string, point1: string, point2: string) {
return cad.sketchAddCircle(get(workbenchIndex).toString(), sketchIdx, point1, point2)
}

export function addLineToSketch(sketchIdx: string, point1: string, point2: string) {
return cad.sketchAddLine(get(workbenchIndex).toString(), sketchIdx, point1, point2)
}

export function addPointToSketch(sketchIdx: string, point: Vector2Like, hidden: boolean): StepHash {
return cad.sketchAddPoint(get(workbenchIndex).toString(), sketchIdx, point.x, point.y).data
}

export function renameStep(stepIdx: string, newName: string): void {
cad.stepRename(get(workbenchIndex).toString(), stepIdx, newName)
}

export function renameWorkbench(newName: string): void {
cad.workbenchRename(get(workbenchIndex).toString(), newName)
}

export function renameProject(newName: string): void {
cad.projectRename(newName)
}

// If the project ever becomes stale, refresh it. This should be pretty rare.
projectIsStale.subscribe(value => {
if (value) {
Expand Down Expand Up @@ -294,44 +222,3 @@ export function flatten(points: Vector3[]): number[] {
}
return pointsFlat
}

function isStringInt(s: string, errorCallback: {(id: any): void; (arg0: string): void}): boolean {
if (typeof s !== "string") console.error("[proectUtils.ts] [isStringInt]", s, "is not a string:", typeof s)
const isInt = !Number.isNaN(parseInt(s, 10))
if (!isInt) errorCallback(s)
return isInt
}

function reduceToInts(data: string[], errorCallback: (id: any) => void): number[] {
function reducer(acc: number[], id: string): number[] {
return isStringInt(id, errorCallback) ? [...acc, parseInt(id, 10)] : acc
}
return data.reduce(reducer, [])
}

function notEmpty(array: unknown[]): boolean {
return array && Array.isArray(array) && array.length > 0
}

export function checkWasmMessage(message: Message, abort = true, logError = true): boolean {
const key = Object.keys(message)[0]
const command = message[key as keyof Message]
if (!command) {
console.error("[projectUtils.ts] [checkWasmMessage]", "messageType not found:", key, message)
return false
}
log("[checkWasmMessage]", "checking...", key, message)

function logOrAbort() {
const error = `[${key}] message failed typecheck:`
if (logError) console.error("[projectUtils.ts]", error, message)
// if (abort && isDevelopment()) throw new Error(`"[projectUtils.ts]" ${error}`)
return false
}

if (!isMessage(command)) {
logOrAbort()
return false
}
return true
}

0 comments on commit e2c4e82

Please sign in to comment.