Logo de Threejs Core Math

Threejs Core Math

Organização
Impertio-Studio
threejs-core-math

Use when working with 3D math in Three.js: vectors, matrices, quaternions, rotations, colors, or coordinate transforms. Prevents the common mistake of mutating shared vectors, using wrong rotation order, or confusing Euler gimbal lock. Covers Vector3, Matrix4, Quaternion, Euler, Color, MathUtils, Box3, Sphere, coordinate system. Keywords: Vector3, Matrix4, Quaternion, Euler, Color, MathUtils, lerp, slerp, cross, dot, normalize, degToRad, Y-up, right-handed, rotate object, position math, smooth interpolation.

Visão geral

Publicado porImpertio-Studio
RepositórioThree.js-Claude-Skill-Package
Nome da habilidadethreejs-core-math
Estrelas
29
Forks
3
Arquivos incluídos
3
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • 3 arquivos incluídos

    Scripts, modelos de documentos e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente leitura e nunca são executados.

  • Código aberto

    Publicada por Impertio-Studio no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Threejs Core Math no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package/tree/master/skills/source/threejs-core/threejs-core-math
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package.git /tmp/Three.js-Claude-Skill-Package
mkdir -p .claude/skills
cp -r /tmp/Three.js-Claude-Skill-Package/skills/source/threejs-core/threejs-core-math .claude/skills/threejs-core-math
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Threejs Core Math em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Threejs Core Math automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Threejs Core Math não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

threejs-core-math

Quick Reference

Coordinate System

Three.js uses a right-handed coordinate system with Y-up:

AxisDirectionNotes
XRightPositive toward screen right
YUpPositive toward ceiling
ZToward viewerPositive out of the screen

Import conversion rules:

SourceConventionConversion
BlenderZ-upglTF exporter converts automatically
FBXZ-upFBXLoader converts automatically
OBJNo standardALWAYS verify orientation after loading
IFCZ-upALWAYS apply -90 degree X rotation or use a converting loader

NEVER assume imported models match Three.js conventions -- ALWAYS verify orientation after loading.

Core Math Classes

ClassPurposeIdentity/Default
Vector3Position, direction, scale(0, 0, 0)
Vector2UV coordinates, 2D positions(0, 0)
Vector4Homogeneous coordinates, shader data(0, 0, 0, 0)
Matrix44x4 transformation matrixIdentity matrix
QuaternionRotation without gimbal lock(0, 0, 0, 1)
EulerHuman-readable rotation angles(0, 0, 0, 'XYZ')
ColorRGB color (0-1 range)(1, 1, 1) white
Box3Axis-aligned bounding boxEmpty (+Inf min, -Inf max)
SphereBounding sphereCenter origin, radius -1
PlaneInfinite planeNormal (1,0,0), constant 0
RayOrigin + directionOrigin (0,0,0), direction (0,0,-1)
Frustum6-plane view frustum--

Critical Warnings

NEVER modify a Vector3/Matrix4/Quaternion that is shared between objects -- most methods mutate in-place. ALWAYS use .clone() before modifying shared instances.

javascript
// WRONG: mutates the shared vector
const offset = new Vector3(1, 0, 0);
meshA.position.add(offset);
meshB.position.add(offset); // offset is still (1, 0, 0) BUT if you
                             // had stored meshA.position somewhere,
                             // it would be mutated

// CORRECT: clone before mutation
const pos = sharedPosition.clone().add(offset);

NEVER interpolate Euler angles directly -- it produces incorrect rotation paths and triggers gimbal lock. ALWAYS convert to Quaternion, use slerp(), then convert back if needed.

NEVER manually set Quaternion x, y, z, w values unless you understand quaternion math. ALWAYS use setFromAxisAngle(), setFromEuler(), or slerp().

NEVER use lerp() on Color for hue-shifting animations -- it produces muddy intermediate colors. ALWAYS use lerpHSL() for transitions through different hues.

ALWAYS use MathUtils.degToRad() when Three.js expects radians -- all rotation methods use radians, not degrees.


Vector3

The most-used math class. All mutating methods return this for chaining.

Arithmetic: add(v), addScalar(s), sub(v), multiply(v), multiplyScalar(s), divide(v), divideScalar(s), negate()

Geometric: dot(v): number, cross(v), length(): number, lengthSq(): number, normalize(), setLength(l), reflect(normal), project(camera), unproject(camera)

Distance: distanceTo(v): number, distanceToSquared(v): number, manhattanDistanceTo(v): number

Interpolation: lerp(v, alpha), lerpVectors(v1, v2, t), clamp(min, max), clampLength(min, max)

Transform: applyMatrix4(m), applyQuaternion(q), applyAxisAngle(axis, angle), applyEuler(euler)

Conversion: setFromMatrixPosition(m), setFromMatrixScale(m), setFromSphericalCoords(r, phi, theta), toArray(arr?, offset?), fromArray(arr, offset?)

Assignment: set(x, y, z), copy(v), clone(), equals(v): boolean

Vector2 differs: has only x, y. No cross() (returns scalar via cross(v): number). No 3D transforms.

Vector4 differs: has x, y, z, w. Used for homogeneous coordinates and shader uniforms.


Matrix4

Column-major storage (WebGL convention). 16 floats in elements array:

elements[0]  elements[4]  elements[8]   elements[12]  // Translation = [12,13,14]
elements[1]  elements[5]  elements[9]   elements[13]
elements[2]  elements[6]  elements[10]  elements[14]
elements[3]  elements[7]  elements[11]  elements[15]

Composition: compose(position, quaternion, scale) / decompose(position, quaternion, scale) -- the standard TRS (Translate-Rotate-Scale) pattern.

Multiplication order: Right-to-left. M1.multiply(M2) means M2 is applied first, then M1. Use premultiply(m) for left-multiplication (this = m * this).

Factory methods: makeTranslation(x,y,z), makeScale(x,y,z), makeRotationX(theta), makeRotationY(theta), makeRotationZ(theta), makeRotationAxis(axis, angle), lookAt(eye, target, up)

Operations: invert(), transpose(), determinant(): number, identity(), extractBasis(x, y, z), extractRotation(m), setPosition(v)


Quaternion

Represents rotation without gimbal lock. ALWAYS prefer Quaternion over Euler for interpolated animations and compound rotations.

javascript
import { Quaternion } from 'three';
const q = new Quaternion(); // identity: (0, 0, 0, 1)

Setters: setFromAxisAngle(axis, angle), setFromEuler(euler), setFromRotationMatrix(m), setFromUnitVectors(vFrom, vTo)

Operations: multiply(q) (q applied first, then this), premultiply(q), slerp(qb, t), slerpQuaternions(qa, qb, t), rotateTowards(q, step), conjugate(), invert(), normalize()

Comparison: dot(q): number, angleTo(q): number, equals(q): boolean


Euler

Human-readable rotation in radians with a rotation order.

javascript
import { Euler } from 'three';
const e = new Euler(0, Math.PI / 2, 0, 'XYZ');

Rotation orders: 'XYZ' (default), 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY'

Gimbal lock: In 'XYZ' order, gimbal lock occurs at Y = +/- 90 degrees. Symptoms: unexpected snapping, loss of one rotational axis.

Methods: setFromRotationMatrix(m), setFromQuaternion(q, order?), reorder(newOrder), equals(euler): boolean

Euler vs Quaternion Decision Tree

ScenarioUse
Setting a fixed rotationEuler -- human-readable
Smooth rotation animationQuaternion + slerp()
Combining multiple rotationsQuaternion + multiply()
Avoiding gimbal lockQuaternion
Reading rotation from user input (degrees)Euler, convert via quaternion.setFromEuler(euler)
Storing rotation in scene graphobject.rotation (Euler) auto-syncs with object.quaternion

Color

javascript
import { Color } from 'three';

new Color(0xff0000);               // hex integer
new Color('red');                   // CSS color name
new Color('rgb(255, 0, 0)');       // CSS rgb string
new Color('#ff0000');              // CSS hex string
new Color('hsl(0, 100%, 50%)');   // CSS hsl string
new Color(1.0, 0.0, 0.0);        // RGB floats (0-1 range)

Properties: r, g, b (number, 0-1 range).

Setters: set(value), setHex(hex), setRGB(r,g,b), setHSL(h,s,l), setStyle(css), setColorName(name)

Getters: getHex(): number, getHexString(): string, getHSL(target): {h,s,l}, getStyle(): string

Interpolation: lerp(color, alpha) (RGB), lerpHSL(color, alpha) (perceptually better for hue shifts), lerpColors(c1, c2, alpha)

Color space: convertSRGBToLinear(), convertLinearToSRGB() -- ALWAYS convert texture colors to linear space for physically correct rendering.


MathUtils

Static utility methods -- NEVER instantiate, ALWAYS access via MathUtils.method().

javascript
import { MathUtils } from 'three';

MathUtils.degToRad(90);           // 1.5707...
MathUtils.clamp(value, 0, 1);    // clamp to range
MathUtils.lerp(0, 100, 0.5);     // 50
MathUtils.mapLinear(5, 0, 10, 0, 100); // 50
MathUtils.smoothstep(0.5, 0, 1); // Hermite ease
MathUtils.damp(current, target, lambda, dt); // frame-rate-independent damping
MathUtils.generateUUID();         // RFC 4122 v4 UUID

damp() is particularly useful for smooth camera follow and UI animations -- it produces exponential decay that is frame-rate independent, unlike naive lerp in an animation loop.


Bounding Volumes

Box3 (Axis-Aligned Bounding Box)

javascript
import { Box3, Vector3 } from 'three';

const box = new Box3();
box.setFromObject(mesh);                    // compute from mesh
box.containsPoint(new Vector3(1, 2, 3));   // boolean
box.intersectsBox(otherBox);               // boolean
box.getCenter(new Vector3());              // center point
box.getSize(new Vector3());                // dimensions

Sphere, Plane, Ray, Frustum

  • Sphere: containsPoint(), intersectsBox(), intersectsSphere(), distanceToPoint()
  • Plane: distanceToPoint(), projectPoint(), intersectLine()
  • Ray: intersectBox(), intersectSphere(), intersectPlane(), distanceToPoint()
  • Frustum: setFromProjectionMatrix(m), containsPoint(), intersectsObject(), intersectsBox()

Reference Links

Official Sources

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Threejs Core Math faz?

Use when working with 3D math in Three.js: vectors, matrices, quaternions, rotations, colors, or coordinate transforms. Prevents the common mistake of mutating shared vectors, using wrong rotation order, or confusing Euler gimbal lock. Covers Vector3, Matrix4, Quaternion, Euler, Color, MathUtils, Box3, Sphere, coordinate system. Keywords: Vector3, Matrix4, Quaternion, Euler, Color, MathUtils, lerp, slerp, cross, dot, normalize, degToRad, Y-up, right-handed, rotate object, position math, smooth interpolation.

Por que usar Threejs Core Math no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Threejs Core Math é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Threejs Core Math no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/Impertio-Studio/Three.js-Claude-Skill-Package/tree/master/skills/source/threejs-core/threejs-core-math. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Threejs Core Math?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Threejs Core Math?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Threejs Core Math com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Threejs Core Math é gratuita?

Sim. A habilidade é publicada no GitHub por Impertio-Studio sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇