Skip to content

Instantly share code, notes, and snippets.

@dclamage
Last active November 6, 2022 20:00
Show Gist options
  • Save dclamage/bba785d617abb6b6a5a5543065ac880b to your computer and use it in GitHub Desktop.
Save dclamage/bba785d617abb6b6a5a5543065ac880b to your computer and use it in GitHub Desktop.
Prevents re-drawing when inactive to save CPU.
// ==UserScript==
// @name Fpuzzles-cpu
// @namespace http://tampermonkey.net/
// @version 1.2
// @description Prevents re-drawing when inactive to save CPU.
// @author Rangsk
// @match https://*.f-puzzles.com/*
// @match https://f-puzzles.com/*
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant none
// @run-at document-end
// ==/UserScript==
// Script idea is inspired by @Crul on the CTC Discord.
(function() {
const doShim = function() {
'use strict';
let drawDirty = false;
const origRequestAnimationFrame = window.requestAnimationFrame;
const origDrawScreen = drawScreen;
drawScreen = function(step, forced) {
origDrawScreen(step, forced);
drawDirty = false;
}
const setDrawDirty = function() {
if (!drawDirty) {
drawDirty = true;
origRequestAnimationFrame(drawScreen);
}
}
let firstDraw = true;
window.requestAnimationFrame = function(callback) {
if (firstDraw) {
origRequestAnimationFrame(callback);
updateTimer();
firstDraw = false;
}
}
// Mark dirty once per second for the timer
const updateTimer = function() {
setDrawDirty();
setTimeout(updateTimer, 1000);
}
// Mark dirty after all user input
const origOnInputEnd = onInputEnd;
onInputEnd = function() {
origOnInputEnd();
setDrawDirty();
}
const origOnMouseMove = document.onmousemove;
let prevHoveredButton = null;
let prevMouseX = null;
let prevMouseY = null;
document.onmousemove = function(mouse) {
let result = origOnMouseMove(mouse);
let mouseMoved = prevMouseX !== mouseX || prevMouseY !== mouseY;
prevMouseX = mouseX;
prevMouseY = mouseY;
if (holding && !testPaused() && !disableInputs) {
setDrawDirty();
}
if (mouseMoved) {
let curHoveredButton = null;
for (let sidebar of sidebars) {
for (let button of sidebar.buttons) {
if (button.hovering()) {
curHoveredButton = button;
break;
}
}
if (curHoveredButton) {
break;
}
}
if (!curHoveredButton) {
for (let button of buttons) {
if (button.hovering()) {
curHoveredButton = button;
break;
}
}
}
if (curHoveredButton !== prevHoveredButton ||
curHoveredButton && descriptions[curHoveredButton.id] ||
prevHoveredButton && descriptions[prevHoveredButton.id]) {
setDrawDirty();
prevHoveredButton = curHoveredButton;
}
}
return result;
}
const prevClosePopups = closePopups;
closePopups = function() {
prevClosePopups();
setDrawDirty();
}
}
let intervalId = setInterval(() => {
if (typeof drawScreen === 'undefined' ||
typeof onInputEnd === 'undefined' ||
!document.onmousemove) {
return;
}
clearInterval(intervalId);
doShim();
}, 16);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment