# Runtime Scripting API

The TerraForge 2 Runtime Scripting API provides developers with powerful tools to control terrain generation and modifications programmatically. This API allows for runtime customization and automation, making it easier to integrate TerraForge 2 into dynamic environments. Below are the primary methods and examples for using the API.

***

### Terrain Generation

#### Basic Terrain Generation

To generate terrain using the `TerraForgeTerrainGenerator` component:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI_TerrainGenerate : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Initiates terrain generation
        terrainGenerator.TerrainGenerate();
    }
}
```

#### Runtime Island Generation Using Seed Switching

This example demonstrates how to use `TerraForge 2` as a runtime island generator by **reusing a predefined setup** (biomes, terrain layers, painting, erosion settings) and generating **a new island every time** simply by switching the seed.

This is useful when:

* You design an island setup once in the editor.
* You want to generate different variations of that island at runtime (for example, for multiplayer sync or world randomization).
* You want to avoid modifying the original `TerrainData` from your prefab.

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI_RuntimeIslandGenerator : MonoBehaviour
{
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        GenerateNewIsland();
    }

    public void GenerateNewIsland()
    {
        // Apply a new random seed
        terrainGenerator.generalSettings.seed = Random.Range(0, 999999);

        // Clone TerrainData to avoid modifying the prefab.
        // CreateAndSetCloneTerrainData() ensures that each island has its own 
        // independent TerrainData, which is important if you're spawning multiple 
        // instances or preserving originals
        terrainGenerator.CreateAndSetCloneTerrainData();

        // Regenerate the island using the current configuration
        terrainGenerator.TerrainGenerate();
    }
}

```

#### Saving Parameters with PlayerPrefs

To save the parameters of the `TerraForgeTerrainGenerator` component after generating terrain:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Generates the terrain
        terrainGenerator.TerrainGenerate();

        // Saves the component data using PlayerPrefs
        terrainGenerator.SaveComponentData();
    }
}
```

#### Loading Saved Parameters with PlayerPrefs

To load previously saved parameters before generating terrain:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Loads the component data from PlayerPrefs
        terrainGenerator.LoadComponentData();

        // Generates the terrain
        terrainGenerator.TerrainGenerate();
    }
}
```

#### Tracking Terrain Generation Completion

To track when the terrain generation process is complete:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Subscribes to the OnGenerationComplete event
        terrainGenerator.OnGenerationComplete += HandleGenerationComplete;

        // Starts the terrain generation process
        terrainGenerator.TerrainGenerate();
    }

    // Method called when terrain generation is complete
    void HandleGenerationComplete()
    {
        Debug.Log("Terrain generation is complete!");
    }

    void OnDestroy()
    {
        // Unsubscribes from the OnGenerationComplete event to prevent memory leaks
        if (terrainGenerator != null)
        {
            terrainGenerator.OnGenerationComplete -= HandleGenerationComplete;
        }
    }
}
```

### Applying LayerSettingsData

Example of loading LayerSettingsData

Here is an example of loading and applying `LayerSettingsData` to `TerrainPainter`:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Painter;

public class TestAPI_LayerSettings : MonoBehaviour
{
    // Reference to the terrain painter
    public TerrainPainter terrainPainter;

    // Reference to the layer settings data to load
    public LayerSettingsData layerSettingsData;

    void Start()
    {
        if (terrainPainter != null && layerSettingsData != null)
        {
            // Apply the specified LayerSettingsData to the TerrainPainter
            terrainPainter.ApplyLayerSettingsData(layerSettingsData);
            Debug.Log("Layer settings applied successfully!");
        }
        else
        {
            Debug.LogError("TerrainPainter or LayerSettingsData is not assigned.");
        }
    }
}
```

### Applying Biome Settings

#### Applying Biome Settings to a Terrain Generator

To apply specific biome settings to the `TerraForgeTerrainGenerator`:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the biome settings
    public BiomeSettings biome;
    
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Applies the biome settings to the terrain generator
        biome.ApplyingBiomeSettings(terrainGenerator, null, false, 15);

        // Generates the terrain
        terrainGenerator.TerrainGenerate();
    }
}

// What the used method looks like in the BiomeSettings component
public class BiomeSettings : ScriptableObject
{
    /// <summary>
    /// Applies the biome settings to the specified terrain generator and terrain game object.
    /// </summary>
    /// <param name="generator">The terrain generator to apply the settings to.</param>
    /// <param name="terrainGameObject">The terrain game object to apply the settings to.</param>
    /// <param name="isEmptyBiome">Indicates if the biome is empty.</param>
    /// <param name="emptyBiomesHeight">The height for empty biomes.</param>
    public void ApplyingBiomeSettings(TerraForgeTerrainGenerator generator, GameObject terrainGameObject, bool isEmptyBiome, float emptyBiomesHeight)
    {
        // Implementation of biome application logic...
    }
}
```

### Modifying Generation Parameters

#### Changing Generation Parameters of the Terrain Generator

To change the generation parameters dynamically:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Change the terrain height parameter
        terrainGenerator.generalSettings.terrainHeight = 12f;

        // Copy and modify terrain layers
        terrainGenerator.terrainLayers = new TerrainLayerSettings[terrainGenerator.terrainLayers.Length];
        for (int i = 0; i < terrainLayers.Length; i++)
        {
            terrainGenerator.terrainLayers[i] = new TerrainLayerSettings(terrainGenerator.terrainLayers[i]);
            terrainGenerator.terrainLayers[i].seed = UnityEngine.Random.Range(0, 1000);
        }

        // Modify hydraulic erosion settings
        terrainGenerator.hydraulicErosionLayerSettings = new HydraulicErosionLayerSettings(terrainGenerator.hydraulicErosionLayerSettings);
        terrainGenerator.hydraulicErosionLayerSettings.inertia = 3f;

        // Generates the terrain with new settings
        terrainGenerator.TerrainGenerate();
    }
}
```

### Advanced Terrain Generation

#### Creating a New TerrainData File

To create a new `TerrainData` file and generate terrain:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Creates and sets a new cloned TerrainData file
        terrainGenerator.CreateAndSetCloneTerrainData();

        // Generates the terrain
        terrainGenerator.TerrainGenerate();
    }
}
```

#### Changing Terrain Resolution

To change the resolution of the terrain:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrain generator
    public TerraForgeTerrainGenerator terrainGenerator;

    void Start()
    {
        // Change the terrain resolution setting
        terrainGenerator.generalSettings.terrainResolution = TerrainResolution.Resolution513;

        // Apply the new resolution and refresh generation
        terrainGenerator.ChangeTerrainResolution(true);
    }
}

// What the used method looks like in the TerraForgeTerrainGenerator component
public class TerraForgeTerrainGenerator : MonoBehaviour, IGenerator
{
    /// <summary>
    /// Changes the terrain resolution based on the resolution specified in the general settings.
    /// </summary>
    /// <param name="refreshGeneration">Flag indicating whether to refresh terrain generation after resolution change.</param>
    public void ChangeTerrainResolution(bool refreshGeneration)
    {
        // Implementation of resolution change logic...
    }
}
```

#### Generating a Terrains Grid with Custom Parameters

To generate a grid of terrains with custom parameters:

```csharp
using UnityEngine;
using TerraForge2.Scripts.Generators;

public class TestAPI : MonoBehaviour
{
    // Reference to the TerraForge terrains grid generator
    public TerraForgeTerrainsGridGenerator terrainsGridGenerator;

    void Start()
    {
        // Set the number of grid columns and lines
        terrainsGridGenerator.gridColumns = 2;
        terrainsGridGenerator.gridLines = 2;

        // Initiates the generation of the terrain grid
        terrainsGridGenerator.NewGenerateTerrainGrid();
    }
}
```

{% hint style="info" %}
These are just examples of usage. You can create your own unique methods and ways of using the `API`. The [demo scenes](../getting-started/demos-and-samples) also partially utilize the above methods.
{% endhint %}
