use litelement properly for debugmenu (#110)

* use litelement properly for debugmenu

* add customEntries to debugMenu

* add bot on move listener to update when view is moved
This commit is contained in:
Romain Beaumont 2021-03-17 00:00:26 +01:00 committed by GitHub
parent 7300456fc9
commit 7ad999d64e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 68 additions and 173 deletions

View file

@ -76,6 +76,12 @@ Some variables are exposed in window for debugging:
* worldView * worldView
* Vec3 * Vec3
* pathfinder * pathfinder
* debugMenu
### How to add more stuff to the debugMenu ?
debugMenu.customEntries['myKey'] = 'myValue'
delete debugMenu.customEntries['myKey']
### Some debugging examples ### Some debugging examples

View file

@ -87,6 +87,7 @@ async function connect (options) {
}) })
hotbar.bot = bot hotbar.bot = bot
debugMenu.bot = bot
bot.on('error', (err) => { bot.on('error', (err) => {
console.log('Encountered error!', err) console.log('Encountered error!', err)
@ -128,7 +129,6 @@ async function connect (options) {
chat.init(bot._client, renderer) chat.init(bot._client, renderer)
playerList.init(bot) playerList.init(bot)
debugMenu.init(bot)
// Create viewer // Create viewer
const viewer = new Viewer(renderer) const viewer = new Viewer(renderer)
@ -141,6 +141,7 @@ async function connect (options) {
window.viewer = viewer window.viewer = viewer
window.Vec3 = Vec3 window.Vec3 = Vec3
window.pathfinder = pathfinder window.pathfinder = pathfinder
window.debugMenu = debugMenu
// Link WorldView and Viewer // Link WorldView and Viewer
viewer.listen(worldView) viewer.listen(worldView)

View file

@ -1,14 +1,23 @@
const { LitElement, html, css } = require('lit-element') const { LitElement, html, css } = require('lit-element')
class DebugMenuEntry {
constructor (text, hidden, breaking) {
this.text = text
this.hidden = hidden
this.breaking = breaking
}
}
class DebugMenu extends LitElement { class DebugMenu extends LitElement {
constructor () {
super()
this.isOpen = false
this.customEntries = {}
}
firstUpdated () {
document.addEventListener('keydown', e => {
e ??= window.event
if (e.key === 'F3') {
this.isOpen = !this.isOpen
e.preventDefault()
}
})
}
static get styles () { static get styles () {
return css` return css`
.debugmenu-wrapper { .debugmenu-wrapper {
@ -41,37 +50,30 @@ class DebugMenu extends LitElement {
static get properties () { static get properties () {
return { return {
debugEntries: { type: Object },
isOpen: { type: Boolean }, isOpen: { type: Boolean },
cursorBlock: { type: Object } cursorBlock: { type: Object },
bot: { type: Object },
customEntries: { type: Object }
}
}
updated (changedProperties) {
if (changedProperties.has('bot')) {
this.bot.on('move', () => {
this.requestUpdate()
})
} }
} }
render () { render () {
return html` if (!this.isOpen) {
<div id="debugmenu-wrapper" class="debugmenu-wrapper"> return html``
<div class="debugmenu" id="debugmenu" style="display: none;">
<p id="debug-entry-renderer">Renderer: three.js r${global.THREE.REVISION}</p>
</br>
${Object.entries(this.debugEntries).map(([id, entry]) => html`
<p id="debug-entry-${id}" style="display:${entry.hidden ? 'none' : 'block'}">${entry.text}</p>${entry.breaking ? html`<br>` : ''}
`)}
</div>
</div>
`
} }
constructor () { const target = this.cursorBlock
super() const targetDiggable = (target && this.bot.canDigBlock(target))
this.debugEntries = {}
this.isOpen = false
}
updated (changedProperties) {
if (changedProperties.has('isOpen')) {
if (this.isOpen) {
this.updateListener = () => {
const pos = this.bot.entity.position const pos = this.bot.entity.position
const rot = [this.bot.entity.yaw, this.bot.entity.pitch] const rot = [this.bot.entity.yaw, this.bot.entity.pitch]
@ -79,15 +81,6 @@ class DebugMenu extends LitElement {
return yaw % 360 - 180 * (yaw < 0 ? -1 : 1) return yaw % 360 - 180 * (yaw < 0 ? -1 : 1)
} }
const minecraftYaw = viewDegToMinecraft(rot[0] * -180 / Math.PI)
const minecraftQuad = Math.floor(((minecraftYaw + 180) / 90 + 0.5) % 4)
const target = this.cursorBlock
const targetDiggable = (target && this.bot.canDigBlock(target))
this.updateEntry(this.positionEntry, `XYZ: ${pos.x.toFixed(3)} / ${pos.y.toFixed(3)} / ${pos.z.toFixed(3)}`)
this.updateEntry(this.chunkEntry, `Chunk: ${Math.floor(pos.x % 16)} ~ ${Math.floor(pos.z % 16)} in ${Math.floor(pos.x / 16)} ~ ${Math.floor(pos.z / 16)}`)
const quadsDescription = [ const quadsDescription = [
'north (towards negative Z)', 'north (towards negative Z)',
'east (towards positive X)', 'east (towards positive X)',
@ -95,128 +88,23 @@ class DebugMenu extends LitElement {
'west (towards negative X)' 'west (towards negative X)'
] ]
this.updateEntry(this.rotationEntryV, `Facing (viewer): ${rot[0].toFixed(3)} ${rot[1].toFixed(3)}`) const minecraftYaw = viewDegToMinecraft(rot[0] * -180 / Math.PI)
this.updateEntry(this.rotationEntryM, `Facing (minecraft): ${quadsDescription[minecraftQuad]} (${minecraftYaw.toFixed(1)} ${(rot[1] * -180 / Math.PI).toFixed(1)})`) const minecraftQuad = Math.floor(((minecraftYaw + 180) / 90 + 0.5) % 4)
if (targetDiggable) { return html`
if (this.getEntry(this.targetBlockEntry).hidden) this.setEntryVisible(this.targetBlockEntry, true) <div id="debugmenu-wrapper" class="debugmenu-wrapper">
<div class="debugmenu" id="debugmenu">
this.updateEntry(this.targetBlockEntry, `Looking at: ${target.position.x} ${target.position.y} ${target.position.z}`) <p id="debug-entry-renderer">Renderer: three.js r${global.THREE.REVISION}</p>
} else if (!targetDiggable && !this.getEntry(this.targetBlockEntry).hidden) { </br>
this.setEntryVisible(this.targetBlockEntry, false) <p>XYZ: ${pos.x.toFixed(3)} / ${pos.y.toFixed(3)} / ${pos.z.toFixed(3)}</p>
} <p>Chunk: ${Math.floor(pos.x % 16)} ~ ${Math.floor(pos.z % 16)} in ${Math.floor(pos.x / 16)} ~ ${Math.floor(pos.z / 16)}</p>
} <p>Facing (viewer): ${rot[0].toFixed(3)} ${rot[1].toFixed(3)}</p>
this.bot.on('move', this.updateListener) <p>Facing (minecraft): ${quadsDescription[minecraftQuad]} (${minecraftYaw.toFixed(1)} ${(rot[1] * -180 / Math.PI).toFixed(1)})</p>
} else if (this.updateListener) { ${targetDiggable ? html`<p>Looking at: ${target.position.x} ${target.position.y} ${target.position.z}</p>` : ''}<br>
this.bot.removeListener('move', this.updateListener) ${Object.entries(this.customEntries).map(([name, value]) => html`<p>${name}: ${value}</p>`)}
this.updateListener = null </div>
} </div>
} `
}
/**
* Creates debug menu entry
*
* @param {string} text - Text to render
* @param {boolean} [breaking=false] - Adds a line break after the entry if set to true (useful if you want to separate a section from everything else)
* @return {number} Debug entry id - keep it somewhere to update entry contents later!
*/
addEntry (text, breaking = false) {
const currentIds = Object.keys(this.debugEntries)
const id = parseInt(currentIds[currentIds.length - 1] ?? -1) + 1
this.debugEntries[id] = new DebugMenuEntry(text, false, breaking)
this.requestUpdate()
return id
}
/**
* Updates entry contents
*
* @param {number} id - Debug entry id (returned with addEntry())
* @param {string} text - Text to render
* @return {boolean} true if successfully updated, false otherwise (if entry doesn't exist)
*/
updateEntry (id, text) {
if (this.debugEntries[id] !== undefined) {
this.debugEntries[id].text = text
if (this.isOpen) this.requestUpdate() // This will make performance comparisons easier should something go wrong
return true
}
return false
}
/**
* Sets entry visibility
*
* @param {number} id - Debug entry id (returned with addEntry())
* @param {boolean} [shouldRender=true] - set to false if you want to hide the entry
* @return {boolean|undefined} current visibility or undefined if entry doesn't exist
*/
setEntryVisible (id, shouldRender = true) {
if (this.debugEntries[id] !== undefined) {
this.debugEntries[id].hidden = !shouldRender
this.requestUpdate()
return this.debugEntries[id].hidden
}
}
/**
* Returns entry internals
*
* @param {number} id - Debug entry id (returned with addEntry())
* @return {DebugEntry} Debug entry internals
*/
getEntry (id) {
return this.debugEntries[id] ?? null
}
/**
* Completely removes debug entry (you won't be able to update it afterwards!)
*
* @param {number} id - Debug entry id (returned with addEntry())
* @return {boolean} true if element existed and was successfully annihilated, false otherwise
*/
removeEntry (id) {
if (this.debugEntries[id]) {
delete this.debugEntries[id]
this.requestUpdate()
return true
}
return false
}
init (bot) {
const debugMenu = this.shadowRoot.querySelector('#debugmenu')
this.isOpen = false
const showMenu = (shouldShow = true) => {
debugMenu.style.display = shouldShow ? 'block' : 'none'
this.isOpen = shouldShow
}
document.addEventListener('keydown', e => {
e ??= window.event
if (e.key === 'F3') {
showMenu(!this.isOpen)
this.requestUpdate()
e.preventDefault()
}
})
this.bot = bot
this.positionEntry = this.addEntry('XYZ: 0 / 0 / 0')
this.chunkEntry = this.addEntry('Chunk: 0 0 0 in 0 0 0')
this.rotationEntryV = this.addEntry('Facing (viewer): 0 0')
this.rotationEntryM = this.addEntry('Facing (minecraft): 0 0')
this.targetBlockEntry = this.addEntry('Looking at: 0 0 0', true)
} }
} }