Integrate Atlas and Realm/Device Sync into Unreal Engine and CryoEngine - Tutorial

====To integrate MongoDB Atlas into Unreal Engine, for Servers, embedded game infra (think WOW etc), you can follow these steps:====

  1. Install the MongoDB C++ driver: Download and install the latest version of the MongoDB C++ driver from the official website.

  2. Create a new C++ class in Unreal Engine: In Unreal Engine, create a new C++ class that will handle the MongoDB functionality.

  3. Include the required MongoDB C++ headers: In the C++ class, include the required MongoDB C++ headers using #include.

  4. Initialize the MongoDB driver: Use the mongocxx::instance class to initialize the MongoDB driver.

  5. Connect to the Atlas cluster: Use the mongocxx::client class to connect to your MongoDB Atlas cluster by passing in the Atlas connection string.

  6. Access a database and collection: Use the mongocxx::database and mongocxx::collection classes to access a specific database and collection.

  7. Perform CRUD operations: Use the MongoDB C++ driver to perform CRUD (create, read, update, delete) operations on the database and collection.

Some useful features you can implement using the MongoDB C++ driver in Unreal Engine include:

  • Using BSON documents: The MongoDB C++ driver allows you to use BSON documents to represent and manipulate data. This can be useful for storing and retrieving complex data structures in your Unreal Engine project.

  • Indexing: The MongoDB C++ driver allows you to create indexes on your collections to improve query performance.

  • Aggregation: The MongoDB C++ driver provides a set of aggregation operators that can be used to perform advanced data processing and analysis on your data.

  • GridFS: The MongoDB C++ driver also provides support for GridFS, a specification for storing and retrieving large files and binary data in MongoDB. This can be useful for storing and retrieving assets in your Unreal Engine project.

For inserting a document into a MongoDB Atlas collection using the C++ driver in Unreal Engine:

#include "mongocxx/client.hpp"
#include "mongocxx/instance.hpp"
#include "bsoncxx/json.hpp"
#include "bsoncxx/builder/stream/document.hpp"

// Initialize the MongoDB driver
mongocxx::instance instance{};

// Connect to the Atlas cluster
mongocxx::client client{mongocxx::uri{"<Atlas connection string>"}};

// Access a database and collection
mongocxx::database db = client["<database name>"];
mongocxx::collection coll = db["<collection name>"];

// Insert a document
bsoncxx::builder::stream::document doc{};
doc << "name" << "Alice" << "age" << 30;
coll.insert_one(doc.view());

// Find documents that match a query
bsoncxx::builder::stream::document query{};
query << "age" << bsoncxx::types::b_int32{30};
mongocxx::cursor cursor = coll.find(query.view());

// Iterate over the results
for (auto&& doc : cursor) {
    UE_LOG(LogTemp, Warning, TEXT("%s"), UTF8_TO_TCHAR(bsoncxx::to_json(doc).c_str()));
}

This code initializes the MongoDB C++ driver, connects to a MongoDB Atlas cluster, accesses a database and collection, inserts a document into the collection, and finds documents that match a query. The results are logged to the Unreal Engine console using UE_LOG.

Note that in a real-world scenario, you would likely want to move this code to a separate thread or coroutine to avoid blocking the game loop. Additionally, you may want to handle errors and exceptions that can occur when interacting with the database.

====MONGODB REALM IMPLEMENTATION INTO UNREAL ENGINE FOR GAME CLIENTS====

To integrate MongoDB Realm into Unreal Engine, you can follow these general steps:

  1. Install the MongoDB Realm SDK for C++:

    • Download the SDK from the MongoDB Realm website.
    • Extract the downloaded files to a directory on your computer.
  2. Create a new Unreal Engine project:

    • Open Unreal Engine and create a new C++ project.
  3. Add the MongoDB Realm SDK to your Unreal Engine project:

    • In the “Solution Explorer” panel in Visual Studio, right-click on your project and select “Add > Existing Item”.
    • Navigate to the directory where you extracted the MongoDB Realm SDK and select the include folder and the lib folder.
  4. Write your code:

    • Include the MongoDB Realm SDK header files in your code.
    • Create a new RealmApp instance and configure it with your MongoDB Realm app ID and any other necessary settings.
    • Authenticate with MongoDB Realm using the SDK’s authentication methods.
    • Use the SDK’s sync and data access APIs to read and write data to your MongoDB Realm app.

Here’s some sample code that shows how to authenticate with MongoDB Realm and read data from a MongoDB Realm collection:

#include "realm/sync/app.hpp"
#include "realm/sync/sync_config.hpp"
#include "realm/sync/sync_user.hpp"
#include "realm/sync/sync_manager.hpp"

using namespace realm;
using namespace realm::app;
using namespace realm::sync;

void ConnectToRealm()
{
    // Initialize the MongoDB Realm app.
    auto app_id = "<your-app-id-here>";
    auto app_config = App::Config{app_id};
    auto realm_app = App::App(app_config);

    // Authenticate with MongoDB Realm using anonymous authentication.
    auto user = realm_app.log_in(AppCredentials::anonymous());

    // Create a configuration for the MongoDB Realm sync client.
    auto sync_config = SyncConfig{};
    sync_config.user = user;
    sync_config.partitioner = [](const std::string& /*partition_value*/) {
        return "default";
    };

    // Create a Realm configuration and open a Realm with it.
    auto realm_config = Realm::Config{};
    realm_config.sync_config = sync_config;
    realm_config.schema_mode = SchemaMode::Automatic;
    realm_config.path = "<your-realm-path-here>";
    auto realm = Realm::get_shared_realm(realm_config);

    // Query the Realm for all documents in a collection.
    auto results = realm->read_group().find_collection("my_collection")->sync();
    for (auto const& object : results) {
        // Do something with the object.
    }
}

Note that this is just a basic example, and you’ll need to customize it to work with your specific MongoDB Realm app and data. You can find more information on the MongoDB Realm C++ SDK in the MongoDB documentation.

CLIENT RESET LOGIC FOR UNREAL ENGINE

I had to make this from scratch since there isn’t any.

> **#include <iostream>**
> **#include <realm.hpp>**
> 
> **int main() {**
> **    // Set up a sync configuration**
> **    realm::SyncConfig config;**
> **    config.user = realm::SyncUser::login("<your Realm app ID>", "<your Realm username>", "<your Realm password>");**
> 
> **    try {**
> **        // Create a synchronized Realm**
> **        realm::Realm realm = realm::SyncManager::shared().get_realm(config);**
> 
> **        // Get the sync session**
> **        auto syncSession = realm.sync_session();**
> 
> **        // Resync the data**
> **        syncSession->refresh();**
> 
> **        // Access the data**
> **        auto objects = realm.objects("Task");**
> 
> **        // Print out the data**
> **        for (auto object : objects) {**
> **            std::cout << object.get_string("name") << std::endl;**
> **        }**
> **    }**
> **    catch (const std::exception& ex) {**
> **        std::cerr << "Error: " << ex.what() << std::endl;**
> **        return 1;**
> **    }**
> 
> **    // Clean up and reset the client before exiting the application**
> **    realm::reset_for_testing();**
> **    return 0;**
> **}**

Amazon Lumberyard is a game engine that allows you to build high-quality games for various platforms. Integrating MongoDB Atlas into Lumberyard can be achieved through the use of the C++ driver provided by MongoDB. Here’s a basic example of how to connect to MongoDB Atlas using the C++ driver in Lumberyard:

PLEASE USE COMMON SENSE AND DON’T PUT THE DRIVER INTO A GAME CLIENT, YOU PUT IT INTO YOUR GAME SERVER

  1. First, make sure that the MongoDB C++ driver is installed in your system. You can download it from the official MongoDB website.

  2. In your Lumberyard project, create a new C++ source file, and include the necessary headers for the MongoDB C++ driver:

#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
  1. In your source file, initialize the MongoDB driver:
mongocxx::instance instance{};
  1. Connect to your MongoDB Atlas cluster using the mongocxx::client class:
mongocxx::client client(mongocxx::uri{"<MongoDB Atlas connection string>"});

Replace <MongoDB Atlas connection string> with your actual connection string.

  1. Access a database and collection in your Atlas cluster:
mongocxx::database db = client["<database name>"];
mongocxx::collection coll = db["<collection name>"];

Replace <database name> and <collection name> with the names of your actual database and collection.

  1. You can now use the mongocxx::collection object to perform CRUD operations on your collection. For example, to insert a document:
bsoncxx::builder::stream::document doc{};
doc << "name" << "John" << "age" << 30;
coll.insert_one(doc.view());
  1. To find documents that match a query:
bsoncxx::builder::stream::document query{};
query << "age" << bsoncxx::types::b_int32{30};
mongocxx::cursor cursor = coll.find(query.view());

for (auto&& doc : cursor) {
    std::cout << bsoncxx::to_json(doc) << std::endl;
}
  1. Add error handling to your code to handle exceptions thrown by the MongoDB C++ driver:
try {
    // Your MongoDB Atlas code here
}
catch (const std::exception& ex) {
    std::cerr << "Error: " << ex.what() << std::endl;
    return 1;
}

That’s a basic example of how to integrate MongoDB Atlas into Amazon Lumberyard using the MongoDB C++ driver. You can use this as a starting point to build more advanced functionality for your Lumberyard game.

FOR GAME CLIENTS

Integrating MongoDB Realm into Lumberyard involves several steps:

  1. Add the MongoDB Realm SDK to your Lumberyard project:

    You can download the MongoDB Realm SDK from the official MongoDB website. Once downloaded, you can add the SDK to your Lumberyard project by following these steps:

    • Copy the Realm SDK files into your project’s source code directory.
    • Add the Realm SDK files to your project’s build system.

    For example, if you are using CMake as your build system, you can add the Realm SDK files to your CMakeLists.txt file.

  2. Initialize the MongoDB Realm SDK:

    In your Lumberyard application code, you need to initialize the MongoDB Realm SDK before you can use it. This involves setting up a configuration object with your MongoDB Realm app ID and calling the realm::App::get() method to retrieve a reference to your app instance.

    // Initialize the MongoDB Realm client
    auto app = realm::app::App::get("<Your App ID>");
    
  3. Authenticate the user:

    You can authenticate the user with MongoDB Realm using any of the supported authentication methods, such as email/password authentication or anonymous authentication. Once authenticated, you can retrieve a reference to the realm::SyncUser object.

    // Authenticate the user
    auto user = app->log_in_with_credentials(realm::app::AppCredentials::anonymous());
    
  4. Set up a sync configuration:

    You need to set up a realm::SyncConfig object with your MongoDB Atlas cluster connection string, the database name, and the collection name that you want to synchronize.

    // Set up a sync configuration
    realm::SyncConfig config;
    config.user = user;
    config.partition_value = "<Partition value>";
    config.sync_route = "<Sync route URL>";
    config.database_name = "<Database name>";
    config.base_url = "<Atlas base URL>";
    config.error_handler = [](std::exception_ptr err) {
        try {
            std::rethrow_exception(err);
        } catch (const std::exception& ex) {
            std::cerr << "Error: " << ex.what() << std::endl;
        }
    };
    
  5. Create a synchronized Realm:

    Use the realm::SyncManager::shared().get_realm(config) method to create a synchronized Realm instance. This method returns a realm::Realm object that you can use to read and write data.

    // Create a synchronized Realm
    realm::Realm realm = realm::SyncManager::shared().get_realm(config);
    
  6. Access and modify synchronized data:

    You can access and modify synchronized data using the realm::Realm object that you created in the previous step. You can use the standard Realm APIs to read and write data. For example:

    // Access a collection in the synchronized Realm
    auto collection = realm.read_group().get_table("<Collection name>");
    
    // Add a new document to the collection
    auto row = collection->create_object();
    row.set_string("<Field name>", "<Field value>");
    
    // Modify an existing document in the collection
    auto results = collection->find_all();
    results[0].set_string("<Field name>", "<New field value>");
    
  7. Clean up and reset the client:

It’s good practice to clean up and reset the MongoDB Realm client before exiting your application. This ensures that any resources used by the client are properly released and that the client is in a clean state for the next time it is used. As with Lumberyard everything is pushed to the cloud for the cloud services.

To clean up and reset the MongoDB Realm client, you can call the close() method on your App instance and the reset_for_testing() function from the realm namespace. Here’s an example:

#include <realm.hpp>

int main(int argc, char* argv[]) {
    // Initialize the MongoDB Realm client
    auto app = realm::app::App::get("<Your App ID>");

    // Your application code here...

    // Clean up and reset the client before exiting the application
    app->close();
    realm::reset_for_testing();
    return 0;
}

In this example, app->close() releases any resources used by the MongoDB Realm client and realm::reset_for_testing() resets the client to a clean state. You should call these functions before your application exits.