/* Voice embeddings visualiser, adapted from xVASynth javascript/embeddings.js. The default layout uses the 3D coordinates exported by the xVASynth app (allData.json). PCA and tSNE instead reduce the stored speaker vectors of the downloaded voices in the page. */ (function () { "use strict"; var SPHERE_RADIUS = 3; var NEED_THREE = "You need at least 3 voices to run dimensionality reduction for the plot"; var state = { voices: [], byId: {}, games: [], gameTitles: {}, gameColours: {}, voiceChecked: {}, data: {}, gendersOn: false, ready: false, looping: false, clicked: null, hoveredId: null, scene: null }; function $(id) { return document.getElementById(id); } function showNotice(text) { $("embeddingsNoticeText").textContent = text; $("embeddingsNotice").hidden = false; } function hideNotice() { $("embeddingsNotice").hidden = true; } function componentToHex(channel) { var hex = Math.max(0, Math.min(255, channel | 0)).toString(16); return hex.length === 1 ? "0" + hex : hex; } function rgbToHex(red, green, blue) { return "#" + componentToHex(red) + componentToHex(green) + componentToHex(blue); } function hexToRgb(hex) { var match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex || ""); if (!match) { return {r: 170, g: 170, b: 170}; } return { r: parseInt(match[1], 16), g: parseInt(match[2], 16), b: parseInt(match[3], 16) }; } function enabledGameIds() { var ids = {}; Array.prototype.forEach.call($("embeddingsGamesListContainer").querySelectorAll("input"), function (box) { if (box.checked) { ids[box.id.replace(/^embs_/, "")] = true; } }); return ids; } function genderAllowed(gender) { if (gender === "male") { return $("embeddingsMalesCkbx").checked; } if (gender === "female") { return $("embeddingsFemalesCkbx").checked; } return $("embeddingsOtherGendersCkbx").checked; } function voicesForReduction() { var games = enabledGameIds(); var onlyInstalled = $("embeddingsOnlyInstalledCkbx").checked; return state.voices.filter(function (voice) { if (!games[voice.gameId]) { return false; } if (state.voiceChecked[voice.voiceId] === false) { return false; } if (!genderAllowed(voice.gender)) { return false; } if (onlyInstalled && !voice.hasPreview) { return false; } return true; }); } function paintPoint(point, brighten) { var colour = state.gendersOn ? point.data.genderColour : point.data.gameColour; var gain = brighten ? 1.5 : 1; point.material.color.r = Math.min(1, colour.r / 255 * gain); point.material.color.g = Math.min(1, colour.g / 255 * gain); point.material.color.b = Math.min(1, colour.b / 255 * gain); } function clearSelection() { if (state.clicked && state.clicked.object) { state.clicked.object.material.emissive.setRGB(0, 0, 0); } state.clicked = null; $("embeddingsVoiceNameDisplay").textContent = ""; $("embeddingsVoiceGenderDisplay").textContent = ""; $("embeddingsVoiceGameDisplay").textContent = ""; } function selectPoint(point) { if (state.clicked && state.clicked.object && state.clicked.object !== point) { state.clicked.object.material.emissive.setRGB(0, 0, 0); } state.clicked = { voiceId: point.data.voiceId, object: point }; point.material.emissive.setRGB(0, 1, 0); var voice = state.byId[point.data.voiceId]; $("embeddingsVoiceNameDisplay").textContent = voice ? voice.voiceName : point.data.voiceId; $("embeddingsVoiceGenderDisplay").textContent = voice ? voice.gender : ""; $("embeddingsVoiceGameDisplay").textContent = state.gameTitles[point.data.game] || point.data.game; } function populateVoicesList() { var games = enabledGameIds(); var query = $("embeddingsSearchBar").value.toLowerCase().trim(); var container = $("embeddingsRecordsContainer"); container.innerHTML = ""; state.voices.forEach(function (voice) { if (!games[voice.gameId]) { return; } var row = document.createElement("div"); row.className = "voice-row"; var box = document.createElement("input"); box.type = "checkbox"; box.id = "embsVoice_" + voice.voiceId; box.checked = state.voiceChecked[voice.voiceId] !== false; box.addEventListener("click", function () { state.voiceChecked[voice.voiceId] = box.checked; recompute(); }); var show = document.createElement("button"); show.type = "button"; show.className = "smallButton"; show.textContent = "Show"; show.style.background = "#" + (state.gameColours[voice.gameId] || "aaaaaa"); show.addEventListener("click", function () { showVoice(voice.voiceId, box.checked); }); var name = document.createElement("div"); name.className = "ellipsis"; name.textContent = voice.voiceName; name.title = voice.voiceName; var game = document.createElement("div"); game.className = "ellipsis"; game.textContent = state.gameTitles[voice.gameId] || voice.gameId; var gender = document.createElement("div"); gender.textContent = voice.gender; var boxCell = document.createElement("div"); boxCell.appendChild(box); var showCell = document.createElement("div"); showCell.appendChild(show); row.appendChild(boxCell); row.appendChild(showCell); row.appendChild(name); row.appendChild(game); row.appendChild(gender); // Search only hides rows. Checked voices stay in the next reduction, as in embeddings.js. if (query && voice.voiceName.toLowerCase().trim().indexOf(query) === -1) { return; } container.appendChild(row); }); } function populateGamesList() { var container = $("embeddingsGamesListContainer"); container.innerHTML = ""; state.games.forEach(function (game) { var button = document.createElement("button"); button.type = "button"; button.className = "game-button"; button.style.setProperty("background-color", "#" + game.colour, "important"); var box = document.createElement("input"); box.type = "checkbox"; box.id = "embs_" + game.id; box.checked = true; var label = document.createElement("span"); label.textContent = game.title; button.appendChild(box); button.appendChild(label); button.addEventListener("click", function (event) { if (event.target === box) { return; } box.checked = !box.checked; populateVoicesList(); recompute(); }); button.addEventListener("contextmenu", function (event) { event.preventDefault(); Array.prototype.forEach.call(container.querySelectorAll("input"), function (other) { other.checked = false; }); box.checked = true; populateVoicesList(); recompute(); }); box.addEventListener("click", function (event) { event.stopPropagation(); populateVoicesList(); recompute(); }); container.appendChild(button); }); } function showVoice(voiceId, enabled) { if (!enabled) { showNotice("This voice is not enabled"); return; } var scene = state.scene; if (!scene) { return; } var point = null; scene.points.forEach(function (candidate) { if (candidate.data.voiceId === voiceId) { point = candidate; } }); if (!point) { showNotice("This voice is not in the current plot"); return; } var camera = scene.camera; scene.controls.target.set(point.position.x, point.position.y, point.position.z); camera.position.set( camera.position.x + (point.position.x - camera.position.x) / 2, camera.position.y + (point.position.y - camera.position.y) / 2, camera.position.z + (point.position.z - camera.position.z) / 2 ); } function refreshPoints() { var scene = state.scene; var data = state.data; var kept = {}; var nextPoints = []; var nextSprites = []; scene.points.concat(scene.sprites).forEach(function (object) { var voiceId = object.data.voiceId; var coords = data[voiceId]; if (!coords) { scene.three.remove(object); if (object.dispose) { object.dispose(); } else if (object.geometry) { object.geometry.dispose(); if (object.material) { object.material.dispose(); } } return; } kept[voiceId] = true; object.data.isMoving = true; object.data.newPos = { x: coords[0], y: coords[1] - (object.data.type === "text" ? SPHERE_RADIUS * 1.5 : 0), z: coords[2] }; if (object.data.type === "text") { nextSprites.push(object); } else { nextPoints.push(object); paintPoint(object, state.hoveredId === voiceId); } }); scene.points = nextPoints; scene.sprites = nextSprites; Object.keys(data).forEach(function (voiceId) { if (kept[voiceId]) { return; } var voice = state.byId[voiceId]; var gameId = voice ? voice.gameId : "other"; var gender = voice ? voice.gender : "other"; var gameRgb = hexToRgb(state.gameColours[gameId]); var genderRgb = gender === "female" ? {r: 200, g: 0, b: 0} : (gender === "male" ? {r: 0, g: 0, b: 200} : {r: 85, g: 85, b: 85}); var geometry = new THREE.SphereGeometry(SPHERE_RADIUS, 50, 50); var material = new THREE.MeshLambertMaterial({ color: state.gendersOn ? rgbToHex(genderRgb.r, genderRgb.g, genderRgb.b) : "#" + (state.gameColours[gameId] || "aaaaaa"), transparent: true }); var point = new THREE.Mesh(geometry, material); point.position.set(data[voiceId][0], data[voiceId][1], data[voiceId][2]); point.data = { type: "point", voiceId: voiceId, game: gameId, gameColour: gameRgb, genderColour: genderRgb }; scene.points.push(point); scene.three.add(point); var sprite = new THREE.TextSprite({ text: voice ? voice.voiceName : voiceId, fontFamily: "Helvetica, sans-serif", fontSize: 2, strokeColor: "#ffffff", strokeWidth: 0, color: "#24ff00", material: {color: "white"} }); sprite.position.set(data[voiceId][0], data[voiceId][1] - SPHERE_RADIUS * 1.5, data[voiceId][2]); sprite.data = {type: "text", voiceId: voiceId, game: gameId}; scene.sprites.push(sprite); scene.three.add(sprite); }); if (state.clicked && !data[state.clicked.voiceId]) { clearSelection(); } else if (state.clicked) { scene.points.forEach(function (point) { if (point.data.voiceId === state.clicked.voiceId) { state.clicked.object = point; point.material.emissive.setRGB(0, 1, 0); } }); } } function recompute() { var voices = voicesForReduction(); if (voices.length <= 2) { showNotice(NEED_THREE); return; } var algorithm = $("embeddingsAlgorithm").value.split("_")[1]; if (algorithm === "xvasynth") { var placed = {}; voices.forEach(function (voice) { if (voice.coords) { placed[voice.voiceId] = voice.coords; } }); state.data = placed; if (state.scene) { refreshPoints(); } hideNotice(); return; } voices = voices.filter(function (voice) { return voice.embedding; }); if (voices.length <= 2) { showNotice(NEED_THREE); return; } var rows = voices.map(function (voice) { return voice.embedding; }); showNotice("Re-computing embeddings and dimensionality reduction on voices. May take a minute the first time, subsequent runs should be instant."); window.setTimeout(function () { try { var coords = window.xvaReduce.project(rows, algorithm); var data = {}; voices.forEach(function (voice, index) { data[voice.voiceId] = coords[index]; }); state.data = data; if (state.scene) { refreshPoints(); } hideNotice(); } catch (error) { console.error(error); showNotice(NEED_THREE); } }, 30); } function updateSize() { var scene = state.scene; var container = $("embeddingsSceneContainer"); if (!scene || container.clientWidth < 2 || container.clientHeight < 2) { return; } scene.camera.aspect = container.clientWidth / container.clientHeight; scene.camera.updateProjectionMatrix(); scene.renderer.setSize(container.clientWidth, container.clientHeight); } function step() { var scene = state.scene; var controls = scene.controls; controls.update(); scene.controls2.target.set(controls.target.x, controls.target.y, controls.target.z); scene.controls2.update(); scene.camera.updateMatrixWorld(); scene.points.concat(scene.sprites).forEach(function (object) { if (!object.data.isMoving || !object.data.newPos) { return; } var next = object.data.newPos; if (Math.abs(object.position.x - next.x) > 0.005 || Math.abs(object.position.y - next.y) > 0.005 || Math.abs(object.position.z - next.z) > 0.005) { object.position.x += (next.x - object.position.x) / 20; object.position.y += (next.y - object.position.y) / 20; object.position.z += (next.z - object.position.z) / 20; } else { object.data.isMoving = false; object.data.newPos = null; } }); scene.raycaster.setFromCamera(scene.mouse, scene.camera); var hits = scene.raycaster.intersectObjects(scene.points, false); var hit = hits.length ? hits[0] : null; if (hit && hit.object && hit.object.data && hit.object.data.type === "point") { scene.renderer.domElement.style.cursor = "pointer"; if (state.hoveredId && state.hoveredId !== hit.object.data.voiceId) { scene.points.forEach(function (point) { if (point.data.voiceId === state.hoveredId) { paintPoint(point, false); } }); } state.hoveredId = hit.object.data.voiceId; paintPoint(hit.object, true); } else { scene.renderer.domElement.style.cursor = "default"; if (state.hoveredId) { scene.points.forEach(function (point) { if (point.data.voiceId === state.hoveredId) { paintPoint(point, false); } }); state.hoveredId = null; } } scene.renderer.render(scene.three, scene.camera); } function ensureLoop() { if (!state.ready || state.looping) { return; } var container = $("embeddingsSceneContainer"); if (document.hidden || container.clientWidth < 2 || container.clientHeight < 2) { return; } state.looping = true; var tick = function () { if (!state.looping) { return; } if (document.hidden || container.clientWidth < 2 || container.clientHeight < 2) { state.looping = false; return; } requestAnimationFrame(tick); step(); }; requestAnimationFrame(tick); } function initScene() { var container = $("embeddingsSceneContainer"); var renderer = new THREE.WebGLRenderer({alpha: true, antialias: true}); renderer.setPixelRatio(window.devicePixelRatio || 1); renderer.setSize(Math.max(container.clientWidth, 2), Math.max(container.clientHeight, 2)); container.appendChild(renderer.domElement); var threeScene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(60, container.clientWidth / Math.max(container.clientHeight, 1), 0.001, 100000); camera.position.set(-100, 0, 0); var controls = new THREE.OrbitControls(camera, renderer.domElement); var controls2 = new THREE.TrackballControls(camera, renderer.domElement); controls.target.set(camera.position.x + 0.15, camera.position.y, camera.position.z); controls.enableDamping = true; controls.dampingFactor = 0.025; controls.screenSpacePanning = true; controls.rotateSpeed = 1 / 6; controls.panSpeed = 1; controls.minDistance = 50; controls.maxDistance = 500; controls2.noRotate = true; controls2.noPan = true; controls2.noZoom = true; controls2.zoomSpeed = 1 / 2; controls2.dynamicDampingFactor = 0.2; var light = new THREE.DirectionalLight(0xffffff, 0.5); light.position.set(-1, 1, 1).normalize(); threeScene.add(light); threeScene.add(new THREE.AmbientLight(0xffffff, 0.5)); var raycaster = new THREE.Raycaster(); var mouse = new THREE.Vector2(); renderer.domElement.addEventListener("mousemove", function (event) { var rect = renderer.domElement.getBoundingClientRect(); mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; }); var pointerDown = null; function pointerRay(event) { var rect = renderer.domElement.getBoundingClientRect(); if (rect.width < 1 || rect.height < 1) { return null; } mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1; mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; raycaster.setFromCamera(mouse, camera); var hits = raycaster.intersectObjects(state.scene.points, false); return hits.length ? hits[0].object : null; } renderer.domElement.addEventListener("mousedown", function (event) { pointerDown = {x: event.clientX, y: event.clientY, button: event.button}; }); window.addEventListener("mouseup", function (event) { if (!pointerDown || event.button !== pointerDown.button) { return; } var smallMove = Math.abs(event.clientX - pointerDown.x) < 10 && Math.abs(event.clientY - pointerDown.y) < 10; var button = pointerDown.button; pointerDown = null; if (!smallMove) { return; } var object = pointerRay(event); if (object && object.data && object.data.type === "point") { if (button === 2) { playPreview(state.byId[object.data.voiceId]); } else if (button === 0) { selectPoint(object); } } else if (button === 0) { clearSelection(); } }); renderer.domElement.addEventListener("contextmenu", function (event) { event.preventDefault(); }); state.scene = { three: threeScene, camera: camera, renderer: renderer, controls: controls, controls2: controls2, raycaster: raycaster, mouse: mouse, points: [], sprites: [] }; state.ready = true; updateSize(); refreshPoints(); ensureLoop(); if (typeof ResizeObserver !== "undefined") { var observer = new ResizeObserver(function () { updateSize(); ensureLoop(); }); observer.observe(container); } document.addEventListener("visibilitychange", ensureLoop); window.addEventListener("resize", function () { updateSize(); ensureLoop(); }); } function playPreview(voice) { if (!voice) { showNotice("Select a voice from the scene below first."); return; } if (!voice.hasPreview) { showNotice("No preview audio file available"); return; } var audio = $("embeddingsPreviewAudio"); audio.src = "preview/" + encodeURIComponent(voice.voiceId); var played = audio.play(); if (played && played.catch) { played.catch(function () { showNotice("No preview audio file available"); }); } } function loadVoice() { if (!state.clicked) { showNotice("Select a voice from the scene below first."); return; } var voice = state.byId[state.clicked.voiceId]; if (!voice || !voice.inSynth) { showNotice("This voice is not in the synthesizer list."); return; } window.parent.postMessage({type: "xvasynth-load-voice", voiceId: voice.voiceId}, window.location.origin); } function bindChrome() { $("embeddingsNoticeClose").addEventListener("click", hideNotice); $("embeddingsCloseHelpUI").addEventListener("click", function () { $("embeddingsHelpUI").hidden = true; }); $("embeddingsSearchBar").addEventListener("keyup", populateVoicesList); $("embeddingsPreviewButton").addEventListener("click", function () { playPreview(state.clicked ? state.byId[state.clicked.voiceId] : null); }); $("embeddingsLoadButton").addEventListener("click", loadVoice); $("embeddingsKey").addEventListener("change", function () { state.gendersOn = $("embeddingsKey").value === "embsKey_gender"; if (state.scene) { state.scene.points.forEach(function (point) { paintPoint(point, state.hoveredId === point.data.voiceId); }); } }); ["embeddingsMalesCkbx", "embeddingsFemalesCkbx", "embeddingsOtherGendersCkbx", "embeddingsOnlyInstalledCkbx", "embeddingsAlgorithm"].forEach(function (id) { $(id).addEventListener("change", recompute); }); } function start(payload) { state.games = payload.games || []; state.voices = payload.voices || []; state.games.forEach(function (game) { state.gameTitles[game.id] = game.title; state.gameColours[game.id] = game.colour; }); state.voices.forEach(function (voice) { state.byId[voice.voiceId] = voice; state.voiceChecked[voice.voiceId] = true; }); populateGamesList(); populateVoicesList(); initScene(); recompute(); } bindChrome(); if (!window.THREE || !window.xvaReduce) { showNotice("The embeddings view could not load its 3D libraries."); return; } fetch("data.json").then(function (response) { if (!response.ok) { throw new Error("data.json " + response.status); } return response.json(); }).then(start).catch(function (error) { console.error(error); showNotice("Could not load voice embeddings."); }); })();