Skip to content

The open alternative to Salesforce, designed for AI.

7.5 KB
Raw Blame
import * as THREE from 'three';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { isDefined } from 'twenty-shared/utils';

import { DRACO_DECODER_PATH } from './draco-decoder-path';
import { mergeGeometries } from './merge-geometries';
import { type HalftoneModelLoader } from './studio-settings-types';

export type ImportedGeometryNormalizationOptions = {
  postRotateZ?: number;
  scaleTarget?: number;
  useLegacyNormalization?: boolean;
};

const LEGACY_IMPORTED_GEOMETRY_SCALE_TARGET = 2.75;

const EMPTY_TEXTURE_DATA_URL =
  'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO8B7Q8AAAAASUVORK5CYII=';

function normalizeTextureCoordinates(geometry: THREE.BufferGeometry) {
  const uv = geometry.getAttribute('uv');

  if (!isDefined(uv)) {
    return;
  }

  let minU = Infinity;
  let minV = Infinity;
  let maxU = -Infinity;
  let maxV = -Infinity;

  for (let index = 0; index < uv.count; index += 1) {
    minU = Math.min(minU, uv.getX(index));
    maxU = Math.max(maxU, uv.getX(index));
    minV = Math.min(minV, uv.getY(index));
    maxV = Math.max(maxV, uv.getY(index));
  }

  const span = Math.max(maxU - minU, maxV - minV);

  if (!(span > 0)) {
    return;
  }

  for (let index = 0; index < uv.count; index += 1) {
    uv.setXY(
      index,
      (uv.getX(index) - minU) / span,
      (uv.getY(index) - minV) / span,
    );
  }

  uv.needsUpdate = true;
}

function normalizeImportedGeometry(
  geometry: THREE.BufferGeometry,
  options: ImportedGeometryNormalizationOptions = {},
) {
  const {
    postRotateZ = 0,
    scaleTarget,
    useLegacyNormalization = false,
  } = options;

  geometry.computeBoundingBox();

  let boundingBox = geometry.boundingBox;
  let center = new THREE.Vector3();
  const size = new THREE.Vector3();

  boundingBox?.getCenter(center);
  boundingBox?.getSize(size);
  geometry.translate(-center.x, -center.y, -center.z);

  if (!useLegacyNormalization) {
    const dimensions = [size.x, size.y, size.z];
    const thinnestAxis = dimensions.indexOf(Math.min(...dimensions));

    if (thinnestAxis === 0) {
      geometry.applyMatrix4(new THREE.Matrix4().makeRotationY(Math.PI / 2));
    } else if (thinnestAxis === 1) {
      geometry.applyMatrix4(new THREE.Matrix4().makeRotationX(Math.PI / 2));
    }
  }

  geometry.computeBoundingBox();
  geometry.computeBoundingSphere();

  const radius = geometry.boundingSphere?.radius || 1;
  const scale = useLegacyNormalization
    ? (scaleTarget ?? LEGACY_IMPORTED_GEOMETRY_SCALE_TARGET) /
      Math.max(size.x, size.y, size.z, 0.001)
    : (scaleTarget ?? 1.6) / radius;
  geometry.scale(scale, scale, scale);

  geometry.computeBoundingBox();
  boundingBox = geometry.boundingBox;
  center = new THREE.Vector3();
  boundingBox?.getCenter(center);
  geometry.translate(-center.x, -center.y, -center.z);

  if (postRotateZ !== 0) {
    geometry.rotateZ(postRotateZ);
  }

  normalizeTextureCoordinates(geometry);
  geometry.computeVertexNormals();
  geometry.computeBoundingBox();
  geometry.computeBoundingSphere();

  return geometry;
}

function createLoadingManager() {
  const loadingManager = new THREE.LoadingManager();
  loadingManager.setURLModifier((url) =>
    /\.(png|jpe?g|webp|gif|bmp)$/i.test(url) ? EMPTY_TEXTURE_DATA_URL : url,
  );

  return loadingManager;
}

function extractMergedGeometry(
  root: THREE.Object3D,
  emptyMessage: string,
  geometryOptions?: ImportedGeometryNormalizationOptions,
) {
  root.updateMatrixWorld(true);

  const geometries: THREE.BufferGeometry[] = [];

  root.traverse((object) => {
    if (!(object instanceof THREE.Mesh) || !object.geometry) {
      return;
    }

    const geometry = object.geometry.clone();

    if (!geometry.attributes.normal) {
      geometry.computeVertexNormals();
    }

    geometry.applyMatrix4(object.matrixWorld);
    geometries.push(geometry);
  });

  if (geometries.length === 0) {
    throw new Error(emptyMessage);
  }

  return normalizeImportedGeometry(
    mergeGeometries(geometries),
    geometryOptions,
  );
}

function parseFbxGeometry(
  buffer: ArrayBuffer,
  resourcePath: string,
  label: string,
  geometryOptions?: ImportedGeometryNormalizationOptions,
) {
  const originalWarn = console.warn;

  console.warn = (...args: unknown[]) => {
    if (typeof args[0] === 'string' && args[0].startsWith('THREE.FBXLoader:')) {
      return;
    }

    originalWarn(...args);
  };

  try {
    const root = new FBXLoader(createLoadingManager()).parse(
      buffer,
      resourcePath,
    );

    return extractMergedGeometry(
      root,
      `${label} did not contain any mesh geometry.`,
      geometryOptions,
    );
  } finally {
    console.warn = originalWarn;
  }
}

function parseGlbGeometry(
  buffer: ArrayBuffer,
  resourcePath: string,
  label: string,
  geometryOptions?: ImportedGeometryNormalizationOptions,
) {
  const dracoLoader = new DRACOLoader();
  dracoLoader.setDecoderPath(DRACO_DECODER_PATH);

  const gltfLoader = new GLTFLoader(createLoadingManager());
  gltfLoader.setDRACOLoader(dracoLoader);

  return new Promise<THREE.BufferGeometry>((resolve, reject) => {
    gltfLoader.parse(
      buffer,
      resourcePath,
      (gltf) => {
        try {
          resolve(
            extractMergedGeometry(
              gltf.scene,
              `${label} did not contain any mesh geometry.`,
              geometryOptions,
            ),
          );
        } catch (error) {
          reject(error);
        }
      },
      reject,
    );
  }).finally(() => {
    dracoLoader.dispose();
  });
}

type GeometryUrlCacheEntry =
  | THREE.BufferGeometry
  | Promise<THREE.BufferGeometry>;

const importedGeometryCache = new Map<string, GeometryUrlCacheEntry>();

function getImportedGeometryCacheKey({
  geometryOptions,
  loader,
  modelUrl,
}: {
  geometryOptions?: ImportedGeometryNormalizationOptions;
  loader: HalftoneModelLoader;
  modelUrl: string;
}) {
  return JSON.stringify({
    geometryOptions: geometryOptions ?? null,
    loader,
    modelUrl,
  });
}

async function loadImportedGeometry(
  loader: HalftoneModelLoader,
  file: File,
  label: string,
) {
  const buffer = await file.arrayBuffer();

  if (loader === 'fbx') {
    return parseFbxGeometry(buffer, '', label);
  }

  return parseGlbGeometry(buffer, '', label);
}

async function loadImportedGeometryFromUrl(
  loader: HalftoneModelLoader,
  modelUrl: string,
  label: string,
  geometryOptions?: ImportedGeometryNormalizationOptions,
) {
  const cacheKey = getImportedGeometryCacheKey({
    geometryOptions,
    loader,
    modelUrl,
  });
  const cachedGeometry = importedGeometryCache.get(cacheKey);

  if (cachedGeometry) {
    return (await cachedGeometry).clone();
  }

  const geometryPromise = (async () => {
    const response = await fetch(modelUrl);

    if (!response.ok) {
      throw new Error(`Unable to load ${label} from ${modelUrl}.`);
    }

    const buffer = await response.arrayBuffer();

    if (loader === 'fbx') {
      return parseFbxGeometry(buffer, '', label, geometryOptions);
    }

    return parseGlbGeometry(buffer, '', label, geometryOptions);
  })();
  importedGeometryCache.set(cacheKey, geometryPromise);

  try {
    const geometry = await geometryPromise;

    importedGeometryCache.set(cacheKey, geometry);

    return geometry.clone();
  } catch (error) {
    importedGeometryCache.delete(cacheKey);
    throw error;
  }
}

export const HALFTONE_GEOMETRY_LOADERS = {
  loadFromFile: loadImportedGeometry,
  loadFromUrl: loadImportedGeometryFromUrl,
};