Skip to content

Field ​

Uma tela compartilhada para movimento físico. Uma bola cai com gravidade de verdade, quica e pode mudar de rota no ar sem perder a velocidade, enquanto a sombra segue um valor numérico com a mesma física. Três botões pedem um toque em três intensidades e dizem exatamente o que a plataforma fez com o pedido. Um bloco gira com a rotação, desliza com a gravidade e respira com o giroscópio, com cada tipo de sensor, sua unidade e seu estado listados com honestidade.

Abrir Field · Requisitos, unidades e limites

  • Gravidade usa o compilador finito do Jolt com pause, progress, stop, mudança de rota, recriação e movimento reduzido. O toque opcional ao pousar acontece uma vez por queda concluída.
  • Resposta tátil retorna native-impact, vibration ou none com requested, disabled, blocked ou unavailable. Um toque aceito nunca é apresentado como sentido.
  • Sensores só começam enquanto estão ligados a algo, acompanham a rotação da tela e ficam parados onde o aparelho não tem dados. Tocar uma inclinação de exemplo reproduz amostras sintéticas e avisa: a origem diz amostra, não este aparelho.

Sem sensores, como na maioria dos navegadores de computador, a cena continua útil: a gravidade e a inclinação de exemplo funcionam, e as linhas de sensor dizem qual entrada falta.

Em cada execução, observe a trajetória da bola, o resultado do pedido tátil e a origem exibida após reproduzir a inclinação. O pedido tátil registra a resposta da plataforma. Uma gravação de tela não mede vibração física. O roteiro de ciclo de vida também confere pausa, troca e descarte de uma reprodução enquanto outro sensor continua ativo.

Simulador iOS 26.2. O roteiro pausa e redireciona a queda, solicita um impacto e reproduz a inclinação sintética.
Emulador Android. O roteiro usa controles nativos e a tela identifica a amostra mesmo quando há um sensor emulado ativo.
Chromium. Um clique aciona a queda, o pedido tátil e a amostra de inclinação no navegador.
vue
<script setup lang="ts">
import { computed, markRaw, onBeforeUnmount, reactive, ref } from 'vue'
import {
  createMotionSurface,
  motionSensorKinds,
  motionSensorUnits,
  type MotionControlledPlayback,
  type MotionHapticResult,
  type MotionHapticStyle,
  type MotionOptions,
  type MotionSensor,
  type MotionSensorKind,
  type MotionSurface,
  type MotionValue,
} from '@getcortexlabs/mavis-core/experimental'
import { useMavisTheme } from '@getcortexlabs/mavis-core/vue'
import { useCatalogLocale } from '../locale'
import { fieldFall, fieldLanding, fieldTilt } from './physics'

const { theme } = useMavisTheme()
const { locale } = useCatalogLocale()
const pt = computed(() => locale.value === 'pt')
const words = computed(() => (pt.value ? fieldWords.pt : fieldWords.en))

const falling = markRaw(createMotionSurface()),
  ground = markRaw(createMotionSurface()),
  touch = markRaw(createMotionSurface()),
  compass = markRaw(createMotionSurface()),
  pulse = markRaw(createMotionSurface())
const edition = ref(0),
  ready = ref(false),
  feedback = ref(false),
  paused = ref(false),
  status = ref('idle'),
  felt = ref<MotionHapticResult>()
const permission = ref(''),
  sensorPaused = ref(false),
  source = ref(''),
  kinds = reactive<Record<MotionSensorKind, string>>(
    Object.fromEntries(motionSensorKinds.map((kind) => [kind, 'idle'])) as Record<
      MotionSensorKind,
      string
    >,
  )
let motion: MotionSurface | undefined,
  shade: MotionSurface | undefined,
  lift: MotionValue | undefined
let playbacks: MotionControlledPlayback[] = []
let sensors: Partial<Record<MotionSensorKind, MotionSensor>> = {}
let operation = 0,
  replaying = 0

const stops = [
  falling.use((value) => {
    motion = value
    ready.value = true
    return () => {
      operation++
      motion = undefined
      playbacks = []
      ready.value = paused.value = false
    }
  }),
  ground.use((value) => {
    shade = value
    lift = value.motionValue(0)
    value.bind({
      scale: lift.to([0, fieldLanding], [0.4, 1]),
      opacity: lift.to([0, fieldLanding], [0.18, 0.6]),
    })
    return () => {
      shade = lift = undefined
    }
  }),
  compass.use((value) => {
    const read = (kind: MotionSensorKind) =>
      (sensors[kind] = value.sensor(kind, { onStatus: (state) => (kinds[kind] = state) }))
    const rotation = read('rotation'),
      gravity = read('gravity'),
      acceleration = read('acceleration')
    value.bind({
      rotate: rotation.z.to([-Math.PI, Math.PI], [-180, 180]),
      x: gravity.x.to([-9.81, 9.81], [-56, 56]),
      scale: acceleration.z.to([0, 9.81, 19.62], [0.9, 1, 1.1]),
    })
    sensorPaused.value = false
    return () => {
      sensors = {}
      permission.value = source.value = ''
      for (const kind of motionSensorKinds) kinds[kind] = 'idle'
    }
  }),
  pulse.use((value) => {
    const read = (kind: MotionSensorKind) =>
      (sensors[kind] = value.sensor(kind, { onStatus: (state) => (kinds[kind] = state) }))
    const spin = read('gyroscope'),
      shake = read('linearAcceleration'),
      field = read('magneticField')
    value.bind({
      scale: spin.z.to([-4, 0, 4], [1.35, 1, 1.35]),
      y: shake.y.to([-6, 6], [10, -10]),
      opacity: field.x.to([-60, 0, 60], [0.7, 1, 0.7]),
    })
  }),
]
onBeforeUnmount(() => stops.forEach((stop) => stop()))

function fall(options: MotionOptions, landing = fieldLanding) {
  if (!motion) return
  const current = ++operation
  const cue: MotionOptions = { ...options, haptic: feedback.value ? 'light' : false }
  const ball = motion.animate({ y: landing }, cue)
  playbacks = [ball]
  if (shade && lift) playbacks.push(shade.animateValue(lift, landing, options))
  status.value = 'running'
  paused.value = false
  void ball.finished.then((completed) => {
    if (current === operation) status.value = completed ? 'completed' : 'cancelled'
  })
}
function drop(toss = false) {
  if (!motion) return
  if (!toss) {
    motion.set({ y: 0 })
    lift?.set(0)
  }
  fall(fieldFall(toss ? -620 : undefined))
}
function redirect() {
  if (status.value !== 'running') return drop()
  fall(fieldFall(), fieldLanding - 56)
}
function pause() {
  const [ball] = playbacks
  if (!ball) return
  for (const playback of playbacks) paused.value ? playback.resume() : playback.pause()
  paused.value = ball.paused
}
function seek() {
  for (const playback of playbacks) playback.progress = 0.5
}
function stop() {
  for (const playback of playbacks) playback.stop()
}
function feel(style: MotionHapticStyle) {
  felt.value = touch.haptic(style)
}
async function enable() {
  const current = sensors
  const list = Object.values(current)
  if (!list.length) return
  // Every request starts inside the same user gesture, before anything yields.
  const results = await Promise.all(list.map((input) => input.requestPermission()))
  if (sensors === current) permission.value = [...new Set(results)].join(',')
}
function pauseSensors() {
  const list = Object.values(sensors)
  if (!list.length) return
  sensorPaused.value = !sensorPaused.value
  for (const input of list) sensorPaused.value ? input.pause() : input.resume()
}
async function replay() {
  const { rotation, gravity, gyroscope } = sensors
  if (!rotation || !gravity || !gyroscope) return
  const current = ++replaying
  source.value = 'replaying'
  const runs = [
    rotation.replay(fieldTilt.rotation),
    gravity.replay(fieldTilt.gravity),
    gyroscope.replay(fieldTilt.gyroscope),
  ]
  const done = await Promise.all(runs.map((run) => run.finished))
  if (current === replaying && sensors.rotation === rotation)
    source.value = done.every(Boolean) ? rotation.snapshot().sampleSource : 'stopped'
}
</script>

<script lang="ts">
export const fieldWords = {
  en: {
    gravity: 'Let it fall.',
    gravityLead:
      'Drop it, toss it again or redirect it in the air. Physics keeps the speed it had.',
    toss: 'Toss',
    drop: 'Drop',
    again: 'Toss again',
    redirect: 'Redirect',
    pause: 'Pause',
    resume: 'Resume',
    stop: 'Stop',
    remount: 'Remount',
    haptics: 'Landing cue',
    feel: 'Feel the weight.',
    feelLead:
      'Ask for a tap in three weights. A request is only a request: phones and browsers can stay silent, and reduced motion turns it off.',
    light: 'Light',
    medium: 'Medium',
    heavy: 'Heavy',
    orientation: 'Follow your orientation.',
    orientationLead:
      'Rotation turns the tile, gravity slides it and the gyroscope makes the ring breathe. Without sensors it simply stays still.',
    enable: 'Enable sensors',
    recenter: 'Recenter',
    sample: 'Play a sample tilt',
    synthetic: 'Synthetic samples, never a device reading.',
    motion: { idle: 'Ready', running: 'Falling', completed: 'Landed', cancelled: 'Interrupted' },
    states: {
      idle: 'Waiting',
      'permission-required': 'Needs permission',
      starting: 'Starting',
      active: 'Live',
      paused: 'Paused',
      unavailable: 'Not on this device',
      denied: 'Permission denied',
      error: 'Error',
      replaying: 'Playing a sample',
      disposed: 'Released',
    },
    backends: { 'native-impact': 'Native impact', vibration: 'Vibration', none: 'No haptics' },
    outcomes: {
      requested: 'requested, the device may still stay silent',
      unavailable: 'not available here',
      blocked: 'blocked until the page is active and touched',
      disabled: 'off under reduced motion',
    },
    permissions: {
      granted: 'Allowed',
      denied: 'Denied',
      unavailable: 'Unavailable',
      'not-required': 'No prompt needed',
    },
    sources: {
      replaying: 'Playing the sample…',
      replay: 'Source: sample, not this device',
      device: 'Source: this device',
      none: 'Source: nothing yet',
      stopped: 'Sample stopped',
    },
    names: {
      rotation: 'Rotation',
      gravity: 'Gravity',
      acceleration: 'Acceleration',
      linearAcceleration: 'Linear acceleration',
      gyroscope: 'Gyroscope',
      magneticField: 'Magnetic field',
    },
  },
  pt: {
    gravity: 'Deixe cair.',
    gravityLead:
      'Solte, lance de novo ou mude a rota no ar. A física mantém a velocidade que tinha.',
    toss: 'Lançar',
    drop: 'Soltar',
    again: 'Relançar',
    redirect: 'Mudar rota',
    pause: 'Pausar',
    resume: 'Continuar',
    stop: 'Parar',
    remount: 'Recriar',
    haptics: 'Toque ao pousar',
    feel: 'Sinta o peso.',
    feelLead:
      'Peça um toque em três intensidades. Um pedido é só um pedido: celulares e navegadores podem ficar em silêncio, e o movimento reduzido desliga o toque.',
    light: 'Leve',
    medium: 'Médio',
    heavy: 'Forte',
    orientation: 'Siga sua orientação.',
    orientationLead:
      'A rotação gira o bloco, a gravidade o desliza e o giroscópio faz o anel respirar. Sem sensores, ele apenas fica parado.',
    enable: 'Ativar sensores',
    recenter: 'Centralizar',
    sample: 'Tocar uma inclinação de exemplo',
    synthetic: 'Amostras sintéticas, nunca uma leitura do aparelho.',
    motion: { idle: 'Pronto', running: 'Caindo', completed: 'Pousou', cancelled: 'Interrompido' },
    states: {
      idle: 'Aguardando',
      'permission-required': 'Precisa de permissão',
      starting: 'Iniciando',
      active: 'Ao vivo',
      paused: 'Pausado',
      unavailable: 'Indisponível aqui',
      denied: 'Permissão negada',
      error: 'Erro',
      replaying: 'Tocando amostra',
      disposed: 'Liberado',
    },
    backends: {
      'native-impact': 'Impacto nativo',
      vibration: 'Vibração',
      none: 'Sem resposta tátil',
    },
    outcomes: {
      requested: 'pedido aceito, o aparelho ainda pode ficar em silêncio',
      unavailable: 'indisponível aqui',
      blocked: 'bloqueado até a página estar ativa e ser tocada',
      disabled: 'desligado pelo movimento reduzido',
    },
    permissions: {
      granted: 'Permitido',
      denied: 'Negado',
      unavailable: 'Indisponível',
      'not-required': 'Sem pedido necessário',
    },
    sources: {
      replaying: 'Tocando a amostra…',
      replay: 'Origem: amostra, não este aparelho',
      device: 'Origem: este aparelho',
      none: 'Origem: nada ainda',
      stopped: 'Amostra interrompida',
    },
    names: {
      rotation: 'Rotação',
      gravity: 'Gravidade',
      acceleration: 'Aceleração',
      linearAcceleration: 'Aceleração linear',
      gyroscope: 'Giroscópio',
      magneticField: 'Campo magnético',
    },
  },
}
</script>

<template>
  <m-column gap="lg">
    <m-card padding="lg" gap="md">
      <m-text variant="overline" tone="accent">01 / {{ pt ? 'GRAVIDADE' : 'GRAVITY' }}</m-text>
      <m-text variant="title">{{ words.gravity }}</m-text>
      <m-text tone="muted">{{ words.gravityLead }}</m-text>
      <m-column
        :height="300"
        padding="md"
        :backgroundColor="theme.colors.elevated"
        radius="lg"
        justify="between"
        align="center"
      >
        <m-button :key="edition" id="field-ball" :motionSurface="falling" @click="drop(true)">{{
          words.toss
        }}</m-button>
        <m-box
          :key="`ground-${edition}`"
          id="field-shadow"
          :motionSurface="ground"
          :width="96"
          :height="12"
          radius="full"
          :backgroundColor="theme.colors.text"
        />
      </m-column>
      <m-row gap="sm" wrap>
        <m-button id="field-drop" :disabled="!ready" @click="drop()">{{ words.drop }}</m-button>
        <m-button id="field-toss" :disabled="!ready" @click="drop(true)">{{
          words.again
        }}</m-button>
        <m-button id="field-redirect" variant="secondary" :disabled="!ready" @click="redirect">{{
          words.redirect
        }}</m-button>
        <m-button id="field-pause" variant="secondary" @click="pause">{{
          paused ? words.resume : words.pause
        }}</m-button>
        <m-button id="field-seek" variant="secondary" @click="seek">50%</m-button>
        <m-button id="field-stop" variant="ghost" @click="stop">{{ words.stop }}</m-button>
        <m-button id="field-remount" variant="ghost" @click="edition++">{{
          words.remount
        }}</m-button>
      </m-row>
      <m-switch id="field-feedback" v-model="feedback" :label="words.haptics" />
      <m-text id="field-status" variant="caption" tone="muted">{{
        words.motion[status as keyof typeof words.motion]
      }}</m-text>
    </m-card>

    <m-card padding="lg" gap="md">
      <m-text variant="overline" tone="accent">02 / {{ pt ? 'TOQUE' : 'TOUCH' }}</m-text>
      <m-text variant="title">{{ words.feel }}</m-text>
      <m-text tone="muted">{{ words.feelLead }}</m-text>
      <m-box :key="`touch-${edition}`" :motionSurface="touch">
        <m-row gap="sm" wrap>
          <m-button id="field-feel-light" variant="secondary" @click="feel('light')">{{
            words.light
          }}</m-button>
          <m-button id="field-feel-medium" variant="secondary" @click="feel('medium')">{{
            words.medium
          }}</m-button>
          <m-button id="field-feel-heavy" @click="feel('heavy')">{{ words.heavy }}</m-button>
        </m-row>
      </m-box>
      <m-text v-if="felt" id="field-felt" variant="caption" tone="muted"
        >{{ words.backends[felt.backend] }} · {{ words.outcomes[felt.status] }}</m-text
      >
    </m-card>

    <m-card padding="lg" gap="md">
      <m-text variant="overline" tone="accent">03 / {{ pt ? 'SENSORES' : 'SENSORS' }}</m-text>
      <m-text variant="title">{{ words.orientation }}</m-text>
      <m-text tone="muted">{{ words.orientationLead }}</m-text>
      <m-row
        :height="160"
        padding="lg"
        :backgroundColor="theme.colors.elevated"
        radius="lg"
        justify="center"
      >
        <m-box
          :key="`pulse-${edition}`"
          id="field-pulse"
          :motionSurface="pulse"
          :width="104"
          :height="104"
          radius="full"
          :backgroundColor="theme.colors.accentSoft"
        >
          <m-row :width="104" :height="104" justify="center">
            <m-box
              :key="edition"
              id="field-compass"
              :motionSurface="compass"
              :width="64"
              :height="64"
              :backgroundColor="theme.colors.accent"
              radius="lg"
            />
          </m-row>
        </m-box>
      </m-row>
      <m-column gap="xs">
        <m-row v-for="kind in motionSensorKinds" :key="kind" justify="between" gap="sm">
          <m-text variant="caption"
            >{{ words.names[kind] }}
            <m-span tone="muted">· {{ motionSensorUnits[kind] }}</m-span></m-text
          >
          <m-text
            :id="`field-kind-${kind}`"
            variant="caption"
            :tone="kinds[kind] === 'active' || kinds[kind] === 'replaying' ? 'success' : 'muted'"
            >{{ words.states[kinds[kind] as keyof typeof words.states] }}</m-text
          >
        </m-row>
      </m-column>
      <m-row gap="sm" wrap>
        <m-button id="field-enable" @click="enable">{{ words.enable }}</m-button>
        <m-button id="field-sensor-pause" variant="secondary" @click="pauseSensors">{{
          sensorPaused ? words.resume : words.pause
        }}</m-button>
        <m-button id="field-recenter" variant="ghost" @click="sensors.rotation?.recenter()">{{
          words.recenter
        }}</m-button>
        <m-button id="field-replay" variant="secondary" @click="replay">{{
          words.sample
        }}</m-button>
      </m-row>
      <m-text variant="caption" tone="muted">{{ words.synthetic }}</m-text>
      <m-text v-if="permission" id="field-permission" variant="caption">{{
        permission
          .split(',')
          .map((result) => words.permissions[result as keyof typeof words.permissions])
          .join(' · ')
      }}</m-text>
      <m-text v-if="source" id="field-source" variant="caption">{{
        words.sources[source as keyof typeof words.sources]
      }}</m-text>
    </m-card>
  </m-column>
</template>

Componentes para NativeScript e Web. Começando por Vue.