Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve devtools #36

Merged
merged 17 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions apps/playground-3d/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,15 @@ import Character from './classes/Character'
character.onCollisionWith(FCuboid, ({ component }) => {
// Cast the component to FCuboid
const cube = component as FCuboid
console.log('Collision with cube : ', cube)
console.log('Character collided with a cube', cube)
// Change the color of the cube to a random color
// cube.setColor(Math.random() * 0xFFFFFF)
})
character.onCollisionWith(sphere, () => {
console.log('Character collided with the sphere!')
console.log('Character collided with the sphere.')
})
character.onCollisionWith(deathZone, () => {
console.log('Character fell into the death zone!')
console.log('Character fell into the death zone.')
character.transform.position = { x: 0, y: 10, z: 0 }
})

Expand Down
379 changes: 224 additions & 155 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"vite": "^5.2.9",
"vitepress": "^1.5.0",
"vitest": "^2.1.2",
"vue": "^3.4.37",
"vue": "^3.5.13",
"vue-tsc": "^2.0.29"
},
"nx": {}
Expand Down
3 changes: 3 additions & 0 deletions packages/devtools/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ declare module '*.ce.vue' {
const component: ReturnType<typeof defineComponent>
export default component
}

// Fibbo version
declare const __FIBBO_VERSION__: string
69 changes: 56 additions & 13 deletions packages/devtools/src/FDebug.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { defineCustomElement, reactive } from 'vue'
import { createApp, reactive } from 'vue'
import type { FScene } from '@fibbojs/core'
import type { FScene as FScene2d } from '@fibbojs/2d'
import type { FScene as FScene3d } from '@fibbojs/3d'
import FDebugPanel from './components/FDebugPanel.ce.vue'
import FDebugComponent from './components/FDebug.vue'
import { FDebug2d } from './FDebug2d'
import { FDebug3d } from './FDebug3d'

// Define the custom Web Component from the Vue component
const FDebugPanelElement = defineCustomElement(FDebugPanel)
import { State } from './State'
import { FLogger } from './FLogger'

/**
* A helper class to debug a given scene
Expand Down Expand Up @@ -39,16 +38,51 @@ export class FDebug {
// Define the scene
this.scene = scene

// Define the custom element in the browser
customElements.define('f-debug-panel', FDebugPanelElement)
// Create and inject the custom element into the DOM
const debugPanel = new FDebugPanelElement({
title: 'Fibbo',
scene: this.scene,
})
// Load devtools state from local storage
State.load()

/**
* Override console methods
*/
// Override console.log
const originalConsoleLog = console.log
console.log = (...args: any[]) => {
originalConsoleLog(...args)
FLogger.log(...args)
}
// Override console.warn
const originalConsoleWarn = console.warn
console.warn = (...args: any[]) => {
originalConsoleWarn(...args)
FLogger.warn(...args)
}
// Override console.error
const originalConsoleError = console.error
console.error = (...args: any[]) => {
originalConsoleError(...args)
FLogger.error(...args)
}

// Fetch the CSS
fetch(import.meta.url.replace('index.es.js', 'style.css'))
.then(res => res.text())
.then((css) => {
// Extract the CSS content
css = css
.split('const __vite__css = "')[1]
.split('\\n"')[0]
const style = document.createElement('style')
style.innerHTML = css
document.head.appendChild(style)
})

// Make the component array reactive
this.scene.components = reactive(this.scene.components) as any
// Make sure added components are reactive
scene.onComponentAdded((component) => {
// @ts-expect-error - Core FComponent does not have transform property
component.transform = reactive(component.transform)
})

// 3D specific debug behavior
if (scene.__IS_3D__) {
Expand All @@ -61,8 +95,17 @@ export class FDebug {
this.debugger2d = new FDebug2d(scene as FScene2d)
}

// Add the debug panel to the body
// Create a HTML element for the debug panel
const debugPanel = document.createElement('div')
debugPanel.id = 'f-debug'
// Append the debug panel to the body
document.body.appendChild(debugPanel)
// Mount the Vue instance
createApp(FDebugComponent, {
title: 'Fibbo',
version: __FIBBO_VERSION__,
scene: this.scene,
}).mount('#f-debug')
}
}

Expand Down
10 changes: 10 additions & 0 deletions packages/devtools/src/FDebug2d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { FScene } from '@fibbojs/2d'
import type { DebugRenderBuffers } from '@dimforge/rapier2d'
import { State } from './State'

/**
* A helper class to debug a given 2d scene
Expand All @@ -15,6 +16,7 @@ export class FDebug2d {
constructor(scene: FScene) {
// Add help grid
const helpGrid = new scene.PIXI.Graphics()
helpGrid.visible = State.helpers
// Draw the grid
for (let i = -1000; i <= 1000; i += 100) {
helpGrid.moveTo(i, -1000)
Expand All @@ -34,6 +36,7 @@ export class FDebug2d {

// Initiliaze debug graphics
const DEBUG_GRAPHICS = new scene.PIXI.Graphics()
DEBUG_GRAPHICS.visible = State.hitboxes
DEBUG_GRAPHICS.zIndex = 1000000
scene.viewport.addChild(DEBUG_GRAPHICS)

Expand Down Expand Up @@ -65,5 +68,12 @@ export class FDebug2d {
DEBUG_GRAPHICS.lineTo(x2, y2)
}
})

State.onHelpersChange((newState) => {
helpGrid.visible = newState
})
State.onHitboxesChange((newState) => {
DEBUG_GRAPHICS.visible = newState
})
}
}
50 changes: 37 additions & 13 deletions packages/devtools/src/FDebug3d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { FLight, FScene } from '@fibbojs/3d'
import { State } from './State'

/**
* A helper class to debug a given 3d scene
Expand All @@ -14,15 +15,18 @@ export class FDebug3d {
constructor(scene: FScene) {
// Add grid helper
const gridHelper = new scene.THREE.GridHelper(10, 10)
gridHelper.visible = State.helpers
scene.scene.add(gridHelper)

// Axes helper
const axesHelper = new scene.THREE.AxesHelper(5)
axesHelper.visible = State.helpers
scene.scene.add(axesHelper)

/**
* When a light is added to the scene, add a helper for it
*/
const lightHelpers: any[] = []
scene.onLightAdded((lightParam) => {
// Cast light to a 3D FLight
const light = lightParam as FLight
Expand All @@ -38,28 +42,48 @@ export class FDebug3d {
helper = new scene.THREE.SpotLightHelper(light.__LIGHT__)
else
return
helper.visible = State.helpers
// Add the helper to the scene
scene.scene.add(helper as any)
// Add the helper to the list of helpers
lightHelpers.push(helper)
})

/**
* Display debug lines on each frame
*/
scene.onFrame(() => {
// Remove previous debug lines
const previousLines = scene.scene.getObjectByName('DEBUG_LINES')
if (previousLines)
scene.scene.remove(previousLines)
if (State.hitboxes) {
// Remove previous debug lines
const previousLines = scene.scene.getObjectByName('DEBUG_LINES')
if (previousLines)
scene.scene.remove(previousLines)

// Render new debug lines
const { vertices, colors } = scene.world.debugRender()
const geometry = new scene.THREE.BufferGeometry()
geometry.setAttribute('position', new scene.THREE.Float32BufferAttribute(vertices, 3))
geometry.setAttribute('color', new scene.THREE.Float32BufferAttribute(colors, 3))
const material = new scene.THREE.LineBasicMaterial({ vertexColors: true })
const lines = new scene.THREE.LineSegments(geometry, material)
lines.name = 'DEBUG_LINES'
scene.scene.add(lines)
// Render new debug lines
const { vertices, colors } = scene.world.debugRender()
const geometry = new scene.THREE.BufferGeometry()
geometry.setAttribute('position', new scene.THREE.Float32BufferAttribute(vertices, 3))
geometry.setAttribute('color', new scene.THREE.Float32BufferAttribute(colors, 3))
const material = new scene.THREE.LineBasicMaterial({ vertexColors: true })
const lines = new scene.THREE.LineSegments(geometry, material)
lines.name = 'DEBUG_LINES'
scene.scene.add(lines)
}
})

State.onHitboxesChange((newState) => {
if (!newState) {
// Remove previous debug lines
const previousLines = scene.scene.getObjectByName('DEBUG_LINES')
if (previousLines)
scene.scene.remove(previousLines)
}
})

State.onHelpersChange((newState) => {
gridHelper.visible = newState
axesHelper.visible = newState
lightHelpers.forEach(helper => helper.visible = newState)
})
}
}
57 changes: 57 additions & 0 deletions packages/devtools/src/FLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
export interface Log {
id: string
content: any[]
type: 'log' | 'warn' | 'error'
timestamp: number
showDetails: boolean
}

export class FLogger {
private static __LOGS__: Log[] = []

private static __CALLBACKS_ON_NEW_LOGS__: ((newLog: Log) => void)[] = []

static log(...args: any[]) {
const newLog = {
id: Math.random().toString(36).substr(2, 9),
content: args,
type: 'log',
timestamp: Date.now(),
showDetails: false,
} as Log
this.__CALLBACKS_ON_NEW_LOGS__.forEach(callback => callback(newLog))
this.__LOGS__.push(newLog)
}

static warn(...args: any[]) {
const newLog = {
id: Math.random().toString(36).substr(2, 9),
content: args,
type: 'warn',
timestamp: Date.now(),
showDetails: false,
} as Log
this.__CALLBACKS_ON_NEW_LOGS__.forEach(callback => callback(newLog))
this.__LOGS__.push(newLog)
}

static error(...args: any[]) {
const newLog = {
id: Math.random().toString(36).substr(2, 9),
content: args,
type: 'error',
timestamp: Date.now(),
showDetails: false,
} as Log
this.__CALLBACKS_ON_NEW_LOGS__.forEach(callback => callback(newLog))
this.__LOGS__.push(newLog)
}

static onLog(callback: (newLog: Log) => void) {
this.__CALLBACKS_ON_NEW_LOGS__.push(callback)
}

static getLogs() {
return this.__LOGS__
}
}
Loading