Hey ya’ll :3
So, I made a userscript for faptap’s intiface connection, and posted it in the faptap thread the other day, because I really wanted to be able to have multiple devices running at the same time. It initially started as a simple command fanout script that duplicated the commands to all available devices.
But apparently that wasn’t enough. I don’t know if it was a side effect of firefox, (i think I had issues on chrome too), but I’ve found even without my script, faptap’s interpolation(? or something) is kinda… meh. Fast beats just merge into a solid vibration and it’s not a great experience, especially with two toys, one of which with two distinct motors. So, decided the best fix was to capture the script and have the userscript run the commands on its own.
Still not enough. Added per-device strength control, with a curve for making the lows lower, or vice versa. Added delay to configure an offset between devices (fun for vibrating devices). Added individual motor control for devices with multiple vibration sources (eg edge 2). Changed settings from per-device to per-motor. Added latency offset.
So, I’ve ended up with this monstrosity and I figured I might as well share. I’ve attempted to add other types (stroke, suction, etc) but I don’t have any to test. If you try this out (especially with something like a stroker), definitely do so without being inside it, first… just in case.
Here’s some screenshots:
Available in full screen!
I should probably add a transparency slider ![]()
Anywayyyy - if you wanna use it, have fun. Should work in Tampermonkey, or whatever your favorite userscript agent is.
ope, won’t let me upload .js files.
open this and copy/paste or
// ==UserScript==
// @name FapTap Intiface Fanout (Direct Funscript)
// @namespace cinnabrad
// @version 2.2
// @description Bypasses FapTap's broken interpolation - reads funscript directly, generates smooth commands
// @match https://faptap.net/*
// @run-at document-start
// @grant none
// ==/UserScript==
(function () {
'use strict';
// ── Global State ─────────────────────────────────────────────────────────
const LIVE_DEVICES = {};
const STORAGE_KEY = 'faptap_intiface_fanout_config_v10';
// Per-device runtime state (not persisted)
const DEVICE_STATE = {};
// Funscript data
let FUNSCRIPT_ACTIONS = null; // Array of {time, pos} sorted by time (pos 0-100)
let FUNSCRIPT_ACTIONS_INVERTED = null; // Same but with inverted positions
// Interpolation caches (amortized O(1) during forward playback)
const INTERP_CACHE = {
normal: { idx: 0, lastTime: -1 },
inverted: { idx: 0, lastTime: -1 }
};
function resetInterpCache() {
INTERP_CACHE.normal.idx = 0;
INTERP_CACHE.normal.lastTime = -1;
INTERP_CACHE.inverted.idx = 0;
INTERP_CACHE.inverted.lastTime = -1;
}
let VIDEO_ELEMENT = null;
let ANIMATION_FRAME_ID = null;
let INTIFACE_WS = null;
let NATIVE_SEND = null;
const DEFAULT_DEVICE_CONFIG = {
enabled: true,
scale: 1.0,
curve: 1.0,
delay: 0,
axes: 1,
minInterval: 50,
threshold: 0.02,
smoothing: false,
invert: false,
// New fields
individualMotors: false, // Toggle for per-motor control
manualControl: false, // Manual control when disabled
manualValue: 0, // Manual intensity 0-1
motors: [] // Per-motor settings (full copy of device settings)
};
const DEFAULT_MOTOR_CONFIG = {
enabled: true,
name: null, // Custom name (null = use "Motor N")
scale: 1.0,
curve: 1.0,
delay: 0,
invert: false,
manualControl: false,
manualValue: 0
};
const GLOBAL_SETTINGS = {
debug: false,
commandSequence: 0,
interpolationRate: 60,
latencyOffset: 0,
showInFullscreen: true
};
let USER_CONFIG = loadConfig();
function loadConfig() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || '{}');
// Load global settings
if (saved._global) {
GLOBAL_SETTINGS.latencyOffset = saved._global.latencyOffset || 0;
GLOBAL_SETTINGS.showInFullscreen = saved._global.showInFullscreen !== false; // default true
}
// Migrate device configs
for (const name in saved) {
if (name === '_global') continue;
if (typeof saved[name] === 'object') {
saved[name] = { ...DEFAULT_DEVICE_CONFIG, ...saved[name] };
// Ensure motors array exists
if (!Array.isArray(saved[name].motors)) {
saved[name].motors = [];
}
}
}
return saved;
} catch { return {}; }
}
function saveConfig() {
try {
// Include global settings
const toSave = {
...USER_CONFIG,
_global: {
latencyOffset: GLOBAL_SETTINGS.latencyOffset,
showInFullscreen: GLOBAL_SETTINGS.showInFullscreen
}
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
}
catch (e) { console.warn('[fanout] Config save failed', e); }
}
function getMotorConfig(deviceCfg, motorIndex) {
// Ensure motor array exists and has entry for this motor
if (!Array.isArray(deviceCfg.motors)) {
deviceCfg.motors = [];
}
while (deviceCfg.motors.length <= motorIndex) {
// Initialize with defaults - NOT inherited from device
deviceCfg.motors.push({ ...DEFAULT_MOTOR_CONFIG });
}
// Return motor config with defaults filled in for any missing fields
return { ...DEFAULT_MOTOR_CONFIG, ...deviceCfg.motors[motorIndex] };
}
function setMotorConfig(deviceCfg, motorIndex, key, value) {
if (!Array.isArray(deviceCfg.motors)) {
deviceCfg.motors = [];
}
while (deviceCfg.motors.length <= motorIndex) {
deviceCfg.motors.push({ ...DEFAULT_MOTOR_CONFIG });
}
deviceCfg.motors[motorIndex][key] = value;
}
function getMotorDisplayName(deviceCfg, motorIndex, device = null) {
const mCfg = getMotorConfig(deviceCfg, motorIndex);
const baseName = mCfg.name || `Motor ${motorIndex}`;
if (device?.actuatorTypes?.[motorIndex]) {
const actType = device.actuatorTypes[motorIndex];
// Show type abbreviation if not default Vibrate
if (actType !== 'Vibrate') {
const typeAbbrev = actType === 'Linear' ? '↕' :
actType === 'Rotate' ? '↻' :
actType === 'Oscillate' ? '↔' : actType;
return `${baseName} ${typeAbbrev}`;
}
}
return baseName;
}
// Send zero to device (used when disabling)
function sendZeroToDevice(device) {
// Clear any pending commands that might override our zero
clearDevicePendingTimeout(device.index);
if (!INTIFACE_WS || INTIFACE_WS.readyState !== 1 || !NATIVE_SEND) {
console.log(`[fanout] Cannot send zero to ${device.name} - WebSocket not ready`);
return;
}
const cfg = USER_CONFIG[device.name];
const numAxes = cfg?.axes || 1;
const scalars = Array.from({ length: numAxes }, (_, i) => ({
Index: i,
Scalar: 0
}));
const commands = buildDeviceCommand(device, scalars);
const packet = JSON.stringify(commands);
NATIVE_SEND(packet);
console.log(`[fanout] Sent zero to ${device.name} (all ${numAxes} motors)`);
// Retry after 100ms to ensure it takes
setTimeout(() => {
if (INTIFACE_WS?.readyState === 1 && NATIVE_SEND) {
NATIVE_SEND(packet);
console.log(`[fanout] Retry zero to ${device.name}`);
}
}, 100);
}
// Send zero to specific motor
function sendZeroToMotor(device, motorIndex) {
// Clear any pending commands that might override our zero
clearDevicePendingTimeout(device.index);
if (!INTIFACE_WS || INTIFACE_WS.readyState !== 1 || !NATIVE_SEND) {
console.log(`[fanout] Cannot send zero to motor ${motorIndex} - WebSocket not ready`);
return;
}
const scalars = [{ Index: motorIndex, Scalar: 0 }];
const commands = buildDeviceCommand(device, scalars);
const packet = JSON.stringify(commands);
NATIVE_SEND(packet);
console.log(`[fanout] Sent zero to ${device.name} motor ${motorIndex}`);
// Retry after 100ms to ensure it takes
setTimeout(() => {
if (INTIFACE_WS?.readyState === 1 && NATIVE_SEND) {
NATIVE_SEND(packet);
console.log(`[fanout] Retry zero to ${device.name} motor ${motorIndex}`);
}
}, 100);
}
// Send manual value to device
function sendManualToDevice(device, value) {
if (!INTIFACE_WS || INTIFACE_WS.readyState !== 1 || !NATIVE_SEND) return;
const cfg = USER_CONFIG[device.name];
const numAxes = cfg?.axes || 1;
const scalars = Array.from({ length: numAxes }, (_, i) => ({
Index: i,
Scalar: clamp01(value)
}));
const commands = buildDeviceCommand(device, scalars);
const packet = JSON.stringify(commands);
NATIVE_SEND(packet);
debugLog(`[${device.name}] Manual: ${(value * 100).toFixed(0)}%`);
}
// Send manual value to specific motor
function sendManualToMotor(device, motorIndex, value) {
if (!INTIFACE_WS || INTIFACE_WS.readyState !== 1 || !NATIVE_SEND) return;
const scalars = [{ Index: motorIndex, Scalar: clamp01(value) }];
const commands = buildDeviceCommand(device, scalars);
const packet = JSON.stringify(commands);
NATIVE_SEND(packet);
debugLog(`[${device.name}] Motor ${motorIndex} Manual: ${(value * 100).toFixed(0)}%`);
}
function clamp01(x) { return Math.max(0, Math.min(1, x)); }
function debugLog(...args) {
if (GLOBAL_SETTINGS.debug) console.log('[fanout]', ...args);
}
function getDeviceState(deviceIndex) {
if (!DEVICE_STATE[deviceIndex]) {
DEVICE_STATE[deviceIndex] = {
lastSentValue: null,
lastSentTime: 0,
pendingTimeout: null,
lastCommandSeq: 0,
smoothedValue: null,
latestTimeMs: null,
latestCommandSeq: 0
};
}
return DEVICE_STATE[deviceIndex];
}
// Clear all pending timeouts to prevent race conditions
function clearAllPendingTimeouts() {
for (const state of Object.values(DEVICE_STATE)) {
if (state.pendingTimeout) {
clearTimeout(state.pendingTimeout);
state.pendingTimeout = null;
}
}
}
// Clear pending timeout for a specific device
function clearDevicePendingTimeout(deviceIndex) {
const state = DEVICE_STATE[deviceIndex];
if (state?.pendingTimeout) {
clearTimeout(state.pendingTimeout);
state.pendingTimeout = null;
}
}
// Get actuator type for a specific motor
function getActuatorType(device, motorIndex) {
return device.actuatorTypes?.[motorIndex] || 'Vibrate';
}
// Build command for a device based on actuator types
function buildDeviceCommand(device, scalars) {
// Group by actuator type - Linear needs LinearCmd, others use ScalarCmd
const scalarMotors = [];
const linearMotors = [];
for (const s of scalars) {
const actType = getActuatorType(device, s.Index);
if (actType === 'Linear') {
linearMotors.push(s);
} else {
scalarMotors.push({ ...s, ActuatorType: actType });
}
}
const commands = [];
if (scalarMotors.length > 0) {
commands.push({
ScalarCmd: {
Id: 1,
DeviceIndex: device.index,
Scalars: scalarMotors
}
});
}
if (linearMotors.length > 0) {
// LinearCmd uses Position (0-1) and Duration (ms)
commands.push({
LinearCmd: {
Id: 1,
DeviceIndex: device.index,
Vectors: linearMotors.map(m => ({
Index: m.Index,
Duration: 100, // Move over 100ms
Position: m.Scalar
}))
}
});
}
return commands;
}
// ── Funscript Parsing ──────────────────────────────────────────────────────
function parseFunscriptCSV(csvText) {
const lines = csvText.trim().split('\n');
const actions = [];
for (const line of lines) {
const parts = line.split(',');
if (parts.length >= 2) {
const time = parseInt(parts[0], 10);
const pos = parseInt(parts[1], 10);
if (!isNaN(time) && !isNaN(pos)) {
actions.push({ time, pos });
}
}
}
// Sort by time (should already be sorted, but be safe)
actions.sort((a, b) => a.time - b.time);
// Store normal version
FUNSCRIPT_ACTIONS = actions;
// Generate and store inverted version (100 - pos)
FUNSCRIPT_ACTIONS_INVERTED = actions.map(a => ({
time: a.time,
pos: 100 - a.pos
}));
resetInterpCache();
console.log(`[fanout] Parsed funscript: ${actions.length} actions, ` +
`duration: ${actions.length > 0 ? (actions[actions.length-1].time / 1000).toFixed(1) : 0}s`);
return actions;
}
// ── Interpolation ──────────────────────────────────────────────────────────
function getInterpolatedPosition(timeMs, inverted = false) {
const actions = inverted ? FUNSCRIPT_ACTIONS_INVERTED : FUNSCRIPT_ACTIONS;
if (!actions || actions.length === 0) return null;
// Clamp to bounds
if (timeMs <= actions[0].time) return actions[0].pos / 100;
const last = actions[actions.length - 1];
if (timeMs >= last.time) return last.pos / 100;
const cache = inverted ? INTERP_CACHE.inverted : INTERP_CACHE.normal;
// If time moved backwards (seek), or cache is out of range, fall back to binary search.
const timeWentBackwards = cache.lastTime !== -1 && timeMs < cache.lastTime;
const cacheBad =
cache.idx < 0 ||
cache.idx >= actions.length - 1 ||
actions[cache.idx].time > timeMs;
if (timeWentBackwards || cacheBad) {
let low = 0, high = actions.length - 1;
while (low < high - 1) {
const mid = (low + high) >> 1;
if (actions[mid].time <= timeMs) low = mid;
else high = mid;
}
cache.idx = low;
} else {
// Move forward until we find the right interval
while (cache.idx < actions.length - 2 && actions[cache.idx + 1].time <= timeMs) {
cache.idx++;
}
}
cache.lastTime = timeMs;
const prev = actions[cache.idx];
const next = actions[cache.idx + 1];
// Linear interpolation
const denom = (next.time - prev.time) || 1;
const t = (timeMs - prev.time) / denom;
const pos = prev.pos + t * (next.pos - prev.pos);
return pos / 100;
}
// ── Command Sending ────────────────────────────────────────────────────────
function sendToDevice(device, timeMs, commandSeq) {
if (!INTIFACE_WS || INTIFACE_WS.readyState !== 1 || !NATIVE_SEND) return;
if (!FUNSCRIPT_ACTIONS) return;
const cfg = USER_CONFIG[device.name];
if (!cfg || !cfg.enabled) return;
const state = getDeviceState(device.index);
// Record latest request so any delayed/rate-limited send uses the newest time
state.latestTimeMs = timeMs;
state.latestCommandSeq = commandSeq;
// Check command ordering
if (commandSeq < state.lastCommandSeq) {
debugLog(`[${device.name}] Dropping outdated command`);
return;
}
state.lastCommandSeq = commandSeq;
// Rate limiting (check before doing lookups)
const minInterval = cfg.minInterval ?? 50;
const now = Date.now();
const timeSinceLast = now - state.lastSentTime;
if (timeSinceLast < minInterval) {
// Only schedule one pending send; when it fires it uses the latest request time/seq.
if (!state.pendingTimeout) {
const waitTime = minInterval - timeSinceLast;
state.pendingTimeout = setTimeout(() => {
state.pendingTimeout = null;
// Use the latest requested time/seq (not the stale one from when we scheduled)
sendToDevice(device, state.latestTimeMs, state.latestCommandSeq);
}, waitTime);
}
return;
}
const numAxes = cfg.axes || 1;
// Helper: send packet and stamp the *actual* send time
const sendPacket = (scalars, debugLabelValue) => {
if (!INTIFACE_WS || INTIFACE_WS.readyState !== 1) return;
const commands = buildDeviceCommand(device, scalars);
NATIVE_SEND(JSON.stringify(commands));
state.lastSentTime = Date.now();
if (debugLabelValue !== undefined) {
debugLog(`[${device.name}] Sent: ${debugLabelValue}`);
}
};
if (cfg.individualMotors && numAxes > 1) {
// Per-motor mode: each motor has its own settings. Delay is applied by sampling earlier time.
for (let i = 0; i < numAxes; i++) {
const mCfg = getMotorConfig(cfg, i);
if (!mCfg.enabled) continue;
const motorDelay = mCfg.delay || 0;
const lookupTime = timeMs - motorDelay;
const rawPosition = getInterpolatedPosition(lookupTime, mCfg.invert);
if (rawPosition === null) continue;
let motorValue = Math.pow(rawPosition, mCfg.curve || 1.0);
motorValue = motorValue * (mCfg.scale ?? 1.0);
motorValue = clamp01(motorValue);
motorValue = Math.round(motorValue * 100) / 100;
// Per-motor thresholding: reuse device-level lastSentValue only in unified mode;
// in motor mode, track last value per motor to avoid spamming.
if (!state.motorLastSent) state.motorLastSent = {};
const lastMotorValue = state.motorLastSent[i];
const threshold = cfg.threshold ?? 0.02;
if (lastMotorValue !== undefined && Math.abs(motorValue - lastMotorValue) < threshold) continue;
state.motorLastSent[i] = motorValue;
const scalars = [{ Index: i, Scalar: motorValue }];
sendPacket(scalars, `M${i}: ${(motorValue * 100).toFixed(0)}%`);
}
return;
}
// Unified mode: all motors share device settings. Delay is applied by sampling earlier time.
const deviceDelay = cfg.delay || 0;
const lookupTime = timeMs - deviceDelay;
const rawPosition = getInterpolatedPosition(lookupTime, cfg.invert);
if (rawPosition === null) return;
let processedValue = Math.pow(rawPosition, cfg.curve || 1.0);
processedValue = processedValue * (cfg.scale ?? 1.0);
if (cfg.smoothing) {
if (state.smoothedValue === null) {
state.smoothedValue = processedValue;
} else {
state.smoothedValue = 0.3 * processedValue + 0.7 * state.smoothedValue;
processedValue = state.smoothedValue;
}
}
processedValue = clamp01(processedValue);
processedValue = Math.round(processedValue * 100) / 100;
// Deduplication / thresholding
const threshold = cfg.threshold ?? 0.02;
if (state.lastSentValue !== null && Math.abs(processedValue - state.lastSentValue) < threshold) {
return;
}
const scalars = [];
for (let axis = 0; axis < numAxes; axis++) {
scalars.push({ Index: axis, Scalar: processedValue });
}
sendPacket(scalars, `${(processedValue * 100).toFixed(0)}%`);
state.lastSentValue = processedValue;
}
function sendToAllDevices(timeMs) {
if (Object.keys(LIVE_DEVICES).length === 0) return;
const commandSeq = ++GLOBAL_SETTINGS.commandSequence;
for (const device of Object.values(LIVE_DEVICES)) {
const cfg = USER_CONFIG[device.name];
if (!cfg || !cfg.enabled || !device.hasVibrate) continue;
sendToDevice(device, timeMs, commandSeq);
}
}
// ── Main Loop ──────────────────────────────────────────────────────────────
let lastLoopTime = 0;
let lastDebugTime = 0;
function interpolationLoop(timestamp) {
ANIMATION_FRAME_ID = requestAnimationFrame(interpolationLoop);
// Rate limit the loop itself
const minLoopInterval = 1000 / GLOBAL_SETTINGS.interpolationRate;
if (timestamp - lastLoopTime < minLoopInterval) return;
lastLoopTime = timestamp;
if (!VIDEO_ELEMENT || !FUNSCRIPT_ACTIONS) return;
if (VIDEO_ELEMENT.paused || VIDEO_ELEMENT.ended) return;
// Apply latency offset (positive = look ahead, send commands early)
const timeMs = VIDEO_ELEMENT.currentTime * 1000 + GLOBAL_SETTINGS.latencyOffset;
// Debug output every second
if (GLOBAL_SETTINGS.debug && timestamp - lastDebugTime > 1000) {
lastDebugTime = timestamp;
const pos = getInterpolatedPosition(timeMs, false);
console.log(`[fanout] Video: ${(VIDEO_ELEMENT.currentTime).toFixed(1)}s (+${GLOBAL_SETTINGS.latencyOffset}ms), Pos: ${pos !== null ? (pos * 100).toFixed(0) + '%' : 'null'}`);
}
// Send time to all devices - each will look up position with its own invert setting
sendToAllDevices(timeMs);
}
function startInterpolation() {
if (ANIMATION_FRAME_ID) return;
console.log('[fanout] Starting interpolation loop');
ANIMATION_FRAME_ID = requestAnimationFrame(interpolationLoop);
}
function stopInterpolation() {
if (ANIMATION_FRAME_ID) {
cancelAnimationFrame(ANIMATION_FRAME_ID);
ANIMATION_FRAME_ID = null;
}
// Clear all pending commands first
clearAllPendingTimeouts();
// Send stop command to all devices (enabled or not, to clear any manual state)
for (const device of Object.values(LIVE_DEVICES)) {
if (device.hasVibrate) {
sendZeroToDevice(device);
}
}
updateStatusDisplay();
}
// ── Status Display Update ────────────────────────────────────────────────
function updateStatusDisplay() {
const statusEl = document.getElementById('ft-status');
if (!statusEl) return;
const funscriptStatus = FUNSCRIPT_ACTIONS
? `<span class="status-ok">✓ Script (${FUNSCRIPT_ACTIONS.length})</span>`
: `<span class="status-warn">⏳ Script</span>`;
const videoStatus = VIDEO_ELEMENT
? `<span class="status-ok">✓ Video</span>`
: `<span class="status-warn">⏳ Video</span>`;
const loopStatus = ANIMATION_FRAME_ID
? `<span class="status-ok">▶ Running</span>`
: `<span class="status-warn">⏸ Idle</span>`;
statusEl.innerHTML = `${funscriptStatus} | ${videoStatus} | ${loopStatus}`;
}
// ── Video Element Detection ────────────────────────────────────────────────
function findVideoElement() {
// Early return if we already have a valid video element
if (VIDEO_ELEMENT && document.contains(VIDEO_ELEMENT)) {
const rect = VIDEO_ELEMENT.getBoundingClientRect();
if (rect.width > 100) return VIDEO_ELEMENT;
}
// FapTap might have multiple video elements - find the main one (usually largest or visible)
const videos = document.querySelectorAll('video');
let bestVideo = null;
let bestScore = 0;
for (const video of videos) {
// Score based on size and visibility
const rect = video.getBoundingClientRect();
const score = rect.width * rect.height;
if (score > bestScore && rect.width > 100) {
bestScore = score;
bestVideo = video;
}
}
if (bestVideo && bestVideo !== VIDEO_ELEMENT) {
VIDEO_ELEMENT = bestVideo;
console.log('[fanout] Video element found:', bestVideo.src || bestVideo.currentSrc || '(blob/stream)');
console.log('[fanout] Video duration:', bestVideo.duration, 'readyState:', bestVideo.readyState);
updateStatusDisplay();
bestVideo.addEventListener('play', () => {
console.log('[fanout] Video play, time:', bestVideo.currentTime.toFixed(2));
if (FUNSCRIPT_ACTIONS) startInterpolation();
updateStatusDisplay();
});
bestVideo.addEventListener('pause', () => {
console.log('[fanout] Video pause');
stopInterpolation();
updateStatusDisplay();
});
bestVideo.addEventListener('ended', () => {
console.log('[fanout] Video ended');
stopInterpolation();
updateStatusDisplay();
});
bestVideo.addEventListener('seeked', () => {
console.log('[fanout] Video seeked to', bestVideo.currentTime.toFixed(2));
});
bestVideo.addEventListener('timeupdate', () => {
// Periodic check that we're still tracking
if (GLOBAL_SETTINGS.debug && Math.floor(bestVideo.currentTime) % 5 === 0) {
debugLog('timeupdate:', bestVideo.currentTime.toFixed(2));
}
});
// If already playing, start immediately
if (!bestVideo.paused && FUNSCRIPT_ACTIONS) {
console.log('[fanout] Video already playing, starting interpolation');
startInterpolation();
}
}
return bestVideo;
}
// Watch for video element to appear
let videoCheckInterval = null;
function watchForVideo() {
findVideoElement();
// Poll for video every 2 seconds (very lightweight)
if (!videoCheckInterval) {
videoCheckInterval = setInterval(() => {
// Check if current video is still valid
if (VIDEO_ELEMENT && !document.contains(VIDEO_ELEMENT)) {
console.log('[fanout] Video element removed, searching for new one');
VIDEO_ELEMENT = null;
}
// Try to find video if we don't have one
if (!VIDEO_ELEMENT) {
findVideoElement();
}
}, 2000);
}
}
// ── Fetch Interception ─────────────────────────────────────────────────────
// FapTap loads funscripts from: /api/assets/scripts/*.csv
const FUNSCRIPT_URL_PATTERN = /\/api\/assets\/scripts\/.*\.csv/i;
function isFunscriptUrl(url) {
if (!url) return false;
return FUNSCRIPT_URL_PATTERN.test(url) || url.endsWith('.funscript') || url.endsWith('.csv');
}
function isFunscriptContent(text) {
if (!text || text.length < 3) return false;
const firstLine = text.substring(0, 50).split('\n')[0].trim();
return /^\d+,\d+$/.test(firstLine);
}
function handleFunscriptData(text, source) {
console.log(`[fanout] ✓ Funscript captured (${source}), size: ${text.length} bytes`);
FUNSCRIPT_ACTIONS = parseFunscriptCSV(text);
updateStatusDisplay();
if (VIDEO_ELEMENT && !VIDEO_ELEMENT.paused) {
startInterpolation();
}
}
const originalFetch = window.fetch;
window.fetch = function(...args) {
const url = typeof args[0] === 'string' ? args[0] : args[0]?.url;
// Fast path: check URL pattern first
const mightBeFunscript = isFunscriptUrl(url);
return originalFetch.apply(this, args).then(response => {
if (mightBeFunscript) {
const clone = response.clone();
clone.text().then(text => {
if (isFunscriptContent(text)) {
handleFunscriptData(text, `fetch: ${url}`);
}
}).catch(() => {});
}
return response;
});
};
// Also intercept XHR
const originalXHROpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, ...rest) {
this._fanoutUrl = url;
this._mightBeFunscript = isFunscriptUrl(url);
// Add load listener once per instance
if (!this._fanoutListener) {
this._fanoutListener = true;
this.addEventListener('load', function() {
if (!this._mightBeFunscript) return;
try {
const text = this.responseText;
if (isFunscriptContent(text)) {
handleFunscriptData(text, `XHR: ${this._fanoutUrl}`);
}
} catch (e) {
console.warn('[fanout] XHR read error:', e);
}
});
}
return originalXHROpen.apply(this, [method, url, ...rest]);
};
// ── WebSocket Logic ────────────────────────────────────────────────────────
const NativeWebSocket = window.WebSocket;
const WS_OPEN = 1;
function FanoutWebSocket(url, protocols) {
const ws = protocols ? new NativeWebSocket(url, protocols) : new NativeWebSocket(url);
console.log('[fanout] WebSocket created:', url);
// Check if this is the Intiface connection
const isIntiface = url.includes('localhost') || url.includes('127.0.0.1') || url.includes('intiface');
if (isIntiface) {
INTIFACE_WS = ws;
NATIVE_SEND = ws.send.bind(ws);
console.log('[fanout] Intiface WebSocket detected');
}
const nativeSend = ws.send.bind(ws);
// Only set up message processing for Intiface socket
if (isIntiface) {
let userOnMessage = null;
Object.defineProperty(ws, 'onmessage', {
get: () => userOnMessage,
set: (fn) => { userOnMessage = fn; }
});
ws.addEventListener('message', function (event) {
processIncomingMessage(event.data);
if (userOnMessage) userOnMessage(event);
});
function processIncomingMessage(data) {
if (typeof data !== 'string') return;
try {
const payload = JSON.parse(data);
const msgs = Array.isArray(payload) ? payload : [payload];
for (const msg of msgs) {
const type = Object.keys(msg)[0];
if (type === 'DeviceList' && msg[type].Devices) {
Object.keys(LIVE_DEVICES).forEach(k => delete LIVE_DEVICES[k]);
for (const d of msg[type].Devices) {
const idx = d.DeviceIndex;
const name = d.DeviceName;
const deviceMsgs = d.DeviceMessages;
let scalarCount = 0;
let hasScalar = false;
let hasLinear = false;
let actuatorTypes = []; // Per-motor actuator types
// Parse ScalarCmd (Vibrate, Rotate, Oscillate, etc.)
if (deviceMsgs?.ScalarCmd) {
hasScalar = true;
if (Array.isArray(deviceMsgs.ScalarCmd)) {
scalarCount = deviceMsgs.ScalarCmd.length;
actuatorTypes = deviceMsgs.ScalarCmd.map(s => s.ActuatorType || 'Vibrate');
} else if (deviceMsgs.ScalarCmd.FeatureCount) {
scalarCount = deviceMsgs.ScalarCmd.FeatureCount;
// Default to Vibrate if no per-motor info
actuatorTypes = Array(scalarCount).fill('Vibrate');
} else {
scalarCount = 1;
actuatorTypes = ['Vibrate'];
}
}
// Parse LinearCmd (Strokers/Pumps)
if (deviceMsgs?.LinearCmd) {
hasLinear = true;
const linearCount = deviceMsgs.LinearCmd.FeatureCount || 1;
// If device has both scalar and linear, linear axes come after
for (let i = 0; i < linearCount; i++) {
actuatorTypes.push('Linear');
}
scalarCount += linearCount;
}
console.log(`[fanout] Device: ${name}, Axes: ${scalarCount}, Types: ${actuatorTypes.join(', ')}`);
LIVE_DEVICES[idx] = {
name,
index: idx,
hasScalar,
hasLinear,
hasVibrate: hasScalar || hasLinear, // backwards compat
scalarCount,
actuatorTypes
};
if (!USER_CONFIG[name]) {
USER_CONFIG[name] = { ...DEFAULT_DEVICE_CONFIG };
if (scalarCount > 0) USER_CONFIG[name].axes = scalarCount;
saveConfig();
}
getDeviceState(idx);
}
ensurePanel();
// If we already have funscript and video, start
if (FUNSCRIPT_ACTIONS && VIDEO_ELEMENT && !VIDEO_ELEMENT.paused) {
startInterpolation();
}
}
}
} catch (e) {
debugLog('Message parse error:', e);
}
}
// Only filter ScalarCmd on Intiface socket
ws.send = function (data) {
// Suppress ALL ScalarCmd from FapTap - we handle vibration ourselves
if (typeof data === 'string' && data.includes('"ScalarCmd"')) {
debugLog('Suppressed FapTap ScalarCmd');
return; // Drop it completely
}
return nativeSend(data);
};
}
return ws;
}
FanoutWebSocket.prototype = NativeWebSocket.prototype;
FanoutWebSocket.CONNECTING = 0;
FanoutWebSocket.OPEN = 1;
FanoutWebSocket.CLOSING = 2;
FanoutWebSocket.CLOSED = 3;
window.WebSocket = FanoutWebSocket;
// ── UI Overlay ─────────────────────────────────────────────────────────────
function createStyles() {
if (document.getElementById('faptap-style')) return;
const style = document.createElement('style');
style.id = 'faptap-style';
style.textContent = `
#faptap-tab {
position: fixed; top: 50%; right: 0;
background: rgba(10,10,10,0.9); border: 1px solid #444; border-right: none;
color: #eee; font-family: sans-serif; z-index: 99998;
padding: 12px 16px 12px 6px; border-radius: 8px 0 0 8px; cursor: move;
writing-mode: vertical-rl; text-orientation: mixed;
font-size: 11px; letter-spacing: 1px; opacity: 0.7;
transition: opacity 0.3s, background 0.2s;
user-select: none;
}
#faptap-tab:hover { opacity: 1; background: rgba(30,30,30,0.95); }
#faptap-panel {
position: fixed; top: 50%; right: 10px;
width: 340px; background: rgba(10,10,10,0.95); border: 1px solid #444;
color: #eee; font-family: sans-serif; z-index: 99999; padding: 12px;
border-radius: 8px; font-size: 13px; max-height: 80vh; overflow-y: auto;
transition: opacity 0.3s;
}
#faptap-panel.hidden { display: none; }
#faptap-panel-header {
cursor: move; user-select: none; margin: -12px -12px 8px -12px;
padding: 8px 12px; background: rgba(255,255,255,0.05); border-radius: 8px 8px 0 0;
display: flex; justify-content: space-between; align-items: center;
}
#faptap-panel-header:active { cursor: grabbing; }
/* Fullscreen mode - nearly transparent when not hovered */
#faptap-tab.fs-mode { opacity: 0.15; }
#faptap-tab.fs-mode:hover { opacity: 1; }
#faptap-panel.fs-mode { opacity: 0.15; }
#faptap-panel.fs-mode:hover, #faptap-panel.fs-mode:focus-within { opacity: 1; }
.dev-row { border-top: 1px solid #333; padding: 8px 0; }
.dev-row:first-child { border-top: none; }
.row-head { display: flex; justify-content: space-between; margin-bottom: 4px; }
.slider-row { display: flex; align-items: center; gap: 8px; margin-top: 2px; }
.slider-row label { width: 55px; opacity: 0.7; font-size: 11px; }
input[type=range] { flex: 1; }
.val-disp { width: 45px; text-align: right; font-variant-numeric: tabular-nums; opacity: 0.9; font-size: 11px; }
.section-label { font-size: 10px; opacity: 0.5; margin-top: 6px; margin-bottom: 2px; }
.toggle-row { display: flex; align-items: center; gap: 8px; margin-top: 4px; }
.toggle-row label { font-size: 11px; opacity: 0.7; }
#ft-debug-toggle { font-size: 10px; opacity: 0.6; cursor: pointer; }
#ft-debug-toggle:hover { opacity: 1; }
#ft-status { font-size: 10px; opacity: 0.6; margin-bottom: 8px; padding: 4px; background: rgba(255,255,255,0.05); border-radius: 4px; }
.status-ok { color: #4f4; }
.status-warn { color: #fa0; }
.motor-row { padding: 6px 0 6px 8px; border-left: 2px solid #555; margin: 4px 0 4px 4px; background: rgba(255,255,255,0.02); }
.motor-row .slider-row { margin-top: 4px; }
.motor-row .toggle-row { margin-top: 2px; }
.motor-name-edit { background: #222; color: #fff; border: 1px solid #555; padding: 2px 4px; font-size: 11px; width: 80px; }
.motor-name-btn { background: none; border: none; cursor: pointer; opacity: 0.6; font-size: 10px; padding: 2px 4px; }
.motor-name-btn:hover { opacity: 1; }
`;
document.head.appendChild(style);
}
// Draggable functionality
function makeDraggable(element, handle = null) {
const dragHandle = handle || element;
let isDragging = false;
let startX, startY, startLeft, startTop;
dragHandle.addEventListener('mousedown', (e) => {
// Don't drag if clicking on interactive elements
if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' ||
e.target.id === 'ft-close' || e.target.id === 'ft-debug-toggle') return;
isDragging = true;
startX = e.clientX;
startY = e.clientY;
const rect = element.getBoundingClientRect();
startLeft = rect.left;
startTop = rect.top;
// Remove any transform that might interfere
element.style.transform = 'none';
element.style.left = startLeft + 'px';
element.style.top = startTop + 'px';
element.style.right = 'auto';
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
let newLeft = startLeft + deltaX;
let newTop = startTop + deltaY;
// Keep within viewport
const rect = element.getBoundingClientRect();
newLeft = Math.max(0, Math.min(newLeft, window.innerWidth - rect.width));
newTop = Math.max(0, Math.min(newTop, window.innerHeight - rect.height));
element.style.left = newLeft + 'px';
element.style.top = newTop + 'px';
});
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false;
// Save position
saveElementPosition(element.id, element.style.left, element.style.top);
}
});
}
// Track fullscreen state for position storage
function isInFullscreen() {
return !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement);
}
function saveElementPosition(id, left, top) {
const suffix = isInFullscreen() ? '_fs' : '_normal';
const positions = JSON.parse(localStorage.getItem('faptap_fanout_positions') || '{}');
positions[id + suffix] = { left, top };
localStorage.setItem('faptap_fanout_positions', JSON.stringify(positions));
}
function restoreElementPosition(element, forceMode = null) {
const suffix = forceMode || (isInFullscreen() ? '_fs' : '_normal');
const positions = JSON.parse(localStorage.getItem('faptap_fanout_positions') || '{}');
const pos = positions[element.id + suffix];
if (pos) {
element.style.transform = 'none';
element.style.right = 'auto';
// Parse pixel values
let left = parseInt(pos.left) || 0;
let top = parseInt(pos.top) || 0;
// Constrain to viewport (with some padding to ensure visibility)
const rect = element.getBoundingClientRect();
const maxLeft = window.innerWidth - Math.min(rect.width, 100);
const maxTop = window.innerHeight - Math.min(rect.height, 50);
left = Math.max(0, Math.min(left, maxLeft));
top = Math.max(0, Math.min(top, maxTop));
element.style.left = left + 'px';
element.style.top = top + 'px';
} else if (suffix === '_fs') {
// Default fullscreen position - center-ish, slightly to the right
element.style.transform = 'none';
element.style.right = 'auto';
if (element.id === 'faptap-panel') {
element.style.left = (window.innerWidth * 0.6) + 'px';
element.style.top = (window.innerHeight * 0.1) + 'px';
} else {
// Tab - default fullscreen position (top only, latched to right)
element.style.left = 'auto';
element.style.right = '0';
element.style.top = (window.innerHeight * 0.5) + 'px';
}
}
}
// Tab-specific position functions (vertical only, latched to right)
function saveTabPosition(top) {
const suffix = isInFullscreen() ? '_fs' : '_normal';
const positions = JSON.parse(localStorage.getItem('faptap_fanout_positions') || '{}');
positions['faptap-tab-top' + suffix] = top;
localStorage.setItem('faptap_fanout_positions', JSON.stringify(positions));
}
function restoreTabPosition(tab, forceMode = null) {
const suffix = forceMode || (isInFullscreen() ? '_fs' : '_normal');
const positions = JSON.parse(localStorage.getItem('faptap_fanout_positions') || '{}');
const savedTop = positions['faptap-tab-top' + suffix];
// Always latch to right side
tab.style.transform = 'none';
tab.style.left = 'auto';
tab.style.right = '0';
if (savedTop) {
let top = parseInt(savedTop) || 0;
// Constrain to viewport
const rect = tab.getBoundingClientRect();
const maxTop = window.innerHeight - Math.min(rect.height, 50);
top = Math.max(0, Math.min(top, maxTop));
tab.style.top = top + 'px';
} else {
// Default to middle
tab.style.top = '50%';
}
}
// Fullscreen handling - move elements into fullscreen container
let fullscreenListenerAdded = false;
function handleFullscreenChange() {
const panel = document.getElementById('faptap-panel');
const tab = document.getElementById('faptap-tab');
if (!panel || !tab) return;
const fsElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement;
console.log('[fanout] Fullscreen change detected, fsElement:', !!fsElement);
if (fsElement && GLOBAL_SETTINGS.showInFullscreen) {
// Entering fullscreen - move elements into fullscreen container
console.log('[fanout] Entering fullscreen mode');
panel.classList.add('fs-mode');
tab.classList.add('fs-mode');
// Move into fullscreen element so they're visible
if (panel.parentElement !== fsElement) {
fsElement.appendChild(panel);
fsElement.appendChild(tab);
}
// Restore fullscreen positions (delayed to allow DOM update)
setTimeout(() => {
restoreElementPosition(panel, '_fs');
restoreTabPosition(tab, '_fs');
}, 50);
} else {
// Exiting fullscreen - move back to body
console.log('[fanout] Exiting fullscreen mode');
panel.classList.remove('fs-mode');
tab.classList.remove('fs-mode');
if (panel.parentElement !== document.body) {
document.body.appendChild(panel);
document.body.appendChild(tab);
}
// Restore normal positions (delayed to allow DOM update)
setTimeout(() => {
restoreElementPosition(panel, '_normal');
restoreTabPosition(tab, '_normal');
}, 50);
}
}
function setupFullscreenListener() {
if (fullscreenListenerAdded) return;
fullscreenListenerAdded = true;
document.addEventListener('fullscreenchange', handleFullscreenChange);
document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
document.addEventListener('mozfullscreenchange', handleFullscreenChange);
// Also handle window resize to keep elements in bounds
window.addEventListener('resize', () => {
const panel = document.getElementById('faptap-panel');
const tab = document.getElementById('faptap-tab');
if (panel) constrainToViewport(panel);
if (tab) constrainToViewport(tab);
});
}
// Keep element within viewport bounds
function constrainToViewport(element) {
const rect = element.getBoundingClientRect();
let needsUpdate = false;
let top = rect.top;
const maxTop = window.innerHeight - Math.min(rect.height, 50);
if (top > maxTop) { top = maxTop; needsUpdate = true; }
if (top < 0) { top = 0; needsUpdate = true; }
// Tab stays latched to right, only constrain vertically
if (element.id === 'faptap-tab') {
if (needsUpdate) {
element.style.top = top + 'px';
}
// Always ensure it's latched right
element.style.left = 'auto';
element.style.right = '0';
element.style.transform = 'none';
} else {
// Panel can move anywhere, constrain both axes
let left = rect.left;
const maxLeft = window.innerWidth - Math.min(rect.width, 100);
if (left > maxLeft) { left = maxLeft; needsUpdate = true; }
if (left < 0) { left = 0; needsUpdate = true; }
if (needsUpdate) {
element.style.left = left + 'px';
element.style.top = top + 'px';
element.style.transform = 'none';
element.style.right = 'auto';
}
}
}
function createPanel() {
// Preserve panel visibility + position state before rebuilding
const existingPanel = document.getElementById('faptap-panel');
const wasVisible = existingPanel ? !existingPanel.classList.contains('hidden') : true;
const wasInFsMode = existingPanel ? existingPanel.classList.contains('fs-mode') : false;
const savedLeft = existingPanel ? existingPanel.style.left : null;
const savedTop = existingPanel ? existingPanel.style.top : null;
const existingParent = existingPanel ? existingPanel.parentElement : null;
// Don't remove yet - we'll swap after creating new one
createStyles();
const p = document.createElement('div');
p.id = 'faptap-panel-new'; // Temp ID to avoid conflicts
// Preserve fs-mode class to avoid opacity flash
if (wasInFsMode) p.classList.add('fs-mode');
// Only auto-hide on the *first* create (prevents the panel snapping shut on any UI change)
const hasExistingConfig = Object.keys(USER_CONFIG).filter(k => k !== '_global').length > 0;
if (!existingPanel && hasExistingConfig) {
p.classList.add('hidden');
} else if (existingPanel && !wasVisible) {
p.classList.add('hidden');
}
const funscriptStatus = FUNSCRIPT_ACTIONS
? `<span class="status-ok">✓ Funscript (${FUNSCRIPT_ACTIONS.length} pts)</span>`
: `<span class="status-warn">⏳ No funscript</span>`;
const videoStatus = VIDEO_ELEMENT
? `<span class="status-ok">✓ Video</span>`
: `<span class="status-warn">⏳ No video</span>`;
p.innerHTML = `
<div id="faptap-panel-header">
<b>Fanout v2.2 (Direct)</b>
<div>
<span id="ft-debug-toggle">[Debug: OFF]</span>
<button id="ft-close" style="margin-left:8px;cursor:pointer;background:#333;border:1px solid #555;color:#fff;padding:2px 8px;border-radius:4px;">×</button>
</div>
</div>
<div id="ft-status">${funscriptStatus} | ${videoStatus}</div>
<div class="section-label" style="margin-top:8px">Global Settings</div>
<div class="slider-row"><label>Latency</label>
<input type="range" id="ft-latency" min="-500" max="500" step="10" value="${GLOBAL_SETTINGS.latencyOffset}">
<span class="val-disp" id="ft-latency-val">${GLOBAL_SETTINGS.latencyOffset}ms</span>
</div>
<div class="toggle-row">
<input type="checkbox" id="ft-fullscreen" ${GLOBAL_SETTINGS.showInFullscreen ? 'checked' : ''}>
<label for="ft-fullscreen">Show in fullscreen (fades when idle)</label>
</div>
<div id="ft-list"></div>
<div style="font-size:10px;text-align:center;margin-top:8px;opacity:0.5">Drag header to move | Toggle: Shift+Alt+F</div>
`;
// Insert new panel into same parent as old (or body if first time)
// This keeps it in the fullscreen container if we're in fullscreen
if (existingParent && existingParent.isConnected) {
existingParent.appendChild(p);
} else {
document.body.appendChild(p);
}
// Now remove old panel and fix ID
if (existingPanel) existingPanel.remove();
p.id = 'faptap-panel';
if (savedLeft) p.style.left = savedLeft;
if (savedTop) p.style.top = savedTop;
// Setup fullscreen listener
setupFullscreenListener();
// Make panel draggable by header
const header = p.querySelector('#faptap-panel-header');
makeDraggable(p, header);
restoreElementPosition(p);
// Latency slider
const latencySlider = document.getElementById('ft-latency');
const latencyVal = document.getElementById('ft-latency-val');
latencySlider.oninput = () => {
GLOBAL_SETTINGS.latencyOffset = Number(latencySlider.value);
latencyVal.textContent = latencySlider.value + 'ms';
saveConfig();
};
// Fullscreen toggle
const fsToggle = document.getElementById('ft-fullscreen');
fsToggle.onchange = (e) => {
GLOBAL_SETTINGS.showInFullscreen = e.target.checked;
saveConfig();
handleFullscreenChange(); // Apply immediately
};
const debugToggle = document.getElementById('ft-debug-toggle');
debugToggle.onclick = () => {
GLOBAL_SETTINGS.debug = !GLOBAL_SETTINGS.debug;
debugToggle.textContent = `[Debug: ${GLOBAL_SETTINGS.debug ? 'ON' : 'OFF'}]`;
};
let tab = document.getElementById('faptap-tab');
if (!tab) {
tab = document.createElement('div');
tab.id = 'faptap-tab';
tab.textContent = '🎮 Fanout';
document.body.appendChild(tab);
}
// Make tab draggable vertically only (stays latched to right edge)
if (!tab._dragInitialized) {
tab._dragInitialized = true;
let tabDragged = false;
let tabStartY, tabStartTop;
tab.addEventListener('mousedown', (e) => {
tabDragged = false;
tabStartY = e.clientY;
const rect = tab.getBoundingClientRect();
tabStartTop = rect.top;
// Keep latched to right, only track top
tab.style.transform = 'none';
tab.style.left = 'auto';
tab.style.right = '0';
tab.style.top = tabStartTop + 'px';
const onMouseMove = (e) => {
const deltaY = e.clientY - tabStartY;
// Only count as drag if moved more than 5px vertically
if (Math.abs(deltaY) > 5) {
tabDragged = true;
}
let newTop = tabStartTop + deltaY;
const rect = tab.getBoundingClientRect();
newTop = Math.max(0, Math.min(newTop, window.innerHeight - rect.height));
tab.style.top = newTop + 'px';
};
const onMouseUp = () => {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
if (tabDragged) {
// Only save top position for tab
saveTabPosition(tab.style.top);
} else {
// It was a click, show panel
const livePanel = document.getElementById('faptap-panel');
if (livePanel) livePanel.classList.remove('hidden');
tab.style.display = 'none';
}
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
e.preventDefault();
});
restoreTabPosition(tab);
}
tab.style.display = p.classList.contains('hidden') ? '' : 'none';
const hidePanel = () => { p.classList.add('hidden'); tab.style.display = ''; };
document.getElementById('ft-close').onclick = hidePanel;
const list = document.getElementById('ft-list');
const devs = Object.values(LIVE_DEVICES).sort((a, b) => a.index - b.index);
if (devs.length === 0) {
list.innerHTML = '<div style="opacity:0.6;padding:10px;">Waiting for devices...</div>';
}
devs.forEach(d => {
const cfg = USER_CONFIG[d.name];
const numAxes = cfg.axes || 1;
const div = document.createElement('div');
div.className = 'dev-row';
const save = () => { USER_CONFIG[d.name] = cfg; saveConfig(); };
// Helper to build settings controls (reused for device and per-motor)
function buildSettingsHtml(prefix, settings, isMotor = false) {
const indent = isMotor ? 'padding-left: 8px;' : '';
const delayHtml = isMotor ? `
<div class="slider-row"><label>Delay</label>
<input type="range" class="${prefix}-de-sl" min="0" max="1000" step="10" value="${settings.delay || 0}">
<span class="val-disp ${prefix}-de-val">${settings.delay || 0}ms</span>
</div>
` : '';
return `
<div style="${indent}">
<div class="slider-row"><label>Scale</label>
<input type="range" class="${prefix}-sc-sl" min="0" max="200" value="${Math.round((settings.scale ?? 1) * 100)}">
<span class="val-disp ${prefix}-sc-val">${Math.round((settings.scale ?? 1) * 100)}%</span>
</div>
<div class="slider-row"><label>Curve</label>
<input type="range" class="${prefix}-cu-sl" min="10" max="400" value="${Math.round((settings.curve ?? 1) * 100)}">
<span class="val-disp ${prefix}-cu-val">${(settings.curve ?? 1).toFixed(1)}</span>
</div>
${delayHtml}
<div class="toggle-row">
<input type="checkbox" class="${prefix}-inv-cb" ${settings.invert ? 'checked' : ''}>
<label>Invert</label>
</div>
</div>
`;
}
// Build per-motor controls HTML (only shown when individualMotors is true)
let motorHtml = '';
if (numAxes > 1 && cfg.individualMotors) {
for (let i = 0; i < numAxes; i++) {
const mCfg = getMotorConfig(cfg, i);
const motorName = getMotorDisplayName(cfg, i, d);
const manualHtml = !mCfg.enabled ? `
<div class="toggle-row" style="margin-left:16px;">
<input type="checkbox" class="m${i}-manual-cb" ${mCfg.manualControl ? 'checked' : ''}>
<label>Manual</label>
${mCfg.manualControl ? `
<input type="range" class="m${i}-manual-sl" min="0" max="100" value="${Math.round((mCfg.manualValue ?? 0) * 100)}" style="width:80px">
<span class="m${i}-manual-val" style="font-size:10px">${Math.round((mCfg.manualValue ?? 0) * 100)}%</span>
` : ''}
</div>
` : '';
motorHtml += `
<div class="motor-row" data-motor="${i}">
<div class="toggle-row">
<input type="checkbox" class="m${i}-en-cb" ${mCfg.enabled ? 'checked' : ''}>
<span class="m${i}-name-display">
<b class="m${i}-name-text">${motorName}</b>
<button class="motor-name-btn m${i}-edit-btn" title="Rename">✏️</button>
</span>
<span class="m${i}-name-editor" style="display:none;">
<input type="text" class="motor-name-edit m${i}-name-input" value="${mCfg.name || ''}" placeholder="Motor ${i}">
<button class="motor-name-btn m${i}-save-btn" title="Save">✓</button>
<button class="motor-name-btn m${i}-cancel-btn" title="Cancel">✕</button>
</span>
</div>
${mCfg.enabled ? buildSettingsHtml(`m${i}`, mCfg, true) : manualHtml}
</div>
`;
}
}
// Manual control for disabled device
const deviceManualHtml = !cfg.enabled ? `
<div class="toggle-row">
<input type="checkbox" class="dev-manual-cb" ${cfg.manualControl ? 'checked' : ''}>
<label>Manual Control</label>
${cfg.manualControl ? `
<input type="range" class="dev-manual-sl" min="0" max="100" value="${Math.round((cfg.manualValue ?? 0) * 100)}" style="width:100px">
<span class="dev-manual-val">${Math.round((cfg.manualValue ?? 0) * 100)}%</span>
` : ''}
</div>
` : '';
// Individual motors toggle (only show if axes > 1)
const individualToggleHtml = numAxes > 1 ? `
<div class="toggle-row">
<input type="checkbox" class="indiv-cb" ${cfg.individualMotors ? 'checked' : ''}>
<label>Control motors individually</label>
</div>
` : '';
div.innerHTML = `
<div class="row-head">
<label style="display:flex;align-items:center;gap:5px;">
<input type="checkbox" class="en-cb" ${cfg.enabled ? 'checked' : ''}>
<b>${d.name}</b> <span style="opacity:0.5;font-size:10px;">(#${d.index})</span>
</label>
<input type="number" class="ax-in" value="${cfg.axes}" min="1" max="9" style="width:30px;background:#222;color:#fff;border:1px solid #555;text-align:center" title="Number of axes">
</div>
${cfg.enabled ? `
${!cfg.individualMotors ? buildSettingsHtml('dev', cfg) : ''}
<div class="slider-row"><label>Delay</label>
<input type="range" class="de-sl" min="0" max="1000" step="10" value="${cfg.delay || 0}">
<span class="val-disp de-val">${cfg.delay || 0}ms</span>
</div>
<div class="section-label">Rate Limiting</div>
<div class="slider-row"><label>Min Intv</label>
<input type="range" class="mi-sl" min="0" max="200" step="10" value="${cfg.minInterval ?? 50}">
<span class="val-disp mi-val">${cfg.minInterval ?? 50}ms</span>
</div>
<div class="slider-row"><label>Threshold</label>
<input type="range" class="th-sl" min="0" max="20" value="${Math.round((cfg.threshold ?? 0.02) * 100)}">
<span class="val-disp th-val">${((cfg.threshold ?? 0.02) * 100).toFixed(0)}%</span>
</div>
<div class="toggle-row">
<input type="checkbox" class="sm-cb" ${cfg.smoothing ? 'checked' : ''}>
<label>Smoothing</label>
</div>
${individualToggleHtml}
${motorHtml}
` : deviceManualHtml}
`;
// Event handlers
div.querySelector('.en-cb').onchange = (e) => {
const wasEnabled = cfg.enabled;
cfg.enabled = e.target.checked;
// Send zero when changing state (clears manual control or stops device)
sendZeroToDevice(d);
// Reset manual control state when enabling
if (!wasEnabled && cfg.enabled) {
cfg.manualControl = false;
cfg.manualValue = 0;
}
save();
createPanel(); // Rebuild UI
};
div.querySelector('.ax-in').onchange = (e) => {
cfg.axes = Number(e.target.value) || 1;
save();
createPanel();
};
// Individual motors toggle
const indivCb = div.querySelector('.indiv-cb');
if (indivCb) {
indivCb.onchange = (e) => {
cfg.individualMotors = e.target.checked;
// Send zero to all motors when switching modes to reset state
sendZeroToDevice(d);
save();
createPanel();
};
}
// Device settings (when not in individual mode)
if (cfg.enabled && !cfg.individualMotors) {
const devScSl = div.querySelector('.dev-sc-sl');
const devScVal = div.querySelector('.dev-sc-val');
if (devScSl) {
devScSl.oninput = () => { cfg.scale = Number(devScSl.value) / 100; devScVal.textContent = devScSl.value + '%'; save(); };
}
const devCuSl = div.querySelector('.dev-cu-sl');
const devCuVal = div.querySelector('.dev-cu-val');
if (devCuSl) {
devCuSl.oninput = () => { cfg.curve = Number(devCuSl.value) / 100; devCuVal.textContent = (Number(devCuSl.value) / 100).toFixed(1); save(); };
}
const devInvCb = div.querySelector('.dev-inv-cb');
if (devInvCb) {
devInvCb.onchange = (e) => { cfg.invert = e.target.checked; save(); };
}
}
// Common controls (delay, rate limiting, smoothing)
if (cfg.enabled) {
const deSl = div.querySelector('.de-sl');
const deVal = div.querySelector('.de-val');
if (deSl) deSl.oninput = () => { cfg.delay = Number(deSl.value); deVal.textContent = deSl.value + 'ms'; save(); };
const miSl = div.querySelector('.mi-sl');
const miVal = div.querySelector('.mi-val');
if (miSl) miSl.oninput = () => { cfg.minInterval = Number(miSl.value); miVal.textContent = miSl.value + 'ms'; save(); };
const thSl = div.querySelector('.th-sl');
const thVal = div.querySelector('.th-val');
if (thSl) thSl.oninput = () => { cfg.threshold = Number(thSl.value) / 100; thVal.textContent = thSl.value + '%'; save(); };
const smCb = div.querySelector('.sm-cb');
if (smCb) smCb.onchange = (e) => { cfg.smoothing = e.target.checked; save(); };
}
// Device manual control (when disabled)
const devManualCb = div.querySelector('.dev-manual-cb');
if (devManualCb) {
devManualCb.onchange = (e) => {
cfg.manualControl = e.target.checked;
if (!cfg.manualControl) {
sendZeroToDevice(d);
}
save();
createPanel();
};
}
const devManualSl = div.querySelector('.dev-manual-sl');
const devManualVal = div.querySelector('.dev-manual-val');
if (devManualSl) {
devManualSl.oninput = () => {
cfg.manualValue = Number(devManualSl.value) / 100;
devManualVal.textContent = devManualSl.value + '%';
sendManualToDevice(d, cfg.manualValue);
save();
};
}
// Per-motor controls
for (let i = 0; i < numAxes; i++) {
const motorEnCb = div.querySelector(`.m${i}-en-cb`);
if (motorEnCb) {
motorEnCb.onchange = (e) => {
const wasEnabled = getMotorConfig(cfg, i).enabled;
setMotorConfig(cfg, i, 'enabled', e.target.checked);
// Send zero when changing state (clears manual control or stops motor)
sendZeroToMotor(d, i);
// Reset manual control state when enabling
if (!wasEnabled && e.target.checked) {
setMotorConfig(cfg, i, 'manualControl', false);
setMotorConfig(cfg, i, 'manualValue', 0);
}
save();
createPanel();
};
}
// Motor settings (when enabled)
const mScSl = div.querySelector(`.m${i}-sc-sl`);
const mScVal = div.querySelector(`.m${i}-sc-val`);
if (mScSl) {
mScSl.oninput = () => {
setMotorConfig(cfg, i, 'scale', Number(mScSl.value) / 100);
mScVal.textContent = mScSl.value + '%';
save();
};
}
const mCuSl = div.querySelector(`.m${i}-cu-sl`);
const mCuVal = div.querySelector(`.m${i}-cu-val`);
if (mCuSl) {
mCuSl.oninput = () => {
setMotorConfig(cfg, i, 'curve', Number(mCuSl.value) / 100);
mCuVal.textContent = (Number(mCuSl.value) / 100).toFixed(1);
save();
};
}
const mDeSl = div.querySelector(`.m${i}-de-sl`);
const mDeVal = div.querySelector(`.m${i}-de-val`);
if (mDeSl) {
mDeSl.oninput = () => {
setMotorConfig(cfg, i, 'delay', Number(mDeSl.value));
mDeVal.textContent = mDeSl.value + 'ms';
save();
};
}
const mInvCb = div.querySelector(`.m${i}-inv-cb`);
if (mInvCb) {
mInvCb.onchange = (e) => { setMotorConfig(cfg, i, 'invert', e.target.checked); save(); };
}
// Motor manual control (when disabled)
const mManualCb = div.querySelector(`.m${i}-manual-cb`);
if (mManualCb) {
mManualCb.onchange = (e) => {
setMotorConfig(cfg, i, 'manualControl', e.target.checked);
if (!e.target.checked) {
sendZeroToMotor(d, i);
}
save();
createPanel();
};
}
const mManualSl = div.querySelector(`.m${i}-manual-sl`);
const mManualVal = div.querySelector(`.m${i}-manual-val`);
if (mManualSl) {
mManualSl.oninput = () => {
const val = Number(mManualSl.value) / 100;
setMotorConfig(cfg, i, 'manualValue', val);
mManualVal.textContent = mManualSl.value + '%';
sendManualToMotor(d, i, val);
save();
};
}
// Motor name editing
const nameDisplay = div.querySelector(`.m${i}-name-display`);
const nameEditor = div.querySelector(`.m${i}-name-editor`);
const nameText = div.querySelector(`.m${i}-name-text`);
const nameInput = div.querySelector(`.m${i}-name-input`);
const editBtn = div.querySelector(`.m${i}-edit-btn`);
const saveBtn = div.querySelector(`.m${i}-save-btn`);
const cancelBtn = div.querySelector(`.m${i}-cancel-btn`);
if (editBtn && nameDisplay && nameEditor) {
editBtn.onclick = () => {
nameDisplay.style.display = 'none';
nameEditor.style.display = '';
nameInput.focus();
nameInput.select();
};
const saveName = () => {
const newName = nameInput.value.trim();
setMotorConfig(cfg, i, 'name', newName || null);
nameText.textContent = newName || `Motor ${i}`;
nameDisplay.style.display = '';
nameEditor.style.display = 'none';
save();
};
const cancelEdit = () => {
nameInput.value = getMotorConfig(cfg, i).name || '';
nameDisplay.style.display = '';
nameEditor.style.display = 'none';
};
saveBtn.onclick = saveName;
cancelBtn.onclick = cancelEdit;
nameInput.onkeydown = (e) => {
if (e.key === 'Enter') saveName();
if (e.key === 'Escape') cancelEdit();
};
}
}
list.appendChild(div);
});
// If currently in fullscreen, move panel and tab into fullscreen container
handleFullscreenChange();
}
function ensurePanel() {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', createPanel);
} else {
createPanel();
}
}
window.addEventListener('keydown', e => {
if (e.shiftKey && e.altKey && e.key.toLowerCase() === 'f') {
const p = document.getElementById('faptap-panel');
const tab = document.getElementById('faptap-tab');
if (p) {
p.classList.toggle('hidden');
if (tab) tab.style.display = p.classList.contains('hidden') ? '' : 'none';
} else {
ensurePanel();
}
}
});
// Start watching for video element
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', watchForVideo);
} else {
watchForVideo();
}
ensurePanel();
console.log('[fanout] v2.2 loaded - Direct Funscript mode');
})();
download and copy from here fanoutuserscript.txt (73.9 KB)




