### Install react-native-filament Source: https://margelo.github.io/react-native-filament/docs/guides Use npm to install the react-native-filament library. ```bash npm i react-native-filament ``` -------------------------------- ### Install react-native-worklets-core Source: https://margelo.github.io/react-native-filament/docs/guides Install the react-native-worklets-core dependency. ```bash npm i react-native-worklets-core ``` -------------------------------- ### Start Metro with cache reset Source: https://margelo.github.io/react-native-filament/docs/guides Start the Metro bundler with the --reset-cache flag to ensure a clean build. ```bash npm start -- --reset-cache ``` -------------------------------- ### Basic Filament Scene Example Source: https://margelo.github.io/react-native-filament/docs/guides Renders a 3D model using FilamentView, DefaultLight, Model, and Camera components. Ensure the FilamentScene component wraps the scene for context. ```javascript import { FilamentScene, FilamentView, DefaultLight, Model, Camera, } from "react-native-filament"; import MyModel from "./MyModel.glb"; function MyScene() { return ( {/* 🏞️ A view to draw the 3D content to */} {/* 💡 A light source, otherwise the scene will be black */} {/* 📦 A 3D model */} {/* 📹 A camera through which the scene is observed and projected onto the view */} ); } ``` -------------------------------- ### Update iOS pods Source: https://margelo.github.io/react-native-filament/docs/guides Navigate to the ios directory and run pod install to update dependencies. ```bash cd ios && pod install ``` -------------------------------- ### Get Entity Bounding Box Source: https://margelo.github.io/react-native-filament/docs/guides/physics Retrieves the axis-aligned bounding box (AABB) and its properties from an asset. ```javascript const boundingBox = asset.boundingBox // returns an aabb bounding box const halfExtents = boundingBox.halfExtents const center = boundingBox.center ``` -------------------------------- ### Rotate Model Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Apply rotation to a model using the `rotate` prop, which expects radians. The example shows converting degrees to radians for rotation around the y-axis. ```javascript import { Model } from "react-native-filament" const rotationInDegree = 45; const angleInRadians = rotationInDegree * (Math.PI / 180); const rotateOnAxis = [0, angleInRadians, 0]; // Rotate on the y-axis ``` -------------------------------- ### Get Entity Transform Source: https://margelo.github.io/react-native-filament/docs/guides/physics Accesses the transform manager to retrieve an entity's transform and world scale. ```javascript const {transformManager} = useFilamentContext() const transform = transformManager.getTransform(entity) // Get the calculated world scale: const [scaleX, scaleY, scaleZ] = transform.scale ``` -------------------------------- ### Get Model Root Entity Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Access the root entity of a loaded model to apply transformations. Ensure the model state is 'loaded' before accessing `rootEntity`. ```typescript import { useModel } from "react-native-filament" const model = useModel(MyModel) const rootEntity = model.state === "loaded" ? model.rootEntity : undefined ``` -------------------------------- ### Create a Spot Light Component Source: https://margelo.github.io/react-native-filament/docs/guides/light Configure a spot light using the `` component with `type="spot"`. This requires specifying inner and outer cone angles. ```javascript import { Light } from "react-native-filament"; ``` -------------------------------- ### Create a Physics World Source: https://margelo.github.io/react-native-filament/docs/guides/physics Initializes a physics world using the useWorld hook with a gravity vector. ```javascript import { useWorld } from 'react-native-filament'; function App() { const world = useWorld([0, -9.8, 0]); } ``` -------------------------------- ### Initialize a Camera component Source: https://margelo.github.io/react-native-filament/docs/guides/camera Defines the camera's position and target point in 3D space. Only one perspective camera is supported per scene. ```javascript import { Camera } from 'react-native-filament' ``` -------------------------------- ### Create a Point Light Component Source: https://margelo.github.io/react-native-filament/docs/guides/light Define a point light source using the `` component with `type="point"`. This light emits from a position in all directions. ```javascript import { Light } from "react-native-filament"; ``` -------------------------------- ### Using EnvironmentalLight with a local IBL asset Source: https://margelo.github.io/react-native-filament/docs/guides/light Import and use the EnvironmentalLight component with a local IBL asset specified using require. Ensure the asset is correctly imported. ```javascript import { EnvironmentalLight } from "react-native-filament"; ``` -------------------------------- ### Load Model from Local File Path Source: https://margelo.github.io/react-native-filament/docs/guides/asset-loading Load models from the device's file system using a `file://` URI. This is useful for cached assets downloaded from the web. Ensure necessary file system permissions are handled. ```javascript ``` -------------------------------- ### Apply Textures to 3D Model Entities Source: https://margelo.github.io/react-native-filament/docs/guides/images Use useBuffer to load an image as a texture and EntitySelector to map that texture to specific named parts of a 3D model. ```javascript import RocketGlb from '~/assets/rocket.glb' const baseColorBlueImage = require('~/assets/rocket_BaseColor_Blue.png') function Renderer() { // Load the texture as a buffer const blueBaseColorBuffer = useBuffer({ source: baseColorBlueImage }) // The name of the material on the entity we want to change const materialName = 'Toy Ship' return ( {blueBaseColorBuffer != null && ( <> {/* Inside the we can use the to apply modifiers */} )} ``` -------------------------------- ### Load Model from Project Assets Source: https://margelo.github.io/react-native-filament/docs/guides/asset-loading Import and use a 3D model file directly from your project's local assets. Ensure Metro bundler configuration is set up correctly. ```javascript import { Model } from 'react-native-filament'; import BusterDrone from './BusterDrone.glb'; ``` -------------------------------- ### Render Model with ModelRenderer Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Use `useModel` to load a model and `ModelRenderer` to display it. `ModelRenderer` accepts standard Model props. ```typescript import { useModel, ModelRenderer } from "react-native-filament" function MyScene() { const model = useModel(MyModel) return } ``` -------------------------------- ### Render Multiple Model Instances Source: https://margelo.github.io/react-native-filament/docs/guides/instancing Use the `instanceCount` prop on the `` component to render multiple copies of a model. Access and transform individual instances using the `` component with the `index` prop. This is more efficient than creating separate `` components. ```javascript {/* We transform the root model to a unit cube, meaning all instances will be scaled to unit cubes */} ``` -------------------------------- ### Configure Metro for asset resolution Source: https://margelo.github.io/react-native-filament/docs/guides Modify your metro.config.js to include '.glb' in assetExts for importing 3D model files. ```javascript const { getDefaultConfig, mergeConfig } = require("@react-native/metro-config"); const defaultConfig = getDefaultConfig(__dirname); /** * Metro configuration * https://metrobundler.dev/docs/configuration * * @type {import('metro-config').MetroConfig} */ const config = { resolver: { // This makes it possible to import .glb files in your code: assetExts: [...(defaultConfig.resolver?.assetExts || []), "glb"], }, }; module.exports = mergeConfig(defaultConfig, config); ``` -------------------------------- ### Configure Asset Directory for Release Source: https://margelo.github.io/react-native-filament/docs/guides/asset-loading Specify custom asset directories in `react-native.config.js` if your assets are not in the default `/assets` directory. This is crucial for release builds. ```javascript module.exports = { assets: [ './app/assets/3d/assets', ], } ``` -------------------------------- ### Using the default IBL image with EnvironmentalLight Source: https://margelo.github.io/react-native-filament/docs/guides/light Utilize the default IBL image provided by react-native-filament by specifying its URI. This is a convenient way to apply environment lighting without managing local assets. ```javascript ``` -------------------------------- ### Load Model from Web URL Source: https://margelo.github.io/react-native-filament/docs/guides/asset-loading Load assets directly from a web URL. This is ideal for dynamically loading assets from a server or CDN. ```javascript ``` -------------------------------- ### Create a Physical Shape Source: https://margelo.github.io/react-native-filament/docs/guides/physics Creates a box shape based on asset extents and applies local scaling. ```javascript // useBoxShape expects a vector of halfExtents, so we can just pass the once from our asset const boxShape = useBoxShape(halfExtents) // Eventually we need to adjust the local scaling of the shape: boxShape.localScaling = transform.scale ``` -------------------------------- ### Create a Directional Light Component Source: https://margelo.github.io/react-native-filament/docs/guides/light Use the `` component to create a directional light source. Ensure you import `Light` from 'react-native-filament'. ```javascript import { Light } from "react-native-filament"; ; ``` -------------------------------- ### Configure Babel for react-native-worklets-core (without reanimated) Source: https://margelo.github.io/react-native-filament/docs/guides Add the react-native-worklets-core plugin to your babel.config.js if you are not using reanimated. ```javascript module.exports = { plugins: [ ["react-native-worklets-core/plugin", { processNestedWorklets: true }], // ... ], // ... }; ``` -------------------------------- ### Create a Rigid Body Source: https://margelo.github.io/react-native-filament/docs/guides/physics Defines a rigid body with mass, shape, and transform, automatically adding it to the physics world. ```javascript const rigidBody = useRigidBody({ id: "box", mass: 1, shape: boxShape, transform: transform, // Pass the world for the body to be automatically added to the world: world: world }) ``` -------------------------------- ### Render a Background Image Source: https://margelo.github.io/react-native-filament/docs/guides/images Use the BackgroundImage component to display a 2D image behind the 3D scene. Requires a pre-compiled .filamat material file. ```javascript import { BackgroundImage, Camera, DefaultLight } from "react-native-filament"; import BackgroundImageMaterial from "./assets/background_image.filamat"; const imageResource = require("./assets/background.jpg"); function Renderer() { return ( ); } ``` -------------------------------- ### Render a cubemap texture skybox Source: https://margelo.github.io/react-native-filament/docs/guides/skybox Use the source property to load a KTX cubemap texture file as the scene background. ```javascript function Scene() { const cubemap = require("./skybox_cubemap.ktx") return ( ) } ``` -------------------------------- ### Update Physics Simulation Source: https://margelo.github.io/react-native-filament/docs/guides/physics Advances the physics simulation within a render callback using the provided time delta. ```javascript const renderCallback = useCallback(({ timeSinceLastFrame }) => { "worklet" // This updates the world at 60Hz/60 FPS. If our actual frame rate // is different stepSimulation will interpolate the physics. world.stepSimulation(timeSinceLastFrame, 1, 1 / 60) }, [world]) ``` -------------------------------- ### Implement CameraManipulator with gestures Source: https://margelo.github.io/react-native-filament/docs/guides/camera Configures a camera manipulator for orbit controls and integrates it with react-native-gesture-handler for user input. ```javascript import { Camera, useCameraManipulator } from 'react-native-filament' import { Gesture } from 'react-native-gesture-handler' const cameraManipulator = useCameraManipulator({ orbitHomePosition: [0, 0, 8], // "Camera location" targetPosition: [0, 0, 0], // "Looking at" orbitSpeed: [0.003, 0.003], }) const panGesture = Gesture.Pan() .onBegin((event) => { const yCorrected = viewHeight - event.translationY cameraManipulator?.grabBegin(event.translationX, yCorrected, false) // false means rotation instead of translation }) .onUpdate((event) => { const yCorrected = viewHeight - event.translationY cameraManipulator?.grabUpdate(event.translationX, yCorrected) }) .onEnd(() => { cameraManipulator?.grabEnd() }) return ``` -------------------------------- ### Load Model from Native Asset Directory Source: https://margelo.github.io/react-native-filament/docs/guides/asset-loading Load assets placed directly within the native Android or iOS project structure. This method offers fast loading, even in debug mode. ```javascript // If the asset is in a subdirectory: ``` -------------------------------- ### Render a static color skybox Source: https://margelo.github.io/react-native-filament/docs/guides/skybox Use the colorInHex property to set a solid background color for the scene. ```javascript import { Skybox } from 'react-native-filament'; ``` -------------------------------- ### Translate Model Position Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Use the `translate` prop to set the position of a model. Units are in meters. ```javascript import { Model } from "react-native-filament" const x = 0 const y = -1 const z = 0 ``` -------------------------------- ### Configure Babel for react-native-reanimated with worklets Source: https://margelo.github.io/react-native-filament/docs/guides If using reanimated, ensure the react-native-reanimated/plugin includes the processNestedWorklets option. ```javascript module.exports = { plugins: [ ["react-native-reanimated/plugin", { processNestedWorklets: true }], // ... ], // ... }; ``` -------------------------------- ### Exclude Default Assets from iOS Build Source: https://margelo.github.io/react-native-filament/docs/guides/light Add `$RNFExcludeAssets = true` to your `ios/Podfile` to prevent shipping the default IBL image and reduce app size. ```ruby $RNFExcludeAssets = true ``` -------------------------------- ### Scale Model Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Adjust the size of a model along the x, y, and z axes using the `scale` prop. ```javascript import { Model } from "react-native-filament" const scale = 2; ``` -------------------------------- ### Exclude Default Assets from Android Build Source: https://margelo.github.io/react-native-filament/docs/guides/light Add `RNF_excludeAssets = true` to your `android/gradle.properties` file to opt-out of shipping the default IBL image. ```properties RNF_excludeAssets = true ``` -------------------------------- ### Update Entity Transform by Rigid Body Source: https://margelo.github.io/react-native-filament/docs/guides/physics Synchronizes an entity's transform with its corresponding rigid body after a simulation step. ```javascript const renderCallback = useCallback(({ timeSinceLastFrame }) => { "worklet" world.stepSimulation(timeSinceLastFrame, 1, 1 / 60) // Update our entity: transformManager.updateTransformByRigidBody(entity, rigidBody) }, [world]) ``` -------------------------------- ### Set Custom Transform Matrix Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Manually set the transformation of an entity using a 16-element column-major matrix array. Ensure the matrix is correctly formatted for Filament's column-major convention. ```typescript transformManager.setTransform(entity, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]) ``` -------------------------------- ### Basic Animator Usage Source: https://margelo.github.io/react-native-filament/docs/guides/animator Use the Animator component to play a specific animation from a glTF asset. Provide the animation index or a shared value. The onAnimationsLoaded callback can be used to access loaded animations. ```javascript import { Model, Animator } from 'react-native-filament' { // The animations have been loaded }} /> ``` -------------------------------- ### Apply Continuous Rotation with TransformManager Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Continuously rotate a model's root entity using `transformManager.setEntityRotation`. This requires the component to be wrapped in a `FilamentScene` to access `useFilamentContext`. The rotation is applied in degrees per frame. ```typescript import { useCallback } from 'react' import { TransformManager, useModel, RenderCallback } from "react-native-filament" function MyScene() { const model = useModel(MyModel) const rootEntity = model.state === "loaded" ? model.rootEntity : undefined // We get the transformManager for the filament context. // For this to work needs to be wrapped with a const { transformManager } = useFilamentContext() const renderCallback: RenderCallback = useCallback(() => { "worklet" // We have to check if the model is ready yet: if (rootEntity == null) return; // Add a rotation of 1 degree every frame on the y-axis and // multiply it with the current transform by setting `true` as last argument transformManager.setEntityRotation(rootEntity, 0.01, [0, 1, 0], true) }, [rootEntity, transformManager]) } ``` -------------------------------- ### Disable Matrix Multiplication for Transformations Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Set `multiplyWithCurrentTransform` to `false` to apply transformations directly, resetting previous ones. This is useful for independent scaling. ```javascript import { Model } from "react-native-filament" import { useState } from 'react'; function GrowingModel() { const [scale, setScale] = useState(1); const growModel = () => setScale(scale + 1); return ( ) } ``` -------------------------------- ### Initialize Shared Value for Animation Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Use `useSharedValue` from `react-native-worklets-core` to create values that can be updated frequently for animations without performance issues. ```javascript import { useSharedValue } from "react-native-worklets-core"; function MyScene() { const rotation = useSharedValue(0); // ... } ``` -------------------------------- ### Animate Model Rotation with Shared Value Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Update a shared value within a `RenderCallback` to animate transformations. Creating a new array for `rotation.value` is necessary to trigger internal listeners. ```javascript import { useCallback } from 'react' import { useSharedValue } from "react-native-worklets-core" import { RenderCallback, FilamentView, Model, Float3 } from "react-native-filament" function MyScene() { const rotation = useSharedValue([0, 0, 0]); const renderCallback: RenderCallback = useCallback(() => { "worklet" // Add a rotation of 1 degree every frame const newY = rotation.value[1] + 0.01, // We need to create a new array for the internal listeners to trigger rotation.value = [0, newY, 0] }, [rotation]) return ( ) } ``` -------------------------------- ### Pass Shared Value to Transformation Prop Source: https://margelo.github.io/react-native-filament/docs/guides/transformation Shared values can be directly passed to transformation props like `rotate`. Ensure the type matches the expected `Float3` for rotation. ```javascript function MyScene() { const rotation = useSharedValue([0, 0, 0]); return } ``` -------------------------------- ### Sync Reanimated Shared Value with useSyncSharedValue Source: https://margelo.github.io/react-native-filament/docs/guides/reanimated Use `useSyncSharedValue` to synchronize a Reanimated shared value with a `react-native-worklets-core` shared value. This allows Reanimated animations to drive values used in React Native Filament components. ```javascript import { useSyncSharedValue } from "react-native-filament"; import { useSharedValue, withTiming } from "react-native-reanimated"; // Create a reanimated shared value to drive the animation const opacity = useSharedValue(0); // Sync the reanimated shared value to a worklets-core shared value const workletsCoreOpacity = useSyncSharedValue(opacity); // Drive the animation using reanimated opacity.value = withTiming(1, { duration: 1000 }); // The worklets-core shared value will have the same value as the // reanimated shared value and can be used in react-native-filament components ``` -------------------------------- ### Create Derived Values with useDerivedValue Source: https://margelo.github.io/react-native-filament/docs/guides/reanimated Utilize `useDerivedValue` from `react-native-filament` to create derived values based on synchronized Reanimated shared values. This hook functions similarly to Reanimated's `useDerivedValue` but is intended for `react-native-worklets-core` shared values. ```javascript import { useSharedValue, withSequence, withSpring, withTiming, } from "react-native-reanimated"; import { useSyncSharedValue, useDerivedValue } from "react-native-filament"; // Create a reanimated shared value to drive the animation const animatedRotationY = useSharedValue(0); // RNF works with rn-worklets-core (RNWC), so create a // RNWC shared value thats synced with the reanimated shared value const rotationY = useSyncSharedValue(animatedRotationY); // This uses useDerivedValue from rn-filament to create a RNWC derived value (RNWC has no API for that yet) const rotation = useDerivedValue < Float3 > (() => { "worklet"; return [0, rotationY.value, 0]; }); // Run a animation: const spin = useCallback(() => { animatedRotationY.value = withSequence( withSpring(Math.PI * 2), withTiming(0, { duration: 0 }) ); }, [animatedRotationY]); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.