Docs
Official Website
  • Metakraft Documentation
  • Getting Started
    • 📖Disclaimer
    • 🚄Our Journey
    • 🊹About
  • How Metakraft AI works
    • 📑Market and Trend Analysis
      • Overview of the current trend and market
      • Existing Gaps and Opportunities in the Market for Metakraft AI
      • The Evolution of 3D Experiences and Technology
    • 🔢Creative Layer: All into Games
      • ⚒EDK
      • 🀖AIGC
        • 🍧Asset Generation
          • Create first Model
          • Block Models
        • 🏃‍♂Text-to-Animation
          • Components
        • 🧑‍💌Character Generation
          • Creating Avatars & Animations
        • 🎮InGame UGC - API
          • Generating API Key
          • Creating a Basic Scene
        • ⚙Custom Models & Tools
      • 🔜IP Management
        • 🔌Launching your IP's
      • 🆔Game ID
      • ⌛KRAFT Protocol
    • 🃏Marketplace
    • 🥜Immersive Media - Games and XR Systems
      • 🛞XR Systems
        • 🥜Head-Mounted Display (HMD)
        • 🖲Tracking Systems
        • ⚙XR Runtime
          • 🔮OpenXR Framework
      • 🖍Game Design Ecosystem
        • Game Engines
        • Spatial Audio
        • Web3.0 SDK
    • 🀖Framework & Compatibility
      • 🛞XR Systems
        • XR Runtime
      • 🖍Game Design Ecosystem
        • Web3.0 SDK
          • Wallet
          • Identity
  • Token Economy
    • 🚀Tokenomics & Utilities
    • 🪙About $KRFT Token
    • 🊹Usecases for Token
  • Roadmap
    • 🚀Roadmap
  • How to Join
    • 🚂SPX Nodes
      • Node Rewards and Benefits
      • Technical Requirements
      • Node-as-a-Service Partnerships
      • Partnering with Third-Party Services
      • Delegating Node Operations
      • Security and Compliance
      • Buyback Program
    • 👟Creator & Ambassador Program
  • Conclusion
    • 🀞Conclusion
    • 🐟Disclaimer
Powered by GitBook
On this page
  1. How Metakraft AI works
  2. Creative Layer: All into Games
  3. AIGC
  4. InGame UGC - API

Creating a Basic Scene

To integrate a 3D model generation API into a WebGL and Babylon.js-based game, you'll need to make an API call to generate the model, load the model into your Babylon.js scene, and handle it appropriately within your game environment. Below is a step-by-step guide with code snippets to help you achieve this.

1. Set Up Babylon.js in Your Web Project

Make sure you have Babylon.js included in your project. If you haven't already set it up, include it in your HTML file:

<script src="https://cdn.babylonjs.com/babylon.js"></script>

Set up a basic Babylon.js scene:

<canvas id="renderCanvas"></canvas>
<script>
    const canvas = document.getElementById("renderCanvas");
    const engine = new BABYLON.Engine(canvas, true);
    
    const createScene = function () {
        const scene = new BABYLON.Scene(engine);
        const camera = new BABYLON.ArcRotateCamera("camera1", Math.PI / 2, Math.PI / 2, 2, BABYLON.Vector3.Zero(), scene);
        camera.attachControl(canvas, true);
        const light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 1, 0), scene);
        light.intensity = 0.7;
        return scene;
    };
    
    const scene = createScene();
    engine.runRenderLoop(function () {
        scene.render();
    });

    window.addEventListener("resize", function () {
        engine.resize();
    });
</script>

2. Make an API Call to KRAFT for 3D Model Generation

You'll need to use fetch or another method to call the Tripo API and get the URL for the generated model.

async function generateModel() {
    const apiKey = 'YOUR_KRAFT_API_KEY';
    const response = await fetch('https://api.metakraft.ai/generateModel', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
            // Include any required parameters here
        })
    });

    if (!response.ok) {
        throw new Error('Failed to generate model');
    }

    const data = await response.json();
    return data.modelUrl; // Assume the API returns the model URL
}

3. Load the Generated Model into Babylon.js

Once you have the URL of the generated model, use Babylon.js’s SceneLoader to load and display it.

async function loadModelIntoScene(scene) {
    try {
        const modelUrl = await generateModel();
        
        BABYLON.SceneLoader.Append("", modelUrl, scene, function (scene) {
            // The model is now loaded into the scene
            console.log("Model loaded successfully");
        }, null, function (scene, message) {
            console.error("Failed to load model:", message);
        });
        
    } catch (error) {
        console.error("Error:", error);
    }
}

// Call the function after scene creation
loadModelIntoScene(scene);

4. Handle the Loaded Model

After the model is loaded, you might want to manipulate it (e.g., positioning, scaling, adding interactions).

BABYLON.SceneLoader.Append("", modelUrl, scene, function (scene) {
    const importedMesh = scene.meshes[scene.meshes.length - 1];
    importedMesh.position = new BABYLON.Vector3(0, 0, 0); // Set model position
    importedMesh.scaling = new BABYLON.Vector3(1, 1, 1); // Set model scale
});

5. Integrate the Model with Game Logic

You can now interact with the loaded model within your game. For example, you can add event listeners for mouse clicks or other interactions:

scene.onPointerObservable.add(function (evt) {
    if (evt.pickInfo.hit && evt.pickInfo.pickedMesh) {
        console.log("Mesh clicked:", evt.pickInfo.pickedMesh.name);
        // Handle interaction with the mesh
    }
}, BABYLON.PointerEventTypes.POINTERPICK);

7. Deployment

Once everything is working as expected, deploy your game as usual, ensuring that the KRAFT API is called correctly in the production environment.

PreviousGenerating API KeyNextCustom Models & Tools

Last updated 9 months ago

🔢
🀖
🎮