### Include QNX Setup Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/CMakeLists.txt Includes the QNX setup script if the QNX platform is detected. ```cmake include(${QNX_PATH}/setup.cmake) ``` -------------------------------- ### Install Engine Dependencies Source: https://github.com/cocos/cocos4/blob/v4.0.0/README.md Run this command in the cloned engine folder to set up the development environment and download/build engine dependencies. ```bash npm install ``` -------------------------------- ### Nintendo Switch Platform Setup Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/CMakeLists.txt Includes the platform-specific setup file for Nintendo Switch. This handles NSwitch-specific configurations. ```cmake if(NX) include(${CMAKE_CURRENT_LIST_DIR}/platform-nx/setup.cmake) ``` -------------------------------- ### Bindings Generator Configuration Example Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/bindings-generator/README.md An example of a configuration file for the bindings generator, specifying classes, events, and header files for code generation. ```ini [cocos2d-x] prefix = cocos2dx events = CCNode#onEnter CCNode#onExit extra_arguments = -I../../cocos2dx/include -I../../cocos2dx/platform -I../../cocos2dx/platform/ios -I../../cocos2dx -I../../cocos2dx/kazmath/include -arch i386 -DTARGET_OS_IPHONE -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk -x c++ headers = ../../cocos2dx/include/cocos2d.h classes = CCSprite functions = my_free_function ``` -------------------------------- ### Define and Build Library Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/harmonyos-next/CMakeLists.txt Configures and builds the main shared library for the project. This includes pre-target setup, adding library sources, and post-target setup. ```cmake cc_openharmony_before_target(${CC_LIB_NAME}) add_library(${CC_LIB_NAME} SHARED ${CC_ALL_SOURCES}) cc_openharmony_after_target(${CC_LIB_NAME}) ``` -------------------------------- ### Simple Version Range Syntax Examples Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/README.md Illustrates basic version range conditions for compatibility. These include greater than, less than, exact version, and excluded versions. ```text >=3.6.0 ``` ```text >3.5.1 ``` ```text <3.5.1 ``` ```text <=3.5.1 ``` ```text 3.3.2 ``` ```text !3.5.0 ``` -------------------------------- ### Constant Initialization Examples Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Demonstrates allowed initializations using constant expressions and constexpr constructors. These are always permitted for static storage duration variables. ```C++ struct Foo { constexpr Foo(int) {} }; int n = 5; // fine, 5 is a constant expression Foo x(2); // fine, 2 is a constant expression and the chosen constructor is constexpr Foo a[] = { Foo(1), Foo(2), Foo(3) }; // fine ``` -------------------------------- ### Project Setup and Variable Definitions Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/xr-spaces/template/CMakeLists.txt Initializes the CMake version, sets the project name and C++ standard, and defines variables for library names and directories. ```cmake cmake_minimum_required(VERSION 3.8) option(APP_NAME "Project Name" "CocosGame") project(${APP_NAME} CXX) set(CC_LIB_NAME cocos) set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) set(CC_PROJ_SOURCES) set(CC_COMMON_SOURCES) set(CC_ALL_SOURCES) ``` -------------------------------- ### Composite Version Range Syntax Examples Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/README.md Demonstrates how to combine version range conditions using 'AND' (space) and 'OR' (||) operators for complex compatibility rules. ```text >=3.6.0 <3.7.0 ``` ```text 3.4.2 || >= 3.6.0 ``` ```text >=3.4.0 !3.4.2 <3.5.0 || 3.6.0 ``` -------------------------------- ### Install Python Dependencies (Windows) Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/bindings-generator/README.md Installs necessary Python dependencies for the bindings generator on Windows using pip. ```bash python -m pip install PyYAML==5.4.1 Cheetah3 ``` -------------------------------- ### Wildcard Version Range Syntax Examples Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/README.md Shows how to use wildcard characters for version ranges, such as '3.x' for any version within the 3.x series or '3.4.x' for versions within 3.4.x. ```text 3.x ``` ```text 3.4.x ``` -------------------------------- ### Install Homebrew Python (macOS) Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/bindings-generator/README.md Installs Python using Homebrew on macOS if a compatible version is not already present. ```bash brew install python ``` -------------------------------- ### Inline Namespace Example Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Demonstrates how inline namespaces make symbols in the inner namespace available in the outer scope, useful for ABI compatibility. ```c++ namespace outer { inline namespace inner { void foo(); } // namespace inner } // namespace outer ``` -------------------------------- ### Variable Naming: Good Examples Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Demonstrates acceptable variable naming conventions for local variables and well-known abbreviations. Use descriptive names that are clear within their scope. ```C++ class MyClass { public: int countFooErrors(const std::vector& foos) { int n = 0; // Clear meaning given limited scope and context for (const auto& foo : foos) { ... ++n; } return n; } void doSomethingImportant() { std::string fqdn = ...; // Well-known abbreviation for Fully Qualified Domain Name } private: const int _maxAllowedConnections = ...; // Clear meaning within context }; ``` -------------------------------- ### Function Overloading Example Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Demonstrates function overloading with different parameter types. Consider std::string_view if overloading between const std::string& and const char*. ```c++ class MyClass { public: void Analyze(const std::string &text); void Analyze(const char *text, size_t textlen); }; ``` -------------------------------- ### Move Constructor Example Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Illustrates defining a move constructor using an rvalue reference. This enables moving values instead of copying, potentially improving performance significantly. ```cpp auto v2(std::move(v1)) ``` -------------------------------- ### Register C++ Class to JavaScript VM Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/bindings/docs/JSB2.0-learning-en.md This snippet demonstrates the complete process of registering a C++ class to the JavaScript virtual machine. It covers defining the class, binding its constructor, methods, properties, and static members, and finally installing it into the JavaScript environment. ```c++ static se::Object* __jsb_ns_SomeClass_proto = nullptr; static se::Class* __jsb_ns_SomeClass_class = nullptr; namespace ns { class SomeClass { public: SomeClass() : xxx(0) {} void foo() { printf("SomeClass::foo\n"); Application::getInstance()->getScheduler()->schedule([this](float dt){ static int counter = 0; ++counter; if (_cb != nullptr) _cb(counter); }, this, 1.0f, CC_REPEAT_FOREVER, 0.0f, false, "iamkey"); } static void static_func() { printf("SomeClass::static_func\n"); } void setCallback(const std::function& cb) { _cb = cb; if (_cb != nullptr) { printf("setCallback(cb)\n"); } else { printf("setCallback(nullptr)\n"); } } int xxx; private: std::function _cb; }; } // namespace ns { static bool js_SomeClass_finalize(se::State& s) { ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); delete cobj; return true; } SE_BIND_FINALIZE_FUNC(js_SomeClass_finalize) static bool js_SomeClass_constructor(se::State& s) { ns::SomeClass* cobj = new ns::SomeClass(); s.thisObject()->setPrivateData(cobj); return true; } SE_BIND_CTOR(js_SomeClass_constructor, __jsb_ns_SomeClass_class, js_SomeClass_finalize) static bool js_SomeClass_foo(se::State& s) { ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); cobj->foo(); return true; } SE_BIND_FUNC(js_SomeClass_foo) static bool js_SomeClass_get_xxx(se::State& s) { ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); s.rval().setInt32(cobj->xxx); return true; } SE_BIND_PROP_GET(js_SomeClass_get_xxx) static bool js_SomeClass_set_xxx(se::State& s) { const auto& args = s.args(); int argc = (int)args.size(); if (argc > 0) { ns::SomeClass* cobj = (ns::SomeClass*)s.nativeThisObject(); cobj->xxx = args[0].toInt32(); return true; } SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", argc, 1); return false; } SE_BIND_PROP_SET(js_SomeClass_set_xxx) static bool js_SomeClass_static_func(se::State& s) { ns::SomeClass::static_func(); return true; } SE_BIND_FUNC(js_SomeClass_static_func) bool js_register_ns_SomeClass(se::Object* global) { // Make sure the namespace exists se::Value nsVal; if (!global->getProperty("ns", &nsVal)) { // If it doesn't exist, create one. Similar as `var ns = {};` in JS. se::HandleObject jsobj(se::Object::createPlainObject()); nsVal.setObject(jsobj); // Set the object to the global object with the property name `ns`. global->setProperty("ns", nsVal); } se::Object* ns = nsVal.toObject(); // Create a se::Class object, developers do not need to consider the release of the se::Class object, which is automatically handled by the ScriptEngine. auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // If the registered class doesn't need a constructor, the last argument can be passed in with nullptr, it will make `new SomeClass();` illegal. // Define member functions, member properties. cls->defineFunction("foo", _SE(js_SomeClass_foo)); cls->defineProperty("xxx", _SE(js_SomeClass_get_xxx), _SE(js_SomeClass_set_xxx)); // Define finalize callback function cls->defineFinalizeFunction(_SE(js_SomeClass_finalize)); // Install the class to JS virtual machine cls->install(); // JSBClassType::registerClass is a helper function in the Cocos2D-X native binding code, which is not a part of the ScriptEngine. JSBClassType::registerClass(cls); // Save the result to global variable for easily use in other places, for example class inheritence. __jsb_ns_SomeClass_proto = cls->getProto(); __jsb_ns_SomeClass_class = cls; // Set a property `yyy` with the string value `helloyyy` for each object instantiated by this class. __jsb_ns_SomeClass_proto->setProperty("yyy", se::Value("helloyyy")); // Register static member variables and static member functions se::Value ctorVal; if (ns->getProperty("SomeClass", &ctorVal) && ctorVal.isObject()) { ctorVal.toObject()->setProperty("static_val", se::Value(200)); ctorVal.toObject()->defineFunction("static_func", _SE(js_SomeClass_static_func)); } // Clear JS exceptions se::ScriptEngine::getInstance()->clearException(); return true; } ``` -------------------------------- ### Cocos Creator Project Setup with CMake Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/xr-pico/template/CMakeLists.txt Configures the minimum CMake version, project name, and library name. It also includes common source files from a shared directory. ```cmake cmake_minimum_required(VERSION 3.8) option(APP_NAME "Project Name" "CocosGame") project(${APP_NAME} CXX) set(CC_LIB_NAME cocos) set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) set(CC_PROJ_SOURCES) set(CC_COMMON_SOURCES) set(CC_ALL_SOURCES) include(${CMAKE_CURRENT_LIST_DIR}/../common/CMakeLists.txt) ``` -------------------------------- ### Common Variable Name Example Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md An example of an acceptable common variable name following the convention of starting with a lowercase letter and using camel case. ```C++ std::string tableName; // OK. ``` -------------------------------- ### JavaScript Equivalent of Write-Only Property Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/swig-config/tutorial/index.md Provides a JavaScript example demonstrating how a write-only property is implemented using `Object.defineProperty`, showing only a `set` function and omitting the `get` function. ```javascript Object.defineProperty(MyNewClass.prototype, 'width', { configurable: true, enumerable: true, set(v) { this._width = v; }, // No get() for property }); ``` -------------------------------- ### Unnamed Namespace for Internal Linkage Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Provides an example of using an unnamed namespace to give definitions internal linkage, ensuring they are not accessible outside the current file. The terminating comment is left empty as per the style guide. ```c++ namespace { ... } // namespace ``` -------------------------------- ### Initialize Project Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/ios/CMakeLists.txt Initializes the project with the specified name and language (C++). ```cmake project(${APP_NAME} CXX) ``` -------------------------------- ### Install Python Dependencies (macOS) Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/bindings-generator/README.md Installs necessary Python dependencies for the bindings generator on macOS using pip3. ```bash sudo easy_install pip3 sudo pip3 install PyYAML==5.4.1 Cheetah3 ``` -------------------------------- ### Underscore in Variable Name Example Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md An example of an unacceptable variable name that uses an underscore, violating the camel case convention. ```C++ std::string table_Name; // Bad - has underscore. ``` -------------------------------- ### Download and Configure Google Test Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tests/unit-test/CMakeLists.txt Downloads and unpacks the Google Test framework at configure time. It then executes CMake to configure the downloaded source. ```cmake configure_file(CMakeLists.txt.in googletest-download/CMakeLists.txt) execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" . RESULT_VARIABLE result WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/googletest-download ) if(result) message(FATAL_ERROR "CMake step for googletest failed: ${result}") endif() ``` -------------------------------- ### Create and Navigate to Build Directory Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/editor-support/spine-wasm/README.md Create a temporary directory for build artifacts and change into it. This isolates build files from the source code. ```bash mkdir temp && cd temp ``` -------------------------------- ### Example: Marking math Property as Warning Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/contribution/deprecated-api.md Demonstrates using markAsWarning to flag the 'toRadian' property in the 'math' object as a warning. ```typescript markAsWarning(math, 'math', [ { 'name': 'toRadian' } ]); ``` -------------------------------- ### Example: Replacing AnimationComponent Property Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/contribution/deprecated-api.md Demonstrates how to use replaceProperty to adapt incompatible parameters for the 'removeClip' property by mapping it to 'removeState'. ```typescript replaceProperty(AnimationComponent.prototype, 'AnimationComponent.prototype', [ { name: 'removeClip', newName: 'removeState', customFunction: function (...args: any) { const arg0 = args[0] as AnimationClip; return AnimationComponent.prototype.removeState.call(this, arg0.name); } } ]); ``` -------------------------------- ### Directly Exporting a Mesh API Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/contribution/modules.md Example of directly exporting a 'Mesh' API from '../cocos/core/assets/mesh' into the '/exports/base' public module. ```typescript // At /exports/base.ts export { Mesh } from '../cocos/core/assets/mesh'; ``` -------------------------------- ### Define Project Sources and Build Target Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/linux/CMakeLists.txt Sets up project source file lists and includes common sources. This is used to define the main executable and link necessary files. ```cmake set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) set(CC_PROJ_SOURCES) set(CC_COMMON_SOURCES) set(CC_ALL_SOURCES) include(${CC_PROJECT_DIR}/../common/CMakeLists.txt) set(EXECUTABLE_NAME ${APP_NAME}) #set(CMAKE_SYSTEM_NAME Linux) cc_linux_before_target(${EXECUTABLE_NAME}) add_executable(${EXECUTABLE_NAME} ${CC_ALL_SOURCES}) cc_linux_after_target(${EXECUTABLE_NAME}) ``` -------------------------------- ### Set Minimum CMake Version Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/android/template/CMakeLists.txt Specifies the minimum version of CMake required for this project. Ensure your CMake installation meets this requirement. ```cmake cmake_minimum_required(VERSION 3.8) ``` -------------------------------- ### Define Source and Resource Directories Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/ios/CMakeLists.txt Sets up variables to hold project directories and lists of sources, assets, and common files. These are used later to build the executable. ```cmake set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) set(CC_UI_RESOURCES) set(CC_PROJ_SOURCES) set(CC_ASSET_FILES) set(CC_COMMON_SOURCES) set(CC_ALL_SOURCES) ``` -------------------------------- ### List Available Build Options Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/CMakeLists.txt A macro call to inspect and potentially list the values of various build configuration options used in the project. ```cmake cc_inspect_values( BUILTIN_COCOS_X_PATH USE_BUILTIN_EXTERNAL USE_MODULES CC_USE_METAL CC_USE_GLES3 CC_USE_GLES2 CC_USE_VULKAN CC_DEBUG_FORCE USE_SE_V8 USE_SE_JSVM USE_V8_DEBUGGER USE_V8_DEBUGGER_FORCE USE_SE_SM USE_SOCKET USE_AUDIO USE_EDIT_BOX USE_VIDEO USE_WEBVIEW USE_MIDDLEWARE USE_DRAGONBONES USE_SPINE USE_SPINE_3_8 USE_SPINE_4_2 USE_WEBSOCKET_SERVER USE_PHYSICS_PHYSX USE_JOB_SYSTEM_TBB USE_JOB_SYSTEM_TASKFLOW USE_XR USE_SERVER_MODE USE_AR_MODULE USE_AR_AUTO USE_AR_CORE USE_AR_ENGINE USE_CCACHE CCACHE_EXECUTABLE NODE_EXECUTABLE NET_MODE USE_REMOTE_LOG USE_BOX2D_JSB ) ``` -------------------------------- ### Example: Removing vmath Property Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/contribution/deprecated-api.md Illustrates using removeProperty to deprecate the 'random' property in 'vmath' and suggests using Math.random instead. ```typescript removeProperty(vmath, 'vmath', [ { 'name': 'random', 'suggest': 'use Math.random.' } ]); ``` -------------------------------- ### Using se::HandleObject for Safer Object Management Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/bindings/docs/JSB2.0-learning-zh.md Compares manual se::Object management with the safer and more concise approach using se::HandleObject, which automates root, unroot, and decRef operations. ```C++ { se::HandleObject obj(se::Object::createPlainObject()); obj->setProperty(...); otherObject->setProperty("foo", se::Value(obj)); } 等价于: { se::Object* obj = se::Object::createPlainObject(); obj->root(); // 在手动创建完对象后立马 root,防止对象被 GC obj->setProperty(...); otherObject->setProperty("foo", se::Value(obj)); obj->unroot(); // 当对象被使用完后,调用 unroot obj->decRef(); // 引用计数减一,避免内存泄露 } ``` -------------------------------- ### iOS Target Pre-processing Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/ios/CMakeLists.txt Calls a custom CMake function to perform actions before the main iOS target is defined. This is used for platform-specific setup. ```cmake cc_ios_before_target(${EXECUTABLE_NAME}) ``` -------------------------------- ### Check Emscripten Compiler Version Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/renderer/gfx-wgpu/readme.md Verify that Emscripten is correctly installed and configured by checking its version. This command should be run in your command prompt or zsh. ```bash emcc -v ``` -------------------------------- ### Set Project and Build Options Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/editor-support/spine-wasm/CMakeLists.txt Configures the project name, C++ standard, and enables WASM, JSON, and binary parsers. ```cmake cmake_minimum_required(VERSION 3.8) set(APP_NAME "spine") set(SPINE_VERSION "3.8") # set(SPINE_VERSION "4.2") set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) project(${APP_NAME}_wasm) set(BUILD_WASM 1) set(ENABLE_JSON_PARSER 1) set(ENABLE_BINARY_PARSER 1) # set(ENABLE_PROFILING "--profiling") # set(ENABLE_MEMORY_PROFILING "--memoryprofiler -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE=$demangleAll") set(VERBOSE_LOG 0) ``` -------------------------------- ### Print Build Information Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/editor-support/spine-wasm/CMakeLists.txt Outputs various build configuration variables to the console for debugging and verification. ```cmake message(">>> --------------------------------------------------------------") message(">>> Current directory: ${CMAKE_CURRENT_LIST_DIR}") message(">>> CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}") message(">>> ENABLE_CLOSURE_COMPILER: ${ENABLE_CLOSURE_COMPILER}") message(">>> ENABLE_JSON_PARSER: ${ENABLE_JSON_PARSER}") message(">>> ENABLE_BINARY_PARSER: ${ENABLE_BINARY_PARSER}") message(">>> ENABLE_PROFILING: ${ENABLE_PROFILING}") message(">>> ENABLE_MEMORY_PROFILING: ${ENABLE_MEMORY_PROFILING}") message(">>>SPINE_EXTRA_FLAGS: ${SPINE_EXTRA_FLAGS}") message(">>> EVAL_CTOR_FLAG: ${EVAL_CTOR_FLAG}") message(">>> --------------------------------------------------------------") message(">>> CMAKE_C_COMPILER_VERSION is ${CMAKE_C_COMPILER_VERSION}") message(">>> CMAKE_CXX_COMPILER_VERSION is ${CMAKE_CXX_COMPILER_VERSION}") message(">>> CMAKE_C_COMPILER_TARGET is ${CMAKE_C_COMPILER_TARGET}") message(">>> CMAKE_CXX_COMPILER_TARGET is ${CMAKE_CXX_COMPILER_TARGET}") message(">>> CMAKE_C_PLATFORM_ID is ${CMAKE_C_PLATFORM_ID}") message(">>> CMAKE_CXX_PLATFORM_ID is ${CMAKE_CXX_PLATFORM_ID}") message(">>> CMAKE_C_COMPILE_FEATURES is ${CMAKE_C_COMPILE_FEATURES}") message(">>> CMAKE_CXX_COMPILE_FEATURES is ${CMAKE_CXX_COMPILE_FEATURES}") message(">>> --------------------------------------------------------------") ``` -------------------------------- ### Example: Replacing vmath Properties Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/contribution/deprecated-api.md Shows how to use replaceProperty to alias 'vec2' to 'Vec2' and 'EPSILON' within the 'vmath' object, targeting the 'math' object. ```typescript replaceProperty(vmath, 'vmath', [ { name: 'vec2', newName: 'Vec2', target: math, targetName: 'math', 'logTimes': 1 }, { name: 'EPSILON', target: math, targetName: 'math', 'logTimes': 2 } ]); ``` -------------------------------- ### Compile WGPU C++ Files with Emscripten Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/renderer/gfx-wgpu/readme.md Compile the WGPU C++ source files into WebAssembly using Emscripten's toolchain. Navigate to the WGPU source directory and execute these commands. ```bash emcmake cmake . ``` ```bash emmake make ``` -------------------------------- ### Acronym Naming Conventions Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/TS_CODING_STYLE.md When using acronyms, maintain consistent casing. If an acronym starts a name, use lowercase for all its characters; otherwise, capitalize all characters. ```typescript // bad let Id = 0; let iD = 0; function requireId () {} // good let id = 0; let uuid = ''; function requireID () {} class AssetUUID {} ``` -------------------------------- ### Generate Compile Commands for Android Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_LINTER_AUTOFIX_GUIDE.md Generates the compile_commands.json file necessary for clang-tidy and clang-format. Ensure LLVM 11+ is installed and NDK environment variables are set. ```bash utils/generate_compile_commands_android.sh # other platforms ``` ```bash utils/generate_compile_commands_android_windows.sh # if using git-bash on windows ``` -------------------------------- ### Configure Filesystem Test Executable Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tests/module-tests/filesystem/CMakeLists.txt Defines the test executable, links it against the ccfilesystem library, and sets up necessary include directories. Platform-specific properties for iOS are also configured. ```cmake add_executable(test-fs test-fs.cpp) target_link_libraries(test-fs PUBLIC ccfilesystem) target_include_directories(test-fs PRIVATE ${CMAKE_CURRENT_LIST_DIR}/../../.. ${CMAKE_CURRENT_LIST_DIR}/../../../cocos ) if(IOS) set_target_properties(test-fs properties XCODE_ATTRIBUTE_ENABLE_BITCODE "NO" ) endif() ``` -------------------------------- ### Include Core HttpClient Source Files Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/CMakeLists.txt Includes the main HttpClient implementation source file for platforms like Windows, macOS, Linux, QNX, and OpenHarmony. This is the primary HTTP client implementation. ```cmake if(WINDOWS OR MACOSX OR LINUX OR QNX OR OPENHARMONY) cocos_source_files( NO_WERROR NO_UBUILD cocos/network/HttpClient.cpp ) endif() ``` -------------------------------- ### Update MyObject.h with New Method Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/swig-config/tutorial/index.md Adds a new method `helloWithAnotherObject` to `MyObject` that accepts an instance of `MyAnotherObject`. This requires the `MyAnotherObject` definition to be available. ```c++ // MyObject.h //...... class MyObject : public MyRef { public: // ...... void helloWithAnotherObject(const my_another_ns::MyAnotherObject &obj) { CC_LOG_DEBUG("==> helloWithAnotherObject, a: %f, b: %d", obj.a, obj.b); } // ...... }; } // namespace my_ns { ``` -------------------------------- ### Get Libpng Copyright Information Source: https://github.com/cocos/cocos4/blob/v4.0.0/licenses/LICENSE_libpng.txt Use this function to conveniently display the libpng copyright notice in 'about' boxes or similar interfaces. It requires a NULL argument. ```c printf("%s",png_get_copyright(NULL)); ``` -------------------------------- ### Build Project with Ninja Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/cocos/editor-support/spine-wasm/README.md Compile the project using the Ninja build system. This command should be executed after CMake has successfully generated the build files. ```bash ninja ``` -------------------------------- ### Android JNI Library Setup Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/CMakeLists.txt Sets up the 'cocos_jni' static library for Android or OHOS (excluding OpenHarmony). It defines include directories and links necessary platform libraries. ```cmake if(ANDROID OR (NOT OPENHARMONY AND OHOS)) cc_enable_werror("${CC_JNI_SRC_FILES}") add_library(cocos_jni STATIC ${CC_JNI_SRC_FILES}) target_include_directories(cocos_jni PUBLIC ${CWD} ${CWD}/cocos ${CC_EXTERNAL_INCLUDES} ) if(ANDROID) target_link_libraries(cocos_jni PUBLIC android_platform android log ) # Export GameActivity_onCreate(), # Refer to: https://github.com/android-ndk/ndk/issues/381. set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -u GameActivity_onCreate") endif() endif() ``` -------------------------------- ### Configure C++ Modules in .i File Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/swig-config/tutorial/index.md Use preprocessor directives to conditionally enable or disable C++ features. Ensure the correct header files are included for module functionality. ```cpp #pragma once #include "cocos/cocos.h" #include "MyRef.h" #ifndef USE_MY_FEATURE #define USE_MY_FEATURE 0 // Disable USE_MY_FEATURE #endif ``` -------------------------------- ### Define CMake Project and Sources Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/windows/CMakeLists.txt Sets the minimum CMake version, project name, and includes common sources. This is a standard setup for C++ projects using CMake. ```cmake cmake_minimum_required(VERSION 3.18) set(APP_NAME "CocosGame" CACHE STRING "Project Name") project(${APP_NAME} CXX) set(CC_PROJECT_DIR ${CMAKE_CURRENT_LIST_DIR}) set(CC_UI_RESOURCES) set(CC_PROJ_SOURCES) set(CC_COMMON_SOURCES) set(CC_ALL_SOURCES) include(${CC_PROJECT_DIR}/../common/CMakeLists.txt) set(EXECUTABLE_NAME ${APP_NAME}) ``` -------------------------------- ### Configure SWIG Generation Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/swig-config/tutorial/index.md Set up the `swig-config.js` file to define input interfaces, output directories, and header search paths for the SWIG parser. ```javascript // swig-config.js 'use strict'; const path = require('path'); const configList = [ [ 'my-module.i', 'jsb_my_module_auto.cpp' ], ]; const projectRoot = path.resolve(path.join(__dirname, '..', '..')); const interfacesDir = path.join(projectRoot, 'tools', 'swig-config'); const bindingsOutDir = path.join(projectRoot, 'native', 'engine', 'common', 'bindings', 'auto'); // includeDirs means header search path for Swig parser const includeDirs = [ path.join(projectRoot, 'native', 'engine', 'common', 'Classes'), ]; module.exports = { interfacesDir, bindingsOutDir, includeDirs, configList }; ``` -------------------------------- ### Project Configuration Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/android/template/CMakeLists.txt Defines the project name and language. The APP_NAME option allows customization of the project's executable name. ```cmake option(APP_NAME "Project Name" "CocosGame") project(${APP_NAME} CXX) ``` -------------------------------- ### Generate JS Bindings with SWIG Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tools/swig-config/README.md Execute the binding generation script using Node.js. Provide the path to your custom configuration file using the `-c` argument. ```bash # If current workspace is not in '/Users/abc/my-project/tools/swig-config' $ node < Engine Root Path >/native/tools/swig-config/genbindings.js -c /Users/abc/my-project/tools/swig-config/swig-config.js ``` ```bash # If you have already navigate to '/Users/abc/my-project/tools/swig-config' directory, you could run the command without -c argument like: $ cd /Users/abc/my-project/tools/swig-config $ node < Engine Root Path >/native/tools/swig-config/genbindings.js ``` -------------------------------- ### Function Naming Convention Source: https://github.com/cocos/cocos4/blob/v4.0.0/docs/CPP_CODING_STYLE.md Outlines the naming convention for regular functions, which start with a lowercase letter and use camel case. Accessors and mutators can be named like variables. ```C++ addTableEntry() deleteUrl() openFileOrDie() ``` -------------------------------- ### Define Executable and Link Libraries Source: https://github.com/cocos/cocos4/blob/v4.0.0/native/tests/module-tests/bindings/CMakeLists.txt Configures the main executable for native bindings and links necessary libraries and include directories. ```cmake set(LIB_NAME test-bindings) add_executable(test-bindings test-bindings.cpp) target_link_libraries(test-bindings PUBLIC ccbindings) target_include_directories(test-bindings PRIVATE ${CMAKE_CURRENT_LIST_DIR}/../../.. ${CMAKE_CURRENT_LIST_DIR}/../../../cocos ) ``` -------------------------------- ### Set Minimum CMake Version and Project Name Source: https://github.com/cocos/cocos4/blob/v4.0.0/templates/xr-huaweivr/template/CMakeLists.txt Specifies the minimum required CMake version and sets the project name. This is a standard starting point for CMake projects. ```cmake cmake_minimum_required(VERSION 3.8) option(APP_NAME "Project Name" "CocosGame") project(${APP_NAME} CXX) ```