diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index b8af6b3..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitignore b/.gitignore index 9476e7f..24302c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ build -source/user_guide/reference/_autosummary/ \ No newline at end of file +source/user_guide/reference/_autosummary/ +.DS_Store diff --git a/README.md b/README.md index cc6bfdd..547f172 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,14 @@ -# Genesis Documentation +# Genesis Documentation (English Version) -1. Create a clean env using python 3.10, install Sphinx and other dependencies +1. Create a clean env using python >= 3.9, install Sphinx and other dependencies ```bash -# In Genesis-dev/ -pip install -e ".[docs]" +pip install genesis-world # Requires Python >= 3.9; ``` 2. Build the documentation and watch the change lively ```bash -# In doc/ +# In genesis-doc/ rm -rf build/; make html; sphinx-autobuild ./source ./build/html -``` \ No newline at end of file +``` diff --git a/README_AGENT.md b/README_AGENT.md new file mode 100644 index 0000000..6cb5c2c --- /dev/null +++ b/README_AGENT.md @@ -0,0 +1,164 @@ +# Genesis API Reference Agent + +A powerful Python agent that integrates all API documentation from the `api_reference` directory and provides a convenient interface for users to query and access API information. + +## Features + +- **Comprehensive Documentation Integration**: Loads and processes all Markdown documentation from the API reference directory +- **Structured Knowledge Base**: Organizes API information into categories (entities, materials, options, scene, sensor) +- **Advanced Search**: Search for APIs by name, description, or parameters +- **Interactive Mode**: User-friendly command-line interface for querying API information +- **Export Functionality**: Export the knowledge base to JSON for external use + +## Installation + +No external dependencies are required. The agent uses only Python standard libraries. + +## Usage + +### Basic Usage + +Run the agent in interactive mode: + +```bash +python genesis_api_agent.py +``` + +### Interactive Commands + +- `help`: Show help information +- `exit`: Exit the agent +- `categories`: List all categories +- `list [category]`: List all APIs (optionally filtered by category) +- `search `: Search for APIs matching query +- `get `: Get detailed information about an API +- ``: Ask a question about the API (experimental) + +### Example Usage + +``` +=== Genesis API Reference Agent === +Type 'help' for available commands, 'exit' to quit. +=================================== + +> categories + +Categories: + - entities: 22 APIs + - materials: 23 APIs + - options: 17 APIs + - scene: 5 APIs + - sensor: 1 APIs + +> list entities + +APIs (22 total): + 1. entities.DroneEntity + 2. entities.Emitter + 3. entities.FEMEntity + 4. entities.HybridEntity + 5. entities.MPMEntity + 6. entities.SFEntity + 7. entities.SPHEntity + 8. entities.Tool + ... + +> search force field + +Search results for 'force field' (1 total): + 1. scene.ForceField (scene) + ForceField 是所有力场的基类,用于在模拟中对物体施加各种类型的力(实际上是加速度场)。 + +> get ForceField + +=== ForceField === +Category: scene + +Summary: + ForceField 是所有力场的基类,用于在模拟中对物体施加各种类型的力(实际上是加速度场)。 + +Inheritance: + ForceField + ├── Constant + ├── Wind + ├── Point + ├── Drag + ├── Noise + ├── Vortex + ├── Turbulence + └── Custom + +Parameters: + - direction (Vector): 力场的方向向量,必须是归一化的三维向量 + - strength (float): 力场的强度(加速度值,单位:m/s²) + - active (bool): 力场是否激活,默认为True + +Code Examples: + Example 1: + ```python + import genesis as gs + + # 创建场景 + scene = gs.Scene() + + # 添加一个球体 + sphere = gs.primitives.Sphere(position=(0, 0, 1)) + scene.add_entity(sphere) + + # 创建并添加恒定力场(恒定加速度) + constant_force = gs.force_fields.Constant(direction=(1, 0, 0), strength=5.0) + scene.add_force_field(constant_force) + + # 构建并运行场景 + scene.build() + for _ in range(100): + scene.step() + ``` +``` + +### Programmatic Usage + +You can also use the agent programmatically: + +```python +from genesis_api_agent import GenesisAPIAgent + +# Initialize the agent +agent = GenesisAPIAgent() + +# List all categories +categories = agent.knowledge_base.keys() + +# Search for APIs +results = agent.search("force field") + +# Get detailed API info +api_info = agent.get_api_info("ForceField") + +# Export knowledge base to JSON +agent.export_knowledge_base("genesis_api_knowledge_base.json") +``` + +## Knowledge Base Structure + +The agent builds a structured knowledge base with the following information for each API: + +- **Title**: API name and title +- **Summary**: Brief description of the API +- **Inheritance**: Class inheritance hierarchy +- **Parameters**: List of parameters with types and descriptions +- **Code Examples**: Usage examples in Python +- **File Path**: Location of the source documentation + +## Extending the Agent + +You can extend the agent by adding new features: + +1. **NLP Integration**: Add natural language processing for better query handling +2. **Web Interface**: Create a web-based UI for the agent +3. **Additional Formats**: Support for exporting to other formats (HTML, PDF) +4. **Live Updates**: Add functionality to update the knowledge base dynamically + +## License + +This project is open source and available under the MIT License. diff --git a/genesis_api_agent.py b/genesis_api_agent.py new file mode 100644 index 0000000..ab0f67a --- /dev/null +++ b/genesis_api_agent.py @@ -0,0 +1,526 @@ +#!/usr/bin/env python3 +""" +Genesis API Reference Agent + +This agent integrates all API documentation from the api_reference directory +and provides a convenient interface for users to query and access API information. +""" + +import os +import re +import glob +from typing import Dict, List, Any, Optional +import json + +class GenesisAPIAgent: + """ + Genesis API Reference Agent that loads and processes all API documentation. + """ + + def __init__(self, docs_path: str = "source/api_reference"): + """ + Initialize the agent and load all documentation. + + Args: + docs_path: Path to the API reference documentation + """ + self.docs_path = docs_path + self.knowledge_base: Dict[str, Any] = { + "entities": {}, + "materials": {}, + "options": {}, + "scene": {}, + "sensor": {}, + "solvers": {}, + "boundaries": {}, + "couplers": {}, + "states": {} + } + self.documents: List[Dict[str, Any]] = [] + + # Load all documentation + self._load_documents() + + # Build knowledge base + self._build_knowledge_base() + + def _load_documents(self) -> None: + """ + Load all Markdown documents from the api_reference directory. + """ + md_files = glob.glob(os.path.join(self.docs_path, "**/*.md"), recursive=True) + + # Map directory names to knowledge base categories + category_map = { + "entity": "entities", + "material": "materials", + "options": "options", + "scene": "scene", + "sensor": "sensor", + "solvers": "solvers", + "boundaries": "boundaries", + "couplers": "couplers", + "states": "states" + } + + for md_file in md_files: + relative_path = os.path.relpath(md_file, self.docs_path) + dir_name = relative_path.split(os.sep)[0] + + # Map directory name to category + category = category_map.get(dir_name, dir_name) + + with open(md_file, "r", encoding="utf-8") as f: + content = f.read() + + document = { + "file_path": md_file, + "relative_path": relative_path, + "category": category, + "content": content, + "title": self._extract_title(content) + } + + self.documents.append(document) + + def _extract_title(self, content: str) -> Optional[str]: + """ + Extract the title from Markdown content. + + Args: + content: Markdown content + + Returns: + Extracted title or None if not found + """ + match = re.match(r"^#\s+(.*)$", content, re.MULTILINE) + if match: + return match.group(1).strip() + return None + + def _build_knowledge_base(self) -> None: + """ + Build a structured knowledge base from the loaded documents. + """ + for doc in self.documents: + category = doc["category"] + title = doc["title"] + + if not title: + continue + + # Extract API name from title (remove backticks if present) + api_name = title.strip("`") + + # Extract summary + summary = self._extract_summary(doc["content"]) + + # Extract code examples + examples = self._extract_code_examples(doc["content"]) + + # Extract parameters + parameters = self._extract_parameters(doc["content"]) + + # Extract inheritance + inheritance = self._extract_inheritance(doc["content"]) + + # Store in knowledge base + if category in self.knowledge_base: + self.knowledge_base[category][api_name] = { + "title": title, + "summary": summary, + "examples": examples, + "parameters": parameters, + "inheritance": inheritance, + "file_path": doc["file_path"], + "relative_path": doc["relative_path"], + "content": doc["content"] + } + + def _extract_summary(self, content: str) -> Optional[str]: + """ + Extract summary from document content. + + Args: + content: Markdown content + + Returns: + Extracted summary or None if not found + """ + lines = content.split("\n") + summary_lines = [] + in_summary = False + + for line in lines: + stripped_line = line.strip() + + # Look for overview section + if stripped_line.startswith("## 概述") or stripped_line.startswith("## Overview"): + in_summary = True + continue + + # Stop at the next heading or code block + if in_summary: + if stripped_line.startswith("##") or stripped_line.startswith("```"): + break + if stripped_line: + summary_lines.append(stripped_line) + + # If no overview section found, try fallback to description after title + if not summary_lines: + in_fallback = False + for line in lines: + stripped_line = line.strip() + + # Start after the title + if stripped_line.startswith("#") and not in_fallback: + in_fallback = True + continue + + # Stop at the next heading or code block + if in_fallback: + if stripped_line.startswith("##") or stripped_line.startswith("```"): + break + if stripped_line: + summary_lines.append(stripped_line) + + if summary_lines: + return " ".join(summary_lines) + return None + + def _extract_code_examples(self, content: str) -> List[str]: + """ + Extract code examples from document content. + + Args: + content: Markdown content + + Returns: + List of code examples + """ + examples = [] + code_blocks = re.findall(r"```python(.*?)```", content, re.DOTALL) + + for block in code_blocks: + examples.append(block.strip()) + + return examples + + def _extract_parameters(self, content: str) -> List[Dict[str, str]]: + """ + Extract parameters from document content. + + Args: + content: Markdown content + + Returns: + List of parameter dictionaries + """ + parameters = [] + + # Look for parameter tables + table_pattern = r"##.*参数.*\n(.*?)\n(?:##|```|$)" + matches = re.findall(table_pattern, content, re.DOTALL) + + for table_content in matches: + # Parse table + lines = table_content.strip().split("\n") + if len(lines) < 3: + continue + + # Skip header and separator lines + for line in lines[2:]: + if not line.strip(): + continue + + # Split by pipe, ignoring leading/trailing pipes + parts = [p.strip() for p in line.strip("|").split("|")] + if len(parts) >= 3: + parameter = { + "name": parts[0], + "type": parts[1], + "description": parts[2] + } + parameters.append(parameter) + + return parameters + + def _extract_inheritance(self, content: str) -> Optional[str]: + """ + Extract inheritance information from document content. + + Args: + content: Markdown content + + Returns: + Extracted inheritance string or None if not found + """ + inheritance_pattern = r"##.*继承关系.*\n```\n(.*?)```" + match = re.search(inheritance_pattern, content, re.DOTALL) + + if match: + return match.group(1).strip() + return None + + def search(self, query: str, category: Optional[str] = None) -> List[Dict[str, Any]]: + """ + Search for API information based on query. + + Args: + query: Search query + category: Optional category filter (entities, materials, options, scene, sensor) + + Returns: + List of matching API entries + """ + results = [] + query_lower = query.lower() + + # Determine which categories to search + categories_to_search = [category] if category else self.knowledge_base.keys() + + for cat in categories_to_search: + if cat not in self.knowledge_base: + continue + + for api_name, api_info in self.knowledge_base[cat].items(): + # Search in title, summary, parameters + if (query_lower in api_name.lower() or + (api_info["summary"] and query_lower in api_info["summary"].lower()) or + any(query_lower in p["name"].lower() for p in api_info["parameters"])): + + results.append({ + "category": cat, + "api_name": api_name, + "title": api_info["title"], + "summary": api_info["summary"], + "parameters": api_info["parameters"], + "inheritance": api_info["inheritance"], + "file_path": api_info["file_path"] + }) + + return results + + def get_api_info(self, api_name: str, category: Optional[str] = None) -> Optional[Dict[str, Any]]: + """ + Get detailed information about a specific API. + + Args: + api_name: Name of the API to retrieve + category: Optional category filter + + Returns: + API information dictionary or None if not found + """ + api_name_lower = api_name.lower() + + # Determine which categories to search + categories_to_search = [category] if category else self.knowledge_base.keys() + + for cat in categories_to_search: + if cat not in self.knowledge_base: + continue + + for name, info in self.knowledge_base[cat].items(): + if api_name_lower == name.lower() or api_name_lower == info["title"].strip("`").lower(): + return { + "category": cat, + "api_name": name, + **info + } + + return None + + def list_apis(self, category: Optional[str] = None) -> List[str]: + """ + List all APIs in the knowledge base. + + Args: + category: Optional category filter + + Returns: + List of API names + """ + apis = [] + + categories_to_list = [category] if category else self.knowledge_base.keys() + + for cat in categories_to_list: + if cat not in self.knowledge_base: + continue + + for api_name in self.knowledge_base[cat].keys(): + apis.append(f"{cat}.{api_name}") + + return apis + + def export_knowledge_base(self, output_path: str = "genesis_api_knowledge_base.json") -> None: + """ + Export the knowledge base to a JSON file. + + Args: + output_path: Path to the output JSON file + """ + with open(output_path, "w", encoding="utf-8") as f: + json.dump(self.knowledge_base, f, indent=2, ensure_ascii=False) + + def interactive_mode(self) -> None: + """ + Start interactive mode for user queries. + """ + print("\n=== Genesis API Reference Agent ===") + print("Type 'help' for available commands, 'exit' to quit.") + print("=" * 50) + + while True: + try: + user_input = input("\n> ").strip() + + if user_input.lower() == "exit": + print("Goodbye!") + break + + elif user_input.lower() == "help": + self._show_help() + + elif user_input.lower().startswith("list"): + parts = user_input.split() + category = parts[1] if len(parts) > 1 else None + self._list_apis(category) + + elif user_input.lower().startswith("search"): + query = user_input[7:].strip() + if query: + self._search(query) + else: + print("Please provide a search query.") + + elif user_input.lower().startswith("get"): + api_name = user_input[4:].strip() + if api_name: + self._get_api_info(api_name) + else: + print("Please provide an API name.") + + elif user_input.lower() == "categories": + self._list_categories() + + else: + # Treat as natural language query + self._natural_language_query(user_input) + + except KeyboardInterrupt: + print("\nGoodbye!") + break + except Exception as e: + print(f"Error: {e}") + + def _show_help(self) -> None: + """ + Show help information. + """ + print("\nAvailable commands:") + print(" help - Show this help message") + print(" exit - Exit the agent") + print(" categories - List all categories") + print(" list [category] - List all APIs (optionally filtered by category)") + print(" search - Search for APIs matching query") + print(" get - Get detailed information about an API") + print(" - Ask a question about the API") + + def _list_categories(self) -> None: + """ + List all categories. + """ + print("\nCategories:") + for category in self.knowledge_base.keys(): + count = len(self.knowledge_base[category]) + print(f" - {category}: {count} APIs") + + def _list_apis(self, category: Optional[str] = None) -> None: + """ + List APIs in interactive mode. + """ + apis = self.list_apis(category) + + if not apis: + print("No APIs found.") + return + + print(f"\nAPIs ({len(apis)} total):") + for i, api in enumerate(apis, 1): + print(f" {i}. {api}") + + def _search(self, query: str) -> None: + """ + Search APIs in interactive mode. + """ + results = self.search(query) + + if not results: + print("No results found.") + return + + print(f"\nSearch results for '{query}' ({len(results)} total):") + for i, result in enumerate(results, 1): + print(f" {i}. {result['api_name']} ({result['category']})") + if result['summary']: + print(f" {result['summary'][:100]}...") + + def _get_api_info(self, api_name: str) -> None: + """ + Get API info in interactive mode. + """ + api_info = self.get_api_info(api_name) + + if not api_info: + print(f"API '{api_name}' not found.") + return + + print(f"\n=== {api_info['title']} ===") + print(f"Category: {api_info['category']}") + + if api_info['summary']: + print(f"\nSummary:") + print(f" {api_info['summary']}") + + if api_info['inheritance']: + print(f"\nInheritance:") + print(f" {api_info['inheritance']}") + + if api_info['parameters']: + print(f"\nParameters:") + for param in api_info['parameters']: + print(f" - {param['name']} ({param['type']}): {param['description']}") + + if api_info['examples']: + print(f"\nCode Examples:") + for i, example in enumerate(api_info['examples'], 1): + print(f" Example {i}:") + print(f" ```python") + print(f"{example[:200]}...") # Show first 200 chars + print(f" ```") + + def _natural_language_query(self, query: str) -> None: + """ + Handle natural language queries. + + Args: + query: Natural language query + """ + # Simple implementation for now - can be enhanced with NLP + print("\nNatural language query handling is not fully implemented yet.") + print("Please use the 'search' or 'get' commands for more precise results.") + + # Fallback to search + self._search(query) + +def main(): + """ + Main function to run the agent. + """ + agent = GenesisAPIAgent() + agent.interactive_mode() + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt index c1d52bf..a382783 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,7 +15,7 @@ sphinx-togglebutton sphinx_design psutil scikit-image -taichi == 1.7.2 +gstaichi pydantic == 2.7.1 numpy == 1.26.4 six @@ -27,7 +27,6 @@ pygltflib mujoco pycollada opencv-python -lxml tetgen screeninfo PyGEL3D diff --git a/source/_static/images/.DS_Store b/source/_static/images/.DS_Store deleted file mode 100644 index 5008ddf..0000000 Binary files a/source/_static/images/.DS_Store and /dev/null differ diff --git a/source/_static/images/contact_force_sensor.png b/source/_static/images/contact_force_sensor.png new file mode 100644 index 0000000..f1f0dbf Binary files /dev/null and b/source/_static/images/contact_force_sensor.png differ diff --git a/source/_static/images/hover_curve.png b/source/_static/images/hover_curve.png new file mode 100644 index 0000000..bf6cef9 Binary files /dev/null and b/source/_static/images/hover_curve.png differ diff --git a/source/_static/images/local_global_indexing.png b/source/_static/images/local_global_indexing.png new file mode 100644 index 0000000..716b951 Binary files /dev/null and b/source/_static/images/local_global_indexing.png differ diff --git a/source/_static/images/manipulation_curve.png b/source/_static/images/manipulation_curve.png new file mode 100644 index 0000000..72fb568 Binary files /dev/null and b/source/_static/images/manipulation_curve.png differ diff --git a/source/_static/images/overview.png b/source/_static/images/overview.png new file mode 100644 index 0000000..77d1cfb Binary files /dev/null and b/source/_static/images/overview.png differ diff --git a/source/_static/videos/batched_IK.mp4 b/source/_static/images/training.gif similarity index 50% rename from source/_static/videos/batched_IK.mp4 rename to source/_static/images/training.gif index 3e6e7b8..3a32a24 100644 Binary files a/source/_static/videos/batched_IK.mp4 and b/source/_static/images/training.gif differ diff --git a/source/_static/videos/depth_camera.mp4 b/source/_static/videos/depth_camera.mp4 new file mode 100644 index 0000000..94a49c2 Binary files /dev/null and b/source/_static/videos/depth_camera.mp4 differ diff --git a/source/_static/videos/hover_env.mp4 b/source/_static/videos/hover_env.mp4 new file mode 100644 index 0000000..7ec133e Binary files /dev/null and b/source/_static/videos/hover_env.mp4 differ diff --git a/source/_static/videos/imu.mp4 b/source/_static/videos/imu.mp4 new file mode 100644 index 0000000..cc00afe Binary files /dev/null and b/source/_static/videos/imu.mp4 differ diff --git a/source/_static/videos/manipulation_rl.mp4 b/source/_static/videos/manipulation_rl.mp4 new file mode 100644 index 0000000..3022475 Binary files /dev/null and b/source/_static/videos/manipulation_rl.mp4 differ diff --git a/source/_static/videos/manipulation_stereo.mp4 b/source/_static/videos/manipulation_stereo.mp4 new file mode 100644 index 0000000..fd2c99e Binary files /dev/null and b/source/_static/videos/manipulation_stereo.mp4 differ diff --git a/source/_static/videos/tactile_fingertips.mp4 b/source/_static/videos/tactile_fingertips.mp4 new file mode 100644 index 0000000..0187c10 Binary files /dev/null and b/source/_static/videos/tactile_fingertips.mp4 differ diff --git a/source/api_reference/boundaries/base_boundary.md b/source/api_reference/boundaries/base_boundary.md new file mode 100644 index 0000000..bd3813f --- /dev/null +++ b/source/api_reference/boundaries/base_boundary.md @@ -0,0 +1,52 @@ +# BaseBoundary + +`BaseBoundary` 是 Genesis 引擎中所有边界的基类,定义了边界的核心接口和生命周期管理。它为不同类型的边界提供了统一的架构和行为模式。 + +## 功能说明 + +`BaseBoundary` 类提供了以下核心功能: + +- 边界的基本身份标识和配置 +- 边界的几何描述和位置管理 +- 边界与实体的交互接口 +- 边界的生命周期管理 +- 与求解器的通信机制 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 边界在系统中的唯一索引 | +| `uid` | `int` | 边界的全局唯一标识符 | +| `name` | `str` | 边界的名称 | +| `type` | `str` | 边界类型(如 "rigid", "particle", "fluid" 等) | +| `position` | `vector` | 边界位置 | +| `rotation` | `quaternion` | 边界旋转 | +| `scale` | `vector` | 边界缩放 | +| `is_built` | `bool` | 边界是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建边界,初始化数据结构 | +| `update()` | 无 | `None` | 更新边界状态 | +| `reset()` | 无 | `None` | 重置边界到初始状态 | +| `check_collision()` | `Entity` | `bool` | 检查与实体的碰撞 | +| `resolve_collision()` | `Entity` | `None` | 处理与实体的碰撞响应 | + +## 继承关系 + +``` +BaseBoundary +├── RigidBoundary +├── ParticleBoundary +└── FluidBoundary +``` + +```{eval-rst} +.. autoclass:: genesis.engine.boundaries.base_boundary.BaseBoundary + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/boundaries/fluid_boundary.md b/source/api_reference/boundaries/fluid_boundary.md new file mode 100644 index 0000000..0b3d680 --- /dev/null +++ b/source/api_reference/boundaries/fluid_boundary.md @@ -0,0 +1,54 @@ +# FluidBoundary + +`FluidBoundary` 是 Genesis 引擎中用于定义流体模拟边界的类,用于处理流体与环境的交互和边界条件。 + +## 功能说明 + +`FluidBoundary` 类提供了以下核心功能: + +- 流体模拟的边界定义 +- 流体与边界的交互处理 +- 边界条件设置(如无滑移、自由表面等) +- 边界的几何形状配置 +- 流体边界的物理属性设置 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 边界在系统中的唯一索引 | +| `uid` | `int` | 边界的全局唯一标识符 | +| `name` | `str` | 边界的名称 | +| `type` | `str` | 边界类型,固定为 "fluid" | +| `position` | `vector` | 边界位置 | +| `rotation` | `quaternion` | 边界旋转 | +| `scale` | `vector` | 边界缩放 | +| `geometry_type` | `str` | 几何类型(如 "box", "cylinder", "custom" 等) | +| `boundary_condition` | `str` | 边界条件(如 "no_slip", "free_slip", "inflow", "outflow" 等) | +| `velocity` | `vector` | 边界速度(用于流入/流出条件) | +| `is_built` | `bool` | 边界是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建流体边界,初始化几何和边界条件 | +| `update()` | 无 | `None` | 更新边界状态 | +| `reset()` | 无 | `None` | 重置边界到初始状态 | +| `set_boundary_condition()` | `str` | `None` | 设置边界条件类型 | +| `set_inflow_velocity()` | `vector` | `None` | 设置流入边界速度 | +| `set_outflow_pressure()` | `float` | `None` | 设置流出边界压力 | + +## 继承关系 + +``` +BaseBoundary +└── FluidBoundary +``` + +```{eval-rst} +.. autoclass:: genesis.engine.boundaries.fluid_boundary.FluidBoundary + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/boundaries/index.md b/source/api_reference/boundaries/index.md new file mode 100644 index 0000000..9c4a196 --- /dev/null +++ b/source/api_reference/boundaries/index.md @@ -0,0 +1,25 @@ +# Boundaries + +Boundary 是 Genesis 引擎中用于定义物理模拟边界条件的组件,它限制了实体的运动范围并处理与环境的交互。边界可以是静态的,也可以是动态的,用于模拟墙壁、地面、容器等物理环境。 + +## 边界类型 + +Genesis 引擎支持多种边界类型,每种类型适用于不同的物理场景: + +- **刚性边界**:用于模拟不可变形的边界,如墙壁、地面 +- **动态边界**:用于模拟可移动的边界,如门、活塞 +- **粒子边界**:用于粒子系统的边界条件 +- **流体边界**:用于流体模拟的特殊边界条件 + +## 边界架构 + +所有边界都继承自统一的 `Boundary` 基类,提供一致的接口和生命周期管理。边界与求解器之间通过明确的接口进行通信,实现了边界与求解器的解耦。 + +```{toctree} +:maxdepth: 2 + +base_boundary +rigid_boundary +particle_boundary +fluid_boundary +``` diff --git a/source/api_reference/boundaries/particle_boundary.md b/source/api_reference/boundaries/particle_boundary.md new file mode 100644 index 0000000..8cb5433 --- /dev/null +++ b/source/api_reference/boundaries/particle_boundary.md @@ -0,0 +1,52 @@ +# ParticleBoundary + +`ParticleBoundary` 是 Genesis 引擎中用于定义粒子系统边界的类,用于限制粒子的运动范围并处理粒子与边界的交互。 + +## 功能说明 + +`ParticleBoundary` 类提供了以下核心功能: + +- 粒子系统的边界定义 +- 粒子与边界的碰撞检测和响应 +- 边界的几何形状配置 +- 粒子边界条件设置 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 边界在系统中的唯一索引 | +| `uid` | `int` | 边界的全局唯一标识符 | +| `name` | `str` | 边界的名称 | +| `type` | `str` | 边界类型,固定为 "particle" | +| `position` | `vector` | 边界位置 | +| `rotation` | `quaternion` | 边界旋转 | +| `scale` | `vector` | 边界缩放 | +| `geometry_type` | `str` | 几何类型(如 "box", "sphere", "cylinder" 等) | +| `boundary_condition` | `str` | 边界条件(如 "reflective", "absorbing", "periodic" 等) | +| `is_built` | `bool` | 边界是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建粒子边界,初始化几何和边界条件 | +| `update()` | 无 | `None` | 更新边界状态 | +| `reset()` | 无 | `None` | 重置边界到初始状态 | +| `set_boundary_condition()` | `str` | `None` | 设置边界条件类型 | +| `check_particle_collision()` | `array` | `array` | 检查粒子与边界的碰撞 | +| `resolve_particle_collision()` | `array, array` | `None` | 处理粒子与边界的碰撞响应 | + +## 继承关系 + +``` +BaseBoundary +└── ParticleBoundary +``` + +```{eval-rst} +.. autoclass:: genesis.engine.boundaries.particle_boundary.ParticleBoundary + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/boundaries/rigid_boundary.md b/source/api_reference/boundaries/rigid_boundary.md new file mode 100644 index 0000000..bda252a --- /dev/null +++ b/source/api_reference/boundaries/rigid_boundary.md @@ -0,0 +1,53 @@ +# RigidBoundary + +`RigidBoundary` 是 Genesis 引擎中用于定义刚性边界的类,用于模拟不可变形的物理边界,如墙壁、地面、容器等。 + +## 功能说明 + +`RigidBoundary` 类提供了以下核心功能: + +- 刚性边界的几何定义(如平面、盒子、球体等) +- 边界的物理属性配置 +- 与刚体和变形体的碰撞检测和响应 +- 边界运动和变换管理 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 边界在系统中的唯一索引 | +| `uid` | `int` | 边界的全局唯一标识符 | +| `name` | `str` | 边界的名称 | +| `type` | `str` | 边界类型,固定为 "rigid" | +| `position` | `vector` | 边界位置 | +| `rotation` | `quaternion` | 边界旋转 | +| `scale` | `vector` | 边界缩放 | +| `geometry_type` | `str` | 几何类型(如 "plane", "box", "sphere" 等) | +| `friction` | `float` | 边界摩擦系数 | +| `restitution` | `float` | 边界弹性恢复系数 | +| `is_built` | `bool` | 边界是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建刚性边界,初始化几何和物理属性 | +| `update()` | 无 | `None` | 更新边界状态 | +| `reset()` | 无 | `None` | 重置边界到初始状态 | +| `set_geometry()` | `str, dict` | `None` | 设置边界几何类型和参数 | +| `move()` | `vector` | `None` | 移动边界到指定位置 | +| `rotate()` | `quaternion` | `None` | 旋转边界到指定姿态 | + +## 继承关系 + +``` +BaseBoundary +└── RigidBoundary +``` + +```{eval-rst} +.. autoclass:: genesis.engine.boundaries.rigid_boundary.RigidBoundary + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/camera/camera.md b/source/api_reference/camera/camera.md deleted file mode 100644 index dfa4e82..0000000 --- a/source/api_reference/camera/camera.md +++ /dev/null @@ -1,8 +0,0 @@ -# `Camera` - -```{eval-rst} -.. automodule:: genesis.vis.camera - :members: - :show-inheritance: - :undoc-members: -``` diff --git a/source/api_reference/couplers/base_coupler.md b/source/api_reference/couplers/base_coupler.md new file mode 100644 index 0000000..2f8e476 --- /dev/null +++ b/source/api_reference/couplers/base_coupler.md @@ -0,0 +1,54 @@ +# BaseCoupler + +`BaseCoupler` 是 Genesis 引擎中所有耦合器的基类,定义了耦合器的核心接口和生命周期管理。它为不同类型的耦合器提供了统一的架构和行为模式。 + +## 功能说明 + +`BaseCoupler` 类提供了以下核心功能: + +- 耦合器的基本身份标识和配置 +- 耦合器与求解器的连接管理 +- 系统间数据交换机制 +- 耦合器的生命周期管理 +- 统一的耦合求解接口 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 耦合器在系统中的唯一索引 | +| `uid` | `int` | 耦合器的全局唯一标识符 | +| `name` | `str` | 耦合器的名称 | +| `type` | `str` | 耦合器类型(如 "sap", "mpm_pbd", "fem_rigid" 等) | +| `solver1` | `Solver` | 第一个连接的求解器 | +| `solver2` | `Solver` | 第二个连接的求解器 | +| `iterations` | `int` | 耦合迭代次数 | +| `is_built` | `bool` | 耦合器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建耦合器,初始化连接和数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的耦合模拟 | +| `reset()` | 无 | `None` | 重置耦合器到初始状态 | +| `connect_solvers()` | `Solver, Solver` | `None` | 连接两个求解器 | +| `exchange_data()` | 无 | `None` | 在连接的求解器之间交换数据 | +| `solve_coupling()` | 无 | `None` | 求解系统间的耦合 | + +## 继承关系 + +``` +BaseCoupler +├── SAPCoupler +├── MPMPBDCoupler +├── MPMSPHCoupler +└── FEMRigidCoupler +``` + +```{eval-rst} +.. autoclass:: genesis.engine.couplers.base_coupler.BaseCoupler + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/couplers/fem_rigid_coupler.md b/source/api_reference/couplers/fem_rigid_coupler.md new file mode 100644 index 0000000..9eadd62 --- /dev/null +++ b/source/api_reference/couplers/fem_rigid_coupler.md @@ -0,0 +1,52 @@ +# FEMRigidCoupler + +`FEMRigidCoupler` 是 FEM(Finite Element Method)与 Rigid Body 系统之间的耦合器,用于处理 FEM 弹性体与刚体之间的碰撞和交互。 + +## 功能说明 + +`FEMRigidCoupler` 类提供了以下核心功能: + +- FEM 与刚体系统的碰撞检测和响应 +- 有限元网格与刚体几何之间的交互 +- 接触力计算和传递 +- 支持弹性体与刚体的复杂交互 +- 可调节的耦合参数 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 耦合器在系统中的唯一索引 | +| `uid` | `int` | 耦合器的全局唯一标识符 | +| `name` | `str` | 耦合器的名称 | +| `type` | `str` | 耦合器类型,固定为 "fem_rigid" | +| `fem_solver` | `FEMSolver` | FEM 求解器 | +| `rigid_solver` | `RigidSolver` | 刚体求解器 | +| `iterations` | `int` | 耦合迭代次数 | +| `friction` | `float` | 碰撞摩擦系数 | +| `restitution` | `float` | 碰撞弹性恢复系数 | +| `is_built` | `bool` | 耦合器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 FEM-Rigid 耦合器,初始化连接和数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 FEM-Rigid 耦合模拟 | +| `reset()` | 无 | `None` | 重置耦合器到初始状态 | +| `detect_collisions()` | 无 | `list` | 检测 FEM 与刚体系统之间的碰撞 | +| `solve_contacts()` | `list` | `None` | 求解碰撞接触点和接触力 | + +## 继承关系 + +``` +BaseCoupler +└── FEMRigidCoupler +``` + +```{eval-rst} +.. autoclass:: genesis.engine.couplers.fem_rigid_coupler.FEMRigidCoupler + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/couplers/index.md b/source/api_reference/couplers/index.md new file mode 100644 index 0000000..4398b6d --- /dev/null +++ b/source/api_reference/couplers/index.md @@ -0,0 +1,27 @@ +# Couplers + +Coupler 是 Genesis 引擎中用于连接不同物理系统或求解器的组件,负责处理不同系统之间的相互作用和数据交换。耦合器实现了多物理场模拟和混合求解器系统。 + +## 耦合器类型 + +Genesis 引擎支持多种耦合器,用于不同类型的物理系统之间的交互: + +- **SAP 耦合器**:用于刚体与其他系统的耦合 +- **MPM-PBD 耦合器**:用于 MPM 与 PBD 系统的耦合 +- **MPM-SPH 耦合器**:用于 MPM 与 SPH 系统的耦合 +- **FEM-Rigid 耦合器**:用于 FEM 与刚体系统的耦合 +- **通用耦合器**:用于自定义系统间的耦合 + +## 耦合器架构 + +所有耦合器都继承自统一的 `Coupler` 基类,提供一致的接口和生命周期管理。耦合器与求解器之间通过明确的接口进行通信,实现了不同物理系统之间的解耦和集成。 + +```{toctree} +:maxdepth: 2 + +base_coupler +sap_coupler +mpm_pbd_coupler +mpm_sph_coupler +fem_rigid_coupler +``` diff --git a/source/api_reference/couplers/mpm_pbd_coupler.md b/source/api_reference/couplers/mpm_pbd_coupler.md new file mode 100644 index 0000000..470465c --- /dev/null +++ b/source/api_reference/couplers/mpm_pbd_coupler.md @@ -0,0 +1,52 @@ +# MPMPBDCoupler + +`MPMPBDCoupler` 是 MPM(Material Point Method)与 PBD(Position Based Dynamics)系统之间的耦合器,用于处理 MPM 流体/固体与 PBD 布料/绳索等之间的交互。 + +## 功能说明 + +`MPMPBDCoupler` 类提供了以下核心功能: + +- MPM 与 PBD 系统的碰撞检测和响应 +- 两种不同物理求解方法之间的数据交换 +- 粒子与网格之间的交互处理 +- 支持流体与布料、流体与绳索等复杂交互 +- 可调节的耦合参数 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 耦合器在系统中的唯一索引 | +| `uid` | `int` | 耦合器的全局唯一标识符 | +| `name` | `str` | 耦合器的名称 | +| `type` | `str` | 耦合器类型,固定为 "mpm_pbd" | +| `mpm_solver` | `MPMSolver` | MPM 求解器 | +| `pbd_solver` | `PBDSolver` | PBD 求解器 | +| `iterations` | `int` | 耦合迭代次数 | +| `damping` | `float` | 耦合阻尼系数 | +| `stiffness` | `float` | 耦合刚度系数 | +| `is_built` | `bool` | 耦合器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 MPM-PBD 耦合器,初始化连接和数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 MPM-PBD 耦合模拟 | +| `reset()` | 无 | `None` | 重置耦合器到初始状态 | +| `detect_collisions()` | 无 | `list` | 检测 MPM 与 PBD 系统之间的碰撞 | +| `solve_coupling()` | 无 | `None` | 求解 MPM-PBD 耦合 | + +## 继承关系 + +``` +BaseCoupler +└── MPMPBDCoupler +``` + +```{eval-rst} +.. autoclass:: genesis.engine.couplers.mpm_pbd_coupler.MPMPBDCoupler + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/couplers/mpm_sph_coupler.md b/source/api_reference/couplers/mpm_sph_coupler.md new file mode 100644 index 0000000..d320c1f --- /dev/null +++ b/source/api_reference/couplers/mpm_sph_coupler.md @@ -0,0 +1,52 @@ +# MPMSPHCoupler + +`MPMSPHCoupler` 是 MPM(Material Point Method)与 SPH(Smoothed Particle Hydrodynamics)系统之间的耦合器,用于处理 MPM 流体/固体与 SPH 流体之间的交互。 + +## 功能说明 + +`MPMSPHCoupler` 类提供了以下核心功能: + +- MPM 与 SPH 系统的碰撞检测和响应 +- 两种粒子方法之间的数据交换和交互 +- 不同粒子系统之间的混合模拟 +- 支持多种流体类型之间的交互 +- 可调节的耦合参数 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 耦合器在系统中的唯一索引 | +| `uid` | `int` | 耦合器的全局唯一标识符 | +| `name` | `str` | 耦合器的名称 | +| `type` | `str` | 耦合器类型,固定为 "mpm_sph" | +| `mpm_solver` | `MPMSolver` | MPM 求解器 | +| `sph_solver` | `SPHSolver` | SPH 求解器 | +| `iterations` | `int` | 耦合迭代次数 | +| `smoothing_length` | `float` | 粒子平滑长度 | +| `coupling_strength` | `float` | 耦合强度 | +| `is_built` | `bool` | 耦合器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 MPM-SPH 耦合器,初始化连接和数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 MPM-SPH 耦合模拟 | +| `reset()` | 无 | `None` | 重置耦合器到初始状态 | +| `detect_collisions()` | 无 | `list` | 检测 MPM 与 SPH 系统之间的碰撞 | +| `solve_coupling()` | 无 | `None` | 求解 MPM-SPH 耦合 | + +## 继承关系 + +``` +BaseCoupler +└── MPMSPHCoupler +``` + +```{eval-rst} +.. autoclass:: genesis.engine.couplers.mpm_sph_coupler.MPMSPHCoupler + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/couplers/sap_coupler.md b/source/api_reference/couplers/sap_coupler.md new file mode 100644 index 0000000..6aef807 --- /dev/null +++ b/source/api_reference/couplers/sap_coupler.md @@ -0,0 +1,53 @@ +# SAPCoupler + +`SAPCoupler` 是分离轴原理(Separating Axis Principle)耦合器,用于处理刚体与其他物理系统之间的碰撞和交互。它是 Genesis 引擎中最常用的耦合器之一。 + +## 功能说明 + +`SAPCoupler` 类提供了以下核心功能: + +- 刚体与其他系统(如 MPM、PBD、FEM 等)的碰撞检测 +- 分离轴原理的高效碰撞检测算法 +- 碰撞响应和接触力计算 +- 支持多种几何形状的碰撞 +- 可调节的碰撞参数 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 耦合器在系统中的唯一索引 | +| `uid` | `int` | 耦合器的全局唯一标识符 | +| `name` | `str` | 耦合器的名称 | +| `type` | `str` | 耦合器类型,固定为 "sap" | +| `solver1` | `Solver` | 第一个连接的求解器(通常是刚体求解器) | +| `solver2` | `Solver` | 第二个连接的求解器 | +| `iterations` | `int` | 耦合迭代次数 | +| `friction` | `float` | 碰撞摩擦系数 | +| `restitution` | `float` | 碰撞弹性恢复系数 | +| `tolerance` | `float` | 碰撞检测公差 | +| `is_built` | `bool` | 耦合器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 SAP 耦合器,初始化碰撞检测数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 SAP 耦合模拟 | +| `reset()` | 无 | `None` | 重置耦合器到初始状态 | +| `detect_collisions()` | 无 | `list` | 检测刚体与其他系统之间的碰撞 | +| `solve_contacts()` | `list` | `None` | 求解碰撞接触点和接触力 | + +## 继承关系 + +``` +BaseCoupler +└── SAPCoupler +``` + +```{eval-rst} +.. autoclass:: genesis.engine.couplers.sap_coupler.SAPCoupler + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/avatar_entity/avatar_entity.md b/source/api_reference/entity/avatar_entity/avatar_entity.md new file mode 100644 index 0000000..3486da0 --- /dev/null +++ b/source/api_reference/entity/avatar_entity/avatar_entity.md @@ -0,0 +1,58 @@ +# `AvatarEntity` + +`AvatarEntity` 是 Genesis 中用于表示具有关节和链接结构的复杂实体(如人形机器人、动物等)的核心类。它提供了完整的骨骼动画、物理模拟和控制功能。 + +## 功能描述 + +`AvatarEntity` 实现了具有多个链接(Link)和关节(Joint)的骨架结构,支持正向运动学(FK)、逆向运动学(IK)、路径规划和力控制等高级功能。它可以用于模拟人物、动物或其他具有复杂运动结构的实体,并支持与其他物理实体的交互。 + +## 主要属性 + +- `links`: 实体的链接列表 +- `joints`: 实体的关节列表 +- `geoms`: 实体的几何形状列表(用于碰撞检测) +- `vgeoms`: 实体的可视化几何形状列表(用于渲染) +- `n_dofs`: 自由度数量 +- `q_start`, `q_end`: 位置状态的起始和结束索引 +- `init_qpos`: 初始关节位置 +- `material`: 实体材料属性 +- `surface`: 表面属性,用于渲染 + +## 核心功能 + +### 运动学控制 +- `forward_kinematics(qpos=None)`: 执行正向运动学计算 +- `inverse_kinematics(target_pos, target_quat=None, link_idx=None)`: 执行逆向运动学计算 +- `inverse_kinematics_multilink(targets)`: 执行多链接逆向运动学计算 + +### 关节控制 +- `control_dofs_position(dof_indices, target_positions, kp=None, kv=None)`: 位置控制 +- `control_dofs_velocity(dof_indices, target_velocities, kv=None)`: 速度控制 +- `control_dofs_force(dof_indices, forces)`: 力控制 +- `set_dofs_position(dof_indices, positions)`: 设置关节位置 +- `set_dofs_velocity(dof_indices, velocities)`: 设置关节速度 + +### 状态查询 +- `get_dofs_position(dof_indices=None)`: 获取关节位置 +- `get_dofs_velocity(dof_indices=None)`: 获取关节速度 +- `get_links_pos(link_indices=None)`: 获取链接位置 +- `get_links_quat(link_indices=None)`: 获取链接四元数 +- `get_links_vel(link_indices=None)`: 获取链接速度 + +### 碰撞检测 +- `detect_collision(other_entity)`: 检测与其他实体的碰撞 +- `get_contacts()`: 获取当前碰撞接触点 + +### 路径规划 +- `plan_path(start_qpos, goal_qpos)`: 规划关节空间路径 + + + scene.step() +``` + +```{eval-rst} +.. autoclass:: genesis.engine.entities.avatar_entity.avatar_entity.AvatarEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/avatar_entity/avatar_geom.md b/source/api_reference/entity/avatar_entity/avatar_geom.md new file mode 100644 index 0000000..9993311 --- /dev/null +++ b/source/api_reference/entity/avatar_entity/avatar_geom.md @@ -0,0 +1,36 @@ +# `AvatarGeom` + +`AvatarGeom` 是 Avatar 实体中用于碰撞检测的几何组件,类似于 RigidGeom,但仅用于碰撞检查。 + +## 功能描述 + +`AvatarGeom` 负责处理 Avatar 实体的碰撞几何形状,包括网格数据、碰撞属性和 SDF(有符号距离场)表示。它主要用于碰撞检测系统,确保 Avatar 实体与其他实体之间的物理交互正确计算。 + +## 主要属性 + +- `T_mesh_to_sdf`: 网格到 SDF 的变换矩阵 +- `contype`, `conaffinity`: 碰撞类型和亲和力参数,用于控制碰撞检测行为 +- `friction`: 摩擦系数 +- `coup_restitution`, `coup_softness`: 耦合恢复系数和柔软度 +- `init_pos`, `init_quat`: 初始位置和四元数 +- `mesh`: 几何网格数据 +- `sdf_val`, `sdf_grad`: SDF 值和梯度 +- `surface`: 表面属性,用于渲染 + +## 主要方法 + +- `get_AABB()`: 获取几何形状的轴对齐包围盒 +- `get_pos()`: 获取当前位置 +- `get_quat()`: 获取当前四元数 +- `get_trimesh()`: 获取三角网格表示 +- `get_verts()`: 获取顶点数据 +- `set_friction(value)`: 设置摩擦系数 +- `set_sol_params(restitution=None, softness=None)`: 设置求解参数 +- `visualize_sdf()`: 可视化 SDF 表示 + +```{eval-rst} +.. autoclass:: genesis.engine.entities.avatar_entity.avatar_geom.AvatarGeom + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/avatar_entity/avatar_joint.md b/source/api_reference/entity/avatar_entity/avatar_joint.md new file mode 100644 index 0000000..18a00f3 --- /dev/null +++ b/source/api_reference/entity/avatar_entity/avatar_joint.md @@ -0,0 +1,37 @@ +# `AvatarJoint` + +`AvatarJoint` 是 Avatar 实体中连接两个链接(Link)的关节组件,类似于 RigidJoint,但仅用于碰撞检查。 + +## 功能描述 + +`AvatarJoint` 定义了 Avatar 实体中两个链接之间的连接关系,包括关节类型、自由度、运动范围和物理属性。它主要用于碰撞检测系统,确保关节连接的正确性,并支持运动学计算。 + +## 主要属性 + +- `name`: 关节名称 +- `type`: 关节类型(如旋转关节、滑动关节等) +- `pos`, `quat`: 关节位置和四元数 +- `link`: 关节所属的链接 +- `dof_idx`, `dof_idx_local`: 自由度索引(全局和局部) +- `n_dofs`: 关节自由度数量 +- `dofs_limit`: 关节运动范围限制 +- `dofs_kp`, `dofs_kv`: 关节刚度和阻尼系数 +- `dofs_armature`: 关节电枢(转动惯量) +- `dofs_frictionloss`: 关节摩擦损失 +- `init_qpos`: 初始关节位置 + +## 主要方法 + +- `get_anchor_pos()`: 获取关节锚点位置 +- `get_anchor_axis()`: 获取关节轴方向 +- `get_pos()`: 获取关节位置 +- `get_quat()`: 获取关节四元数 +- `set_sol_params(restitution=None, softness=None)`: 设置求解参数 + + +```{eval-rst} +.. autoclass:: genesis.engine.entities.avatar_entity.avatar_joint.AvatarJoint + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/avatar_entity/avatar_link.md b/source/api_reference/entity/avatar_entity/avatar_link.md new file mode 100644 index 0000000..64975d2 --- /dev/null +++ b/source/api_reference/entity/avatar_entity/avatar_link.md @@ -0,0 +1,42 @@ +# `AvatarLink` + +`AvatarLink` 是 Avatar 实体中的链接组件,类似于 RigidLink,但使用 `AvatarGeom` 和 `AvatarVisGeom` 来处理碰撞和可视化。 + +## 功能描述 + +`AvatarLink` 代表 Avatar 实体中的一个刚性链接,是构成 Avatar 骨架结构的基本单元。每个链接可以包含多个几何形状(用于碰撞检测)和可视化几何形状(用于渲染),并具有质量、惯性等物理属性。链接之间通过关节(Joint)连接,形成完整的骨架结构。 + +## 主要属性 + +- `name`: 链接名称 +- `pos`, `quat`: 链接位置和四元数 +- `inertial_mass`: 链接质量 +- `inertial_pos`, `inertial_quat`: 惯性系位置和四元数 +- `inertial_i`: 惯性张量 +- `geoms`: 碰撞几何形状列表 +- `vgeoms`: 可视化几何形状列表 +- `joints`: 链接所属的关节列表 +- `parent_idx`, `child_idxs`: 父链接索引和子链接索引列表 +- `is_fixed`: 链接是否固定 +- `is_leaf`: 链接是否为叶节点 + +## 主要方法 + +- `get_pos()`: 获取链接位置 +- `get_quat()`: 获取链接四元数 +- `get_ang()`: 获取链接角速度 +- `get_vel()`: 获取链接线速度 +- `get_mass()`: 获取链接质量 +- `get_AABB()`: 获取链接的轴对齐包围盒 +- `get_verts()`: 获取碰撞几何形状的顶点 +- `get_vverts()`: 获取可视化几何形状的顶点 +- `set_friction(value)`: 设置摩擦系数 +- `set_mass(value)`: 设置链接质量 + + +```{eval-rst} +.. autoclass:: genesis.engine.entities.avatar_entity.avatar_link.AvatarLink + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/avatar_entity/index.md b/source/api_reference/entity/avatar_entity/index.md new file mode 100644 index 0000000..663cbe8 --- /dev/null +++ b/source/api_reference/entity/avatar_entity/index.md @@ -0,0 +1,8 @@ +# AvatarEntity + +```{toctree} +avatar_entity +avatar_link +avatar_joint +avatar_geom +``` \ No newline at end of file diff --git a/source/api_reference/entity/base_entity.md b/source/api_reference/entity/base_entity.md new file mode 100644 index 0000000..724d3ce --- /dev/null +++ b/source/api_reference/entity/base_entity.md @@ -0,0 +1,65 @@ +# BaseEntity + +`BaseEntity` 是 Genesis 引擎中所有实体类的基类,定义了所有实体共享的核心属性和方法。它为不同类型的实体(如刚体、变形体、流体等)提供了统一的接口和基础架构。 + +## 功能说明 + +`BaseEntity` 类提供了以下核心功能: + +- 实体的基本身份标识(idx、uid、name) +- 与场景和模拟器的关联 +- 物理求解器的连接 +- 材质和形态的管理 +- 实体构建和初始化机制 +- 统一的实体生命周期管理 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 实体在场景中的唯一索引 | +| `uid` | `int` | 实体的全局唯一标识符 | +| `name` | `str` | 实体的名称 | +| `scene` | `Scene` | 实体所属的场景对象 | +| `sim` | `Simulator` | 管理实体的模拟器对象 | +| `solver` | `Solver` | 处理实体物理模拟的求解器 | +| `material` | `Material` | 实体的物理材质属性 | +| `morph` | `Morph` | 实体的几何形态配置 | +| `surface` | `Surface` | 实体的渲染表面属性 | +| `is_built` | `bool` | 实体是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建实体,初始化物理属性和约束 | +| `update()` | 无 | `None` | 更新实体状态 | +| `reset()` | 无 | `None` | 重置实体到初始状态 | +| `remove()` | 无 | `None` | 从场景中移除实体 | + +## 继承关系 + +`BaseEntity` 是所有实体类的基类,以下是主要的继承关系: + +``` +BaseEntity +├── RigidEntity +├── AvatarEntity +├── MPMEntity +├── PBD2DEntity +├── PBD3DEntity +├── FEMEntity +├── SPHEntity +├── HybridEntity +├── Emitter +├── DroneEntity +├── ToolEntity +└── SFEntity +``` + +```{eval-rst} +.. autoclass:: genesis.engine.entities.base_entity.BaseEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/drone_entity.md b/source/api_reference/entity/drone_entity.md new file mode 100644 index 0000000..2ad78e1 --- /dev/null +++ b/source/api_reference/entity/drone_entity.md @@ -0,0 +1,31 @@ +# `DroneEntity` + +`DroneEntity` 是 Genesis 引擎中用于模拟无人机的实体类,提供了无人机的物理模拟和控制功能。 + +## 功能说明 + +- 模拟无人机的物理运动,包括位置、姿态、速度等 +- 支持无人机的控制输入,如油门、俯仰、滚转、偏航 +- 提供无人机状态获取和设置接口 +- 支持与其他实体的交互 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 实体在场景中的索引 | +| `uid` | int | 实体的唯一标识符 | +| `is_built` | bool | 实体是否已构建完成 | +| `scene` | Scene | 所属的场景对象 | +| `sim` | Simulator | 所属的模拟器对象 | +| `solver` | Solver | 处理该实体的求解器 | +| `material` | Material | 实体的材料属性 | +| `morph` | Morph | 实体的形态配置 | +| `surface` | Surface | 实体的表面约束或几何 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.drone_entity.DroneEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/emitter.md b/source/api_reference/entity/emitter.md new file mode 100644 index 0000000..027ad44 --- /dev/null +++ b/source/api_reference/entity/emitter.md @@ -0,0 +1,33 @@ +# `Emitter` + +`Emitter` 是 Genesis 引擎中用于发射粒子的实体类,可以创建和发射各种类型的粒子,用于模拟烟雾、火焰、流体等效果。 + +## 功能说明 + +- 支持各种类型粒子的发射,如流体粒子、烟雾粒子等 +- 可配置发射速率、方向、范围等参数 +- 支持动态调整发射属性 +- 可以与其他实体进行交互 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 实体在场景中的索引 | +| `uid` | int | 实体的唯一标识符 | +| `is_built` | bool | 实体是否已构建完成 | +| `scene` | Scene | 所属的场景对象 | +| `sim` | Simulator | 所属的模拟器对象 | +| `solver` | Solver | 处理该实体的求解器 | +| `material` | Material | 实体的材料属性 | +| `morph` | Morph | 实体的形态配置 | +| `surface` | Surface | 实体的表面约束或几何 | +| `emission_rate` | float | 粒子发射速率 | +| `emission_direction` | list | 粒子发射方向 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.emitter.Emitter + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/fem_entity.md b/source/api_reference/entity/fem_entity.md new file mode 100644 index 0000000..6c34554 --- /dev/null +++ b/source/api_reference/entity/fem_entity.md @@ -0,0 +1,33 @@ +# `FEMEntity` + +`FEMEntity` 是 Genesis 引擎中基于有限元法 (FEM) 的实体类,用于模拟可变形物体的物理行为,如布料、弹性体等。 + +## 功能说明 + +- 基于有限元法模拟物体的变形和应力分布 +- 支持各种材料模型,如线性弹性、非线性弹性等 +- 提供节点位置、速度、加速度等状态的获取和设置接口 +- 支持与其他实体的交互和碰撞 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 实体在场景中的索引 | +| `uid` | int | 实体的唯一标识符 | +| `is_built` | bool | 实体是否已构建完成 | +| `scene` | Scene | 所属的场景对象 | +| `sim` | Simulator | 所属的模拟器对象 | +| `solver` | Solver | 处理该实体的求解器 | +| `material` | Material | 实体的材料属性 | +| `morph` | Morph | 实体的形态配置 | +| `surface` | Surface | 实体的表面约束或几何 | +| `n_nodes` | int | 有限元网格的节点数量 | +| `n_elements` | int | 有限元网格的单元数量 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.fem_entity.FEMEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/hybrid_entity.md b/source/api_reference/entity/hybrid_entity.md new file mode 100644 index 0000000..0553f5b --- /dev/null +++ b/source/api_reference/entity/hybrid_entity.md @@ -0,0 +1,32 @@ +# `HybridEntity` + +`HybridEntity` 是 Genesis 引擎中用于模拟混合物理系统的实体类,它结合了多种物理模拟方法,如有限元法、粒子法等,用于模拟复杂的物理现象。 + +## 功能说明 + +- 结合多种物理模拟方法,提供更灵活的模拟能力 +- 支持不同物理模型之间的耦合和转换 +- 提供统一的接口来管理混合系统 +- 支持与其他实体的交互 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 实体在场景中的索引 | +| `uid` | int | 实体的唯一标识符 | +| `is_built` | bool | 实体是否已构建完成 | +| `scene` | Scene | 所属的场景对象 | +| `sim` | Simulator | 所属的模拟器对象 | +| `solver` | Solver | 处理该实体的求解器 | +| `material` | Material | 实体的材料属性 | +| `morph` | Morph | 实体的形态配置 | +| `surface` | Surface | 实体的表面约束或几何 | +| `n_components` | int | 混合系统的组件数量 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.hybrid_entity.HybridEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/index.md b/source/api_reference/entity/index.md index b6df163..cb2f2f2 100644 --- a/source/api_reference/entity/index.md +++ b/source/api_reference/entity/index.md @@ -1,5 +1,22 @@ # Entity +An `Entity` object is the abstraction of everything that requires physics simulation (except for rendering) in a scene. +This covers rigid-bodied or deformable objects, liquid, etc., simulated with different physics solvers such as MPM, PBD, etc. + ```{toctree} -rigidentity/index -``` \ No newline at end of file +:maxdepth: 2 + +base_entity +rigid_entity/index +avatar_entity/index +mpm_entity +pbd_entity/index +fem_entity +sph_entity +hybrid_entity +emitter +drone_entity +particle_entity +tool_entity/index +sf +``` diff --git a/source/api_reference/entity/mpm_entity.md b/source/api_reference/entity/mpm_entity.md new file mode 100644 index 0000000..897027b --- /dev/null +++ b/source/api_reference/entity/mpm_entity.md @@ -0,0 +1,33 @@ +# `MPMEntity` + +`MPMEntity` 是 Genesis 引擎中基于物质点法 (MPM) 的实体类,用于模拟各种复杂的可变形物体和流体,如沙子、水、塑料等。 + +## 功能说明 + +- 基于物质点法模拟连续介质的物理行为 +- 支持各种材料模型,如弹性体、塑性体、流体等 +- 提供粒子位置、速度、密度等状态的获取和设置接口 +- 支持大变形和复杂的物理交互 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 实体在场景中的索引 | +| `uid` | int | 实体的唯一标识符 | +| `is_built` | bool | 实体是否已构建完成 | +| `scene` | Scene | 所属的场景对象 | +| `sim` | Simulator | 所属的模拟器对象 | +| `solver` | Solver | 处理该实体的求解器 | +| `material` | Material | 实体的材料属性 | +| `morph` | Morph | 实体的形态配置 | +| `surface` | Surface | 实体的表面约束或几何 | +| `n_particles` | int | 物质点的数量 | +| `particle_size` | float | 每个物质点的大小 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.mpm_entity.MPMEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/particle_entity.md b/source/api_reference/entity/particle_entity.md new file mode 100644 index 0000000..c3d5070 --- /dev/null +++ b/source/api_reference/entity/particle_entity.md @@ -0,0 +1,56 @@ +# ParticleEntity + +`ParticleEntity` 是 Genesis 引擎中用于粒子系统的实体类,用于创建和管理由离散粒子组成的物理对象。它支持多种粒子模拟类型,如烟雾、火焰、粒子效果等。 + +## 功能说明 + +`ParticleEntity` 类提供了以下核心功能: + +- 创建和管理大量离散粒子 +- 粒子的物理属性和行为控制 +- 粒子发射和生命周期管理 +- 粒子间的相互作用 +- 与其他实体的碰撞检测和响应 +- 粒子渲染属性控制 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 实体在场景中的唯一索引 | +| `uid` | `int` | 实体的全局唯一标识符 | +| `name` | `str` | 实体的名称 | +| `n_particles` | `int` | 粒子数量 | +| `particle_positions` | `array` | 粒子位置数组 | +| `particle_velocities` | `array` | 粒子速度数组 | +| `particle_masses` | `array` | 粒子质量数组 | +| `particle_radii` | `array` | 粒子半径数组 | +| `particle_colors` | `array` | 粒子颜色数组 | +| `emission_rate` | `float` | 粒子发射速率 | +| `lifetime` | `float` | 粒子生命周期 | +| `is_built` | `bool` | 实体是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建粒子实体,初始化粒子属性 | +| `update()` | 无 | `None` | 更新粒子状态 | +| `reset()` | 无 | `None` | 重置粒子实体到初始状态 | +| `emit()` | `int` | `None` | 发射指定数量的粒子 | +| `remove_particle()` | `int` | `None` | 移除指定索引的粒子 | +| `clear_particles()` | 无 | `None` | 清除所有粒子 | + +## 继承关系 + +``` +BaseEntity +└── ParticleEntity +``` + +```{eval-rst} +.. autoclass:: genesis.engine.entities.particle_entity.ParticleEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/pbd_entity/index.md b/source/api_reference/entity/pbd_entity/index.md new file mode 100644 index 0000000..e23f0b3 --- /dev/null +++ b/source/api_reference/entity/pbd_entity/index.md @@ -0,0 +1,21 @@ +# PBDEntity + +PBDEntity 是基于位置的动力学(Position-Based Dynamics, PBD)系统中的实体基类,用于模拟柔性物体、流体和其他非刚性体。PBD 是一种高效的物理模拟方法,通过直接约束粒子位置来实现真实的物理行为。 + +## PBD 实体分类 + +Genesis 提供了多种 PBD 实体类型,以支持不同的模拟需求: + +- **PBDParticleEntity**: 基本的粒子实体,用于模拟离散粒子系统 +- **PBDFreeParticleEntity**: 自由粒子实体,不受约束的粒子集合 +- **PBD2DEntity**: 2D PBD 实体,用于模拟平面结构(如布料、薄膜) +- **PBD3DEntity**: 3D PBD 实体,用于模拟三维网格结构 +- **PBDTetEntity**: 四面体 PBD 实体,用于模拟体积物体(如软组织、弹性体) + +```{toctree} +pbd_particle +pbd_free_particle +pbd_2d +pbd_3d +pbd_tet +``` diff --git a/source/api_reference/entity/pbd_entity/pbd_2d.md b/source/api_reference/entity/pbd_entity/pbd_2d.md new file mode 100644 index 0000000..249388d --- /dev/null +++ b/source/api_reference/entity/pbd_entity/pbd_2d.md @@ -0,0 +1,37 @@ +# `PBD2DEntity` + +`PBD2DEntity` 是 PBD 系统中的 2D 实体,用于模拟平面结构,如布料、薄膜和其他二维柔性物体。它基于三角形网格构建,支持各种二维物理约束。 + +## 功能说明 + +该类提供了创建和管理二维柔性物体的功能,支持设置物体的材料属性、形态参数和物理约束,如拉伸约束、弯曲约束和碰撞约束。 + +## 主要属性 + +| 属性名称 | 描述 | +|---------|------| +| `idx` | 实体在场景中的唯一索引 | +| `uid` | 实体的唯一标识符 | +| `scene` | 实体所属的场景对象 | +| `sim` | 模拟器对象 | +| `solver` | PBD 求解器对象 | +| `material` | 实体的材料属性 | +| `morph` | 实体的形态参数 | +| `surface` | 实体的表面属性 | +| `mesh` | 实体的网格数据 | +| `vmesh` | 实体的可视化网格 | +| `is_built` | 实体是否已构建完成 | +| `particle_start` | 实体粒子在全局粒子缓冲区中的起始索引 | +| `particle_end` | 实体粒子在全局粒子缓冲区中的结束索引 | +| `n_particles` | 实体包含的粒子数量 | +| `particle_size` | 粒子的大小 | +| `elem_start` | 实体元素在全局元素缓冲区中的起始索引 | +| `elem_end` | 实体元素在全局元素缓冲区中的结束索引 | +| `n_elems` | 实体包含的元素数量 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.pbd_entity.PBD2DEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/pbd_entity/pbd_3d.md b/source/api_reference/entity/pbd_entity/pbd_3d.md new file mode 100644 index 0000000..87f4b8a --- /dev/null +++ b/source/api_reference/entity/pbd_entity/pbd_3d.md @@ -0,0 +1,39 @@ +# `PBD3DEntity` + +`PBD3DEntity` 是 PBD 系统中的 3D 实体,用于模拟三维网格结构,如柔性物体、绳索和其他三维柔性结构。它基于四面体或三角形网格构建,支持各种三维物理约束。 + +## 功能说明 + +该类提供了创建和管理三维柔性物体的功能,支持设置物体的材料属性、形态参数和物理约束,如拉伸约束、弯曲约束、体积约束和碰撞约束。 + +## 主要属性 + +| 属性名称 | 描述 | +|---------|------| +| `idx` | 实体在场景中的唯一索引 | +| `uid` | 实体的唯一标识符 | +| `scene` | 实体所属的场景对象 | +| `sim` | 模拟器对象 | +| `solver` | PBD 求解器对象 | +| `material` | 实体的材料属性 | +| `morph` | 实体的形态参数 | +| `surface` | 实体的表面属性 | +| `mesh` | 实体的网格数据 | +| `vmesh` | 实体的可视化网格 | +| `is_built` | 实体是否已构建完成 | +| `particle_start` | 实体粒子在全局粒子缓冲区中的起始索引 | +| `particle_end` | 实体粒子在全局粒子缓冲区中的结束索引 | +| `n_particles` | 实体包含的粒子数量 | +| `particle_size` | 粒子的大小 | +| `elem_start` | 实体元素在全局元素缓冲区中的起始索引 | +| `elem_end` | 实体元素在全局元素缓冲区中的结束索引 | +| `n_elems` | 实体包含的元素数量 | +| `edges` | 实体的边数据 | +| `n_edges` | 实体包含的边数量 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.pbd_entity.PBD3DEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/pbd_entity/pbd_free_particle.md b/source/api_reference/entity/pbd_entity/pbd_free_particle.md new file mode 100644 index 0000000..2bce38c --- /dev/null +++ b/source/api_reference/entity/pbd_entity/pbd_free_particle.md @@ -0,0 +1,34 @@ +# `PBDFreeParticleEntity` + +`PBDFreeParticleEntity` 是 PBD 系统中的自由粒子实体,用于模拟不受约束的粒子集合。它与 `PBDParticleEntity` 类似,但通常用于模拟不受结构约束的粒子系统,如流体或松散的粒子群。 + +## 功能说明 + +该类提供了创建和管理自由粒子系统的功能,支持设置粒子的位置、速度、质量等属性,但不包含结构约束(如连接性约束)。 + +## 主要属性 + +| 属性名称 | 描述 | +|---------|------| +| `idx` | 实体在场景中的唯一索引 | +| `uid` | 实体的唯一标识符 | +| `scene` | 实体所属的场景对象 | +| `sim` | 模拟器对象 | +| `solver` | PBD 求解器对象 | +| `material` | 实体的材料属性 | +| `morph` | 实体的形态参数 | +| `surface` | 实体的表面属性 | +| `mesh` | 实体的网格数据 | +| `vmesh` | 实体的可视化网格 | +| `is_built` | 实体是否已构建完成 | +| `particle_start` | 实体粒子在全局粒子缓冲区中的起始索引 | +| `particle_end` | 实体粒子在全局粒子缓冲区中的结束索引 | +| `n_particles` | 实体包含的粒子数量 | +| `particle_size` | 粒子的大小 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.pbd_entity.PBDFreeParticleEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/pbd_entity/pbd_particle.md b/source/api_reference/entity/pbd_entity/pbd_particle.md new file mode 100644 index 0000000..a6aa147 --- /dev/null +++ b/source/api_reference/entity/pbd_entity/pbd_particle.md @@ -0,0 +1,34 @@ +# `PBDParticleEntity` + +`PBDParticleEntity` 是 PBD 系统中的基本粒子实体,用于模拟离散粒子系统。它包含一组粒子及其相关的物理属性和约束。 + +## 功能说明 + +该类提供了创建和管理粒子系统的基本功能,支持设置粒子的位置、速度、质量等属性,并可以应用各种物理约束。 + +## 主要属性 + +| 属性名称 | 描述 | +|---------|------| +| `idx` | 实体在场景中的唯一索引 | +| `uid` | 实体的唯一标识符 | +| `scene` | 实体所属的场景对象 | +| `sim` | 模拟器对象 | +| `solver` | PBD 求解器对象 | +| `material` | 实体的材料属性 | +| `morph` | 实体的形态参数 | +| `surface` | 实体的表面属性 | +| `mesh` | 实体的网格数据 | +| `vmesh` | 实体的可视化网格 | +| `is_built` | 实体是否已构建完成 | +| `particle_start` | 实体粒子在全局粒子缓冲区中的起始索引 | +| `particle_end` | 实体粒子在全局粒子缓冲区中的结束索引 | +| `n_particles` | 实体包含的粒子数量 | +| `particle_size` | 粒子的大小 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.pbd_entity.PBDParticleEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/pbd_entity/pbd_tet.md b/source/api_reference/entity/pbd_entity/pbd_tet.md new file mode 100644 index 0000000..02abb44 --- /dev/null +++ b/source/api_reference/entity/pbd_entity/pbd_tet.md @@ -0,0 +1,37 @@ +# `PBDTetEntity` + +`PBDTetEntity` 是 PBD 系统中的四面体实体,用于模拟体积物体,如软组织、弹性体和其他具有体积特性的三维物体。它基于四面体网格构建,支持体积约束和其他三维物理约束。 + +## 功能说明 + +该类提供了创建和管理体积物体的功能,支持设置物体的材料属性、形态参数和物理约束,如拉伸约束、弯曲约束、体积约束和碰撞约束。 + +## 主要属性 + +| 属性名称 | 描述 | +|---------|------| +| `idx` | 实体在场景中的唯一索引 | +| `uid` | 实体的唯一标识符 | +| `scene` | 实体所属的场景对象 | +| `sim` | 模拟器对象 | +| `solver` | PBD 求解器对象 | +| `material` | 实体的材料属性 | +| `morph` | 实体的形态参数 | +| `surface` | 实体的表面属性 | +| `mesh` | 实体的网格数据 | +| `vmesh` | 实体的可视化网格 | +| `is_built` | 实体是否已构建完成 | +| `particle_start` | 实体粒子在全局粒子缓冲区中的起始索引 | +| `particle_end` | 实体粒子在全局粒子缓冲区中的结束索引 | +| `n_particles` | 实体包含的粒子数量 | +| `particle_size` | 粒子的大小 | +| `edges` | 实体的边数据 | +| `n_edges` | 实体包含的边数量 | + + +```{eval-rst} +.. autoclass:: genesis.engine.entities.pbd_entity.PBDTetEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/rigid_entity/index.md b/source/api_reference/entity/rigid_entity/index.md new file mode 100644 index 0000000..cccc582 --- /dev/null +++ b/source/api_reference/entity/rigid_entity/index.md @@ -0,0 +1,25 @@ +# RigidEntity + +`RigidEntity` 是 Genesis 引擎中用于模拟刚体系统的核心实体类。刚体是指在模拟过程中不会发生变形的物体,是物理模拟中的基础构建块之一。 + +## RigidEntity 概述 + +`RigidEntity` 类提供了创建和管理刚体系统的功能,支持多个刚体链接(RigidLink)的组合,通过关节(RigidJoint)连接,实现复杂的机械结构和运动模拟。 + +## 刚体系统组成 + +Genesis 引擎的刚体系统由以下核心组件构成: + +- **RigidEntity**: 刚体实体的主容器,管理整个刚体系统 +- **RigidLink**: 单个刚体链接,是刚体系统的基本单元,具有质量、惯性等物理属性 +- **RigidGeom**: 刚体的碰撞几何形状,用于碰撞检测 +- **RigidVisGeom**: 刚体的可视化几何形状,用于渲染 +- **RigidJoint**: 刚体链接之间的关节约束,控制链接之间的运动方式 + +```{toctree} +rigid_entity +rigid_link +rigid_joint +rigid_geom +rigid_visgeom +``` \ No newline at end of file diff --git a/source/api_reference/entity/rigid_entity/rigid_entity.md b/source/api_reference/entity/rigid_entity/rigid_entity.md new file mode 100644 index 0000000..a10444b --- /dev/null +++ b/source/api_reference/entity/rigid_entity/rigid_entity.md @@ -0,0 +1,45 @@ +# `RigidEntity` + +`RigidEntity` 是 Genesis 引擎中刚体系统的核心类,用于创建和管理刚体实体。它可以包含多个刚体链接(RigidLink),通过关节(RigidJoint)连接,形成复杂的机械结构。 + +## 功能说明 + +`RigidEntity` 类提供了以下主要功能: + +- 创建和管理多个刚体链接(RigidLink) +- 定义链接之间的关节约束(RigidJoint) +- 处理刚体的物理属性(质量、惯性、摩擦等) +- 支持刚体的位置、姿态和运动控制 +- 提供碰撞检测和响应机制 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 实体在引擎中的全局索引 | +| `uid` | `int` | 实体的唯一标识符 | +| `name` | `str` | 实体的名称 | +| `links` | `list` | 实体包含的刚体链接列表 | +| `joints` | `list` | 实体包含的关节列表 | +| `n_links` | `int` | 链接数量 | +| `n_joints` | `int` | 关节数量 | +| `n_dofs` | `int` | 自由度数量 | +| `n_qs` | `int` | 状态变量数量 | +| `dofs_idx` | `list` | 自由度在全局索引中的位置 | +| `dofs_stiffness` | `list` | 自由度的刚度参数 | +| `dofs_damping` | `list` | 自由度的阻尼参数 | +| `dofs_kp` | `list` | 位置控制增益 | +| `dofs_kv` | `list` | 速度控制增益 | +| `dofs_invweight` | `list` | 自由度的逆权重 | +| `dofs_frictionloss` | `list` | 自由度的摩擦损失 | +| `dofs_limit` | `list` | 自由度的运动限制 | +| `dofs_force_range` | `list` | 自由度的力范围限制 | +| `is_built` | `bool` | 实体是否已构建完成 | +| `solver` | `object` | 关联的求解器对象 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.rigid_entity.rigid_entity.RigidEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/rigid_entity/rigid_geom.md b/source/api_reference/entity/rigid_entity/rigid_geom.md new file mode 100644 index 0000000..0a538e2 --- /dev/null +++ b/source/api_reference/entity/rigid_entity/rigid_geom.md @@ -0,0 +1,48 @@ +# `RigidGeom` + +`RigidGeom` 用于定义刚体链接的碰撞几何形状,主要用于碰撞检测和碰撞响应。每个 RigidLink 可以包含多个 RigidGeom,它们共同定义了刚体的碰撞边界。 + +## 功能说明 + +`RigidGeom` 类提供了以下主要功能: + +- 定义碰撞几何形状的类型和参数 +- 设置几何形状的位置和姿态 +- 管理碰撞材质属性(摩擦、 restitution 等) +- 提供碰撞检测所需的几何信息 +- 支持多种几何形状类型(盒子、球体、圆柱体、胶囊体、网格等) + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 几何形状在引擎中的全局索引 | +| `idx_local` | `int` | 几何形状在链接中的局部索引 | +| `uid` | `int` | 几何形状的唯一标识符 | +| `name` | `str` | 几何形状的名称 | +| `type` | `str` | 几何形状类型(box, sphere, cylinder, capsule, mesh等) | +| `link` | `RigidLink` | 所属的刚体链接 | +| `entity` | `RigidEntity` | 所属的刚体实体 | +| `pos` | `list` | 几何形状在链接坐标系中的位置 [x, y, z] | +| `quat` | `list` | 几何形状在链接坐标系中的姿态四元数 [w, x, y, z] | +| `size` | `list` | 几何形状的尺寸参数,根据类型不同而变化 | +| `material` | `str` | 碰撞材质名称 | +| `friction` | `float` | 摩擦系数 | +| `restitution` | `float` | restitution 系数(弹性) | +| `thickness` | `float` | 几何形状的厚度(用于某些类型) | +| `mesh` | `object` | 网格对象(如果类型为mesh) | +| `n_verts` | `int` | 顶点数量(如果类型为mesh) | +| `n_faces` | `int` | 面数量(如果类型为mesh) | +| `n_edges` | `int` | 边数量(如果类型为mesh) | +| `vert_start` | `int` | 顶点起始索引(如果类型为mesh) | +| `vert_end` | `int` | 顶点结束索引(如果类型为mesh) | +| `face_start` | `int` | 面起始索引(如果类型为mesh) | +| `face_end` | `int` | 面结束索引(如果类型为mesh) | +| `is_built` | `bool` | 几何形状是否已构建完成 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.rigid_entity.rigid_geom.RigidGeom + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/rigid_entity/rigid_joint.md b/source/api_reference/entity/rigid_entity/rigid_joint.md new file mode 100644 index 0000000..4a36d04 --- /dev/null +++ b/source/api_reference/entity/rigid_entity/rigid_joint.md @@ -0,0 +1,51 @@ +# `RigidJoint` + +`RigidJoint` 用于定义两个 RigidLink 之间的约束关系,限制它们的相对运动。关节可以有不同的类型,如铰链关节、球关节等,每种类型提供不同的自由度限制。 + +## 功能说明 + +`RigidJoint` 类提供了以下主要功能: + +- 定义两个刚体链接之间的约束关系 +- 支持多种关节类型(铰链、球关节、棱柱、固定等) +- 提供关节的位置和角度控制 +- 允许设置关节的物理参数(刚度、阻尼、摩擦等) +- 支持关节的运动限制(角度范围、位移范围等) + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 关节在引擎中的全局索引 | +| `idx_local` | `int` | 关节在实体中的局部索引 | +| `uid` | `int` | 关节的唯一标识符 | +| `name` | `str` | 关节的名称 | +| `type` | `str` | 关节类型(hinge, ball, prismatic, fixed等) | +| `link` | `RigidLink` | 关联的主要链接 | +| `entity` | `RigidEntity` | 所属的刚体实体 | +| `pos` | `list` | 关节位置 [x, y, z] | +| `quat` | `list` | 关节姿态四元数 [w, x, y, z] | +| `axis` | `list` | 关节轴向量 [x, y, z](用于铰链和棱柱关节) | +| `n_dofs` | `int` | 关节的自由度数量 | +| `n_qs` | `int` | 关节的状态变量数量 | +| `dofs_idx` | `list` | 关节自由度在全局索引中的位置 | +| `dofs_idx_local` | `list` | 关节自由度在实体中的局部索引 | +| `dofs_kp` | `list` | 位置控制增益 | +| `dofs_kv` | `list` | 速度控制增益 | +| `dofs_stiffness` | `list` | 刚度参数 | +| `dofs_damping` | `list` | 阻尼参数 | +| `dofs_invweight` | `list` | 逆权重 | +| `dofs_frictionloss` | `list` | 摩擦损失 | +| `dofs_limit` | `list` | 运动限制 | +| `dofs_force_range` | `list` | 力范围限制 | +| `dofs_motion_ang` | `list` | 运动角度 | +| `dofs_motion_vel` | `list` | 运动速度 | +| `sol_params` | `list` | 求解器参数 | +| `is_built` | `bool` | 关节是否已构建完成 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.rigid_entity.rigid_joint.RigidJoint + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/rigid_entity/rigid_link.md b/source/api_reference/entity/rigid_entity/rigid_link.md new file mode 100644 index 0000000..5b838ff --- /dev/null +++ b/source/api_reference/entity/rigid_entity/rigid_link.md @@ -0,0 +1,48 @@ +# `RigidLink` + +`RigidLink` 是 RigidEntity 的基本组成单元,代表一个刚体。每个 RigidEntity 可以包含多个 RigidLink,每个链接可以包含多个碰撞几何形状(RigidGeom)和可视化几何形状(RigidVisGeom)。 + +## 功能说明 + +`RigidLink` 类提供了以下主要功能: + +- 定义刚体的物理属性(质量、惯性张量) +- 管理碰撞几何形状(RigidGeom)用于碰撞检测 +- 管理可视化几何形状(RigidVisGeom)用于渲染 +- 处理刚体的位置、姿态和运动 +- 提供获取链接边界框、顶点等信息的方法 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 链接在引擎中的全局索引 | +| `idx_local` | `int` | 链接在实体中的局部索引 | +| `uid` | `int` | 链接的唯一标识符 | +| `name` | `str` | 链接的名称 | +| `entity` | `RigidEntity` | 所属的刚体实体 | +| `geoms` | `list` | 碰撞几何形状列表 | +| `vgeoms` | `list` | 可视化几何形状列表 | +| `joints` | `list` | 关联的关节列表 | +| `n_geoms` | `int` | 碰撞几何形状数量 | +| `n_vgeoms` | `int` | 可视化几何形状数量 | +| `n_joints` | `int` | 关节数量 | +| `n_dofs` | `int` | 自由度数量 | +| `n_qs` | `int` | 状态变量数量 | +| `pos` | `list` | 链接的位置 [x, y, z] | +| `quat` | `list` | 链接的姿态四元数 [w, x, y, z] | +| `inertial_mass` | `float` | 链接的质量 | +| `inertial_pos` | `list` | 惯性中心位置 | +| `inertial_quat` | `list` | 惯性坐标系姿态 | +| `inertial_i` | `list` | 惯性张量 | +| `is_free` | `bool` | 链接是否为自由刚体 | +| `is_leaf` | `bool` | 链接是否为叶节点 | +| `parent_idx` | `int` | 父链接索引 | +| `child_idxs` | `list` | 子链接索引列表 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.rigid_entity.rigid_link.RigidLink + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/rigid_entity/rigid_visgeom.md b/source/api_reference/entity/rigid_entity/rigid_visgeom.md new file mode 100644 index 0000000..0503f53 --- /dev/null +++ b/source/api_reference/entity/rigid_entity/rigid_visgeom.md @@ -0,0 +1,43 @@ +# `RigidVisGeom` + +`RigidVisGeom` 是用于可视化刚体链接的几何形状,与 `RigidGeom` 相对应,但仅用于渲染目的,不参与碰撞检测。每个 RigidLink 可以包含多个 RigidVisGeom,它们共同定义了刚体的可视化外观。 + +## 功能说明 + +`RigidVisGeom` 类提供了以下主要功能: + +- 定义刚体链接的可视化几何形状 +- 设置可视化形状的位置和姿态 +- 管理表面材质和纹理 +- 提供渲染所需的几何信息 +- 支持与碰撞几何形状不同的可视化表示 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 可视化几何形状在引擎中的全局索引 | +| `uid` | `int` | 可视化几何形状的唯一标识符 | +| `link` | `RigidLink` | 所属的刚体链接 | +| `entity` | `RigidEntity` | 所属的刚体实体 | +| `pos` | `list` | 可视化形状在链接坐标系中的位置 [x, y, z] | +| `quat` | `list` | 可视化形状在链接坐标系中的姿态四元数 [w, x, y, z] | +| `init_pos` | `list` | 初始位置 [x, y, z] | +| `init_quat` | `list` | 初始姿态四元数 [w, x, y, z] | +| `vmesh` | `object` | 可视化网格对象 | +| `n_vverts` | `int` | 可视化顶点数量 | +| `n_vfaces` | `int` | 可视化面数量 | +| `init_vverts` | `list` | 初始可视化顶点坐标 | +| `init_vfaces` | `list` | 初始可视化面索引 | +| `init_vnormals` | `list` | 初始可视化法线向量 | +| `uvs` | `list` | UV 纹理坐标 | +| `surface` | `object` | 表面材质对象 | +| `metadata` | `dict` | 元数据信息 | +| `is_built` | `bool` | 可视化几何形状是否已构建完成 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.rigid_entity.rigid_geom.RigidVisGeom + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/rigidentity/index.md b/source/api_reference/entity/rigidentity/index.md deleted file mode 100644 index d03ba4e..0000000 --- a/source/api_reference/entity/rigidentity/index.md +++ /dev/null @@ -1,9 +0,0 @@ -# RigidEntity - -```{toctree} -rigidentity -rigidlink -rigidjoint -rigidgeom -rigidvisgeom -``` \ No newline at end of file diff --git a/source/api_reference/entity/rigidentity/rigidentity.md b/source/api_reference/entity/rigidentity/rigidentity.md deleted file mode 100644 index e287095..0000000 --- a/source/api_reference/entity/rigidentity/rigidentity.md +++ /dev/null @@ -1,8 +0,0 @@ -# `gs.RigidEntity` - -```{eval-rst} -.. autoclass:: genesis.engine.entities.rigid_entity.rigid_entity.RigidEntity - :members: - :show-inheritance: - :undoc-members: -``` diff --git a/source/api_reference/entity/rigidentity/rigidgeom.md b/source/api_reference/entity/rigidentity/rigidgeom.md deleted file mode 100644 index e4555c5..0000000 --- a/source/api_reference/entity/rigidentity/rigidgeom.md +++ /dev/null @@ -1,8 +0,0 @@ -# `gs.RigidGeom` - -```{eval-rst} -.. autoclass:: genesis.engine.entities.rigid_entity.rigid_geom.RigidGeom - :members: - :show-inheritance: - :undoc-members: -``` diff --git a/source/api_reference/entity/rigidentity/rigidjoint.md b/source/api_reference/entity/rigidentity/rigidjoint.md deleted file mode 100644 index e99bf40..0000000 --- a/source/api_reference/entity/rigidentity/rigidjoint.md +++ /dev/null @@ -1,8 +0,0 @@ -# `gs.RigidJoint` - -```{eval-rst} -.. autoclass:: genesis.engine.entities.rigid_entity.rigid_joint.RigidJoint - :members: - :show-inheritance: - :undoc-members: -``` diff --git a/source/api_reference/entity/rigidentity/rigidlink.md b/source/api_reference/entity/rigidentity/rigidlink.md deleted file mode 100644 index f08df1b..0000000 --- a/source/api_reference/entity/rigidentity/rigidlink.md +++ /dev/null @@ -1,8 +0,0 @@ -# `gs.RigidLink` - -```{eval-rst} -.. autoclass:: genesis.engine.entities.rigid_entity.rigid_link.RigidLink - :members: - :show-inheritance: - :undoc-members: -``` diff --git a/source/api_reference/entity/rigidentity/rigidvisgeom.md b/source/api_reference/entity/rigidentity/rigidvisgeom.md deleted file mode 100644 index 2ca447e..0000000 --- a/source/api_reference/entity/rigidentity/rigidvisgeom.md +++ /dev/null @@ -1,8 +0,0 @@ -# `gs.RigidVisGeom` - -```{eval-rst} -.. autoclass:: genesis.engine.entities.rigid_entity.rigid_geom.RigidVisGeom - :members: - :show-inheritance: - :undoc-members: -``` diff --git a/source/api_reference/entity/sf.md b/source/api_reference/entity/sf.md new file mode 100644 index 0000000..b9beff7 --- /dev/null +++ b/source/api_reference/entity/sf.md @@ -0,0 +1,52 @@ +# `SFEntity` + +## 概述 + +`SFEntity` 是 Genesis 引擎中用于模拟烟雾/火焰(Smoke/Fire)效果的实体类。目前,烟雾/火焰功能主要通过 `SFOptions` 类进行配置,用于设置烟雾/火焰模拟的参数,如时间步长、分辨率、求解器迭代次数、衰减系数、温度阈值以及入口参数等。 + +## 主要功能 + +- 模拟烟雾和火焰的物理行为 +- 支持通过 `SFOptions` 配置模拟参数 +- 可设置入口位置、速度和强度 +- 支持温度阈值和衰减系数调整 +- 与其他实体类型(如刚体、软体)进行交互 + +## 使用示例 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 配置SF求解器选项 +scene.options.solver.sf_options.dt = 0.01 +scene.options.solver.sf_options.res = 256 +scene.options.solver.sf_options.decay = 0.98 +scene.options.solver.sf_options.inlet_pos = (0.5, 0.0, 0.1) +scene.options.solver.sf_options.inlet_vel = (0, 0, 2) +scene.options.solver.sf_options.inlet_s = 500.0 + +# 添加一个简单的刚体实体作为障碍物 +scene.add_entity(type='rigid', mesh=gs.Mesh.create_box(size=[0.5, 0.5, 1.0]), pos=[0.0, 0.0, 0.5]) + +# 构建并运行模拟 +scene.build() +for i in range(200): + scene.step() + if i % 10 == 0: + scene.render() + +scene.release() +``` + +```{eval-rst} +.. note:: + 烟雾/火焰实体的完整接口正在开发中。目前,烟雾/火焰模拟主要通过配置 `SFOptions` 来实现。 + +.. autoclass:: genesis.options.solvers.SFOptions + :members: + :show-inheritance: + :undoc-members: +``` \ No newline at end of file diff --git a/source/api_reference/entity/sph_entity.md b/source/api_reference/entity/sph_entity.md new file mode 100644 index 0000000..a959c5c --- /dev/null +++ b/source/api_reference/entity/sph_entity.md @@ -0,0 +1,34 @@ +# `SPHEntity` + +`SPHEntity` 是 Genesis 引擎中基于光滑粒子流体动力学 (SPH) 的粒子实体类,用于模拟流体效果,如液体、气体等。 + +## 功能说明 + +- 基于 SPH 方法模拟流体的运动和相互作用 +- 支持各种流体属性,如密度、粘度、表面张力等 +- 提供粒子位置、速度、密度等状态的获取和设置接口 +- 支持与其他实体的交互和碰撞 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 实体在场景中的索引 | +| `uid` | int | 实体的唯一标识符 | +| `is_built` | bool | 实体是否已构建完成 | +| `scene` | Scene | 所属的场景对象 | +| `sim` | Simulator | 所属的模拟器对象 | +| `solver` | Solver | 处理该实体的求解器 | +| `material` | Material | 实体的材料属性 | +| `morph` | Morph | 实体的形态配置 | +| `surface` | Surface | 实体的表面约束或几何 | +| `n_particles` | int | 粒子的数量 | +| `particle_size` | float | 每个粒子的大小 | +| `particle_start` | int | 该实体粒子的起始索引 | + +```{eval-rst} +.. autoclass:: genesis.engine.entities.sph_entity.SPHEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/entity/tool.md b/source/api_reference/entity/tool.md new file mode 100644 index 0000000..c054246 --- /dev/null +++ b/source/api_reference/entity/tool.md @@ -0,0 +1,49 @@ +# `ToolEntity` + +## 概述 + +`ToolEntity` 是 Genesis 引擎中的工具实体类,是 `RigidEntity` 的简化形式,主要用于支持单向工具到其他物体的耦合交互。它没有内部动力学,只能从单个网格创建,是可微分刚体-软体交互的临时解决方案。 + +## 主要功能 + +- 作为 `RigidEntity` 的简化形式,支持基本的刚性体属性 +- 实现单向工具到其他物体的耦合交互 +- 支持从单个网格创建工具实体 +- 用于可微分刚体-软体交互场景 +- 由 `ToolOptions` 类配置模拟参数 + +## 使用示例 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 创建工具实体 +mesh = gs.Mesh.create_cube() +tool_entity = scene.add_entity(type='tool', mesh=mesh) + +# 设置工具实体位置 +tool_entity.set_position([0, 0, 1]) + +# 配置工具求解器选项 +scene.options.solver.tool_options.dt = 0.01 +scene.options.solver.tool_options.floor_height = 0.0 + +# 运行模拟 +scene.build() +for i in range(100): + # 在每一帧更新工具实体位置 + tool_entity.set_position([0, 0, 1 + 0.5 * gs.math.sin(i * 0.1)]) + scene.step() + +scene.release() +``` + +```{eval-rst} +.. autoclass:: genesis.engine.entities.tool.ToolEntity + :members: + :show-inheritance: + :undoc-members: +``` \ No newline at end of file diff --git a/source/api_reference/entity/tool_entity/index.md b/source/api_reference/entity/tool_entity/index.md new file mode 100644 index 0000000..9a410bd --- /dev/null +++ b/source/api_reference/entity/tool_entity/index.md @@ -0,0 +1,9 @@ +# Tool Entity + +ToolEntity 是 Genesis 引擎中的工具实体类,是 `RigidEntity` 的简化形式,主要用于支持单向工具到其他物体的耦合交互。 + +```{toctree} +:maxdepth: 2 + +tool_entity +``` diff --git a/source/api_reference/entity/tool_entity/tool_entity.md b/source/api_reference/entity/tool_entity/tool_entity.md new file mode 100644 index 0000000..deea69a --- /dev/null +++ b/source/api_reference/entity/tool_entity/tool_entity.md @@ -0,0 +1,80 @@ +# `ToolEntity` + +## 概述 + +`ToolEntity` 是 Genesis 引擎中的工具实体类,是 `RigidEntity` 的简化形式,主要用于支持单向工具到其他物体的耦合交互。它没有内部动力学,只能从单个网格创建,是可微分刚体-软体交互的临时解决方案。 + +## 主要功能 + +- 作为 `RigidEntity` 的简化形式,支持基本的刚性体属性 +- 实现单向工具到其他物体的耦合交互 +- 支持从单个网格创建工具实体 +- 用于可微分刚体-软体交互场景 +- 由 `ToolOptions` 类配置模拟参数 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 实体在引擎中的全局索引 | +| `uid` | `int` | 实体的唯一标识符 | +| `name` | `str` | 实体的名称 | +| `mesh` | `Mesh` | 工具实体的网格 | +| `position` | `vector` | 实体位置 | +| `rotation` | `quaternion` | 实体旋转 | +| `scale` | `vector` | 实体缩放 | +| `is_built` | `bool` | 实体是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建工具实体,初始化物理属性 | +| `update()` | 无 | `None` | 更新实体状态 | +| `reset()` | 无 | `None` | 重置实体到初始状态 | +| `set_position()` | `vector` | `None` | 设置实体位置 | +| `set_rotation()` | `quaternion` | `None` | 设置实体旋转 | +| `set_scale()` | `vector` | `None` | 设置实体缩放 | + +## 使用示例 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 创建工具实体 +mesh = gs.Mesh.create_cube() +tool_entity = scene.add_entity(type='tool', mesh=mesh) + +# 设置工具实体位置 +tool_entity.set_position([0, 0, 1]) + +# 配置工具求解器选项 +scene.options.solver.tool_options.dt = 0.01 +scene.options.solver.tool_options.floor_height = 0.0 + +# 运行模拟 +scene.build() +for i in range(100): + # 在每一帧更新工具实体位置 + tool_entity.set_position([0, 0, 1 + 0.5 * gs.math.sin(i * 0.1)]) + scene.step() + +scene.release() +``` + +## 继承关系 + +``` +BaseEntity +└── ToolEntity +``` + +```{eval-rst} +.. autoclass:: genesis.engine.entities.tool.ToolEntity + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/index.md b/source/api_reference/index.md index 4a06cef..c6f8f20 100644 --- a/source/api_reference/index.md +++ b/source/api_reference/index.md @@ -4,7 +4,12 @@ :titlesonly: scene/index -camera/index entity/index +material/index +sensor/index options/index +solvers/index +boundaries/index +couplers/index +states/index ``` diff --git a/source/api_reference/material/avatar.md b/source/api_reference/material/avatar.md new file mode 100644 index 0000000..f988889 --- /dev/null +++ b/source/api_reference/material/avatar.md @@ -0,0 +1,28 @@ +# `gs.materials.Avatar` + +`Avatar` 是 Genesis 引擎中用于定义虚拟角色材料属性的类,用于模拟虚拟角色的物理行为,如肌肉、骨骼等。 + +## 功能说明 + +- 定义虚拟角色的物理材料属性 +- 支持肌肉参数的配置,如刚度、阻尼等 +- 提供材料属性的获取和设置接口 +- 支持与其他物理系统的交互 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `density` | float | 材料密度 | +| `youngs_modulus` | float | 杨氏模量 | +| `poisson_ratio` | float | 泊松比 | +| `muscle_stiffness` | float | 肌肉刚度 | +| `muscle_damping` | float | 肌肉阻尼 | + + +```{eval-rst} +.. autoclass:: genesis.engine.materials.avatar.Avatar + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/base.md b/source/api_reference/material/base.md new file mode 100644 index 0000000..1a44cdd --- /dev/null +++ b/source/api_reference/material/base.md @@ -0,0 +1,68 @@ +# MaterialBase + +`MaterialBase` 是 Genesis 引擎中所有材质类的基类,定义了所有材质共享的核心属性和方法。它为不同类型的材质(如刚体材质、变形体材质、流体材质等)提供了统一的接口和基础架构。 + +## 功能说明 + +`MaterialBase` 类提供了以下核心功能: + +- 材质的基本身份标识和分类 +- 共享物理属性的定义(如密度、摩擦系数等) +- 材质参数的初始化和验证 +- 与物理求解器的兼容机制 +- 统一的材质属性访问接口 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 材质在材质库中的唯一索引 | +| `uid` | `int` | 材质的全局唯一标识符 | +| `name` | `str` | 材质的名称 | +| `type` | `str` | 材质类型(如 "rigid", "elastic", "liquid" 等) | +| `density` | `float` | 材质的密度 | +| `friction` | `float` | 材质的摩擦系数 | +| `restitution` | `float` | 材质的弹性恢复系数 | +| `is_built` | `bool` | 材质是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建材质,初始化物理参数 | +| `update()` | 无 | `None` | 更新材质属性 | +| `reset()` | 无 | `None` | 重置材质到初始状态 | + +## 继承关系 + +`MaterialBase` 是所有材质类的基类,以下是主要的继承关系: + +``` +MaterialBase +├── RigidMaterial +├── AvatarMaterial +├── FEMMaterial +│ ├── FEMElasticMaterial +│ └── FEMMuscleMaterial +├── MPMMaterial +│ ├── MPMElasticMaterial +│ ├── MPMElastoPlasticMaterial +│ ├── MPMLiquidMaterial +│ ├── MPMMuscleMaterial +│ ├── MPMSandMaterial +│ └── MPMSnowMaterial +├── PBDMaterial +│ ├── PBDClothMaterial +│ ├── PBDElasticMaterial +│ ├── PBDLiquidMaterial +│ └── PBDParticleMaterial +└── SPHMaterial + └── SPHLiquidMaterial +``` + +```{eval-rst} +.. autoclass:: genesis.engine.materials.base.MaterialBase + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/fem/elastic.md b/source/api_reference/material/fem/elastic.md new file mode 100644 index 0000000..f575454 --- /dev/null +++ b/source/api_reference/material/fem/elastic.md @@ -0,0 +1,28 @@ +# `gs.materials.FEM.Elastic` + +## 概述 +`Elastic` 是 FEM(有限元方法)的弹性材料类,用于模拟具有弹性特性的物体。 + +## 主要功能 +- 支持多种本构模型(线性弹性、稳定 Neo-Hookean、线性共旋转) +- 可配置的杨氏模量、泊松比和密度 +- 支持水弹性接触和摩擦 +- 提供能量和应力计算功能 + +## 参数说明 + +| 参数 | 类型 | 默认值 | 描述 | +|------|------|--------|------| +| E | float | 1e6 | 杨氏模量,控制材料的刚度 | +| nu | float | 0.2 | 泊松比,描述材料在应力下的体积变化 | +| rho | float | 1000 | 材料密度(kg/m³) | +| hydroelastic_modulus | float | 1e7 | 水弹性接触的水弹性模量 | +| friction_mu | float | 0.1 | 摩擦系数 | +| model | str | 'linear' | 应力计算使用的本构模型,可选值:'linear'、'stable_neohookean'、'linear_corotated' | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.FEM.elastic.Elastic + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/fem/index.md b/source/api_reference/material/fem/index.md new file mode 100644 index 0000000..dd03bdd --- /dev/null +++ b/source/api_reference/material/fem/index.md @@ -0,0 +1,6 @@ +# FEM + +```{toctree} +elastic +muscle +``` \ No newline at end of file diff --git a/source/api_reference/material/fem/muscle.md b/source/api_reference/material/fem/muscle.md new file mode 100644 index 0000000..41e2c5c --- /dev/null +++ b/source/api_reference/material/fem/muscle.md @@ -0,0 +1,28 @@ +# `gs.materials.FEM.Muscle` + +## 概述 +`Muscle` 是 FEM(有限元方法)的肌肉材料类,用于模拟具有肌肉特性的物体,支持多肌肉组。 + +## 主要功能 +- 继承自弹性材料,支持多种本构模型 +- 支持多个肌肉组,可独立控制 +- 可配置的杨氏模量、泊松比和密度 +- 提供能量和应力计算功能 + +## 参数说明 + +| 参数 | 类型 | 默认值 | 描述 | +|------|------|--------|------| +| E | float | 1e6 | 杨氏模量,控制材料的刚度 | +| nu | float | 0.2 | 泊松比,描述材料在应力下的体积变化 | +| rho | float | 1000 | 材料密度(kg/m³) | +| model | str | 'linear' | 应力计算使用的本构模型,可选值:'linear'、'stable_neohookean' | +| n_groups | int | 1 | 肌肉组的数量 | + + +```{eval-rst} +.. autoclass:: genesis.engine.materials.FEM.muscle.Muscle + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/hybrid.md b/source/api_reference/material/hybrid.md new file mode 100644 index 0000000..96fdc14 --- /dev/null +++ b/source/api_reference/material/hybrid.md @@ -0,0 +1,80 @@ +# HybridMaterial + +`HybridMaterial` 是 Genesis 引擎中用于混合多种材质特性的材质类,它允许将不同类型的材质(如弹性、塑性、流体等)组合在一起,用于模拟复杂的物理现象。 + +## 功能说明 + +`HybridMaterial` 类提供了以下核心功能: + +- 多种材质类型的混合和组合 +- 可调节的混合权重和参数 +- 支持不同物理状态之间的过渡 +- 复杂材料特性的模拟 +- 与多种求解器兼容 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 材质在材质库中的唯一索引 | +| `uid` | `int` | 材质的全局唯一标识符 | +| `name` | `str` | 材质的名称 | +| `base_material` | `Material` | 基础材质类型 | +| `blend_material` | `Material` | 混合材质类型 | +| `blend_weight` | `float` | 混合权重(0.0-1.0) | +| `density` | `float` | 材质的密度 | +| `friction` | `float` | 材质的摩擦系数 | +| `restitution` | `float` | 材质的弹性恢复系数 | +| `is_built` | `bool` | 材质是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建混合材质,初始化物理参数 | +| `update()` | 无 | `None` | 更新材质属性 | +| `reset()` | 无 | `None` | 重置材质到初始状态 | +| `set_blend_weight()` | `float` | `None` | 设置混合权重 | +| `set_base_material()` | `Material` | `None` | 设置基础材质 | +| `set_blend_material()` | `Material` | `None` | 设置混合材质 | + +## 继承关系 + +``` +MaterialBase +└── HybridMaterial +``` + +## 使用示例 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 创建混合材质 +hybrid_material = scene.create_material( + type='hybrid', + base_material='elastic', + blend_material='plastic', + blend_weight=0.5, + density=1000.0, + friction=0.3, + restitution=0.1 +) + +# 设置材质属性 +hybrid_material.set_blend_weight(0.7) + +# 创建使用混合材质的实体 +mesh = gs.Mesh.create_sphere(radius=0.5) +entity = scene.add_entity(type='mpm', mesh=mesh, material=hybrid_material) +``` + +```{eval-rst} +.. autoclass:: genesis.engine.materials.hybrid.HybridMaterial + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/index.md b/source/api_reference/material/index.md new file mode 100644 index 0000000..5ad1dec --- /dev/null +++ b/source/api_reference/material/index.md @@ -0,0 +1,14 @@ +# Material + +A `Material` object specifies the physical material of each entity. +You could find the physical properties and their corresponding values here such as the stiffness of an object. + +```{toctree} +base +rigid +avatar +mpm/index +fem/index +pbd/index +sph/index +``` \ No newline at end of file diff --git a/source/api_reference/material/mpm/elastic.md b/source/api_reference/material/mpm/elastic.md new file mode 100644 index 0000000..884ccb3 --- /dev/null +++ b/source/api_reference/material/mpm/elastic.md @@ -0,0 +1,33 @@ +# `gs.materials.MPM.Elastic` + +## 概述 + +`Elastic` 是 MPM (Material Point Method) 模拟中使用的弹性材料类,用于模拟具有线性弹性特性的物体。该类实现了多种应力模型,并支持不同的粒子采样方法。 + +## 主要功能 + +- 实现了线性弹性本构模型 +- 支持多种应力模型(corotation 和 neohooken) +- 提供灵活的材料参数配置 +- 支持多种粒子采样方法(pbs、regular、random) +- 基于 Lame 参数计算弹性特性 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `E` | float | 1e6 | 杨氏模量,衡量材料的刚度 | +| `nu` | float | 0.2 | 泊松比,描述材料在受力时的横向收缩特性 | +| `rho` | float | 1000 | 密度 (kg/m³),材料单位体积的质量 | +| `lam` | float | None | 第一 Lame 参数,默认通过 E 和 nu 计算 | +| `mu` | float | None | 第二 Lame 参数(剪切模量),默认通过 E 和 nu 计算 | +| `sampler` | str | 'pbs' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `model` | str | 'corotation' | 应力模型,可选值:'corotation'、'neohooken' | + + +```{eval-rst} +.. autoclass:: genesis.engine.materials.MPM.elastic.Elastic + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/mpm/elasto_plastic.md b/source/api_reference/material/mpm/elasto_plastic.md new file mode 100644 index 0000000..8fa5a54 --- /dev/null +++ b/source/api_reference/material/mpm/elasto_plastic.md @@ -0,0 +1,32 @@ +# `gs.materials.MPM.ElastoPlastic` + +## 概述 + +`ElastoPlastic` 是 MPM (Material Point Method) 模拟中使用的弹塑性材料类,用于模拟同时具有弹性和塑性变形特性的物体。该类支持多种屈服准则,可以模拟材料在超过弹性极限后的塑性流动行为。 + +## 主要功能 + +- 结合了弹性和塑性变形特性 +- 支持多种屈服准则(von Mises、Drucker-Prager 等) +- 提供灵活的材料参数配置 +- 支持多种粒子采样方法 +- 基于 Lame 参数计算弹性特性 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `E` | float | 1e6 | 杨氏模量,衡量材料的刚度 | +| `nu` | float | 0.2 | 泊松比,描述材料在受力时的横向收缩特性 | +| `rho` | float | 1000 | 密度 (kg/m³),材料单位体积的质量 | +| `lam` | float | None | 第一 Lame 参数,默认通过 E 和 nu 计算 | +| `mu` | float | None | 第二 Lame 参数(剪切模量),默认通过 E 和 nu 计算 | +| `sampler` | str | 'random' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `yield_criterion` | str | 'von_mises' | 屈服准则,可选值:'von_mises'、'drucker_prager' 等 | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.MPM.elasto_plastic.ElastoPlastic + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/mpm/index.md b/source/api_reference/material/mpm/index.md new file mode 100644 index 0000000..f48a006 --- /dev/null +++ b/source/api_reference/material/mpm/index.md @@ -0,0 +1,10 @@ +# MPM + +```{toctree} +elastic +elasto_plastic +liquid +muscle +sand +snow +``` \ No newline at end of file diff --git a/source/api_reference/material/mpm/liquid.md b/source/api_reference/material/mpm/liquid.md new file mode 100644 index 0000000..4fd0361 --- /dev/null +++ b/source/api_reference/material/mpm/liquid.md @@ -0,0 +1,33 @@ +# `gs.materials.MPM.Liquid` + +## 概述 + +`Liquid` 是 MPM (Material Point Method) 模拟中使用的液体材料类,用于模拟具有不可压缩或可压缩流体特性的物质。该类实现了流体动力学方程,可以模拟液体的流动、飞溅等行为。 + +## 主要功能 + +- 实现了流体动力学方程 +- 支持不可压缩或可压缩流体模拟 +- 提供灵活的流体参数配置 +- 支持多种粒子采样方法 +- 模拟液体的表面张力和粘性特性 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `E` | float | 1e6 | 杨氏模量(用于可压缩流体),默认值为 1e6 | +| `nu` | float | 0.2 | 泊松比(用于可压缩流体),默认值为 0.2 | +| `rho` | float | 1000 | 密度 (kg/m³),液体单位体积的质量,默认值为 1000 | +| `lam` | float | None | 第一 Lame 参数,默认通过 E 和 nu 计算 | +| `mu` | float | None | 第二 Lame 参数,默认通过 E 和 nu 计算 | +| `sampler` | str | 'random' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `bulk_modulus` | float | None | 体积模量,衡量流体的可压缩性 | + + +```{eval-rst} +.. autoclass:: genesis.engine.materials.MPM.liquid.Liquid + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/mpm/muscle.md b/source/api_reference/material/mpm/muscle.md new file mode 100644 index 0000000..13149b9 --- /dev/null +++ b/source/api_reference/material/mpm/muscle.md @@ -0,0 +1,34 @@ +# `gs.materials.MPM.Muscle` + +## 概述 + +`Muscle` 是 MPM (Material Point Method) 模拟中使用的肌肉材料类,用于模拟生物肌肉组织的力学特性。该类支持多个肌肉组,可以模拟肌肉的收缩、伸展等行为,适用于生物力学和角色动画等场景。 + +## 主要功能 + +- 模拟生物肌肉组织的力学特性 +- 支持多个独立的肌肉组 +- 实现肌肉的收缩和伸展行为 +- 提供灵活的材料参数配置 +- 支持多种应力模型和粒子采样方法 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `E` | float | 1e6 | 杨氏模量,衡量肌肉的刚度,默认值为 1e6 | +| `nu` | float | 0.2 | 泊松比,描述肌肉在受力时的横向收缩特性,默认值为 0.2 | +| `rho` | float | 1000 | 密度 (kg/m³),肌肉组织单位体积的质量,默认值为 1000 | +| `lam` | float | None | 第一 Lame 参数,默认通过 E 和 nu 计算 | +| `mu` | float | None | 第二 Lame 参数(剪切模量),默认通过 E 和 nu 计算 | +| `sampler` | str | 'pbs' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `model` | str | 'corotation' | 应力模型,可选值:'corotation'、'neohooken' | +| `n_groups` | int | 1 | 肌肉组数量,默认值为 1 | + + +```{eval-rst} +.. autoclass:: genesis.engine.materials.MPM.muscle.Muscle + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/mpm/sand.md b/source/api_reference/material/mpm/sand.md new file mode 100644 index 0000000..bb854c0 --- /dev/null +++ b/source/api_reference/material/mpm/sand.md @@ -0,0 +1,32 @@ +# `gs.materials.MPM.Sand` + +## 概述 + +`Sand` 是 MPM (Material Point Method) 模拟中使用的沙子材料类,用于模拟颗粒状物质的力学特性。该类实现了基于摩擦角的塑性模型,可以模拟沙子的流动、堆积、崩塌等行为。 + +## 主要功能 + +- 实现了基于摩擦角的颗粒材料模型 +- 模拟沙子的流动、堆积、崩塌等行为 +- 支持压力相关的塑性屈服 +- 提供灵活的材料参数配置 +- 支持多种粒子采样方法 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `E` | float | 1e6 | 杨氏模量,衡量沙子的刚度,默认值为 1e6 | +| `nu` | float | 0.2 | 泊松比,描述沙子在受力时的横向收缩特性,默认值为 0.2 | +| `rho` | float | 1000 | 密度 (kg/m³),沙子单位体积的质量,默认值为 1000 | +| `lam` | float | None | 第一 Lame 参数,默认通过 E 和 nu 计算 | +| `mu` | float | None | 第二 Lame 参数(剪切模量),默认通过 E 和 nu 计算 | +| `sampler` | str | 'random' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `friction_angle` | float | 45 | 摩擦角(度),用于计算内部压力相关的塑性屈服,默认值为 45 | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.MPM.sand.Sand + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/mpm/snow.md b/source/api_reference/material/mpm/snow.md new file mode 100644 index 0000000..9796ea6 --- /dev/null +++ b/source/api_reference/material/mpm/snow.md @@ -0,0 +1,33 @@ +# `gs.materials.MPM.Snow` + +## 概述 + +`Snow` 是 MPM (Material Point Method) 模拟中使用的雪材料类,是一种特殊的弹塑性材料,当被压缩时会变硬。该类实现了专门的雪力学模型,可以模拟雪的堆积、压实、坍塌等行为。 + +## 主要功能 + +- 实现了雪的特殊力学模型(受压变硬特性) +- 模拟雪的堆积、压实、坍塌等行为 +- 不支持 von Mises 屈服准则 +- 提供灵活的材料参数配置 +- 支持多种粒子采样方法 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `E` | float | 1e6 | 杨氏模量,衡量雪的刚度,默认值为 1e6 | +| `nu` | float | 0.2 | 泊松比,描述雪在受力时的横向收缩特性,默认值为 0.2 | +| `rho` | float | 1000 | 密度 (kg/m³),雪单位体积的质量,默认值为 1000 | +| `lam` | float | None | 第一 Lame 参数,默认通过 E 和 nu 计算 | +| `mu` | float | None | 第二 Lame 参数(剪切模量),默认通过 E 和 nu 计算 | +| `sampler` | str | 'random' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `yield_lower` | float | 2.5e-2 | 屈服条件的下限,默认值为 2.5e-2 | +| `yield_higher` | float | 4.5e-3 | 屈服条件的上限,默认值为 4.5e-3 | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.MPM.snow.Snow + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/pbd/cloth.md b/source/api_reference/material/pbd/cloth.md new file mode 100644 index 0000000..b08621a --- /dev/null +++ b/source/api_reference/material/pbd/cloth.md @@ -0,0 +1,33 @@ +# `gs.materials.PBD.Cloth` + +## 概述 + +`Cloth` 是 PBD (Position Based Dynamics) 模拟中使用的布料材料类,用于模拟柔性布料的力学特性。该类基于弹性材料扩展,专门针对布料的拉伸、弯曲和空气阻力等特性进行了优化。 + +## 主要功能 + +- 实现了布料的拉伸和弯曲约束 +- 支持空气阻力模拟 +- 提供摩擦系数配置 +- 支持可调节的约束松弛参数 +- 适用于模拟各种布料材质(如丝绸、棉布、皮革等) + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `rho` | float | 1000 | 密度 (kg/m³),布料单位体积的质量 | +| `static_friction` | float | 0.15 | 静摩擦系数,控制布料与其他物体开始滑动前的最大切向力 | +| `kinetic_friction` | float | 0.0 | 动摩擦系数,控制布料与其他物体滑动过程中的阻力 | +| `stretch_compliance` | float | 0.0 | 拉伸柔度 (m/N),控制布料拉伸约束的柔软度 | +| `bending_compliance` | float | 0.0 | 弯曲柔度 (rad/N),控制布料的弯曲难易程度 | +| `stretch_relaxation` | float | 0.3 | 拉伸松弛参数,较小的值会减弱拉伸约束 | +| `bending_relaxation` | float | 0.1 | 弯曲松弛参数,较小的值会减弱弯曲约束 | +| `air_resistance` | float | 1e-3 | 空气阻力系数,控制布料在空气中运动时受到的阻力 | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.PBD.cloth.Cloth + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/pbd/elastic.md b/source/api_reference/material/pbd/elastic.md new file mode 100644 index 0000000..e63bb6b --- /dev/null +++ b/source/api_reference/material/pbd/elastic.md @@ -0,0 +1,34 @@ +# `gs.materials.PBD.Elastic` + +## 概述 + +`Elastic` 是 PBD (Position Based Dynamics) 模拟中使用的弹性材料类,用于模拟具有弹性变形特性的物体。该类实现了基于位置的约束求解器,可以模拟弹性体的拉伸、弯曲和体积保持等行为。 + +## 主要功能 + +- 实现了基于位置的弹性约束求解 +- 支持拉伸、弯曲和体积约束 +- 提供摩擦系数配置 +- 支持可调节的约束松弛参数 +- 适用于模拟各种弹性体材料 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `rho` | float | 1000 | 密度 (kg/m³),材料单位体积的质量 | +| `static_friction` | float | 0.15 | 静摩擦系数,控制粒子间开始滑动前的最大切向力 | +| `kinetic_friction` | float | 0.0 | 动摩擦系数,控制粒子滑动过程中的阻力 | +| `stretch_compliance` | float | 0.0 | 拉伸柔度 (m/N),控制粒子间拉伸约束的柔软度 | +| `bending_compliance` | float | 0.0 | 弯曲柔度 (rad/N),控制材料的弯曲难易程度 | +| `volume_compliance` | float | 0.0 | 体积柔度 (m³/N),控制四面体单元的可压缩性 | +| `stretch_relaxation` | float | 0.1 | 拉伸松弛参数,较小的值会减弱拉伸约束 | +| `bending_relaxation` | float | 0.1 | 弯曲松弛参数,较小的值会减弱弯曲约束 | +| `volume_relaxation` | float | 0.1 | 体积松弛参数,较小的值会减弱体积约束 | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.PBD.elastic.Elastic + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/pbd/index.md b/source/api_reference/material/pbd/index.md new file mode 100644 index 0000000..90d2a00 --- /dev/null +++ b/source/api_reference/material/pbd/index.md @@ -0,0 +1,33 @@ +# PBD + +## 概述 + +PBD (Position Based Dynamics) 材料模块提供了一组用于基于位置动力学模拟的材料类。这些材料类使用基于位置的约束求解方法,能够高效地模拟各种物理现象,尤其适合实时应用和游戏开发。 + +## 材料类型 + +本模块包含以下几种材料类型: + +```{toctree} +elastic +cloth +liquid +particle +``` + +## 使用场景 + +PBD材料模块适用于以下场景: + +- 布料模拟(如衣物、旗帜等) +- 弹性物体模拟(如橡胶、弹性体等) +- 液体模拟(如水、油等) +- 粒子效果(如爆炸、烟雾等) + +## 特点 + +- 基于位置的约束求解方法 +- 高效稳定的物理模拟 +- 支持多种约束类型(拉伸、弯曲、体积等) +- 易于参数化和调整 +- 适用于实时应用 \ No newline at end of file diff --git a/source/api_reference/material/pbd/liquid.md b/source/api_reference/material/pbd/liquid.md new file mode 100644 index 0000000..94a3314 --- /dev/null +++ b/source/api_reference/material/pbd/liquid.md @@ -0,0 +1,29 @@ +# `gs.materials.PBD.Liquid` + +## 概述 + +`Liquid` 是 PBD (Position Based Dynamics) 模拟中使用的液体材料类,用于模拟不可压缩流体的力学特性。该类基于粒子的方法实现了流体动力学方程,可以模拟液体的流动、飞溅、表面张力等行为。 + +## 主要功能 + +- 实现了不可压缩流体模拟 +- 支持密度和粘度约束 +- 提供多种粒子采样方法 +- 支持可调节的约束松弛参数 +- 适用于模拟各种液体(如水、油、蜂蜜等) + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `rho` | float | 1000.0 | 流体的静止密度 (kg/m³),默认值为水的密度 | +| `sampler` | str | 'pbs' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | +| `density_relaxation` | float | 0.2 | 密度约束的松弛因子,控制位置校正的强度以保证不可压缩性 | +| `viscosity_relaxation` | float | 0.01 | 粘度求解器的松弛因子,影响相邻粒子间相对速度的平滑程度 | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.PBD.liquid.Liquid + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/pbd/particle.md b/source/api_reference/material/pbd/particle.md new file mode 100644 index 0000000..3cf4d37 --- /dev/null +++ b/source/api_reference/material/pbd/particle.md @@ -0,0 +1,27 @@ +# `gs.materials.PBD.Particle` + +## 概述 + +`Particle` 是 PBD (Position Based Dynamics) 模拟中使用的粒子材料类,用于创建没有粒子间相互作用的基于粒子的实体。这些粒子只受外部力(如重力)的影响,适用于创建粒子效果和动画。 + +## 主要功能 + +- 创建基于粒子的实体 +- 粒子间没有相互作用 +- 只受外部力的影响 +- 支持多种粒子采样方法 +- 适用于创建粒子动画效果 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `rho` | float | 1000.0 | 粒子的密度,默认值为 1000.0 | +| `sampler` | str | 'pbs' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.PBD.particle.Particle + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/rigid.md b/source/api_reference/material/rigid.md new file mode 100644 index 0000000..40c4fa4 --- /dev/null +++ b/source/api_reference/material/rigid.md @@ -0,0 +1,28 @@ +# `gs.materials.Rigid` + +`Rigid` 是 Genesis 引擎中用于定义刚体材料属性的类,用于模拟刚体的物理行为,如碰撞、摩擦等。 + +## 功能说明 + +- 定义刚体的物理材料属性 +- 支持摩擦、恢复系数等参数的配置 +- 提供材料属性的获取和设置接口 +- 支持与其他物理系统的交互 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `density` | float | 材料密度 | +| `friction` | float | 摩擦系数 | +| `restitution` | float | 恢复系数 | +| `youngs_modulus` | float | 杨氏模量 | +| `poisson_ratio` | float | 泊松比 | + + +```{eval-rst} +.. autoclass:: genesis.engine.materials.rigid.Rigid + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/material/sph/index.md b/source/api_reference/material/sph/index.md new file mode 100644 index 0000000..8122c2c --- /dev/null +++ b/source/api_reference/material/sph/index.md @@ -0,0 +1,31 @@ +# SPH + +## 概述 + +SPH (Smoothed Particle Hydrodynamics) 材料模块提供了基于光滑粒子流体动力学方法的材料类。SPH 是一种无网格的数值方法,通过将连续介质离散为一组粒子来模拟流体的运动和行为。 + +## 材料类型 + +本模块包含以下材料类型: + +```{toctree} +liquid +``` + +## 使用场景 + +SPH材料模块适用于以下场景: + +- 复杂流体模拟(如水、油、蜂蜜等) +- 流体自由表面流动 +- 流体与固体的交互 +- 流体飞溅、破碎和合并效果 +- 海洋、河流等大规模流体场景 + +## 特点 + +- 无网格数值方法,无需复杂的网格生成 +- 能够自然模拟自由表面和复杂的流体动力学现象 +- 支持密度、粘度、表面张力等流体特性的调整 +- 适用于模拟各种不同性质的流体 +- 支持多种粒子采样方法 \ No newline at end of file diff --git a/source/api_reference/material/sph/liquid.md b/source/api_reference/material/sph/liquid.md new file mode 100644 index 0000000..f8f4673 --- /dev/null +++ b/source/api_reference/material/sph/liquid.md @@ -0,0 +1,31 @@ +# `gs.materials.SPH.Liquid` + +## 概述 + +`Liquid` 是 SPH (Smoothed Particle Hydrodynamics) 模拟中使用的液体材料类,用于模拟流体的力学特性。SPH 方法通过平滑粒子近似来模拟连续流体,适用于模拟复杂的流体行为,如飞溅、破碎和自由表面流动。 + +## 主要功能 + +- 实现了基于SPH方法的流体模拟 +- 支持密度、粘度和表面张力参数设置 +- 提供多种粒子采样方法 +- 支持可调节的状态刚度和指数参数 +- 适用于模拟各种液体(如水、油、蜂蜜等) + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `rho` | float | 1000.0 | 流体的静止密度 (kg/m³),默认值为水的密度 | +| `stiffness` | float | 50000.0 | 状态刚度 (N/m²),控制压力随压缩的增加程度 | +| `exponent` | float | 7.0 | 状态指数,控制压力随密度的非线性缩放程度 | +| `mu` | float | 0.005 | 流体的粘度,衡量流体内部摩擦的度量 | +| `gamma` | float | 0.01 | 流体的表面张力,控制材料在边界处的"结块"强度 | +| `sampler` | str | 'pbs' | 粒子采样方法,可选值:'pbs'、'regular'、'random' | + +```{eval-rst} +.. autoclass:: genesis.engine.materials.SPH.liquid.Liquid + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/options/morph/file_morph/drone.md b/source/api_reference/options/morph/file_morph/drone.md index ee0ba35..575da84 100644 --- a/source/api_reference/options/morph/file_morph/drone.md +++ b/source/api_reference/options/morph/file_morph/drone.md @@ -1,4 +1,37 @@ # `gs.morphs.Drone` + +## 概述 + +`Drone` 类用于从文件加载无人机模型,是 `FileMorph` 类的子类。它专门用于无人机模型,提供了特殊的参数来配置无人机的螺旋桨、电机和控制相关属性。 + +## 主要功能 + +- 从文件加载无人机模型 +- 支持设置无人机的初始位置和姿态 +- 控制无人机的可视化和碰撞属性 +- 可配置螺旋桨的链接名称和属性 +- 支持合并固定链接以简化模型 +- 可配置是否优先使用模型文件中定义的材质 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `file_path` | str | None | 要加载的无人机模型文件路径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 无人机的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 无人机的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 无人机的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化无人机模型 | +| `collision` | bool | True | 无人机是否需要参与碰撞检测 | +| `requires_jac_and_IK` | bool | False | 无人机是否需要雅可比矩阵和逆运动学计算 | +| `fixed` | bool | False | 是否固定无人机,使其不可移动 | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `merge_fixed_links` | bool | True | 是否合并无人机的固定链接以简化模型 | +| `prioritize_urdf_material` | bool | True | 是否优先使用模型文件中定义的材质 | +| `propellers_link_name` | list | [] | 无人机螺旋桨的链接名称列表 | +| `decompose_robot_error_threshold` | float | 0.0001 | 无人机分解时的误差阈值 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Drone ``` diff --git a/source/api_reference/options/morph/file_morph/file_morph.md b/source/api_reference/options/morph/file_morph/file_morph.md index b4a0dd5..854d5ef 100644 --- a/source/api_reference/options/morph/file_morph/file_morph.md +++ b/source/api_reference/options/morph/file_morph/file_morph.md @@ -1,4 +1,33 @@ # `gs.morphs.FileMorph` + +## 概述 + +`FileMorph` 是 Genesis 中用于从文件加载形态的基类。它提供了从各种文件格式加载模型和形态的接口,是创建复杂场景和对象的基础。 + +## 主要功能 + +- 从各种文件格式加载形态 +- 支持设置加载模型的位置和姿态 +- 控制模型的可视化和碰撞属性 +- 提供统一的接口来加载不同格式的文件 +- 支持设置模型的自由度和运动约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `file_path` | str | None | 要加载的文件路径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 模型的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 模型的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 模型的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化模型,仅用于 RigidEntity | +| `collision` | bool | True | 模型是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 模型是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | + + ```{eval-rst} .. autoclass:: genesis.options.morphs.FileMorph ``` diff --git a/source/api_reference/options/morph/file_morph/mesh.md b/source/api_reference/options/morph/file_morph/mesh.md index f03d9c3..0770a09 100644 --- a/source/api_reference/options/morph/file_morph/mesh.md +++ b/source/api_reference/options/morph/file_morph/mesh.md @@ -1,4 +1,41 @@ # `gs.morphs.Mesh` + +## 概述 + +`Mesh` 类用于从文件加载3D网格模型,是 `FileMorph` 类的子类。它支持加载各种常见的3D模型格式,如OBJ、STL、PLY等,是创建复杂3D对象的基础。 + +## 主要功能 + +- 从各种3D模型文件格式加载网格 +- 支持设置模型的位置和姿态 +- 控制模型的可视化和碰撞属性 +- 可用于刚体实体和其他需要网格形状的实体类型 +- 支持设置网格的自由度和运动约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `file_path` | str | None | 要加载的3D模型文件路径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 模型的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 模型的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 模型的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化模型,仅用于 RigidEntity | +| `collision` | bool | True | 模型是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 模型是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `order` | int | 1 | FEM网格的阶数,仅用于 FEMEntity | +| `mindihedral` | int | 10 | 四面体化过程中的最小二面角(度),仅用于需要四面体化的体积实体 | +| `minratio` | float | 1.1 | 四面体化过程中的最小四面体质量比,仅用于需要四面体化的体积实体 | +| `nobisect` | bool | True | 是否在四面体化过程中禁用二分法,仅用于需要四面体化的体积实体 | +| `quality` | bool | True | 是否在四面体化过程中提高质量,仅用于需要四面体化的体积实体 | +| `maxvolume` | float | -1.0 | 最大四面体体积,-1.0 表示无限制,仅用于需要四面体化的体积实体 | +| `verbose` | int | 0 | 四面体化过程中的详细程度,仅用于需要四面体化的体积实体 | +| `force_retet` | bool | False | 是否强制重新四面体化,仅用于需要四面体化的体积实体 | +| `decompose_robot_error_threshold` | float | 0.0001 | 机器人分解时的误差阈值 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Mesh ``` diff --git a/source/api_reference/options/morph/file_morph/mjcf.md b/source/api_reference/options/morph/file_morph/mjcf.md index a0616c9..6dd2deb 100644 --- a/source/api_reference/options/morph/file_morph/mjcf.md +++ b/source/api_reference/options/morph/file_morph/mjcf.md @@ -1,4 +1,35 @@ # `gs.morphs.MJCF` + +## 概述 + +`MJCF` 类用于从MJCF (MuJoCo XML Format) 文件加载模型,是 `FileMorph` 类的子类。MJCF是MuJoCo物理引擎使用的XML格式,用于定义物理模拟场景、机器人模型和环境。 + +## 主要功能 + +- 从MJCF文件加载完整的物理模拟模型 +- 支持设置模型的初始位置和姿态 +- 控制模型的可视化和碰撞属性 +- 支持合并固定链接以简化模型 +- 可配置是否优先使用MJCF文件中定义的材质 +- 支持设置模型的自由度和运动约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `file_path` | str | None | 要加载的MJCF文件路径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 模型的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 模型的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 模型的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化模型 | +| `collision` | bool | True | 模型是否需要参与碰撞检测 | +| `requires_jac_and_IK` | bool | False | 模型是否需要雅可比矩阵和逆运动学计算 | +| `fixed` | bool | False | 是否固定模型的基链接 | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `merge_fixed_links` | bool | True | 是否合并模型的固定链接以简化模型 | +| `decompose_robot_error_threshold` | float | 0.0001 | 模型分解时的误差阈值 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.MJCF ``` diff --git a/source/api_reference/options/morph/file_morph/terrain.md b/source/api_reference/options/morph/file_morph/terrain.md index 8744130..0cb2e37 100644 --- a/source/api_reference/options/morph/file_morph/terrain.md +++ b/source/api_reference/options/morph/file_morph/terrain.md @@ -1,4 +1,34 @@ # `gs.morphs.Terrain` + +## 概述 + +`Terrain` 类用于从文件加载地形模型,是 `FileMorph` 类的子类。它支持加载各种地形文件格式,用于创建复杂的物理模拟环境。 + +## 主要功能 + +- 从地形文件加载地形模型 +- 支持设置地形的位置和姿态 +- 控制地形的可视化和碰撞属性 +- 可用于创建复杂的物理模拟环境 +- 支持设置地形的自由度和运动约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `file_path` | str | None | 要加载的地形文件路径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 地形的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 地形的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 地形的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化地形 | +| `collision` | bool | True | 地形是否需要参与碰撞检测 | +| `requires_jac_and_IK` | bool | False | 地形是否需要雅可比矩阵和逆运动学计算 | +| `fixed` | bool | True | 是否固定地形,使其不可移动 | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `merge_fixed_links` | bool | True | 是否合并地形的固定链接以简化模型 | +| `decompose_robot_error_threshold` | float | 0.0001 | 地形分解时的误差阈值 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Terrain ``` diff --git a/source/api_reference/options/morph/file_morph/urdf.md b/source/api_reference/options/morph/file_morph/urdf.md index ccfbf87..a9f955b 100644 --- a/source/api_reference/options/morph/file_morph/urdf.md +++ b/source/api_reference/options/morph/file_morph/urdf.md @@ -1,4 +1,36 @@ # `gs.morphs.URDF` + +## 概述 + +`URDF` 类用于从URDF (Unified Robot Description Format) 文件加载机器人模型,是 `FileMorph` 类的子类。URDF是ROS机器人操作系统中常用的机器人描述格式,包含机器人的关节、连杆、传感器和执行器信息。 + +## 主要功能 + +- 从URDF文件加载完整的机器人模型 +- 支持设置机器人的初始位置和姿态 +- 控制机器人的可视化和碰撞属性 +- 支持合并固定链接以简化模型 +- 可配置是否优先使用URDF文件中定义的材质 +- 支持设置机器人的自由度和运动约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `file_path` | str | None | 要加载的URDF文件路径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 机器人的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 机器人的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 机器人的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化机器人模型 | +| `collision` | bool | True | 机器人是否需要参与碰撞检测 | +| `requires_jac_and_IK` | bool | False | 机器人是否需要雅可比矩阵和逆运动学计算 | +| `fixed` | bool | False | 是否固定机器人的基链接 | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `prioritize_urdf_material` | bool | True | 是否优先使用URDF文件中定义的材质 | +| `merge_fixed_links` | bool | True | 是否合并机器人的固定链接以简化模型 | +| `decompose_robot_error_threshold` | float | 0.0001 | 机器人分解时的误差阈值 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.URDF ``` diff --git a/source/api_reference/options/morph/morph.md b/source/api_reference/options/morph/morph.md index 1cb4ec2..5702577 100644 --- a/source/api_reference/options/morph/morph.md +++ b/source/api_reference/options/morph/morph.md @@ -1,4 +1,29 @@ # `gs.morphs.Morph` + +## 概述 + +`Morph` 是 Genesis 中表示实体形态的基类,封装了实体的几何形状和位姿信息。它是所有具体形态类的抽象基类,提供了创建各种实体形态的基础框架。 + +## 主要功能 + +- 封装实体的几何形状和位姿信息 +- 提供创建各种实体形态的统一接口 +- 支持设置实体的初始位置和姿态 +- 控制实体的可视化和碰撞属性 +- 支持设置实体的自由度和运动约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `pos` | tuple | (0.0, 0.0, 0.0) | 实体的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 实体的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 实体的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化实体,仅用于 RigidEntity | +| `collision` | bool | True | 实体是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 实体是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `is_free` | bool | True | 实体是否可以自由移动,仅用于 RigidEntity | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Morph ``` diff --git a/source/api_reference/options/morph/primitive/box.md b/source/api_reference/options/morph/primitive/box.md index 4e18333..a945cd1 100644 --- a/source/api_reference/options/morph/primitive/box.md +++ b/source/api_reference/options/morph/primitive/box.md @@ -1,4 +1,39 @@ # `gs.morphs.Box` + +## 概述 + +`Box` 类用于创建立方体形状的几何体,是 `Primitive` 类的子类。它提供了创建具有指定尺寸的立方体的接口,可用于构建各种场景对象。 + +## 主要功能 + +- 创建指定尺寸的立方体 +- 支持设置立方体的位置和姿态 +- 控制立方体的可视化和碰撞属性 +- 可用于刚体实体和其他需要立方体形状的实体类型 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `size` | tuple | (1.0, 1.0, 1.0) | 立方体的尺寸 (x, y, z),表示在各个轴上的长度 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 立方体的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 立方体的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 立方体的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化立方体,仅用于 RigidEntity | +| `collision` | bool | True | 立方体是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 立方体是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `order` | int | 1 | FEM网格的阶数,仅用于 FEMEntity | +| `mindihedral` | int | 10 | 四面体化过程中的最小二面角(度),仅用于需要四面体化的体积实体 | +| `minratio` | float | 1.1 | 四面体化过程中的最小四面体质量比,仅用于需要四面体化的体积实体 | +| `nobisect` | bool | True | 是否在四面体化过程中禁用二分法,仅用于需要四面体化的体积实体 | +| `quality` | bool | True | 是否在四面体化过程中提高质量,仅用于需要四面体化的体积实体 | +| `maxvolume` | float | -1.0 | 最大四面体体积,-1.0 表示无限制,仅用于需要四面体化的体积实体 | +| `verbose` | int | 0 | 四面体化过程中的详细程度,仅用于需要四面体化的体积实体 | +| `force_retet` | bool | False | 是否强制重新四面体化,仅用于需要四面体化的体积实体 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Box ``` diff --git a/source/api_reference/options/morph/primitive/cylinder.md b/source/api_reference/options/morph/primitive/cylinder.md index 43df868..6f82fa7 100644 --- a/source/api_reference/options/morph/primitive/cylinder.md +++ b/source/api_reference/options/morph/primitive/cylinder.md @@ -1,4 +1,40 @@ # `gs.morphs.Cylinder` + +## 概述 + +`Cylinder` 类用于创建圆柱体形状的几何体,是 `Primitive` 类的子类。它提供了创建具有指定半径和高度的圆柱体的接口,可用于构建各种场景对象。 + +## 主要功能 + +- 创建指定半径和高度的圆柱体 +- 支持设置圆柱体的位置和姿态 +- 控制圆柱体的可视化和碰撞属性 +- 可用于刚体实体和其他需要圆柱体形状的实体类型 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `radius` | float | 1.0 | 圆柱体的半径 | +| `height` | float | 1.0 | 圆柱体的高度 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 圆柱体的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 圆柱体的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 圆柱体的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化圆柱体,仅用于 RigidEntity | +| `collision` | bool | True | 圆柱体是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 圆柱体是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `order` | int | 1 | FEM网格的阶数,仅用于 FEMEntity | +| `mindihedral` | int | 10 | 四面体化过程中的最小二面角(度),仅用于需要四面体化的体积实体 | +| `minratio` | float | 1.1 | 四面体化过程中的最小四面体质量比,仅用于需要四面体化的体积实体 | +| `nobisect` | bool | True | 是否在四面体化过程中禁用二分法,仅用于需要四面体化的体积实体 | +| `quality` | bool | True | 是否在四面体化过程中提高质量,仅用于需要四面体化的体积实体 | +| `maxvolume` | float | -1.0 | 最大四面体体积,-1.0 表示无限制,仅用于需要四面体化的体积实体 | +| `verbose` | int | 0 | 四面体化过程中的详细程度,仅用于需要四面体化的体积实体 | +| `force_retet` | bool | False | 是否强制重新四面体化,仅用于需要四面体化的体积实体 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Cylinder ``` diff --git a/source/api_reference/options/morph/primitive/plane.md b/source/api_reference/options/morph/primitive/plane.md index 899e1ea..7bafa1e 100644 --- a/source/api_reference/options/morph/primitive/plane.md +++ b/source/api_reference/options/morph/primitive/plane.md @@ -1,4 +1,33 @@ # `gs.morphs.Plane` + +## 概述 + +`Plane` 类用于创建平面形状的几何体,是 `Primitive` 类的子类。它提供了创建具有指定尺寸的平面的接口,通常用于构建地面或其他平面表面。 + +## 主要功能 + +- 创建指定尺寸的平面 +- 支持设置平面的位置和姿态 +- 控制平面的可视化和碰撞属性 +- 可用于刚体实体和其他需要平面形状的实体类型 +- 支持设置平面的纹理平铺大小 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `pos` | tuple | (0.0, 0.0, 0.0) | 平面的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 平面的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 平面的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化平面,仅用于 RigidEntity | +| `collision` | bool | True | 平面是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 平面是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `plane_size` | tuple | (1e3, 1e3) | 平面的尺寸 (width, depth),默认值很大以模拟无限平面 | +| `tile_size` | tuple | (1, 1) | 每个纹理平铺的大小,用于可视化 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Plane ``` diff --git a/source/api_reference/options/morph/primitive/primitive.md b/source/api_reference/options/morph/primitive/primitive.md index adf51eb..cc489ef 100644 --- a/source/api_reference/options/morph/primitive/primitive.md +++ b/source/api_reference/options/morph/primitive/primitive.md @@ -1,4 +1,31 @@ # `gs.morphs.Primitive` + +## 概述 + +`Primitive` 是 Genesis 中用于创建基本几何形状的形态类。它提供了创建各种基本几何体(如立方体、球体、圆柱体等)的接口,是构建简单场景和对象的基础。 + +## 主要功能 + +- 创建各种基本几何形状 +- 支持设置几何体的尺寸和属性 +- 控制几何体的可视化和碰撞属性 +- 支持设置几何体的自由度和运动约束 +- 提供统一的接口来创建不同类型的基本几何体 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `pos` | tuple | (0.0, 0.0, 0.0) | 几何体的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 几何体的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 几何体的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化几何体,仅用于 RigidEntity | +| `collision` | bool | True | 几何体是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 几何体是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Primitive ``` diff --git a/source/api_reference/options/morph/primitive/sphere.md b/source/api_reference/options/morph/primitive/sphere.md index 5fd238c..2f849ca 100644 --- a/source/api_reference/options/morph/primitive/sphere.md +++ b/source/api_reference/options/morph/primitive/sphere.md @@ -1,4 +1,39 @@ # `gs.morphs.Sphere` + +## 概述 + +`Sphere` 类用于创建球体形状的几何体,是 `Primitive` 类的子类。它提供了创建具有指定半径的球体的接口,可用于构建各种场景对象。 + +## 主要功能 + +- 创建指定半径的球体 +- 支持设置球体的位置和姿态 +- 控制球体的可视化和碰撞属性 +- 可用于刚体实体和其他需要球体形状的实体类型 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `radius` | float | 1.0 | 球体的半径 | +| `pos` | tuple | (0.0, 0.0, 0.0) | 球体的初始位置 (x, y, z) | +| `euler` | tuple | (0.0, 0.0, 0.0) | 球体的初始欧拉角 (roll, pitch, yaw),使用弧度制 | +| `quat` | tuple | None | 球体的初始四元数 (w, x, y, z),如果指定则忽略 euler 参数 | +| `visualization` | bool | True | 是否需要可视化球体,仅用于 RigidEntity | +| `collision` | bool | True | 球体是否需要参与碰撞检测,仅用于 RigidEntity | +| `requires_jac_and_IK` | bool | False | 球体是否需要雅可比矩阵和逆运动学计算,仅用于 RigidEntity | +| `fixed` | bool | False | 是否固定实体的基链接,仅用于 RigidEntity | +| `contype` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `conaffinity` | int | 0xFFFF | 用于接触过滤的 32 位整数位掩码 | +| `order` | int | 1 | FEM网格的阶数,仅用于 FEMEntity | +| `mindihedral` | int | 10 | 四面体化过程中的最小二面角(度),仅用于需要四面体化的体积实体 | +| `minratio` | float | 1.1 | 四面体化过程中的最小四面体质量比,仅用于需要四面体化的体积实体 | +| `nobisect` | bool | True | 是否在四面体化过程中禁用二分法,仅用于需要四面体化的体积实体 | +| `quality` | bool | True | 是否在四面体化过程中提高质量,仅用于需要四面体化的体积实体 | +| `maxvolume` | float | -1.0 | 最大四面体体积,-1.0 表示无限制,仅用于需要四面体化的体积实体 | +| `verbose` | int | 0 | 四面体化过程中的详细程度,仅用于需要四面体化的体积实体 | +| `force_retet` | bool | False | 是否强制重新四面体化,仅用于需要四面体化的体积实体 | + ```{eval-rst} .. autoclass:: genesis.options.morphs.Sphere ``` diff --git a/source/api_reference/options/options.md b/source/api_reference/options/options.md index 0e4bc72..7415b13 100644 --- a/source/api_reference/options/options.md +++ b/source/api_reference/options/options.md @@ -1,4 +1,28 @@ # `gs.options.Options` + +`Options` 是 Genesis 引擎中所有选项类的基类,用于设置场景中特定组件的参数。 + +## 功能说明 + +- 提供参数验证和类型检查功能 +- 支持参数的序列化和反序列化 +- 提供参数复制和属性复制功能 +- 作为所有选项类的统一接口 + +## 主要方法 + +| 方法名 | 描述 | +| ------ | ---- | +| `copy_attributes_from(source)` | 从源对象复制属性 | +| `copy()` | 创建对象的副本 | +| `dict()` | 将对象转换为字典 | +| `json()` | 将对象转换为 JSON 字符串 | +| `model_dump()` | 将对象转换为字典(Pydantic v2 API) | +| `model_dump_json()` | 将对象转换为 JSON 字符串(Pydantic v2 API) | + ```{eval-rst} .. autoclass:: genesis.options.options.Options + :members: + :show-inheritance: + :undoc-members: ``` diff --git a/source/api_reference/options/renderer/batchrenderer.md b/source/api_reference/options/renderer/batchrenderer.md new file mode 100644 index 0000000..5dceb6f --- /dev/null +++ b/source/api_reference/options/renderer/batchrenderer.md @@ -0,0 +1,39 @@ +# `gs.renderers.BatchRenderer` + +## 概述 + +`BatchRenderer` 是 Genesis 中的批量渲染器类,它允许一次性渲染多个场景或视角,提高渲染效率。批量渲染器适合需要生成大量图像或动画的应用场景,如批量生成训练数据、动画渲染等。 + +## 主要功能 + +- 支持批量渲染多个场景或视角 +- 提供多种渲染模式和选项 +- 支持多线程渲染,提高渲染效率 +- 支持材质和纹理渲染 +- 适合需要生成大量图像或动画的应用场景 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `renderer` | object | None | 使用的渲染器实例,可以是 Rasterizer 或 RayTracer | +| `num_threads` | int | 4 | 用于渲染的线程数量 | +| `output_format` | str | "png" | 输出图像的格式,可以是 "png"、"jpg"、"exr" 或 "tiff" | +| `output_path` | str | "./output" | 输出图像的路径 | +| `file_prefix` | str | "render" | 输出文件名的前缀 | +| `file_suffix` | str | "" | 输出文件名的后缀 | +| `start_frame` | int | 0 | 开始渲染的帧编号 | +| `end_frame` | int | 100 | 结束渲染的帧编号 | +| `step_frame` | int | 1 | 渲染的帧步长 | +| `save_depth` | bool | False | 是否保存深度图 | +| `save_normals` | bool | False | 是否保存法线图 | +| `save_albedo` | bool | False | 是否保存反照率图 | +| `save_material` | bool | False | 是否保存材质图 | +| `save_id` | bool | False | 是否保存ID图 | +| `save_mask` | bool | False | 是否保存掩码图 | +| `wireframe` | bool | False | 是否启用线框模式 | +| `debug` | bool | False | 是否启用调试模式 | + +```{eval-rst} +.. autoclass:: genesis.options.renderers.BatchRenderer +``` diff --git a/source/api_reference/options/renderer/index.md b/source/api_reference/options/renderer/index.md index a54b41c..6d8a413 100644 --- a/source/api_reference/options/renderer/index.md +++ b/source/api_reference/options/renderer/index.md @@ -7,4 +7,5 @@ This configures the backend renderer used by all the cameras in a scene. renderer rasterizer raytracer +batchrenderer ``` diff --git a/source/api_reference/options/renderer/rasterizer.md b/source/api_reference/options/renderer/rasterizer.md index b29e9d5..70d6367 100644 --- a/source/api_reference/options/renderer/rasterizer.md +++ b/source/api_reference/options/renderer/rasterizer.md @@ -1,4 +1,40 @@ # `gs.renderers.Rasterizer` + +## 概述 + +`Rasterizer` 是 Genesis 中的光栅化渲染器类,它使用传统的光栅化技术来渲染场景。光栅化渲染器具有较高的性能,适合实时渲染场景,但在某些视觉效果上(如全局光照、反射等)可能不如光线追踪渲染器。 + +## 主要功能 + +- 使用光栅化技术进行实时渲染 +- 支持阴影、抗锯齿和基本的后处理效果 +- 提供多种渲染模式和选项 +- 支持材质和纹理渲染 +- 适合需要高性能的实时应用场景 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `vis_mode` | str | "default" | 可视化模式,可以是 "default"、"wireframe"、"normals"、"uv"、"vertex_color" 或 "material" | +| `smooth` | bool | True | 是否启用平滑着色 | +| `double_sided` | bool | False | 是否启用双面渲染 | +| `shadows` | bool | True | 是否启用阴影 | +| `shadowmap_size` | int | 1024 | 阴影贴图的分辨率 | +| `msaa_samples` | int | 1 | 多重采样抗锯齿的采样数量 | +| `temporal_aa` | bool | False | 是否启用时间抗锯齿 | +| `bloom` | bool | False | 是否启用光晕效果 | +| `bloom_threshold` | float | 1.0 | 光晕效果的阈值 | +| `bloom_radius` | float | 1.0 | 光晕效果的半径 | +| `bloom_intensity` | float | 1.0 | 光晕效果的强度 | +| `ambient_occlusion` | bool | False | 是否启用环境光遮蔽 | +| `ambient_occlusion_radius` | float | 0.5 | 环境光遮蔽的半径 | +| `ambient_occlusion_intensity` | float | 1.0 | 环境光遮蔽的强度 | +| `tone_mapping` | bool | True | 是否启用色调映射 | +| `tone_mapping_exposure` | float | 1.0 | 色调映射的曝光值 | +| `wireframe` | bool | False | 是否启用线框模式 | +| `debug` | bool | False | 是否启用调试模式 | + ```{eval-rst} .. autoclass:: genesis.options.renderers.Rasterizer ``` diff --git a/source/api_reference/options/renderer/raytracer.md b/source/api_reference/options/renderer/raytracer.md index 447d2ce..8614d13 100644 --- a/source/api_reference/options/renderer/raytracer.md +++ b/source/api_reference/options/renderer/raytracer.md @@ -1,4 +1,44 @@ # `gs.renderers.RayTracer` + +## 概述 + +`RayTracer` 是 Genesis 中的光线追踪渲染器类,它使用光线追踪技术来渲染场景。光线追踪渲染器可以产生非常真实的视觉效果,包括全局光照、反射、折射和阴影等,但通常比光栅化渲染器的性能要低。 + +## 主要功能 + +- 使用光线追踪技术进行高质量渲染 +- 支持全局光照、反射、折射等高级视觉效果 +- 提供多种采样和抗锯齿选项 +- 支持材质和纹理渲染 +- 适合需要高质量视觉效果的应用场景 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `samples_per_pixel` | int | 16 | 每像素的采样数量 | +| `max_bounces` | int | 8 | 光线的最大反弹次数 | +| `diffuse_samples` | int | 8 | 漫反射采样数量 | +| `specular_samples` | int | 8 | 镜面反射采样数量 | +| `transparency_samples` | int | 8 | 透明度采样数量 | +| `ambient_occlusion` | bool | True | 是否启用环境光遮蔽 | +| `ambient_occlusion_samples` | int | 4 | 环境光遮蔽采样数量 | +| `ambient_occlusion_distance` | float | 1.0 | 环境光遮蔽的距离 | +| `shadows` | bool | True | 是否启用阴影 | +| `shadow_samples` | int | 4 | 阴影采样数量 | +| `caustics` | bool | False | 是否启用焦散效果 | +| `caustics_samples` | int | 16 | 焦散效果采样数量 | +| `global_illumination` | bool | True | 是否启用全局光照 | +| `global_illumination_samples` | int | 8 | 全局光照采样数量 | +| `anti_aliasing` | bool | True | 是否启用抗锯齿 | +| `denoise` | bool | False | 是否启用去噪 | +| `denoise_strength` | float | 0.5 | 去噪强度 | +| `tone_mapping` | bool | True | 是否启用色调映射 | +| `tone_mapping_exposure` | float | 1.0 | 色调映射的曝光值 | +| `tone_mapping_gamma` | float | 2.2 | 色调映射的伽马值 | +| `wireframe` | bool | False | 是否启用线框模式 | +| `debug` | bool | False | 是否启用调试模式 | + ```{eval-rst} .. autoclass:: genesis.options.renderers.RayTracer ``` diff --git a/source/api_reference/options/renderer/renderer.md b/source/api_reference/options/renderer/renderer.md deleted file mode 100644 index 4694ca0..0000000 --- a/source/api_reference/options/renderer/renderer.md +++ /dev/null @@ -1,4 +0,0 @@ -# `gs.renderers.Renderer` -```{eval-rst} -.. autoclass:: genesis.options.renderers.Renderer -``` diff --git a/source/api_reference/options/renderer/rendereroptions.md b/source/api_reference/options/renderer/rendereroptions.md new file mode 100644 index 0000000..2907f36 --- /dev/null +++ b/source/api_reference/options/renderer/rendereroptions.md @@ -0,0 +1,118 @@ +# `gs.renderers.RendererOptions` + +## 概述 + +`RendererOptions` 是 Genesis 中渲染器的配置选项类,用于设置渲染器的各种参数,如分辨率、阴影、抗锯齿等。它是所有具体渲染器(如 Rasterizer、RayTracer、BatchRenderer)的基础配置类。 + +## 主要功能 + +- 设置渲染器的基本参数,如分辨率、阴影和抗锯齿 +- 配置光源和环境光 +- 控制材质和纹理的渲染效果 +- 支持多种渲染后端的配置 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `width` | int | 1024 | 渲染图像的宽度(像素) | +| `height` | int | 768 | 渲染图像的高度(像素) | +| `shadow` | bool | True | 是否启用阴影效果 | +| `shadowmap_size` | int | 1024 | 阴影贴图的分辨率 | +| `shadowmap_bias` | float | 0.0005 | 阴影贴图的偏移值,用于减少阴影失真 | +| `shadowmap_pcf` | int | 3 | 阴影贴图的PCF(Percentage Closer Filtering)采样大小 | +| `shadowmap_softness` | float | 1.0 | 阴影的柔和度 | +| `shadowmap_cascade` | int | 4 | 阴影贴图的级联数量,用于提高远处阴影的质量 | +| `shadowmap_cascade_split` | list[float] | [0.1, 0.25, 0.5] | 阴影贴图级联的分割比例 | +| `shadowmap_cascade_fade` | float | 0.1 | 阴影贴图级联之间的淡入淡出比例 | +| `shadowmap_cascade_fade_depth` | float | 1.0 | 阴影贴图级联淡出的深度范围 | +| `shadowmap_cascade_fade_resolution` | int | 128 | 阴影贴图级联淡出的分辨率 | +| `shadowmap_cascade_fade_resolution_depth` | int | 128 | 阴影贴图级联淡出深度的分辨率 | +| `shadowmap_cascade_fade_resolution_normal` | int | 128 | 阴影贴图级联淡出法线的分辨率 | +| `shadowmap_cascade_fade_resolution_position` | int | 128 | 阴影贴图级联淡出位置的分辨率 | +| `shadowmap_cascade_fade_resolution_uv` | int | 128 | 阴影贴图级联淡出UV的分辨率 | +| `shadowmap_cascade_fade_resolution_color` | int | 128 | 阴影贴图级联淡出颜色的分辨率 | +| `shadowmap_cascade_fade_resolution_mask` | int | 128 | 阴影贴图级联淡出掩码的分辨率 | +| `shadowmap_cascade_fade_resolution_depth_stencil` | int | 128 | 阴影贴图级联淡出深度模板的分辨率 | +| `shadowmap_cascade_fade_resolution_multisample` | int | 128 | 阴影贴图级联淡出多重采样的分辨率 | +| `shadowmap_cascade_fade_resolution_accumulation` | int | 128 | 阴影贴图级联淡出累积的分辨率 | +| `shadowmap_cascade_fade_resolution_motion` | int | 128 | 阴影贴图级联淡出运动的分辨率 | +| `shadowmap_cascade_fade_resolution_id` | int | 128 | 阴影贴图级联淡出ID的分辨率 | +| `shadowmap_cascade_fade_resolution_material` | int | 128 | 阴影贴图级联淡出材质的分辨率 | +| `shadowmap_cascade_fade_resolution_lighting` | int | 128 | 阴影贴图级联淡出光照的分辨率 | +| `shadowmap_cascade_fade_resolution_ambient` | int | 128 | 阴影贴图级联淡出环境光的分辨率 | +| `shadowmap_cascade_fade_resolution_specular` | int | 128 | 阴影贴图级联淡出高光的分辨率 | +| `shadowmap_cascade_fade_resolution_reflection` | int | 128 | 阴影贴图级联淡出反射的分辨率 | +| `shadowmap_cascade_fade_resolution_refraction` | int | 128 | 阴影贴图级联淡出折射的分辨率 | +| `shadowmap_cascade_fade_resolution_transparency` | int | 128 | 阴影贴图级联淡出透明度的分辨率 | +| `shadowmap_cascade_fade_resolution_emission` | int | 128 | 阴影贴图级联淡出发射的分辨率 | +| `shadowmap_cascade_fade_resolution_occlusion` | int | 128 | 阴影贴图级联淡出遮挡的分辨率 | +| `shadowmap_cascade_fade_resolution_ssao` | int | 128 | 阴影贴图级联淡出SSAO的分辨率 | +| `shadowmap_cascade_fade_resolution_ssdo` | int | 128 | 阴影贴图级联淡出SSDO的分辨率 | +| `shadowmap_cascade_fade_resolution_ssr` | int | 128 | 阴影贴图级联淡出SSR的分辨率 | +| `shadowmap_cascade_fade_resolution_volume` | int | 128 | 阴影贴图级联淡出体积的分辨率 | +| `shadowmap_cascade_fade_resolution_particle` | int | 128 | 阴影贴图级联淡出粒子的分辨率 | +| `shadowmap_cascade_fade_resolution_terrain` | int | 128 | 阴影贴图级联淡出地形的分辨率 | +| `shadowmap_cascade_fade_resolution_water` | int | 128 | 阴影贴图级联淡出水面的分辨率 | +| `shadowmap_cascade_fade_resolution_sky` | int | 128 | 阴影贴图级联淡出天空的分辨率 | +| `msaa` | int | 1 | 多重采样抗锯齿的采样数量 | +| `temporal_aa` | bool | False | 是否启用时间抗锯齿 | +| `temporal_aa_samples` | int | 4 | 时间抗锯齿的采样数量 | +| `temporal_aa_mix` | float | 0.8 | 时间抗锯齿的混合因子 | +| `bloom` | bool | False | 是否启用光晕效果 | +| `bloom_threshold` | float | 1.0 | 光晕效果的阈值 | +| `bloom_radius` | float | 1.0 | 光晕效果的半径 | +| `bloom_intensity` | float | 1.0 | 光晕效果的强度 | +| `ambient_occlusion` | bool | False | 是否启用环境光遮蔽 | +| `ambient_occlusion_radius` | float | 1.0 | 环境光遮蔽的半径 | +| `ambient_occlusion_intensity` | float | 1.0 | 环境光遮蔽的强度 | +| `ambient_occlusion_quality` | int | 1 | 环境光遮蔽的质量级别 | +| `dof` | bool | False | 是否启用景深效果 | +| `dof_focus_distance` | float | 10.0 | 景深效果的焦点距离 | +| `dof_focus_range` | float | 1.0 | 景深效果的焦点范围 | +| `dof_aperture` | float | 0.1 | 景深效果的光圈大小 | +| `dof_blur_range` | float | 10.0 | 景深效果的模糊范围 | +| `motion_blur` | bool | False | 是否启用运动模糊 | +| `motion_blur_intensity` | float | 1.0 | 运动模糊的强度 | +| `motion_blur_quality` | int | 1 | 运动模糊的质量级别 | +| `tone_mapping` | bool | True | 是否启用色调映射 | +| `tone_mapping_exposure` | float | 1.0 | 色调映射的曝光值 | +| `tone_mapping_gamma` | float | 2.2 | 色调映射的伽马值 | +| `tone_mapping_white_balance` | list[float] | [1.0, 1.0, 1.0] | 色调映射的白平衡 | +| `fog` | bool | False | 是否启用雾效 | +| `fog_color` | list[float] | [0.5, 0.5, 0.5] | 雾效的颜色 | +| `fog_start` | float | 10.0 | 雾效开始的距离 | +| `fog_end` | float | 100.0 | 雾效结束的距离 | +| `fog_density` | float | 0.01 | 雾效的密度 | +| `skybox` | bool | True | 是否启用天空盒 | +| `skybox_texture` | str | None | 天空盒纹理的路径 | +| `environment_map` | bool | False | 是否启用环境贴图 | +| `environment_map_texture` | str | None | 环境贴图的路径 | +| `environment_map_intensity` | float | 1.0 | 环境贴图的强度 | +| `environment_map_rotation` | float | 0.0 | 环境贴图的旋转角度 | +| `wireframe` | bool | False | 是否启用线框模式 | +| `debug` | bool | False | 是否启用调试模式 | +| `debug_mode` | str | None | 调试模式的类型 | +| `debug_color` | list[float] | [1.0, 0.0, 0.0] | 调试模式的颜色 | +| `debug_opacity` | float | 1.0 | 调试模式的透明度 | +| `debug_size` | float | 1.0 | 调试模式的大小 | +| `debug_thickness` | float | 1.0 | 调试模式的厚度 | +| `debug_quality` | int | 1 | 调试模式的质量级别 | +| `debug_show_normals` | bool | False | 是否显示法线 | +| `debug_show_tangents` | bool | False | 是否显示切线 | +| `debug_show_bitangents` | bool | False | 是否显示副切线 | +| `debug_show_uvs` | bool | False | 是否显示UV坐标 | +| `debug_show_vertex_colors` | bool | False | 是否显示顶点颜色 | +| `debug_show_bounding_boxes` | bool | False | 是否显示边界框 | +| `debug_show_wireframe` | bool | False | 是否显示线框 | +| `debug_show_normals_length` | float | 0.1 | 法线显示的长度 | +| `debug_show_tangents_length` | float | 0.1 | 切线显示的长度 | +| `debug_show_bitangents_length` | float | 0.1 | 副切线显示的长度 | +| `debug_show_uvs_scale` | float | 1.0 | UV坐标显示的缩放比例 | +| `debug_show_vertex_colors_scale` | float | 1.0 | 顶点颜色显示的缩放比例 | +| `debug_show_bounding_boxes_color` | list[float] | [1.0, 0.0, 0.0] | 边界框显示的颜色 | +| `debug_show_wireframe_color` | list[float] | [0.0, 1.0, 0.0] | 线框显示的颜色 | + +```{eval-rst} +.. autoclass:: genesis.options.renderers.RendererOptions +``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/avatar_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/avatar_options.md index de78c19..9941add 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/avatar_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/avatar_options.md @@ -1,4 +1,29 @@ # `gs.options.AvatarOptions` + +## 概述 + +`AvatarOptions` 是 Genesis 中配置 AvatarSolver 的选项类,用于设置与虚拟角色相关的模拟参数。AvatarEntity 类似于 RigidEntity,但没有内部物理特性,主要用于控制虚拟角色的碰撞和逆运动学(IK)行为。 + +## 主要功能 + +- 配置 AvatarSolver 的时间步长 +- 启用或禁用碰撞检测 +- 设置自碰撞和相邻碰撞的参数 +- 配置逆运动学(IK)的目标数量 +- 限制动态约束的最大数量 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `enable_collision` | bool | False | 是否启用碰撞检测。 | +| `enable_self_collision` | bool | False | 是否启用每个实体内部的自碰撞。 | +| `enable_adjacent_collision` | bool | False | 是否启用每个实体内部连续父子身体对之间的碰撞。 | +| `max_collision_pairs` | int | 300 | 最大碰撞对数量。 | +| `IK_max_targets` | int | 6 | 最大逆运动学(IK)目标数量。增加此值不会影响IK求解速度,但会增加内存使用。 | +| `max_dynamic_constraints` | int | 8 | 动态约束(如吸盘)的最大数量。 | + ```{eval-rst} .. autoclass:: genesis.options.solvers.AvatarOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/coupler_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/coupler_options.md deleted file mode 100644 index f76117e..0000000 --- a/source/api_reference/options/simulator_coupler_and_solver_options/coupler_options.md +++ /dev/null @@ -1,4 +0,0 @@ -# `gs.options.CouplerOptions` -```{eval-rst} -.. autoclass:: genesis.options.solvers.CouplerOptions -``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/fem_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/fem_options.md index e4e8c9d..568eac7 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/fem_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/fem_options.md @@ -1,4 +1,40 @@ # `gs.options.FEMOptions` + +## 概述 + +`FEMOptions` 是 Genesis 中配置有限元方法(FEM)求解器的选项类,用于设置 FEM 模拟的参数,如时间步长、阻尼、重力、求解器类型(显式/隐式)以及各种迭代参数。 + +## 主要功能 + +- 配置 FEM 求解器的时间步长和重力 +- 设置阻尼参数 +- 选择使用显式或隐式求解器 +- 配置牛顿迭代参数(用于隐式求解器) +- 设置 PCG 求解器参数(用于隐式求解器) +- 调整线搜索参数(用于隐式求解器) +- 启用/禁用顶点约束 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `gravity` | Optional[tuple] | None | 重力加速度(N/kg)。如果为 None,则从 `SimOptions` 继承。 | +| `damping` | Optional[float] | 0.0 | 阻尼系数。 | +| `floor_height` | Optional[float] | None | 地板高度(米)。如果为 None,则从 `SimOptions` 继承。 | +| `use_implicit_solver` | bool | False | 是否使用隐式求解器。默认使用显式求解器。 | +| `n_newton_iterations` | int | 1 | 牛顿迭代次数。仅当使用隐式求解器时有效。 | +| `n_pcg_iterations` | int | 500 | PCG 迭代次数。仅当使用隐式求解器时有效。 | +| `n_linesearch_iterations` | int | 0 | 线搜索迭代次数。仅当使用隐式求解器时有效。 | +| `newton_dx_threshold` | float | 1e-06 | 牛顿求解器的阈值。仅当使用隐式求解器时有效。 | +| `pcg_threshold` | float | 1e-06 | PCG 求解器的阈值。仅当使用隐式求解器时有效。 | +| `linesearch_c` | float | 0.0001 | 线搜索充分下降参数。仅当使用隐式求解器时有效。 | +| `linesearch_tau` | float | 0.5 | 线搜索步长缩减因子。仅当使用隐式求解器时有效。 | +| `damping_alpha` | float | 0.5 | 隐式求解器的 Rayleigh 阻尼因子 α。仅当使用隐式求解器时有效。 | +| `damping_beta` | float | 0.0005 | 隐式求解器的 Rayleigh 阻尼因子 β。仅当使用隐式求解器时有效。 | +| `enable_vertex_constraints` | bool | False | 是否启用顶点约束。 | + + ```{eval-rst} .. autoclass:: genesis.options.solvers.FEMOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/mpm_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/mpm_options.md index 92d5f32..9ba971a 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/mpm_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/mpm_options.md @@ -1,4 +1,31 @@ # `gs.options.MPMOptions` + +## 概述 + +`MPMOptions` 是 Genesis 中配置物质点法(MPM)求解器的选项类,用于设置 MPM 模拟的参数,如时间步长、重力、粒子大小、网格密度、模拟域边界等。 + +## 主要功能 + +- 配置 MPM 求解器的时间步长和重力 +- 设置粒子大小和网格密度 +- 启用/禁用 CPIC(兼容粒子单元)以支持与薄物体的耦合 +- 定义模拟域的上下边界 +- 配置稀疏网格相关参数 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `gravity` | Optional[tuple] | None | 重力加速度(N/kg)。如果为 None,则从 `SimOptions` 继承。 | +| `particle_size` | Optional[float] | None | 粒子直径(米)。如果未指定,将基于 `grid_density` 计算粒子大小。 | +| `grid_density` | float | 64 | 每米的网格单元数量。 | +| `enable_CPIC` | bool | False | 是否启用 CPIC(兼容粒子单元)以支持与薄物体的耦合。 | +| `lower_bound` | tuple | (-1.0, -1.0, 0.0) | 模拟域的下界(米)。 | +| `upper_bound` | tuple | (1.0, 1.0, 1.0) | 模拟域的上界(米)。 | +| `use_sparse_grid` | bool | False | 是否使用稀疏网格。除非了解其影响,否则不建议修改。 | +| `leaf_block_size` | int | 8 | 稀疏模式下叶子块的大小。 | + ```{eval-rst} .. autoclass:: genesis.options.solvers.MPMOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/pbd_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/pbd_options.md index c9d6e77..e03f8fc 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/pbd_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/pbd_options.md @@ -1,4 +1,34 @@ # `gs.options.PBDOptions` + +## 概述 + +`PBDOptions` 是 Genesis 中配置位置基动力学(PBD)求解器的选项类,用于设置 PBD 模拟的参数,如时间步长、重力、各种约束求解器的迭代次数、粒子大小、空间哈希网格参数和模拟域边界等。 + +## 主要功能 + +- 配置 PBD 求解器的时间步长和重力 +- 设置各种约束求解器的最大迭代次数(拉伸、弯曲、体积、密度、粘度) +- 定义粒子大小 +- 配置空间哈希网格参数 +- 设置模拟域的上下边界 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `gravity` | Optional[tuple] | None | 重力加速度(N/kg)。如果为 None,则从 `SimOptions` 继承。 | +| `max_stretch_solver_iterations` | int | 4 | 拉伸约束求解器的最大迭代次数。 | +| `max_bending_solver_iterations` | int | 1 | 弯曲约束求解器的最大迭代次数。 | +| `max_volume_solver_iterations` | int | 1 | 体积约束求解器的最大迭代次数。 | +| `max_density_solver_iterations` | int | 1 | 密度约束求解器的最大迭代次数。 | +| `max_viscosity_solver_iterations` | int | 1 | 粘度约束求解器的最大迭代次数。 | +| `particle_size` | Optional[float] | 0.01 | 粒子直径(米)。 | +| `hash_grid_res` | Optional[tuple] | None | 空间哈希网格的大小(米)。如果为 None,则自动计算。 | +| `hash_grid_cell_size` | Optional[float] | None | 空间哈希网格的单元格大小(米)。这应该至少是 `particle_size` 的 1.25 倍。如果为 None,则自动计算。 | +| `lower_bound` | tuple | (-100.0, -100.0, 0.0) | 模拟域的下界(米)。 | +| `upper_bound` | tuple | (100.0, 100.0, 100.0) | 模拟域的上界(米)。 | + ```{eval-rst} .. autoclass:: genesis.options.solvers.PBDOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/rigid_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/rigid_options.md index 9cb393d..096eb03 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/rigid_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/rigid_options.md @@ -1,4 +1,55 @@ # `gs.options.RigidOptions` + +## 概述 + +`RigidOptions` 是 Genesis 中配置刚体动力学求解器的选项类,用于设置刚体模拟的参数,如碰撞检测、约束求解、积分器类型、休眠机制等。该类提供了丰富的参数来控制刚体模拟的行为和性能。 + +## 主要功能 + +- 配置刚体模拟的时间步长和重力 +- 控制碰撞检测行为(自碰撞、相邻碰撞、碰撞对数量等) +- 设置约束求解器参数(迭代次数、容差、求解器类型等) +- 配置积分器类型 +- 启用/禁用休眠机制以提高性能 +- 支持批处理信息输出 +- 提供与Mujoco兼容性选项 +- 支持GJK碰撞检测算法 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `gravity` | Optional[tuple] | None | 重力加速度(N/kg)。如果为 None,则从 `SimOptions` 继承。 | +| `enable_collision` | bool | True | 是否启用碰撞检测。 | +| `enable_joint_limit` | bool | True | 是否启用关节限制。 | +| `enable_self_collision` | bool | True | 是否启用自碰撞检测。 | +| `enable_adjacent_collision` | bool | False | 是否启用相邻碰撞检测。 | +| `disable_constraint` | bool | False | 是否禁用约束。 | +| `max_collision_pairs` | int | 300 | 最大碰撞对数量。 | +| `integrator` | enum | approximate_implicitfast | 积分器类型。 | +| `IK_max_targets` | int | 6 | 逆运动学的最大目标数量。 | +| `batch_links_info` | Optional[bool] | False | 是否启用批量链接信息输出。 | +| `batch_joints_info` | Optional[bool] | False | 是否启用批量关节信息输出。 | +| `batch_dofs_info` | Optional[bool] | False | 是否启用批量自由度信息输出。 | +| `constraint_solver` | enum | Newton | 约束求解器类型。 | +| `iterations` | int | 50 | 约束求解器的最大迭代次数。 | +| `tolerance` | float | 1e-08 | 约束求解器的容差。 | +| `ls_iterations` | int | 50 | 线性搜索的最大迭代次数。 | +| `ls_tolerance` | float | 0.01 | 线性搜索的容差。 | +| `sparse_solve` | bool | False | 是否使用稀疏求解。 | +| `contact_resolve_time` | Optional[float] | None | 接触分辨率时间。 | +| `constraint_timeconst` | float | 0.01 | 约束时间常数。 | +| `use_contact_island` | bool | False | 是否使用接触岛。 | +| `box_box_detection` | bool | True | 是否启用盒对盒检测。 | +| `use_hibernation` | bool | False | 是否启用休眠机制。注意:休眠功能尚未经过充分测试,将很快完全支持。 | +| `hibernation_thresh_vel` | float | 0.001 | 休眠速度阈值。 | +| `hibernation_thresh_acc` | float | 0.01 | 休眠加速度阈值。 | +| `max_dynamic_constraints` | int | 8 | 最大动态约束数量。 | +| `enable_multi_contact` | bool | True | 是否启用多接触点。 | +| `enable_mujoco_compatibility` | bool | False | 是否启用Mujoco兼容性。 | +| `use_gjk_collision` | bool | True | 是否使用GJK( Gilbert-Johnson-Keerthi)碰撞检测算法代替MPR( Minkowski Portal Refinement)。 | + ```{eval-rst} .. autoclass:: genesis.options.solvers.RigidOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/sap_coupler_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/sap_coupler_options.md new file mode 100644 index 0000000..7286760 --- /dev/null +++ b/source/api_reference/options/simulator_coupler_and_solver_options/sap_coupler_options.md @@ -0,0 +1,40 @@ +# `gs.options.SAPCouplerOptions` + +## 概述 + +`SAPCouplerOptions`是 Genesis 中配置耦合器求解器的选项类,用于设置耦合器的迭代参数、收敛阈值、接触刚度等参数,以控制不同求解器之间的耦合行为。 + +## 主要功能 + +- 配置 SAP 耦合器的迭代参数 +- 设置 PCG 求解器的收敛阈值 +- 调整线搜索迭代参数 +- 配置接触刚度参数 +- 设置 FEM 和刚体的接触类型 +- 启用/禁用刚体与 FEM 之间的耦合 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `n_sap_iterations` | int | 5 | SAP 迭代次数 | +| `n_pcg_iterations` | int | 100 | PCG 迭代次数 | +| `n_linesearch_iterations` | int | 10 | 线搜索迭代次数 | +| `sap_convergence_atol` | float | 1e-06 | SAP 绝对收敛容差 | +| `sap_convergence_rtol` | float | 1e-05 | SAP 相对收敛容差 | +| `sap_taud` | float | 0.1 | SAP 阻尼参数 | +| `sap_beta` | float | 1.0 | SAP 松弛因子 | +| `sap_sigma` | float | 0.001 | SAP 惩罚参数 | +| `pcg_threshold` | float | 1e-06 | PCG 求解器阈值 | +| `linesearch_ftol` | float | 1e-06 | 线搜索函数容差 | +| `linesearch_max_step_size` | float | 1.5 | 线搜索最大步长 | +| `hydroelastic_stiffness` | float | 1e8 | 水弹性接触刚度 | +| `point_contact_stiffness` | float | 1e8 | 点接触刚度 | +| `fem_floor_contact_type` | str | "tet" | FEM 与地板的接触类型,可选值:"tet"、"vert"、"none" | +| `enable_fem_self_tet_contact` | bool | True | 是否启用基于四面体的自接触 | +| `rigid_floor_contact_type` | str | "vert" | 刚体与地板的接触类型,可选值:"vert"、"none" | +| `enable_rigid_fem_contact` | bool | True | 是否启用刚体与 FEM 求解器之间的耦合 | + +```{eval-rst} +.. autoclass:: genesis.options.solvers.SAPCouplerOptions +``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/sf_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/sf_options.md index d854a9d..d1da35a 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/sf_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/sf_options.md @@ -1,4 +1,33 @@ # `gs.options.SFOptions` + +## 概述 + +`SFOptions` 是 Genesis 中配置 SF(Smoke/Fire,烟雾/火焰)求解器的选项类,用于设置烟雾/火焰模拟的参数,如时间步长、分辨率、求解器迭代次数、衰减系数、温度阈值以及入口参数等。 + +## 主要功能 + +- 配置 SF 求解器的时间步长 +- 设置模拟分辨率 +- 调整求解器迭代次数 +- 配置温度阈值和衰减系数 +- 设置入口参数(位置、速度、方向、强度) + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `res` | Optional[int] | 128 | 模拟分辨率。 | +| `solver_iters` | Optional[int] | 500 | 求解器迭代次数。 | +| `decay` | Optional[float] | 0.99 | 衰减系数。 | +| `T_low` | Optional[float] | 1.0 | 低温阈值。 | +| `T_high` | Optional[float] | 0.0 | 高温阈值。 | +| `inlet_pos` | Optional[tuple[int, int, int]] | (0.6, 0.0, 0.1) | 入口位置。 | +| `inlet_vel` | Optional[tuple[int, int, int]] | (0, 0, 1) | 入口速度。 | +| `inlet_quat` | Optional[tuple[int, int, int, int]] | (1, 0, 0, 0) | 入口方向(四元数)。 | +| `inlet_s` | Optional[float] | 400.0 | 入口强度。 | + + ```{eval-rst} .. autoclass:: genesis.options.solvers.SFOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/sim_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/sim_options.md index 9940354..b955d02 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/sim_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/sim_options.md @@ -1,4 +1,30 @@ # `gs.options.SimOptions` + +## 概述 + +`SimOptions` 是 Genesis 中配置顶层模拟器的选项类,它指定了模拟器的全局设置,如时间步长、重力、子步数等。这些设置将应用于所有求解器,除非求解器自身的选项中指定了不同的值。 + +## 主要功能 + +- 配置模拟器的全局时间步长和子步数 +- 设置重力和地板高度 +- 启用或禁用可微分模式 +- 配置接触处理方式 +- 为所有求解器提供默认设置 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | float | 0.01 | 每个模拟步骤的时间持续时间(秒) | +| `substeps` | int | 1 | 每个模拟步骤的子步骤数量 | +| `substeps_local` | Optional[int] | None | 存储在GPU内存中的子步骤数量,用于可微分模式 | +| `gravity` | tuple | (0.0, 0.0, -9.81) | 重力加速度(N/kg),默认指向负z轴方向 | +| `floor_height` | float | 0.0 | 地板的高度(米) | +| `requires_grad` | bool | False | 是否启用可微分模式 | +| `use_hydroelastic_contact` | bool | False | 是否使用水弹性接触 | + + ```{eval-rst} .. autoclass:: genesis.options.solvers.SimOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/sph_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/sph_options.md index 49a51e9..5df5ab9 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/sph_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/sph_options.md @@ -1,4 +1,35 @@ # `gs.options.SPHOptions` + +## 概述 + +`SPHOptions` 是 Genesis 中配置光滑粒子流体动力学(SPH)求解器的选项类,用于设置 SPH 模拟的参数,如时间步长、重力、粒子大小、压力求解器类型、模拟域边界、哈希网格参数以及各种求解器迭代次数和容差等。 + +## 主要功能 + +- 配置 SPH 求解器的时间步长和重力 +- 设置粒子大小和压力求解器类型(如 WCSPH、DFSPH) +- 定义模拟域的上下边界 +- 配置空间哈希网格参数 +- 设置密度和散度求解器的迭代次数和容差 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `gravity` | Optional[tuple] | None | 重力加速度(N/kg)。如果为 None,则从 `SimOptions` 继承。 | +| `particle_size` | float | 0.02 | 粒子直径(米)。 | +| `pressure_solver` | str | "WCSPH" | 压力求解器类型,可选值为 "WCSPH" 或 "DFSPH"。 | +| `lower_bound` | tuple | (-100.0, -100.0, 0.0) | 模拟域的下界(米)。 | +| `upper_bound` | tuple | (100.0, 100.0, 100.0) | 模拟域的上界(米)。 | +| `hash_grid_res` | Optional[tuple] | None | 空间哈希网格的大小(米)。如果为 None,则自动计算。 | +| `hash_grid_cell_size` | Optional[float] | None | 空间哈希网格的单元格大小(米)。这应该至少是 `particle_size` 的 2 倍。如果为 None,则自动计算。 | +| `max_divergence_error` | float | 0.1 | DFSPH 方法的最大散度误差。 | +| `max_density_error_percent` | float | 0.05 | DFSPH 方法的最大密度误差百分比(0.05 表示 0.05%)。 | +| `max_divergence_solver_iterations` | int | 100 | 散度求解器的最大迭代次数。 | +| `max_density_solver_iterations` | int | 100 | 密度求解器的最大迭代次数。 | + + ```{eval-rst} .. autoclass:: genesis.options.solvers.SPHOptions ``` diff --git a/source/api_reference/options/simulator_coupler_and_solver_options/tool_options.md b/source/api_reference/options/simulator_coupler_and_solver_options/tool_options.md index b150ad2..759ac88 100644 --- a/source/api_reference/options/simulator_coupler_and_solver_options/tool_options.md +++ b/source/api_reference/options/simulator_coupler_and_solver_options/tool_options.md @@ -1,4 +1,21 @@ # `gs.options.ToolOptions` + +## 概述 + +`ToolOptions` 是 Genesis 中配置 ToolSolver 的选项类,用于设置工具实体(ToolEntity)的模拟参数。ToolEntity 是 RigidEntity 的简化形式,支持单向工具->其他物体的耦合,但没有内部动力学,只能从单个网格创建。这是可微分刚体-软体交互的临时解决方案,一旦 RigidSolver 支持可微分模式,该求解器将被移除。 + +## 主要功能 + +- 配置 ToolSolver 的时间步长 +- 设置地板高度 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `dt` | Optional[float] | None | 每个模拟步骤的时间持续时间(秒)。如果为 None,则从 `SimOptions` 继承。 | +| `floor_height` | Optional[float] | None | 地板的高度(米)。如果为 None,则从 `SimOptions` 继承。 | + ```{eval-rst} .. autoclass:: genesis.options.solvers.ToolOptions ``` diff --git a/source/api_reference/options/surface/emission/emission.md b/source/api_reference/options/surface/emission/emission.md index b42edae..a0a7cfb 100644 --- a/source/api_reference/options/surface/emission/emission.md +++ b/source/api_reference/options/surface/emission/emission.md @@ -1,4 +1,42 @@ # `gs.surfaces.Emission` + +`gs.surfaces.Emission` 是Genesis引擎中的自发光表面类型,主要用于创建能够自身发光的物体。在Genesis的光线追踪管道中,光源不是特殊类型的对象,而是带有自发光表面的实体。 + +## 主要功能 + +- 允许物体自身发光,用于创建各种光源效果 +- 支持自定义发光颜色和强度 +- 可以使用纹理贴图定义发光区域和图案 +- 继承了基础表面的所有属性(颜色、透明度、粗糙度等) +- 适用于创建霓虹灯、指示灯、发光标志等效果 +- 支持双面发光效果 +- 可与其他材质属性结合使用,创建复杂的视觉效果 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|-------|------|--------|------| +| color | Optional[tuple] | None | 表面颜色,采用RGB格式,值范围为 [0, 1] | +| opacity | Optional[float] | None | 表面不透明度,值范围为 [0, 1],0表示完全透明,1表示完全不透明 | +| roughness | Optional[float] | None | 表面粗糙度,值范围为 [0, 1],0表示完全光滑,1表示完全粗糙 | +| metallic | Optional[float] | None | 金属度,值范围为 [0, 1],0表示非金属,1表示金属 | +| emissive | Optional[tuple] | None | 自发光颜色,采用RGB格式,值范围为 [0, ∞],值越大发光越强 | +| ior | Optional[float] | None | 折射率,用于计算透明和半透明材质的光学特性 | +| opacity_texture | Optional[Texture] | None | 不透明度纹理贴图 | +| roughness_texture | Optional[Texture] | None | 粗糙度纹理贴图 | +| metallic_texture | Optional[Texture] | None | 金属度纹理贴图 | +| normal_texture | Optional[Texture] | None | 法线贴图 | +| emissive_texture | Optional[Texture] | None | 自发光纹理贴图,用于定义发光区域和图案 | +| default_roughness | float | 1.0 | 默认粗糙度值,当roughness参数未设置时使用 | +| vis_mode | Optional[str] | None | 可视化模式,控制表面的渲染方式 | +| smooth | bool | True | 是否使用平滑着色,False表示使用平面着色 | +| double_sided | Optional[bool] | None | 是否双面渲染表面 | +| beam_angle | float | 180 | 光束角度,用于控制表面的光照效果 | +| normal_diff_clamp | float | 180 | 法线差异限制,用于优化渲染效果 | +| recon_backend | str | splashsurf | 重建后端,用于表面重建操作 | +| generate_foam | bool | False | 是否生成泡沫效果 | +| foam_options | Optional[FoamOptions] | None | 泡沫效果选项配置 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Emission ``` diff --git a/source/api_reference/options/surface/emission/index.md b/source/api_reference/options/surface/emission/index.md index 1ab90e1..8391e91 100644 --- a/source/api_reference/options/surface/emission/index.md +++ b/source/api_reference/options/surface/emission/index.md @@ -1,5 +1,16 @@ # Emission +Emission(自发光)材质是Genesis引擎中一种特殊的表面材质类型,主要用于创建能够自身发光的物体,如光源、霓虹灯、发光标志等。 + +## 主要特点 + +- 支持自定义发光颜色和强度 +- 可调整发光区域和纹理 +- 适用于创建各种光源效果 +- 支持与其他材质属性(如颜色、透明度)结合使用 +- 可用于模拟真实世界中的发光物体 +- 提供多种发光模式和配置选项 + ```{toctree} :maxdepth: 2 diff --git a/source/api_reference/options/surface/glass/glass.md b/source/api_reference/options/surface/glass/glass.md index 2132cf4..f02ad92 100644 --- a/source/api_reference/options/surface/glass/glass.md +++ b/source/api_reference/options/surface/glass/glass.md @@ -1,4 +1,48 @@ # `gs.surfaces.Glass` + +`gs.surfaces.Glass` 是Genesis引擎中用于模拟玻璃材质的表面类型,支持真实的光折射和反射效果,适用于创建各种透明和半透明的物体。 + +## 主要功能 + +- 模拟真实玻璃的光学特性,包括折射和反射 +- 默认粗糙度为0.0,提供极高的表面光滑度 +- 默认折射率为1.5,模拟普通玻璃的光学特性 +- 支持透明度调整,可创建半透明效果 +- 支持次表面散射效果,增强真实感 +- 支持厚度参数,用于模拟不同厚度的玻璃 +- 提供多种纹理贴图选项,包括透明度、法线、厚度等 +- 与光线追踪渲染器完全兼容 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|-------|------|--------|------| +| color | Optional[tuple] | None | 表面颜色,采用RGB格式,值范围为 [0, 1] | +| opacity | Optional[float] | None | 表面不透明度,值范围为 [0, 1],0表示完全透明,1表示完全不透明 | +| roughness | float | 0.0 | 表面粗糙度,值范围为 [0, 1],0表示完全光滑,1表示完全粗糙 | +| metallic | Optional[float] | None | 金属度,值范围为 [0, 1],0表示非金属,1表示金属 | +| emissive | Optional[tuple] | None | 自发光颜色,采用RGB格式,值范围为 [0, ∞] | +| ior | float | 1.5 | 折射率,用于计算光的折射效果(普通玻璃的折射率约为1.5) | +| opacity_texture | Optional[Texture] | None | 不透明度纹理贴图 | +| roughness_texture | Optional[Texture] | None | 粗糙度纹理贴图 | +| metallic_texture | Optional[Texture] | None | 金属度纹理贴图 | +| normal_texture | Optional[Texture] | None | 法线贴图,用于增强表面细节 | +| emissive_texture | Optional[Texture] | None | 自发光纹理贴图 | +| default_roughness | float | 1.0 | 默认粗糙度值,当roughness参数未设置时使用 | +| vis_mode | Optional[str] | None | 可视化模式,控制表面的渲染方式 | +| smooth | bool | True | 是否使用平滑着色,False表示使用平面着色 | +| double_sided | Optional[bool] | None | 是否双面渲染表面 | +| beam_angle | float | 180 | 光束角度,用于控制表面的光照效果 | +| normal_diff_clamp | float | 180 | 法线差异限制,用于优化渲染效果 | +| recon_backend | str | splashsurf | 重建后端,用于表面重建操作 | +| generate_foam | bool | False | 是否生成泡沫效果 | +| foam_options | Optional[FoamOptions] | None | 泡沫效果选项配置 | +| subsurface | bool | False | 是否开启次表面散射效果 | +| thickness | Optional[float] | None | 玻璃厚度,用于模拟真实玻璃的厚度效果 | +| thickness_texture | Optional[Texture] | None | 厚度纹理贴图 | +| specular_texture | Optional[Texture] | None | 高光纹理贴图 | +| transmission_texture | Optional[Texture] | None | 透射纹理贴图 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Glass ``` diff --git a/source/api_reference/options/surface/glass/index.md b/source/api_reference/options/surface/glass/index.md index 51530d6..59c65ab 100644 --- a/source/api_reference/options/surface/glass/index.md +++ b/source/api_reference/options/surface/glass/index.md @@ -1,5 +1,17 @@ # Glass +Glass(玻璃)材质是Genesis引擎中用于模拟透明和半透明材料的表面类型,主要用于创建玻璃、水、宝石等具有折射和反射特性的物体。 + +## 主要特点 + +- 支持真实的光折射和反射效果 +- 可调整折射率(IOR)以模拟不同类型的透明材料 +- 支持色散效果,增强视觉真实感 +- 提供预设的玻璃和水材质,便于快速使用 +- 支持透明度和颜色调整 +- 适用于创建窗户、水杯、水面等场景 +- 与光线追踪渲染器完全兼容 + ```{toctree} :maxdepth: 2 diff --git a/source/api_reference/options/surface/glass/water.md b/source/api_reference/options/surface/glass/water.md index 6a01a16..8b4273d 100644 --- a/source/api_reference/options/surface/glass/water.md +++ b/source/api_reference/options/surface/glass/water.md @@ -1,4 +1,48 @@ # `gs.surfaces.Water` + +`gs.surfaces.Water` 是Genesis引擎中用于模拟水面材质的表面类型,是 `Glass` 表面的快捷方式,预配置了适合模拟水的参数值。 + +## 主要功能 + +- 预配置的水材质,使用适合水的参数值 +- 默认颜色为蓝绿色 (0.61, 0.98, 0.93),模拟自然水面 +- 默认粗糙度为0.2,模拟水面的轻微波动 +- 默认折射率为1.2,符合水的光学特性 +- 支持透明度调整,可创建清澈或浑浊的水面效果 +- 支持纹理贴图,可添加波纹、泡沫等细节 +- 支持生成泡沫效果,增强水面真实感 +- 与流体模拟系统兼容,可用于动态水面 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|-------|------|--------|------| +| color | tuple | (0.61, 0.98, 0.93) | 表面颜色,采用RGB格式,默认值为蓝绿色 | +| opacity | Optional[float] | None | 表面不透明度,值范围为 [0, 1],0表示完全透明,1表示完全不透明 | +| roughness | float | 0.2 | 表面粗糙度,值范围为 [0, 1],0表示完全光滑,1表示完全粗糙 | +| metallic | Optional[float] | None | 金属度,值范围为 [0, 1],0表示非金属,1表示金属 | +| emissive | Optional[tuple] | None | 自发光颜色,采用RGB格式,值范围为 [0, ∞] | +| ior | float | 1.2 | 折射率,用于计算光的折射效果(水的折射率约为1.333,这里使用1.2作为模拟值) | +| opacity_texture | Optional[Texture] | None | 不透明度纹理贴图 | +| roughness_texture | Optional[Texture] | None | 粗糙度纹理贴图 | +| metallic_texture | Optional[Texture] | None | 金属度纹理贴图 | +| normal_texture | Optional[Texture] | None | 法线贴图,用于增强表面细节 | +| emissive_texture | Optional[Texture] | None | 自发光纹理贴图 | +| default_roughness | float | 1.0 | 默认粗糙度值,当roughness参数未设置时使用 | +| vis_mode | Optional[str] | None | 可视化模式,控制表面的渲染方式 | +| smooth | bool | True | 是否使用平滑着色,False表示使用平面着色 | +| double_sided | Optional[bool] | None | 是否双面渲染表面 | +| beam_angle | float | 180 | 光束角度,用于控制表面的光照效果 | +| normal_diff_clamp | float | 180 | 法线差异限制,用于优化渲染效果 | +| recon_backend | str | splashsurf | 重建后端,用于表面重建操作 | +| generate_foam | bool | False | 是否生成泡沫效果 | +| foam_options | Optional[FoamOptions] | None | 泡沫效果选项配置 | +| subsurface | bool | False | 是否开启次表面散射效果 | +| thickness | Optional[float] | None | 水体厚度,用于模拟真实水体的厚度效果 | +| thickness_texture | Optional[Texture] | None | 厚度纹理贴图 | +| specular_texture | Optional[Texture] | None | 高光纹理贴图 | +| transmission_texture | Optional[Texture] | None | 透射纹理贴图 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Water ``` diff --git a/source/api_reference/options/surface/metal/aluminium.md b/source/api_reference/options/surface/metal/aluminium.md index 54f2745..1885932 100644 --- a/source/api_reference/options/surface/metal/aluminium.md +++ b/source/api_reference/options/surface/metal/aluminium.md @@ -1,4 +1,20 @@ # `gs.surfaces.Aluminium` + +`gs.surfaces.Aluminium` 是Genesis引擎中用于模拟铝金属材质的表面类型,是 `Metal` 表面的快捷方式,预配置了适合铝的参数值。 + +## 主要功能 + +- 模拟真实铝金属的光学特性和颜色表现 +- 默认设置 `metal_type = 'aluminium'`,无需手动指定 +- 默认粗糙度为0.1,提供典型的铝表面光滑度 +- 支持调整各种金属参数,如粗糙度、颜色等 +- 与光线追踪渲染器完全兼容 +- 支持各种纹理贴图,包括法线、粗糙度等 + +## 参数说明 + +该类继承了 `Metal` 类的所有参数,并将 `metal_type` 默认设置为 `'aluminium'`。有关详细参数说明,请参考 [Metal](./metal.md) 类的文档。 + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Aluminium ``` diff --git a/source/api_reference/options/surface/metal/copper.md b/source/api_reference/options/surface/metal/copper.md index 2472703..12e0a32 100644 --- a/source/api_reference/options/surface/metal/copper.md +++ b/source/api_reference/options/surface/metal/copper.md @@ -1,4 +1,20 @@ # `gs.surfaces.Copper` + +`gs.surfaces.Copper` 是Genesis引擎中用于模拟铜金属材质的表面类型,是 `Metal` 表面的快捷方式,预配置了适合铜的参数值。 + +## 主要功能 + +- 模拟真实铜金属的光学特性和颜色表现(典型的铜红色) +- 默认设置 `metal_type = 'copper'`,无需手动指定 +- 默认粗糙度为0.1,提供典型的铜表面光滑度 +- 支持调整各种金属参数,如粗糙度、颜色等 +- 与光线追踪渲染器完全兼容 +- 支持各种纹理贴图,包括法线、粗糙度等 + +## 参数说明 + +该类继承了 `Metal` 类的所有参数,并将 `metal_type` 默认设置为 `'copper'`。有关详细参数说明,请参考 [Metal](./metal.md) 类的文档。 + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Copper ``` diff --git a/source/api_reference/options/surface/metal/gold.md b/source/api_reference/options/surface/metal/gold.md index f3db50d..a796031 100644 --- a/source/api_reference/options/surface/metal/gold.md +++ b/source/api_reference/options/surface/metal/gold.md @@ -1,4 +1,20 @@ # `gs.surfaces.Gold` + +`gs.surfaces.Gold` 是Genesis引擎中用于模拟金金属材质的表面类型,是 `Metal` 表面的快捷方式,预配置了适合金的参数值。 + +## 主要功能 + +- 模拟真实金金属的光学特性和颜色表现(典型的金黄色) +- 默认设置 `metal_type = 'gold'`,无需手动指定 +- 默认粗糙度为0.1,提供典型的金表面光滑度 +- 支持调整各种金属参数,如粗糙度、颜色等 +- 与光线追踪渲染器完全兼容 +- 支持各种纹理贴图,包括法线、粗糙度等 + +## 参数说明 + +该类继承了 `Metal` 类的所有参数,并将 `metal_type` 默认设置为 `'gold'`。有关详细参数说明,请参考 [Metal](./metal.md) 类的文档。 + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Gold ``` diff --git a/source/api_reference/options/surface/metal/index.md b/source/api_reference/options/surface/metal/index.md index ab09e7d..4490143 100644 --- a/source/api_reference/options/surface/metal/index.md +++ b/source/api_reference/options/surface/metal/index.md @@ -1,5 +1,17 @@ # Metal +Metal模块包含了Genesis引擎中用于模拟各种金属材质的表面类型,这些材质支持真实的金属反射特性和高光效果,适用于创建各种金属物体。 + +## 主要特点 + +- 支持多种预设金属材质,包括铁、铝、铜和金 +- 模拟真实金属的光学特性,包括高反射率和特定的颜色表现 +- 默认情况下具有高金属度和低粗糙度,提供典型的金属外观 +- 支持自定义金属参数,如粗糙度、金属度、颜色等 +- 与光线追踪渲染器完全兼容,提供真实的光影效果 +- 支持各种纹理贴图,包括法线、粗糙度、金属度等 +- 可用于创建从粗糙铸铁到抛光镜面金属的各种效果 + ```{toctree} :maxdepth: 2 diff --git a/source/api_reference/options/surface/metal/iron.md b/source/api_reference/options/surface/metal/iron.md index d22e178..12fc15c 100644 --- a/source/api_reference/options/surface/metal/iron.md +++ b/source/api_reference/options/surface/metal/iron.md @@ -1,4 +1,20 @@ # `gs.surfaces.Iron` + +`gs.surfaces.Iron` 是Genesis引擎中用于模拟铁金属材质的表面类型,是 `Metal` 表面的快捷方式,预配置了适合铁的参数值。 + +## 主要功能 + +- 模拟真实铁金属的光学特性和颜色表现(典型的银灰色) +- 默认设置 `metal_type = 'iron'`,无需手动指定 +- 默认粗糙度为0.1,提供典型的铁表面光滑度 +- 支持调整各种金属参数,如粗糙度、颜色等 +- 与光线追踪渲染器完全兼容 +- 支持各种纹理贴图,包括法线、粗糙度等 + +## 参数说明 + +该类继承了 `Metal` 类的所有参数,并将 `metal_type` 默认设置为 `'iron'`。有关详细参数说明,请参考 [Metal](./metal.md) 类的文档。 + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Iron ``` diff --git a/source/api_reference/options/surface/metal/metal.md b/source/api_reference/options/surface/metal/metal.md index b387737..233e860 100644 --- a/source/api_reference/options/surface/metal/metal.md +++ b/source/api_reference/options/surface/metal/metal.md @@ -1,4 +1,45 @@ # `gs.surfaces.Metal` + +`gs.surfaces.Metal` 是Genesis引擎中用于模拟金属材质的表面类型,支持真实的金属反射特性和高光效果,适用于创建各种金属物体。 + +## 主要功能 + +- 模拟真实金属的光学特性,包括高反射率和特定的颜色表现 +- 默认粗糙度为0.1,提供典型的金属表面光滑度 +- 支持自定义金属类型,包括铁、铝、铜和金 +- 默认金属类型为铁(iron) +- 支持调整金属度参数,控制金属特性的强度 +- 支持各种纹理贴图,包括法线、粗糙度、金属度等 +- 与光线追踪渲染器完全兼容,提供真实的光影效果 +- 可用于创建从粗糙到抛光的各种金属表面效果 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|-------|------|--------|------| +| color | Optional[tuple] | None | 表面颜色,采用RGB格式,值范围为 [0, 1] | +| opacity | Optional[float] | None | 表面不透明度,值范围为 [0, 1],0表示完全透明,1表示完全不透明 | +| roughness | Optional[float] | 0.1 | 表面粗糙度,值范围为 [0, 1],0表示完全光滑,1表示完全粗糙 | +| metallic | Optional[float] | None | 金属度,值范围为 [0, 1],0表示非金属,1表示金属 | +| emissive | Optional[tuple] | None | 自发光颜色,采用RGB格式,值范围为 [0, ∞] | +| ior | Optional[float] | None | 折射率,用于计算光的折射效果 | +| opacity_texture | Optional[Texture] | None | 不透明度纹理贴图 | +| roughness_texture | Optional[Texture] | None | 粗糙度纹理贴图 | +| metallic_texture | Optional[Texture] | None | 金属度纹理贴图 | +| normal_texture | Optional[Texture] | None | 法线贴图,用于增强表面细节 | +| emissive_texture | Optional[Texture] | None | 自发光纹理贴图 | +| default_roughness | float | 1.0 | 默认粗糙度值,当roughness参数未设置时使用 | +| vis_mode | Optional[str] | None | 可视化模式,控制表面的渲染方式 | +| smooth | bool | True | 是否使用平滑着色,False表示使用平面着色 | +| double_sided | Optional[bool] | None | 是否双面渲染表面 | +| beam_angle | float | 180 | 光束角度,用于控制表面的光照效果 | +| normal_diff_clamp | float | 180 | 法线差异限制,用于优化渲染效果 | +| recon_backend | str | splashsurf | 重建后端,用于表面重建操作 | +| generate_foam | bool | False | 是否生成泡沫效果 | +| foam_options | Optional[FoamOptions] | None | 泡沫效果选项配置 | +| metal_type | Optional[str] | iron | 金属类型,可选值为 iron, aluminium, copper, gold | +| diffuse_texture | Optional[Texture] | None | 漫反射纹理贴图 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Metal ``` diff --git a/source/api_reference/options/surface/plastic/collision.md b/source/api_reference/options/surface/plastic/collision.md index b598393..50cbb19 100644 --- a/source/api_reference/options/surface/plastic/collision.md +++ b/source/api_reference/options/surface/plastic/collision.md @@ -1,4 +1,87 @@ # `gs.surfaces.Collision` + +`gs.surfaces.Collision` 是Genesis引擎中用于碰撞几何体的默认表面类型,主要用于物理碰撞检测和模拟,同时也提供了基本的视觉渲染能力。 + +## 主要功能 + +- 为碰撞几何体提供默认的灰色外观(默认颜色为 (0.5, 0.5, 0.5)) +- 支持基本的视觉属性调整(颜色、透明度、粗糙度等) +- 继承了Plastic类的所有功能,适用于各种碰撞场景 +- 与物理引擎完全兼容,确保精确的碰撞检测 +- 支持纹理贴图功能,可自定义碰撞体外观 +- 提供双面渲染选项,适用于复杂碰撞几何体 +- 支持法线贴图,增强碰撞体的视觉细节 +- 可配置光束角度和法线差异限制,优化渲染效果 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|-------|------|--------|------| +| color | tuple | (0.5, 0.5, 0.5) | 表面颜色,采用RGB格式,值范围为 [0, 1] | +| opacity | Optional[float] | None | 表面不透明度,值范围为 [0, 1],0表示完全透明,1表示完全不透明 | +| roughness | Optional[float] | None | 表面粗糙度,值范围为 [0, 1],0表示完全光滑,1表示完全粗糙 | +| metallic | Optional[float] | None | 金属度,值范围为 [0, 1],0表示非金属,1表示金属 | +| emissive | Optional[tuple] | None | 自发光颜色,采用RGB格式,值范围为 [0, ∞] | +| ior | Optional[float] | 1.0 | 折射率,用于计算透明和半透明材质的光学特性 | +| opacity_texture | Optional[Texture] | None | 不透明度纹理贴图,用于创建透明区域的图案 | +| roughness_texture | Optional[Texture] | None | 粗糙度纹理贴图,用于创建表面粗糙度的变化 | +| metallic_texture | Optional[Texture] | None | 金属度纹理贴图,用于创建金属和非金属区域的混合 | +| normal_texture | Optional[Texture] | None | 法线贴图,用于增强表面细节和立体感 | +| emissive_texture | Optional[Texture] | None | 自发光纹理贴图,用于创建发光区域的图案 | +| default_roughness | float | 1.0 | 默认粗糙度值,当roughness参数未设置时使用 | +| vis_mode | Optional[str] | None | 可视化模式,控制表面的渲染方式 | +| smooth | bool | True | 是否使用平滑着色,False表示使用平面着色 | +| double_sided | Optional[bool] | None | 是否双面渲染表面 | +| beam_angle | float | 180 | 光束角度,用于控制表面的光照效果 | +| normal_diff_clamp | float | 180 | 法线差异限制,用于优化渲染效果 | +| recon_backend | str | splashsurf | 重建后端,用于表面重建操作 | +| generate_foam | bool | False | 是否生成泡沫效果 | +| foam_options | Optional[FoamOptions] | None | 泡沫效果选项配置 | +| diffuse_texture | Optional[Texture] | None | 漫反射纹理贴图,用于控制表面的颜色和图案 | +| specular_texture | Optional[Texture] | None | 高光纹理贴图,用于控制表面的高光效果 | + +## 使用示例 + +### 基本碰撞表面配置 +```python +import genesis as gs + +# 创建一个基本的碰撞表面 +collision_surface = gs.surfaces.Collision( + color=(0.8, 0.8, 0.8), # 浅灰色 + opacity=1.0, # 完全不透明 + roughness=0.5 # 中等粗糙度 +) +``` + +### 半透明碰撞表面 +```python +import genesis as gs + +# 创建一个半透明的碰撞表面 +collision_surface = gs.surfaces.Collision( + color=(0.2, 0.6, 0.8), # 蓝色 + opacity=0.5, # 半透明 + smooth=True # 平滑着色 +) +``` + +### 使用纹理的碰撞表面 +```python +import genesis as gs + +# 创建一个带有纹理的碰撞表面 +collision_surface = gs.surfaces.Collision( + color=(1.0, 1.0, 1.0), # 白色基础色 + roughness_texture=gs.textures.Texture( + path="textures/roughness_map.png" + ), + normal_texture=gs.textures.Texture( + path="textures/normal_map.png" + ) +) +``` + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Collision :show-inheritance: diff --git a/source/api_reference/options/surface/plastic/default.md b/source/api_reference/options/surface/plastic/default.md index 8f0cdf0..4ba9035 100644 --- a/source/api_reference/options/surface/plastic/default.md +++ b/source/api_reference/options/surface/plastic/default.md @@ -1,4 +1,47 @@ # `gs.surfaces.Default` + +## 概述 + +`gs.surfaces.Default` 是 Genesis 引擎中默认使用的表面材质类,实际上是 `gs.surfaces.Plastic` 类的别名,但添加了一些额外的透射参数。它提供了一个通用的材质配置,适用于大多数不需要特殊材质效果的场景。 + +## 主要功能 + +- **Plastic类的完全功能**:继承了 Plastic 类的所有功能和参数 +- **额外透射参数**:添加了 specular_trans 和 diffuse_trans 参数用于控制透射效果 +- **通用材质配置**:作为默认材质,提供了适用于大多数场景的合理默认值 +- **完全兼容**:与 Plastic 类完全兼容,可以在任何使用 Plastic 的地方使用 Default + +## 参数说明 + +Default 类继承了 Plastic 类的所有参数,并添加了以下额外参数: + +| 参数名称 | 类型 | 默认值 | 描述 | +| --- | --- | --- | --- | +| `color` | `Optional[tuple]` | `None` | 表面颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `opacity` | `Optional[float]` | `None` | 表面透明度,取值范围 0.0(完全透明)到 1.0(完全不透明) | +| `roughness` | `Optional[float]` | `None` | 表面粗糙度,取值范围 0.0(完全光滑)到 1.0(完全粗糙) | +| `metallic` | `Optional[float]` | `None` | 金属度,通常设置为较低值(如 0.0)以模拟塑料特性 | +| `emissive` | `Optional[tuple]` | `None` | 发射光颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `ior` | `Optional[float]` | `None` | 折射率 | +| `opacity_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 透明度纹理 | +| `roughness_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 粗糙度纹理 | +| `metallic_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 金属度纹理 | +| `normal_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 法线纹理 | +| `emissive_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 发射光纹理 | +| `diffuse_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 漫反射纹理 | +| `specular_trans` | `Optional[float]` | `0.0` | 镜面透射系数,控制镜面透射效果的强度 | +| `diffuse_trans` | `Optional[float]` | `0.0` | 漫反射透射系数,控制漫反射透射效果的强度 | +| `default_roughness` | `float` | `1.0` | 默认粗糙度值 | +| `vis_mode` | `Optional[str]` | `None` | 可视化模式 | +| `smooth` | `bool` | `True` | 是否启用平滑着色 | +| `double_sided` | `Optional[bool]` | `None` | 是否启用双面渲染 | +| `beam_angle` | `float` | `180` | 发射光的光束角度 | +| `normal_diff_clamp` | `float` | `180` | 计算表面法线时的阈值 | +| `recon_backend` | `str` | `splashsurf` | 表面重建后端,可选值:['splashsurf', 'openvdb'] | +| `generate_foam` | `bool` | `False` | 是否为基于粒子的实体生成泡沫效果 | +| `foam_options` | `Optional[genesis.options.misc.FoamOptions]` | `None` | 泡沫生成选项 | + + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Default :show-inheritance: diff --git a/source/api_reference/options/surface/plastic/index.md b/source/api_reference/options/surface/plastic/index.md index c50ec77..08d52f5 100644 --- a/source/api_reference/options/surface/plastic/index.md +++ b/source/api_reference/options/surface/plastic/index.md @@ -1,5 +1,16 @@ # Plastic +## 概述 + +塑料材质是 Genesis 引擎中常用的一种非金属材质类型,提供了多种预设配置以满足不同的视觉需求。塑料材质通常具有较低的金属度值,支持多种表面粗糙度设置,并可根据需要调整透明度和颜色。 + +## 主要特点 + +- **多种预设配置**:提供默认、光滑、粗糙、反射和碰撞等多种预设 +- **可定制性**:支持调整颜色、粗糙度、透明度等参数 +- **性能优化**:针对不同渲染后端进行了性能优化 +- **广泛适用**:适用于各种非金属物体,如玩具、容器、电子产品外壳等 + ```{toctree} :maxdepth: 2 diff --git a/source/api_reference/options/surface/plastic/plastic.md b/source/api_reference/options/surface/plastic/plastic.md index 0a7b0d1..fe2ed53 100644 --- a/source/api_reference/options/surface/plastic/plastic.md +++ b/source/api_reference/options/surface/plastic/plastic.md @@ -1,4 +1,46 @@ # `gs.surfaces.Plastic` + +## 概述 + +`gs.surfaces.Plastic` 是 `gs.surfaces.Surface` 类的子类,专门用于创建和配置塑料材质。它继承了 Surface 类的所有功能,并添加了塑料材质特有的漫反射纹理和高光纹理参数,使塑料材质的视觉效果更加真实。 + +## 主要功能 + +- **继承Surface类功能**:包括颜色、粗糙度、金属度等基本材质属性 +- **漫反射纹理支持**:添加 diffuse_texture 用于精细控制塑料表面的漫反射特性 +- **高光纹理支持**:添加 specular_texture 用于控制塑料表面的高光效果 +- **灵活的参数控制**:支持调整透明度、折射率等光学参数 +- **表面重建选项**:继承 Surface 类的表面重建配置 + +## 参数说明 + +Plastic 类继承了 Surface 类的所有参数,并添加了以下额外参数: + +| 参数名称 | 类型 | 默认值 | 描述 | +| --- | --- | --- | --- | +| `color` | `Optional[tuple]` | `None` | 表面颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `opacity` | `Optional[float]` | `None` | 表面透明度,取值范围 0.0(完全透明)到 1.0(完全不透明) | +| `roughness` | `Optional[float]` | `None` | 表面粗糙度,取值范围 0.0(完全光滑)到 1.0(完全粗糙) | +| `metallic` | `Optional[float]` | `None` | 金属度,通常设置为较低值(如 0.0)以模拟塑料特性 | +| `emissive` | `Optional[tuple]` | `None` | 发射光颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `ior` | `float` | `1.0` | 折射率,默认值为 1.0 | +| `opacity_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 透明度纹理 | +| `roughness_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 粗糙度纹理 | +| `metallic_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 金属度纹理 | +| `normal_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 法线纹理 | +| `emissive_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 发射光纹理 | +| `diffuse_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 漫反射纹理,控制塑料表面的漫反射特性 | +| `specular_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 高光纹理,控制塑料表面的高光效果 | +| `default_roughness` | `float` | `1.0` | 默认粗糙度值 | +| `vis_mode` | `Optional[str]` | `None` | 可视化模式 | +| `smooth` | `bool` | `True` | 是否启用平滑着色 | +| `double_sided` | `Optional[bool]` | `None` | 是否启用双面渲染 | +| `beam_angle` | `float` | `180` | 发射光的光束角度 | +| `normal_diff_clamp` | `float` | `180` | 计算表面法线时的阈值 | +| `recon_backend` | `str` | `splashsurf` | 表面重建后端,可选值:['splashsurf', 'openvdb'] | +| `generate_foam` | `bool` | `False` | 是否为基于粒子的实体生成泡沫效果 | +| `foam_options` | `Optional[genesis.options.misc.FoamOptions]` | `None` | 泡沫生成选项 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Plastic :show-inheritance: diff --git a/source/api_reference/options/surface/plastic/reflective.md b/source/api_reference/options/surface/plastic/reflective.md index 9114ab2..54b3d9c 100644 --- a/source/api_reference/options/surface/plastic/reflective.md +++ b/source/api_reference/options/surface/plastic/reflective.md @@ -1,4 +1,97 @@ # `gs.surfaces.Reflective` + +`gs.surfaces.Reflective` 是Genesis引擎中一种高反射性塑料表面的快捷方式,比 `Smooth` 表面更加光滑,主要用于创建具有强烈镜面反射效果的材质。 + +## 主要功能 + +- 提供高反射性的塑料材质,默认粗糙度极低(0.01) +- 设置了较高的折射率(2.0),增强反射效果 +- 继承了Plastic类的所有功能,支持各种视觉属性调整 +- 适用于创建类似镜面的反射表面 +- 支持纹理贴图功能,可自定义反射表面外观 +- 提供双面渲染选项,适用于复杂几何体 +- 支持法线贴图,增强表面细节 +- 与物理引擎兼容,可用于碰撞检测 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|-------|------|--------|------| +| color | Optional[tuple] | None | 表面颜色,采用RGB格式,值范围为 [0, 1] | +| opacity | Optional[float] | None | 表面不透明度,值范围为 [0, 1],0表示完全透明,1表示完全不透明 | +| roughness | float | 0.01 | 表面粗糙度,值范围为 [0, 1],0表示完全光滑,1表示完全粗糙 | +| metallic | Optional[float] | None | 金属度,值范围为 [0, 1],0表示非金属,1表示金属 | +| emissive | Optional[tuple] | None | 自发光颜色,采用RGB格式,值范围为 [0, ∞] | +| ior | float | 2.0 | 折射率,用于计算透明和半透明材质的光学特性 | +| opacity_texture | Optional[Texture] | None | 不透明度纹理贴图,用于创建透明区域的图案 | +| roughness_texture | Optional[Texture] | None | 粗糙度纹理贴图,用于创建表面粗糙度的变化 | +| metallic_texture | Optional[Texture] | None | 金属度纹理贴图,用于创建金属和非金属区域的混合 | +| normal_texture | Optional[Texture] | None | 法线贴图,用于增强表面细节和立体感 | +| emissive_texture | Optional[Texture] | None | 自发光纹理贴图,用于创建发光区域的图案 | +| default_roughness | float | 1.0 | 默认粗糙度值,当roughness参数未设置时使用 | +| vis_mode | Optional[str] | None | 可视化模式,控制表面的渲染方式 | +| smooth | bool | True | 是否使用平滑着色,False表示使用平面着色 | +| double_sided | Optional[bool] | None | 是否双面渲染表面 | +| beam_angle | float | 180 | 光束角度,用于控制表面的光照效果 | +| normal_diff_clamp | float | 180 | 法线差异限制,用于优化渲染效果 | +| recon_backend | str | splashsurf | 重建后端,用于表面重建操作 | +| generate_foam | bool | False | 是否生成泡沫效果 | +| foam_options | Optional[FoamOptions] | None | 泡沫效果选项配置 | +| diffuse_texture | Optional[Texture] | None | 漫反射纹理贴图,用于控制表面的颜色和图案 | +| specular_texture | Optional[Texture] | None | 高光纹理贴图,用于控制表面的高光效果 | + +## 使用示例 + +### 基本反射表面配置 +```python +import genesis as gs + +# 创建一个基本的反射表面 +reflective_surface = gs.surfaces.Reflective( + color=(0.9, 0.9, 0.9), # 白色 + opacity=1.0 # 完全不透明 +) +``` + +### 彩色反射表面 +```python +import genesis as gs + +# 创建一个彩色的反射表面 +reflective_surface = gs.surfaces.Reflective( + color=(0.2, 0.3, 0.8), # 蓝色 + ior=1.5 # 调整折射率 +) +``` + +### 半透明反射表面 +```python +import genesis as gs + +# 创建一个半透明的反射表面 +reflective_surface = gs.surfaces.Reflective( + color=(1.0, 0.8, 0.2), # 黄色 + opacity=0.8, # 半透明 + roughness=0.05 # 略微增加粗糙度 +) +``` + +### 使用纹理的反射表面 +```python +import genesis as gs + +# 创建一个带有纹理的反射表面 +reflective_surface = gs.surfaces.Reflective( + color=(1.0, 1.0, 1.0), # 白色基础色 + specular_texture=gs.textures.Texture( + path="textures/specular_map.png" + ), + normal_texture=gs.textures.Texture( + path="textures/normal_map.png" + ) +) +``` + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Reflective :show-inheritance: diff --git a/source/api_reference/options/surface/plastic/rough.md b/source/api_reference/options/surface/plastic/rough.md index dd8a236..6a41b28 100644 --- a/source/api_reference/options/surface/plastic/rough.md +++ b/source/api_reference/options/surface/plastic/rough.md @@ -1,4 +1,40 @@ # `gs.surfaces.Rough` + +## 概述 + +`gs.surfaces.Rough` 是 Genesis 引擎中用于创建粗糙塑料表面的快捷类。它继承自 `gs.surfaces.Plastic` 类,并将粗糙度 (`roughness`) 默认设置为 1.0(完全粗糙),折射率 (`ior`) 默认设置为 1.5,适合模拟砂纸、粗布等粗糙表面效果。 + +## 主要功能 + +- **继承Plastic类功能**:包括颜色、透明度、纹理支持等塑料材质的所有特性 +- **默认高粗糙度**:粗糙度默认值为 1.0,无需手动设置即可获得完全粗糙的表面效果 +- **优化的折射率**:折射率默认值为 1.5,提供更真实的光学效果 +- **快速配置**:作为快捷类,可在不指定额外参数的情况下创建粗糙塑料材质 + +## 参数说明 + +Rough 类继承了 Plastic 类的所有参数,但对以下参数设置了特定的默认值: + +| 参数名称 | 类型 | 默认值 | 描述 | +| --- | --- | --- | --- | +| `color` | `Optional[tuple]` | `None` | 表面颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `opacity` | `Optional[float]` | `None` | 表面透明度,取值范围 0.0(完全透明)到 1.0(完全不透明) | +| `roughness` | `float` | `1.0` | 表面粗糙度,固定为完全粗糙 | +| `metallic` | `Optional[float]` | `None` | 金属度,通常设置为较低值(如 0.0)以模拟塑料特性 | +| `emissive` | `Optional[tuple]` | `None` | 发射光颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `ior` | `float` | `1.5` | 折射率,默认值为 1.5 | +| `opacity_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 透明度纹理 | +| `roughness_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 粗糙度纹理 | +| `metallic_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 金属度纹理 | +| `normal_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 法线纹理 | +| `emissive_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 发射光纹理 | +| `diffuse_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 漫反射纹理 | +| `specular_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 高光纹理 | +| `default_roughness` | `float` | `1.0` | 默认粗糙度值 | +| `vis_mode` | `Optional[str]` | `None` | 可视化模式 | +| `smooth` | `bool` | `True` | 是否启用平滑着色 | +| `double_sided` | `Optional[bool]` | `None` | 是否启用双面渲染 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Rough :show-inheritance: diff --git a/source/api_reference/options/surface/plastic/smooth.md b/source/api_reference/options/surface/plastic/smooth.md index 14cc993..4c4cfe9 100644 --- a/source/api_reference/options/surface/plastic/smooth.md +++ b/source/api_reference/options/surface/plastic/smooth.md @@ -1,4 +1,29 @@ # `gs.surfaces.Smooth` + +`gs.surfaces.Smooth` 是Genesis引擎中用于模拟光滑塑料表面的表面类型,是 `Plastic` 表面的快捷方式,预配置了适合光滑塑料的参数值。 + +## 主要功能 + +- 模拟光滑塑料材质的光学特性和外观 +- 默认设置 `roughness = 0.1`,提供典型的光滑塑料表面效果 +- 默认设置 `smooth = True`,启用平滑着色 +- 默认折射率 `ior = 1.5`,适合大多数塑料材料 +- 支持调整各种塑料参数,如颜色、透明度、粗糙度等 +- 与光线追踪渲染器完全兼容 +- 支持各种纹理贴图,包括颜色、粗糙度、法线等 + +## 参数说明 + +该类继承了 `Plastic` 类的所有参数,并将以下参数设置为特定的默认值: + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| `roughness` | `float` | `0.1` | 表面粗糙度,设置为较低值以模拟光滑塑料 | +| `smooth` | `bool` | `True` | 启用平滑着色,提供更光滑的表面外观 | +| `ior` | `float` | `1.5` | 折射率,适合大多数塑料材料 | + +有关完整参数说明,请参考 [Plastic](./plastic.md) 类的文档。 + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Smooth :show-inheritance: diff --git a/source/api_reference/options/surface/surface.md b/source/api_reference/options/surface/surface.md index c399b94..e1fdfeb 100644 --- a/source/api_reference/options/surface/surface.md +++ b/source/api_reference/options/surface/surface.md @@ -1,4 +1,45 @@ # `gs.surfaces.Surface` + +## 概述 + +`gs.surfaces.Surface` 是 Genesis 引擎中用于定义和控制实体表面属性的核心类。它允许用户配置材料的视觉外观(如颜色、粗糙度、金属度)、光学特性(如折射率、发射光)以及表面重建和渲染选项。 + +## 主要功能 + +- **视觉属性配置**:设置颜色、粗糙度、金属度等基本材质属性 +- **纹理支持**:支持多种纹理类型(透明度、粗糙度、金属度、法线、发射光) +- **光学特性**:控制折射率、透明度等光学参数 +- **表面重建**:配置表面重建后端(splashsurf 或 openvdb) +- **发射光效果**:设置发光颜色和光束角度 +- **双面渲染**:支持双面渲染选项 +- **泡沫生成**:为基于粒子的实体启用泡沫生成效果 +- **平滑着色**:控制表面平滑着色选项 + +## 参数说明 + +| 参数名称 | 类型 | 默认值 | 描述 | +| --- | --- | --- | --- | +| `color` | `Optional[tuple]` | `None` | 表面颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `opacity` | `Optional[float]` | `None` | 表面透明度,取值范围 0.0(完全透明)到 1.0(完全不透明) | +| `roughness` | `Optional[float]` | `None` | 表面粗糙度,取值范围 0.0(完全光滑)到 1.0(完全粗糙) | +| `metallic` | `Optional[float]` | `None` | 金属度,取值范围 0.0(非金属)到 1.0(金属) | +| `emissive` | `Optional[tuple]` | `None` | 发射光颜色,格式为 (R, G, B),取值范围 0.0-1.0 | +| `ior` | `Optional[float]` | `None` | 折射率,影响光在介质中的传播 | +| `opacity_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 透明度纹理 | +| `roughness_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 粗糙度纹理 | +| `metallic_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 金属度纹理 | +| `normal_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 法线纹理 | +| `emissive_texture` | `Optional[genesis.options.textures.Texture]` | `None` | 发射光纹理 | +| `default_roughness` | `float` | `1.0` | 默认粗糙度值 | +| `vis_mode` | `Optional[str]` | `None` | 可视化模式 | +| `smooth` | `bool` | `True` | 是否启用平滑着色 | +| `double_sided` | `Optional[bool]` | `None` | 是否启用双面渲染 | +| `beam_angle` | `float` | `180` | 发射光的光束角度 | +| `normal_diff_clamp` | `float` | `180` | 计算表面法线时的阈值 | +| `recon_backend` | `str` | `splashsurf` | 表面重建后端,可选值:['splashsurf', 'openvdb'] | +| `generate_foam` | `bool` | `False` | 是否为基于粒子的实体生成泡沫效果 | +| `foam_options` | `Optional[genesis.options.misc.FoamOptions]` | `None` | 泡沫生成选项 | + ```{eval-rst} .. autoclass:: genesis.options.surfaces.Surface ``` diff --git a/source/api_reference/options/texture/color_texture.md b/source/api_reference/options/texture/color_texture.md index d4436b2..bef47e7 100644 --- a/source/api_reference/options/texture/color_texture.md +++ b/source/api_reference/options/texture/color_texture.md @@ -1,4 +1,23 @@ # `gs.textures.ColorTexture` + +## 概述 + +`gs.textures.ColorTexture` 是 `gs.textures.Texture` 类的子类,用于创建单一颜色的纹理。它是 Genesis 引擎中最基本的纹理类型之一,通过设置单一颜色值来为材质添加均匀的颜色效果。ColorTexture 可以作为材质的颜色属性使用,也可以与其他纹理类型结合应用。 + +## 主要功能 + +- **单一颜色纹理**:创建具有均匀颜色的纹理 +- **灵活的颜色设置**:支持使用浮点数(灰度)或 RGB 元组设置颜色 +- **与材质系统集成**:可作为各种材质的颜色纹理使用 +- **简洁的 API**:使用简单直观的接口创建颜色纹理 +- **高质量渲染**:支持精确的颜色控制和渲染 + +## 参数说明 + +| 参数名称 | 类型 | 默认值 | 描述 | +| --- | --- | --- | --- | +| `color` | `Union[float, List[float]]` | `(1.0, 1.0, 1.0)` | 纹理颜色。可以是单个浮点数(表示灰度值,范围 0.0-1.0)或 RGB 元组(范围 0.0-1.0) | + ```{eval-rst} .. autoclass:: genesis.options.textures.ColorTexture :show-inheritance: diff --git a/source/api_reference/options/texture/image_texture.md b/source/api_reference/options/texture/image_texture.md index 3f943f3..eeee95e 100644 --- a/source/api_reference/options/texture/image_texture.md +++ b/source/api_reference/options/texture/image_texture.md @@ -1,4 +1,31 @@ # `gs.textures.ImageTexture` + +## 概述 + +`gs.textures.ImageTexture` 是 `gs.textures.Texture` 类的子类,用于创建基于图像的纹理。它允许用户通过图像文件或图像数组为材质添加复杂的颜色变化和细节,是创建真实感材质的重要工具。ImageTexture 支持多种图像格式和编码方式,可应用于材质的各种属性。 + +## 主要功能 + +- **基于图像的纹理**:支持通过图像文件或图像数组创建纹理 +- **灵活的图像源**:可从文件路径或 NumPy 数组加载图像 +- **图像编码控制**:支持 sRGB 和线性编码方式 +- **颜色调整**:可通过 image_color 参数调整图像颜色强度 +- **高质量渲染**:支持高分辨率图像和各种图像格式 +- **与材质系统集成**:可作为各种材质属性的纹理使用 + +## 参数说明 + +| 参数名称 | 类型 | 默认值 | 描述 | +| --- | --- | --- | --- | +| `image_path` | `Optional[str]` | `None` | 图像文件路径 | +| `image_array` | `Optional[numpy.ndarray]` | `None` | 图像数组(NumPy 格式) | +| `image_color` | `Union[float, List[float], None]` | `None` | 图像颜色因子,与图像颜色相乘,可用于调整图像亮度或颜色 | +| `encoding` | `str` | `'srgb'` | 图像编码方式。可选值: + - `'srgb'`: RGB 图像的标准编码方式 + - `'linear'`: 通用图像(如透明度、粗糙度、法线贴图等)的编码方式 | + +## 使用示例 + ```{eval-rst} .. autoclass:: genesis.options.textures.ImageTexture :show-inheritance: diff --git a/source/api_reference/options/texture/index.md b/source/api_reference/options/texture/index.md index 57d5b95..8e99d84 100644 --- a/source/api_reference/options/texture/index.md +++ b/source/api_reference/options/texture/index.md @@ -1,5 +1,17 @@ # Texture +## 概述 + +纹理 (Texture) 是 Genesis 引擎中用于增强材质视觉效果的重要组件。通过纹理,可以为表面添加颜色变化、细节、法线信息和其他视觉特性,使渲染结果更加真实和丰富。纹理系统支持多种纹理类型,包括基本颜色纹理和图像纹理,可与各种材质类型结合使用。 + +## 主要特点 + +- **多种纹理类型**:支持颜色纹理和图像纹理等多种纹理格式 +- **灵活的应用方式**:可应用于材质的颜色、粗糙度、法线等多个属性 +- **高质量渲染**:支持高分辨率纹理和各种纹理映射技术 +- **与材质系统无缝集成**:可与塑料、金属、玻璃等材质类型完美配合 +- **纹理坐标控制**:支持纹理坐标变换和映射方式调整 + ```{toctree} :maxdepth: 2 diff --git a/source/api_reference/options/texture/texture.md b/source/api_reference/options/texture/texture.md index d809779..a015a96 100644 --- a/source/api_reference/options/texture/texture.md +++ b/source/api_reference/options/texture/texture.md @@ -1,4 +1,33 @@ # `gs.textures.Texture` + +## 概述 + +`gs.textures.Texture` 是 Genesis 引擎中所有纹理类型的基类,提供了纹理系统的核心功能和接口。它定义了纹理对象的基本属性和方法,但**不应该直接实例化**,而是通过其子类(如 `ColorTexture` 和 `ImageTexture`)来创建具体的纹理对象。 + +## 主要功能 + +- **纹理系统基类**:为所有纹理类型提供统一的接口和基础功能 +- **纹理属性管理**:支持纹理的基本属性设置和获取 +- **纹理处理方法**:提供纹理裁剪、维度检查、简化等纹理处理功能 +- **与材质系统集成**:作为材质属性的重要组成部分,支持各种材质类型 +- **序列化支持**:提供纹理数据的序列化和反序列化功能 + +## 使用注意事项 + +- **不可直接实例化**:Texture 类是一个抽象基类,应该通过其子类创建纹理对象 +- **子类继承**:所有自定义纹理类型都应该继承自 Texture 类 +- **与材质结合使用**:纹理通常作为材质的属性(如颜色纹理、粗糙度纹理等)来使用 +- **纹理坐标**:纹理映射时需要考虑纹理坐标的设置和变换 + +## 可用方法 + +Texture 类提供了以下主要方法: + +- `apply_cutoff()`:应用纹理截止值 +- `check_dim()`:检查纹理维度 +- `check_simplify()`:检查并简化纹理 +- `is_black()`:检查纹理是否为黑色 + ```{eval-rst} .. autoclass:: genesis.options.textures.Texture :show-inheritance: diff --git a/source/api_reference/options/vis/index.md b/source/api_reference/options/vis/index.md index 59c04ac..c6a6706 100644 --- a/source/api_reference/options/vis/index.md +++ b/source/api_reference/options/vis/index.md @@ -1,5 +1,15 @@ # Viewer & Visualization +可视化系统是 Genesis API 的重要组成部分,提供了场景渲染和交互式查看功能,帮助用户实时预览和调试场景设置。 + +## 主要特点 + +- 提供交互式场景查看器,支持实时渲染和预览 +- 支持多种视图模式和视角控制 +- 提供相机参数和渲染设置的调整功能 +- 支持场景元素的选择和高亮显示 +- 支持多种渲染质量和性能设置 + ```{toctree} :maxdepth: 2 diff --git a/source/api_reference/options/vis/viewer.md b/source/api_reference/options/vis/viewer.md index 7930e38..88eb1d9 100644 --- a/source/api_reference/options/vis/viewer.md +++ b/source/api_reference/options/vis/viewer.md @@ -1,4 +1,29 @@ # `gs.options.ViewerOptions` + +`ViewerOptions` 是 Genesis API 中用于配置场景查看器行为和相机参数的类,允许用户自定义查看器的窗口大小、渲染性能和相机设置。 + +## 主要功能 + +- 配置查看器窗口的分辨率和显示属性 +- 控制查看器的运行模式(主线程或后台线程) +- 设置渲染刷新率和 FPS 限制 +- 自定义相机的位置、朝向和视场角 +- 控制查看器的交互行为 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| res | `Optional[tuple]` | `None` | 查看器窗口的分辨率,格式为 (宽度, 高度) | +| run_in_thread | `Optional[bool]` | `None` | 是否在后台线程运行查看器(在 MacOS 上不支持) | +| refresh_rate | `int` | `60` | 查看器的刷新率(帧/秒) | +| max_FPS | `Optional[int]` | `60` | 查看器的最大 FPS 限制,会同步仿真速度 | +| camera_pos | `tuple` | `(3.5, 0.5, 2.5)` | 相机的位置坐标 (x, y, z) | +| camera_lookat | `tuple` | `(0.0, 0.0, 0.5)` | 相机的注视点坐标 (x, y, z) | +| camera_up | `tuple` | `(0.0, 0.0, 1.0)` | 相机的上向量 (x, y, z) | +| camera_fov | `float` | `40` | 相机的视场角(度数) | +| enable_interaction | `bool` | `False` | 是否启用查看器交互功能 | + ```{eval-rst} .. autoclass:: genesis.options.ViewerOptions :show-inheritance: diff --git a/source/api_reference/options/vis/vis.md b/source/api_reference/options/vis/vis.md index 8ac8e9b..7117364 100644 --- a/source/api_reference/options/vis/vis.md +++ b/source/api_reference/options/vis/vis.md @@ -1,4 +1,42 @@ # `gs.options.VisOptions` + +`VisOptions` 是 Genesis API 中用于配置可视化和渲染选项的核心类,允许用户自定义场景的视觉呈现效果和交互行为。 + +## 主要功能 + +- 控制世界坐标系和链接坐标系的显示 +- 配置阴影、反射和背景颜色等视觉效果 +- 管理场景中的灯光设置 +- 控制粒子的渲染方式和大小 +- 支持物理边界的可视化 +- 提供渲染质量和性能的调整选项 + +## 参数说明 + +| 参数名 | 类型 | 默认值 | 描述 | +|--------|------|--------|------| +| show_world_frame | `bool` | `False` | 是否显示世界坐标系 | +| world_frame_size | `float` | `1.0` | 世界坐标系的大小 | +| show_link_frame | `bool` | `False` | 是否显示链接坐标系 | +| link_frame_size | `float` | `0.2` | 链接坐标系的大小 | +| show_cameras | `bool` | `False` | 是否显示场景中的相机 | +| shadow | `bool` | `True` | 是否启用阴影效果 | +| plane_reflection | `bool` | `False` | 是否启用平面反射效果 | +| env_separate_rigid | `bool` | `False` | 是否将环境物体与刚性物体分开渲染 | +| background_color | `tuple` | `(0.04, 0.08, 0.12)` | 背景颜色 (RGB 格式,范围 0.0-1.0) | +| ambient_light | `tuple` | `(0.1, 0.1, 0.1)` | 环境光强度 (RGB 格式,范围 0.0-1.0) | +| visualize_mpm_boundary | `bool` | `False` | 是否可视化 MPM 边界 | +| visualize_sph_boundary | `bool` | `False` | 是否可视化 SPH 边界 | +| visualize_pbd_boundary | `bool` | `False` | 是否可视化 PBD 边界 | +| segmentation_level | `str` | `link` | 分割级别,默认为 "link" | +| render_particle_as | `str` | `sphere` | 粒子渲染形状,默认为 "sphere" | +| particle_size_scale | `float` | `1.0` | 粒子大小缩放因子 | +| contact_force_scale | `float` | `0.01` | 接触力的可视化缩放因子 | +| n_support_neighbors | `int` | `12` | 支持邻居数量 | +| n_rendered_envs | `Optional[int]` | `None` | 渲染的环境数量 | +| rendered_envs_idx | `Optional[list]` | `None` | 要渲染的环境索引列表 | +| lights | `list` | `[{'type': 'directional', 'dir': (-1, -1, -1), 'color': (1.0, 1.0, 1.0), 'intensity': 5.0}]` | 灯光配置列表 | + ```{eval-rst} .. autoclass:: genesis.options.VisOptions :show-inheritance: diff --git a/source/api_reference/scene/coupler.md b/source/api_reference/scene/coupler.md deleted file mode 100644 index 9893a09..0000000 --- a/source/api_reference/scene/coupler.md +++ /dev/null @@ -1,7 +0,0 @@ -# `Coupler` - -```{eval-rst} -.. autoclass:: genesis.engine.coupler.Coupler - :members: - :undoc-members: -``` \ No newline at end of file diff --git a/source/api_reference/scene/force_field.md b/source/api_reference/scene/force_field.md index 10c1a86..15f9bf6 100644 --- a/source/api_reference/scene/force_field.md +++ b/source/api_reference/scene/force_field.md @@ -1,7 +1,279 @@ -# Force Field +# `ForceField` + +## 概述 +`ForceField` 是所有力场的基类,用于在模拟中对物体施加各种类型的力(实际上是加速度场)。 + +## 主要功能 +- 提供统一的接口用于所有类型的力场 +- 支持激活/停用力场 +- 包含多种预定义的力场类型,如恒定力、风力、点力等 +- 支持自定义力场函数 + +## 继承关系 +``` +ForceField +├── Constant +├── Wind +├── Point +├── Drag +├── Noise +├── Vortex +├── Turbulence +└── Custom +``` + +## 力场类型详情 + +### 1. Constant(恒定力场) + +**功能说明**: +恒定力场在所有空间点施加方向和大小恒定的加速度。它模拟了均匀力场,如重力场(在小范围内可近似为恒定力场)。 + +**主要参数**: +- `direction`:力场的方向向量,必须是归一化的三维向量 +- `strength`:力场的强度(加速度值,单位:m/s²) +- `active`:力场是否激活,默认为True + +**典型应用**: +- 模拟重力场(方向向下,强度约为9.8 m/s²) +- 施加恒定的推进力或拉力 +- 测试物体在均匀力场中的运动 + +### 2. Wind(风力场) + +**功能说明**: +风力场模拟了自然界中的风,具有基本方向和强度,同时可以添加湍流效果以模拟风的不规则性。 + +**主要参数**: +- `direction`:主风向向量,必须是归一化的三维向量 +- `strength`:基础风速强度(m/s²) +- `turbulence`:湍流强度,0表示完全均匀的风,1表示最强的湍流效果 +- `turbulence_scale`:湍流尺度,控制湍流涡流的大小 +- `active`:力场是否激活,默认为True + +**典型应用**: +- 模拟自然风环境 +- 测试结构在风中的稳定性 +- 产生飘动或摇晃的效果 + +### 3. Point(点力场) + +**功能说明**: +点力场从一个点源向外辐射力(或向内吸引),力的大小随距离变化。 + +**主要参数**: +- `position`:点力场的源位置(三维向量) +- `strength`:力场强度,正值表示排斥力,负值表示吸引力 +- `falloff`:衰减指数,控制力随距离减弱的速率(通常为2表示平方反比衰减) +- `radius`:力场影响的最大半径,超出此半径的物体不受影响 +- `active`:力场是否激活,默认为True + +**典型应用**: +- 模拟万有引力(falloff=2) +- 创建吸引力或排斥力源 +- 模拟爆炸或冲击效果 + +### 4. Drag(阻力场) + +**功能说明**: +阻力场施加与物体运动方向相反的力,模拟流体阻力或空气阻力。 + +**主要参数**: +- `coefficient`:阻力系数,控制阻力的强度 +- `exponent`:速度指数,1表示线性阻力(粘性阻力),2表示二次阻力(惯性阻力) +- `active`:力场是否激活,默认为True + +**典型应用**: +- 模拟空气阻力 +- 模拟物体在水中的运动 +- 使运动物体自然减速 + +### 5. Noise(噪声力场) + +**功能说明**: +噪声力场使用Perlin或Simplex噪声生成空间变化的力场,创造自然、无规则的运动模式。 + +**主要参数**: +- `scale`:噪声的空间尺度,控制力场变化的频率 +- `strength`:噪声力场的强度 +- `octaves`:噪声的八度数量,控制力场的细节丰富程度 +- `persistence`:噪声的持续性,控制高八度噪声的影响程度 +- `active`:力场是否激活,默认为True + +**典型应用**: +- 模拟自然水流或气流 +- 产生复杂的流体运动模式 +- 创建有机、自然的运动效果 + +### 6. Vortex(涡流力场) + +**功能说明**: +涡流力场创建一个旋转的力场,模拟漩涡或龙卷风效果。 + +**主要参数**: +- `position`:涡流中心位置 +- `axis`:涡流旋转轴方向 +- `strength`:涡流强度 +- `radius`:涡流影响半径 +- `active`:力场是否激活,默认为True + +**典型应用**: +- 模拟龙卷风 +- 创建漩涡或漩涡效果 +- 产生旋转的流体运动 + +### 7. Turbulence(湍流力场) + +**功能说明**: +湍流力场在基本力场的基础上添加湍流扰动,增强真实感。 + +**主要参数**: +- `base_force`:基础力场(可选) +- `strength`:湍流强度 +- `scale`:湍流尺度 +- `octaves`:噪声八度数量 +- `active`:力场是否激活,默认为True + +**典型应用**: +- 增强风力或水流的真实感 +- 模拟复杂的流体动力学效果 +- 产生更自然的运动模式 + +### 8. Custom(自定义力场) + +**功能说明**: +自定义力场允许用户通过Python函数定义任意复杂的力场行为,提供最大的灵活性。 + +**主要参数**: +- `force_func`:用户定义的力场函数,接收位置、速度和时间参数,返回三维力向量 +- `active`:力场是否激活,默认为True + +**典型应用**: +- 实现特殊的物理效果 +- 模拟复杂的力场交互 +- 研究自定义物理现象 + +## 使用示例 + +### 使用恒定力场 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 添加一个球体 +sphere = gs.primitives.Sphere(position=(0, 0, 1)) +scene.add_entity(sphere) + +# 创建并添加恒定力场(恒定加速度) +constant_force = gs.force_fields.Constant(direction=(1, 0, 0), strength=5.0) +scene.add_force_field(constant_force) + +# 构建并运行场景 +scene.build() +for _ in range(100): + scene.step() +``` + +### 使用风力场 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 添加多个球体 +for i in range(5): + sphere = gs.primitives.Sphere( + position=(i-2, 0, 2), + radius=0.2 + ) + scene.add_entity(sphere) + +# 创建并添加风力场 +wind = gs.force_fields.Wind( + direction=(1, 0, 0), + strength=3.0, + turbulence=0.1 +) +scene.add_force_field(wind) + +# 构建并运行场景 +scene.build() +for _ in range(200): + scene.step() +``` + +### 使用点力场 + +```python +import genesis as gs + +# 创建场景 +scene = gs.Scene() + +# 添加多个球体 +for i in range(3): + for j in range(3): + sphere = gs.primitives.Sphere( + position=(i-1, j-1, 2), + radius=0.15 + ) + scene.add_entity(sphere) + +# 创建并添加点力场(吸引力) +point_force = gs.force_fields.Point( + position=(0, 0, 0), + strength=-10.0, # 负值表示吸引力 + falloff=2.0 # 平方反比衰减 +) +scene.add_force_field(point_force) + +# 构建并运行场景 +scene.build() +for _ in range(150): + scene.step() +``` + +### 使用自定义力场 + +```python +import genesis as gs +import numpy as np + +# 创建场景 +scene = gs.Scene() + +# 添加一个球体 +sphere = gs.primitives.Sphere(position=(0, 0, 2)) +scene.add_entity(sphere) + +# 定义自定义力场函数 +def custom_force(position, velocity, time): + # 创建一个随时间变化的正弦力场 + force = np.array([ + np.sin(time * 2.0), + np.cos(time * 2.0), + -5.0 + ]) + return force + +# 创建并添加自定义力场 +custom_ff = gs.force_fields.Custom(force_func=custom_force) +scene.add_force_field(custom_ff) + +# 构建并运行场景 +scene.build() +for _ in range(200): + scene.step() +``` ```{eval-rst} .. automodule:: genesis.engine.force_fields :members: + :show-inheritance: :undoc-members: ``` \ No newline at end of file diff --git a/source/api_reference/scene/index.md b/source/api_reference/scene/index.md index 42ff751..a47acce 100644 --- a/source/api_reference/scene/index.md +++ b/source/api_reference/scene/index.md @@ -2,10 +2,17 @@ A ``genesis.Scene`` object wraps all components in a simulation environment, including a simulator (containing multiple physics solvers), entities, and a visualizer (controlling both the viewer and all the cameras). Basically, everything happens inside a scene. +## 主要特点 + +- 提供统一的场景管理接口,整合所有模拟组件 +- 支持多种物理求解器和模拟方法 +- 提供可视化和渲染功能 +- 支持场景元素(实体、力场、网格等)的创建和管理 +- 提供模拟控制和执行功能 + ```{toctree} scene simulator -coupler force_field mesh ``` diff --git a/source/api_reference/scene/mesh.md b/source/api_reference/scene/mesh.md index 46f2370..5093899 100644 --- a/source/api_reference/scene/mesh.md +++ b/source/api_reference/scene/mesh.md @@ -1,7 +1,19 @@ # `Mesh` +## 概述 +`Mesh` 是 Genesis 自己的三角网格对象,它是 `trimesh.Trimesh` 的包装器,提供了一些额外的功能和属性。 + +## 主要功能 +- 支持凸化(convexification)和简化(decimation)处理 +- 提供网格重网格化(remeshing)和四面体化(tetrahedralization)功能 +- 支持从多种格式加载网格(如 OBJ、GLTF、USD 等) +- 提供粒子采样功能 +- 支持表面和纹理设置 + + ```{eval-rst} .. autoclass:: genesis.engine.mesh.Mesh :members: + :show-inheritance: :undoc-members: ``` \ No newline at end of file diff --git a/source/api_reference/scene/scene.md b/source/api_reference/scene/scene.md index 37721f5..1e3abfa 100644 --- a/source/api_reference/scene/scene.md +++ b/source/api_reference/scene/scene.md @@ -1,5 +1,41 @@ # `Scene` +`Scene` 是 Genesis 引擎中用于管理模拟场景的核心类,它包含了模拟器、实体、传感器等所有模拟组件,是物理模拟的容器。基本上,所有的模拟活动都在场景内部进行。 + +## 功能说明 + +- 管理场景中的所有实体和组件 +- 提供实体的添加、删除和查询接口 +- 控制模拟的运行、暂停和重置 +- 支持场景状态的保存和加载 +- 提供调试可视化功能 +- 支持多相机渲染 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `simulator` | Simulator | 场景中的模拟器对象 | +| `entities` | list | 场景中的所有实体列表 | +| `n_entities` | int | 场景中的实体数量 | +| `time` | float | 当前模拟时间 | +| `step` | int | 当前模拟步数 | + +## 主要方法 + +| 方法名 | 描述 | +| ------ | ---- | +| `add_entity(entity)` | 向场景中添加一个实体 | +| `add_force_field(force_field)` | 向场景中添加一个力场 | +| `add_light(light)` | 向场景中添加一个光源 | +| `add_sensor(sensor)` | 向场景中添加一个传感器 | +| `build()` | 构建场景,这是运行模拟前的必要操作 | +| `step()` | 运行一个模拟时间步 | +| `reset()` | 将场景重置到初始状态 | +| `save_checkpoint(path)` | 保存场景状态到文件 | +| `load_checkpoint(path)` | 从文件加载场景状态 | +| `render_all_cameras()` | 使用批渲染器渲染所有相机的场景 | + ```{eval-rst} .. autoclass:: genesis.engine.scene.Scene :members: diff --git a/source/api_reference/scene/simulator.md b/source/api_reference/scene/simulator.md index 3b93c2d..4cc8fe7 100644 --- a/source/api_reference/scene/simulator.md +++ b/source/api_reference/scene/simulator.md @@ -1,5 +1,27 @@ # `Simulator` +`Simulator` 是 Genesis 引擎中用于执行物理模拟的核心类,它包含了多个物理求解器,负责处理实体的物理行为和相互作用。 + +## 功能说明 + +- 管理多个物理求解器(如刚体、流体、可变形体等) +- 执行物理模拟的时间步长更新 +- 处理实体之间的碰撞和接触 +- 支持求解器选项的配置 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `gravity` | list | 重力加速度向量 | +| `dt` | float | 模拟时间步长 | +| `substeps` | int | 每个时间步的子步数 | +| `entities` | list | 模拟器中的所有实体列表 | +| `solvers` | list | 模拟器中的所有求解器列表 | +| `active_solvers` | list | 当前激活的求解器列表 | +| `cur_t` | float | 当前模拟时间 | +| `cur_step_global` | int | 当前全局步数 | + ```{eval-rst} .. autoclass:: genesis.engine.simulator.Simulator :members: diff --git a/source/api_reference/sensor/camera.md b/source/api_reference/sensor/camera.md new file mode 100644 index 0000000..71aeffc --- /dev/null +++ b/source/api_reference/sensor/camera.md @@ -0,0 +1,37 @@ +# `Camera` + +`Camera` 是 Genesis 引擎中用于模拟相机的类,用于获取场景的视觉信息,支持多种相机参数和渲染选项。 + +## 功能说明 + +- 控制相机的位置、姿态和视角参数 +- 支持透视投影和正交投影 +- 提供场景渲染功能,包括 RGB 图像、深度图、分割图等 +- 支持相机跟随实体运动 +- 支持录制视频 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +| ------ | ---- | ---- | +| `idx` | int | 相机索引 | +| `uid` | int | 相机唯一标识符 | +| `pos` | list | 相机位置 | +| `lookat` | list | 相机看向的点 | +| `up` | list | 相机上方向向量 | +| `fov` | float | 视场角(度) | +| `focal_len` | float | 焦距 | +| `aspect_ratio` | float | 宽高比 | +| `near` | float | 近裁剪面 | +| `far` | float | 远裁剪面 | +| `res` | list | 分辨率 [宽度, 高度] | +| `extrinsics` | list | 相机外参矩阵 | +| `intrinsics` | list | 相机内参矩阵 | +| `transform` | list | 相机变换矩阵 | + +```{eval-rst} +.. automodule:: genesis.vis.camera + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/camera/index.md b/source/api_reference/sensor/index.md similarity index 72% rename from source/api_reference/camera/index.md rename to source/api_reference/sensor/index.md index 6033d3c..004a914 100644 --- a/source/api_reference/camera/index.md +++ b/source/api_reference/sensor/index.md @@ -1,4 +1,4 @@ -# Camera +# Sensor ```{toctree} camera ``` diff --git a/source/api_reference/solvers/base_solver.md b/source/api_reference/solvers/base_solver.md new file mode 100644 index 0000000..3756af7 --- /dev/null +++ b/source/api_reference/solvers/base_solver.md @@ -0,0 +1,57 @@ +# BaseSolver + +`BaseSolver` 是 Genesis 引擎中所有求解器的基类,定义了求解器的核心接口和生命周期管理。它为不同类型的求解器提供了统一的架构和行为模式。 + +## 功能说明 + +`BaseSolver` 类提供了以下核心功能: + +- 求解器的基本身份标识和配置 +- 时间步长管理 +- 求解器初始化和构建 +- 物理模拟的主要循环(预测、求解、更新) +- 求解器状态管理 +- 与实体和场景的交互接口 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `type` | `str` | 求解器类型(如 "rigid", "pbd", "mpm" 等) | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `iterations` | `int` | 求解迭代次数 | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建求解器,初始化内部数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的物理模拟 | +| `reset()` | 无 | `None` | 重置求解器到初始状态 | +| `predict()` | 无 | `None` | 预测实体的运动 | +| `solve()` | 无 | `None` | 求解物理约束和力 | +| `update()` | 无 | `None` | 更新实体状态 | + +## 继承关系 + +``` +BaseSolver +├── RigidSolver +├── PBDSolver +├── MPMSolver +├── FEMSolver +├── SPHSolver +└── HybridSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.base_solver.BaseSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/solvers/fem_solver.md b/source/api_reference/solvers/fem_solver.md new file mode 100644 index 0000000..ce510b1 --- /dev/null +++ b/source/api_reference/solvers/fem_solver.md @@ -0,0 +1,51 @@ +# FEMSolver + +`FEMSolver` 是有限元方法(Finite Element Method)求解器,用于高精度弹性体模拟。它通过离散化物体为有限个单元,求解偏微分方程来模拟物体的变形和应力分布。 + +## 功能说明 + +`FEMSolver` 类提供了以下核心功能: + +- 有限元方法模拟 +- 高精度弹性体和肌肉模拟 +- 应力和应变计算 +- 多种材料模型支持 +- 自适应网格细化 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `n_elements` | `int` | 有限元数量 | +| `n_nodes` | `int` | 节点数量 | +| `iterations` | `int` | 求解迭代次数 | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 FEM 求解器,初始化数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 FEM 模拟 | +| `reset()` | 无 | `None` | 重置 FEM 求解器到初始状态 | +| `compute_stiffness_matrix()` | 无 | `None` | 计算刚度矩阵 | +| `solve_equations()` | 无 | `None` | 求解有限元方程 | + +## 继承关系 + +``` +BaseSolver +└── FEMSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.fem_solver.FEMSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/solvers/hybrid_solver.md b/source/api_reference/solvers/hybrid_solver.md new file mode 100644 index 0000000..177d28a --- /dev/null +++ b/source/api_reference/solvers/hybrid_solver.md @@ -0,0 +1,51 @@ +# HybridSolver + +`HybridSolver` 是 Genesis 引擎中用于处理不同物理系统之间相互作用的求解器,它能够将多种求解器组合在一起,实现复杂场景的物理模拟。 + +## 功能说明 + +`HybridSolver` 类提供了以下核心功能: + +- 多种求解器的集成和协调 +- 不同物理系统之间的耦合 +- 统一的时间步长管理 +- 跨求解器的碰撞检测和响应 +- 复杂场景的高效模拟 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `solvers` | `list` | 包含的求解器列表 | +| `n_solvers` | `int` | 求解器数量 | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建混合求解器,初始化数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的混合模拟 | +| `reset()` | 无 | `None` | 重置混合求解器到初始状态 | +| `add_solver()` | `Solver` | `None` | 添加求解器到混合系统 | +| `remove_solver()` | `int` | `None` | 移除指定索引的求解器 | +| `solve_coupling()` | 无 | `None` | 求解不同求解器之间的耦合 | + +## 继承关系 + +``` +BaseSolver +└── HybridSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.hybrid_solver.HybridSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/solvers/index.md b/source/api_reference/solvers/index.md new file mode 100644 index 0000000..f94b6bd --- /dev/null +++ b/source/api_reference/solvers/index.md @@ -0,0 +1,30 @@ +# Solvers + +Solver 是 Genesis 引擎中负责物理模拟计算的核心组件,不同类型的实体使用不同的求解器来处理其物理行为。求解器根据物理原理和数值方法,计算实体在每个时间步的运动和状态变化。 + +## 求解器类型 + +Genesis 引擎支持多种求解器,每种求解器针对不同类型的物理现象进行优化: + +- **刚体求解器**:用于处理刚体动力学 +- **PBD 求解器**:基于位置的动力学,用于布料、绳索等变形体 +- **MPM 求解器**:物质点方法,用于流体、弹性体等 +- **FEM 求解器**:有限元方法,用于高精度弹性体模拟 +- **SPH 求解器**:光滑粒子流体动力学,用于流体模拟 +- **耦合求解器**:用于处理不同物理系统之间的相互作用 + +## 求解器架构 + +所有求解器都继承自统一的 `Solver` 基类,提供一致的接口和生命周期管理。求解器与实体之间通过明确的接口进行通信,实现了实体与求解器的解耦。 + +```{toctree} +:maxdepth: 2 + +base_solver +rigid_solver +pbd_solver +mpm_solver +fem_solver +sph_solver +hybrid_solver +``` diff --git a/source/api_reference/solvers/mpm_solver.md b/source/api_reference/solvers/mpm_solver.md new file mode 100644 index 0000000..58d4243 --- /dev/null +++ b/source/api_reference/solvers/mpm_solver.md @@ -0,0 +1,51 @@ +# MPMSolver + +`MPMSolver` 是物质点方法(Material Point Method)求解器,用于模拟流体、弹性体、塑性体等复杂物质的物理行为。它结合了拉格朗日和欧拉方法的优点,能够处理大变形和破碎现象。 + +## 功能说明 + +`MPMSolver` 类提供了以下核心功能: + +- 物质点方法模拟 +- 多种材料模型支持(弹性、塑性、流体等) +- 碰撞检测和响应 +- 自适应网格和粒子管理 +- 高精度物理模拟 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `grid_resolution` | `vector` | 背景网格分辨率 | +| `grid_size` | `vector` | 背景网格大小 | +| `n_particles` | `int` | 物质点数量 | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 MPM 求解器,初始化数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 MPM 模拟 | +| `reset()` | 无 | `None` | 重置 MPM 求解器到初始状态 | +| `particle_to_grid()` | 无 | `None` | 将粒子数据转换到背景网格 | +| `grid_to_particle()` | 无 | `None` | 将网格数据转换回粒子 | + +## 继承关系 + +``` +BaseSolver +└── MPMSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.mpm_solver.MPMSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/solvers/pbd_solver.md b/source/api_reference/solvers/pbd_solver.md new file mode 100644 index 0000000..e6235ce --- /dev/null +++ b/source/api_reference/solvers/pbd_solver.md @@ -0,0 +1,52 @@ +# PBDSolver + +`PBDSolver` 是基于位置的动力学(Position-Based Dynamics)求解器,用于模拟布料、绳索、软物体等变形体。它通过迭代求解位置约束来实现物理效果,具有良好的稳定性和视觉效果。 + +## 功能说明 + +`PBDSolver` 类提供了以下核心功能: + +- 基于位置的约束求解 +- 布料和绳索模拟 +- 碰撞检测和响应 +- 多种约束类型支持(距离、弯曲、体积等) +- 可调节的物理参数 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `iterations` | `int` | 求解迭代次数 | +| `constraint_iterations` | `int` | 约束求解迭代次数 | +| `damping` | `float` | 阻尼系数 | +| `stiffness` | `float` | 刚度系数 | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 PBD 求解器,初始化数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 PBD 模拟 | +| `reset()` | 无 | `None` | 重置 PBD 求解器到初始状态 | +| `solve_constraints()` | 无 | `None` | 求解位置约束 | +| `update_velocities()` | 无 | `None` | 更新粒子速度 | + +## 继承关系 + +``` +BaseSolver +└── PBDSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.pbd_solver.PBDSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/solvers/rigid_solver.md b/source/api_reference/solvers/rigid_solver.md new file mode 100644 index 0000000..7972274 --- /dev/null +++ b/source/api_reference/solvers/rigid_solver.md @@ -0,0 +1,50 @@ +# RigidSolver + +`RigidSolver` 是 Genesis 引擎中用于处理刚体动力学的求解器,负责计算刚体的运动、碰撞和约束。它基于经典力学原理,处理刚体之间的相互作用。 + +## 功能说明 + +`RigidSolver` 类提供了以下核心功能: + +- 刚体动力学计算(位置、速度、加速度) +- 碰撞检测和响应 +- 关节约束求解 +- 接触力计算 +- 刚体链和多体系统处理 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `iterations` | `int` | 求解迭代次数 | +| `tol` | `float` | 求解收敛 tolerance | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建刚体求解器,初始化数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的刚体模拟 | +| `reset()` | 无 | `None` | 重置刚体求解器到初始状态 | +| `solve_collisions()` | 无 | `None` | 求解刚体之间的碰撞 | +| `solve_constraints()` | 无 | `None` | 求解关节和约束 | + +## 继承关系 + +``` +BaseSolver +└── RigidSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.rigid_solver.RigidSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/solvers/sph_solver.md b/source/api_reference/solvers/sph_solver.md new file mode 100644 index 0000000..3967e0b --- /dev/null +++ b/source/api_reference/solvers/sph_solver.md @@ -0,0 +1,54 @@ +# SPHSolver + +`SPHSolver` 是光滑粒子流体动力学(Smoothed Particle Hydrodynamics)求解器,用于模拟流体的流动、飞溅和破碎现象。它通过粒子之间的相互作用力来模拟流体行为。 + +## 功能说明 + +`SPHSolver` 类提供了以下核心功能: + +- 光滑粒子流体动力学模拟 +- 不可压缩流体模拟 +- 表面张力和粘性处理 +- 碰撞检测和响应 +- 高效的粒子邻居搜索 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 求解器在系统中的唯一索引 | +| `uid` | `int` | 求解器的全局唯一标识符 | +| `name` | `str` | 求解器的名称 | +| `dt` | `float` | 时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `n_particles` | `int` | 流体粒子数量 | +| `h` | `float` | 光滑长度 | +| `rest_density` | `float` | 流体静止密度 | +| `viscosity` | `float` | 流体粘性系数 | +| `surface_tension` | `float` | 表面张力系数 | +| `is_built` | `bool` | 求解器是否已完全构建 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `build()` | 无 | `None` | 构建 SPH 求解器,初始化数据结构 | +| `step()` | 无 | `None` | 执行一个时间步的 SPH 模拟 | +| `reset()` | 无 | `None` | 重置 SPH 求解器到初始状态 | +| `find_neighbors()` | 无 | `None` | 查找粒子邻居 | +| `compute_densities()` | 无 | `None` | 计算粒子密度 | +| `compute_forces()` | 无 | `None` | 计算粒子间作用力 | + +## 继承关系 + +``` +BaseSolver +└── SPHSolver +``` + +```{eval-rst} +.. autoclass:: genesis.engine.solvers.sph_solver.SPHSolver + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/states/base_state.md b/source/api_reference/states/base_state.md new file mode 100644 index 0000000..75ac18f --- /dev/null +++ b/source/api_reference/states/base_state.md @@ -0,0 +1,53 @@ +# BaseState + +`BaseState` 是 Genesis 引擎中所有状态类的基类,定义了状态管理的核心接口和功能。它为不同类型的状态提供了统一的架构和行为模式。 + +## 功能说明 + +`BaseState` 类提供了以下核心功能: + +- 状态的基本身份标识和配置 +- 状态数据的存储和访问 +- 状态的序列化和反序列化 +- 状态的复制和克隆 +- 状态的插值和预测 +- 状态的重置和初始化 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 状态在系统中的唯一索引 | +| `uid` | `int` | 状态的全局唯一标识符 | +| `name` | `str` | 状态的名称 | +| `type` | `str` | 状态类型(如 "entity", "solver", "scene" 等) | +| `timestamp` | `float` | 状态的时间戳 | +| `is_initialized` | `bool` | 状态是否已初始化 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `initialize()` | 无 | `None` | 初始化状态数据 | +| `update()` | 无 | `None` | 更新状态数据 | +| `reset()` | 无 | `None` | 重置状态到初始状态 | +| `copy()` | 无 | `State` | 创建状态的副本 | +| `serialize()` | 无 | `dict` | 将状态序列化为字典 | +| `deserialize()` | `dict` | `None` | 从字典反序列化状态 | +| `interpolate()` | `State, float` | `State` | 在当前状态和目标状态之间插值 | + +## 继承关系 + +``` +BaseState +├── EntityState +├── SolverState +└── SceneState +``` + +```{eval-rst} +.. autoclass:: genesis.engine.states.base_state.BaseState + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/states/entity_state.md b/source/api_reference/states/entity_state.md new file mode 100644 index 0000000..5da1c2b --- /dev/null +++ b/source/api_reference/states/entity_state.md @@ -0,0 +1,57 @@ +# EntityState + +`EntityState` 是 Genesis 引擎中用于存储实体状态信息的类,包含了实体的位置、速度、姿态等动态属性。每个实体都有一个对应的 `EntityState` 对象来管理其物理状态。 + +## 功能说明 + +`EntityState` 类提供了以下核心功能: + +- 实体位置、速度、加速度的存储和管理 +- 实体姿态(旋转、角速度、角加速度)的管理 +- 实体物理属性(质量、惯性等)的存储 +- 实体状态的复制和插值 +- 状态的序列化和反序列化 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 状态在系统中的唯一索引 | +| `uid` | `int` | 状态的全局唯一标识符 | +| `entity_idx` | `int` | 对应的实体索引 | +| `position` | `vector` | 实体位置 | +| `velocity` | `vector` | 实体速度 | +| `acceleration` | `vector` | 实体加速度 | +| `rotation` | `quaternion` | 实体旋转 | +| `angular_velocity` | `vector` | 实体角速度 | +| `angular_acceleration` | `vector` | 实体角加速度 | +| `scale` | `vector` | 实体缩放 | +| `mass` | `float` | 实体质量 | +| `inertia` | `matrix` | 实体惯性张量 | +| `is_active` | `bool` | 实体是否激活 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `initialize()` | 无 | `None` | 初始化实体状态 | +| `update()` | 无 | `None` | 更新实体状态 | +| `reset()` | 无 | `None` | 重置实体状态到初始值 | +| `copy()` | 无 | `EntityState` | 创建实体状态的副本 | +| `serialize()` | 无 | `dict` | 将实体状态序列化为字典 | +| `deserialize()` | `dict` | `None` | 从字典反序列化实体状态 | +| `interpolate()` | `EntityState, float` | `EntityState` | 在当前状态和目标状态之间插值 | + +## 继承关系 + +``` +BaseState +└── EntityState +``` + +```{eval-rst} +.. autoclass:: genesis.engine.states.entity_state.EntityState + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/states/index.md b/source/api_reference/states/index.md new file mode 100644 index 0000000..025ca20 --- /dev/null +++ b/source/api_reference/states/index.md @@ -0,0 +1,31 @@ +# States + +State 是 Genesis 引擎中用于管理和存储物理模拟状态的组件,它包含了实体、求解器和整个场景的当前状态信息。状态管理是物理模拟中的重要组成部分,负责记录和更新系统的动态变化。 + +## 状态类型 + +Genesis 引擎中的状态可以分为以下几类: + +- **实体状态**:存储单个实体的状态信息(位置、速度、姿态等) +- **求解器状态**:存储求解器的内部状态和计算数据 +- **场景状态**:存储整个场景的全局状态信息 +- **材质状态**:存储材质的动态属性 + +## 状态架构 + +所有状态类都继承自统一的 `State` 基类,提供一致的接口和状态管理机制。状态类负责: + +- 状态数据的存储和组织 +- 状态的序列化和反序列化 +- 状态的复制和克隆 +- 状态的插值和预测 +- 状态的重置和初始化 + +```{toctree} +:maxdepth: 2 + +base_state +entity_state +solver_state +scene_state +``` diff --git a/source/api_reference/states/scene_state.md b/source/api_reference/states/scene_state.md new file mode 100644 index 0000000..3d7646f --- /dev/null +++ b/source/api_reference/states/scene_state.md @@ -0,0 +1,56 @@ +# SceneState + +`SceneState` 是 Genesis 引擎中用于存储整个场景全局状态信息的类,包含了场景的时间、环境参数、全局物理设置等信息。它是场景级别的状态管理器。 + +## 功能说明 + +`SceneState` 类提供了以下核心功能: + +- 场景时间和帧率管理 +- 全局物理参数(重力、阻尼等)的存储 +- 环境参数(光照、背景等)的管理 +- 场景状态的复制和重置 +- 状态的序列化和反序列化 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 状态在系统中的唯一索引 | +| `uid` | `int` | 状态的全局唯一标识符 | +| `time` | `float` | 当前场景时间 | +| `frame` | `int` | 当前场景帧数 | +| `fps` | `float` | 目标帧率 | +| `gravity` | `vector` | 全局重力加速度 | +| `damping` | `float` | 全局阻尼系数 | +| `ambient_light` | `color` | 环境光照颜色 | +| `background_color` | `color` | 背景颜色 | +| `is_paused` | `bool` | 场景是否暂停 | +| `is_initialized` | `bool` | 状态是否已初始化 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `initialize()` | 无 | `None` | 初始化场景状态 | +| `update()` | 无 | `None` | 更新场景状态 | +| `reset()` | 无 | `None` | 重置场景状态到初始值 | +| `copy()` | 无 | `SceneState` | 创建场景状态的副本 | +| `serialize()` | 无 | `dict` | 将场景状态序列化为字典 | +| `deserialize()` | `dict` | `None` | 从字典反序列化场景状态 | +| `set_paused()` | `bool` | `None` | 设置场景暂停状态 | +| `set_time()` | `float` | `None` | 设置场景时间 | + +## 继承关系 + +``` +BaseState +└── SceneState +``` + +```{eval-rst} +.. autoclass:: genesis.engine.states.scene_state.SceneState + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/api_reference/states/solver_state.md b/source/api_reference/states/solver_state.md new file mode 100644 index 0000000..d701866 --- /dev/null +++ b/source/api_reference/states/solver_state.md @@ -0,0 +1,55 @@ +# SolverState + +`SolverState` 是 Genesis 引擎中用于存储求解器内部状态信息的类,包含了求解器的计算数据、迭代状态等信息。每个求解器都有一个对应的 `SolverState` 对象来管理其内部状态。 + +## 功能说明 + +`SolverState` 类提供了以下核心功能: + +- 求解器内部计算数据的存储 +- 迭代状态和收敛信息的管理 +- 求解器参数的动态存储 +- 求解器状态的复制和重置 +- 状态的序列化和反序列化 + +## 主要属性 + +| 属性名 | 类型 | 描述 | +|--------|------|------| +| `idx` | `int` | 状态在系统中的唯一索引 | +| `uid` | `int` | 状态的全局唯一标识符 | +| `solver_idx` | `int` | 对应的求解器索引 | +| `iterations` | `int` | 当前迭代次数 | +| `residual` | `float` | 求解残差 | +| `converged` | `bool` | 求解是否收敛 | +| `time_step` | `float` | 当前时间步长 | +| `gravity` | `vector` | 重力加速度 | +| `internal_data` | `dict` | 求解器内部数据 | +| `is_initialized` | `bool` | 状态是否已初始化 | + +## 主要方法 + +| 方法名 | 参数 | 返回值 | 描述 | +|--------|------|--------|------| +| `initialize()` | 无 | `None` | 初始化求解器状态 | +| `update()` | 无 | `None` | 更新求解器状态 | +| `reset()` | 无 | `None` | 重置求解器状态到初始值 | +| `copy()` | 无 | `SolverState` | 创建求解器状态的副本 | +| `serialize()` | 无 | `dict` | 将求解器状态序列化为字典 | +| `deserialize()` | `dict` | `None` | 从字典反序列化求解器状态 | +| `set_converged()` | `bool` | `None` | 设置求解收敛状态 | +| `set_residual()` | `float` | `None` | 设置求解残差 | + +## 继承关系 + +``` +BaseState +└── SolverState +``` + +```{eval-rst} +.. autoclass:: genesis.engine.states.solver_state.SolverState + :members: + :show-inheritance: + :undoc-members: +``` diff --git a/source/conf.py b/source/conf.py index da3cc0f..ebdb8d9 100644 --- a/source/conf.py +++ b/source/conf.py @@ -1,7 +1,11 @@ import os +import sys +# Prefer local source: add monorepo root (two levels up) if it contains `genesis/` +_local_repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) +if os.path.isdir(os.path.join(_local_repo_root, "genesis")): + sys.path.insert(0, _local_repo_root) import genesis as gs - __version__ = gs.__version__ # Configuration file for the Sphinx documentation builder. # @@ -32,11 +36,11 @@ "sphinx_subfigure", "sphinxcontrib.video", "sphinx_togglebutton", - "sphinx_design" + "sphinx_design", ] # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html -myst_enable_extensions = ["colon_fence", "dollarmath"] +myst_enable_extensions = ["colon_fence", "dollarmath", "amsmath", "dollarmath"] # https://github.com/executablebooks/MyST-Parser/issues/519#issuecomment-1037239655 myst_heading_anchors = 4 @@ -75,16 +79,16 @@ "github_repo": "genesis-doc", "github_version": "main", "conf_py_path": "/source/", - "doc_path": "/source" + "doc_path": "/source", } html_css_files = [ - 'css/custom.css', + "css/custom.css", ] -html_static_path = ['_static'] +html_static_path = ["_static"] ### Autodoc configurations ### autodoc_typehints = "signature" autodoc_typehints_description_target = "all" -autodoc_default_flags = ['members', 'show-inheritance', 'undoc-members'] +autodoc_default_flags = ["members", "show-inheritance", "undoc-members"] autodoc_member_order = "bysource" -autosummary_generate = True \ No newline at end of file +autosummary_generate = True diff --git a/source/index.md b/source/index.md index b2cbfd0..fe787b9 100644 --- a/source/index.md +++ b/source/index.md @@ -3,6 +3,13 @@ ```{figure} _static/images/teaser.png ``` +[![GitHub Repo stars](https://img.shields.io/github/stars/Genesis-Embodied-AI/Genesis?style=plastic&logo=GitHub&logoSize=auto)](https://github.com/Genesis-Embodied-AI/Genesis) +[![PyPI version](https://badge.fury.io/py/genesis-world.svg?icon=si%3Apython)](https://pypi.org/project/genesis-world/) +[![Website](https://img.shields.io/website?url=https%3A%2F%2Fgenesis-embodied-ai.github.io%2F)](https://genesis-embodied-ai.github.io/) +[![Discord](https://img.shields.io/discord/1322086972302430269?logo=discord)](https://discord.gg/nukCuhB47p) + + + ## What is Genesis? Genesis is a physics platform designed for general purpose *Robotics/Embodied AI/Physical AI* applications. It is simultaneously multiple things: @@ -21,8 +28,6 @@ Genesis is built and will continuously evolve with the following ***long-term mi 2. **Unifying a wide spectrum of state-of-the-art physics solvers** into a single framework, allowing re-creating the whole physical world in a virtual realm with the highest possible physical, visual and sensory fidelity, using the most advanced simulation techniques. 3. **Minimizing human effort** in collecting and generating data for robotics and other domains, letting the data flywheel spin on its own. -Project Page: [https://genesis-embodied-ai.github.io/](https://genesis-embodied-ai.github.io/) - ## Key Features Compared to prior simulation platforms, here we highlight several key features of Genesis: @@ -69,9 +74,9 @@ We sincerely welcome *any forms of contributions* from the community to make the If you used Genesis in your research, we would appreciate it if you could cite it. We are still working on a technical report, and before it's public, you could consider citing: ``` -@software{Genesis, +@misc{Genesis, author = {Genesis Authors}, - title = {Genesis: A Universal and Generative Physics Engine for Robotics and Beyond}, + title = {Genesis: A Generative and Universal Physics Engine for Robotics and Beyond}, month = {December}, year = {2024}, url = {https://github.com/Genesis-Embodied-AI/Genesis} diff --git a/source/user_guide/advanced_topics/collision_contacts_forces.md b/source/user_guide/advanced_topics/collision_contacts_forces.md index ed985bd..031480a 100644 --- a/source/user_guide/advanced_topics/collision_contacts_forces.md +++ b/source/user_guide/advanced_topics/collision_contacts_forces.md @@ -1,4 +1,160 @@ -# 💥 Collision, Contacts & Forces +# 💥 Rigid Collision Detection +Genesis provides a highly-efficient, feature-rich collision detection and contact generation pipeline for rigid bodies. The Python implementation lives in `genesis/engine/solvers/rigid/collider_decomp.py`. This page gives a *conceptual* overview of the algorithmic building blocks so that you can understand, extend or debug the code. -Coming soon... +> **Scope.** The focus is on rigid–rigid interactions. Soft-body / particle collisions rely on different solvers are in other files like `genesis/engine/coupler.py`. + +--- + +## Pipeline Overview + +The whole procedure can be seen as three successive stages: + +1. **AABB Update** – update world–space Axis-Aligned Bounding Boxes for every geometry. +2. **Broad Phase (Sweep-and-Prune)** – quickly reject obviously non-intersecting geom pairs based on AABB and output *possible* collision pairs. +3. **Narrow Phase** – robustly compute the actual contact manifold (normal, penetration depth, position, etc.) for every surviving pair using primitive-spcific algoirithm, SDF, MPR, or GJK. + +`Collider` orchestrates all three stages through the public `detection()` method: + +```python +collider.detection() # updates AABBs → SAP broad phase → narrow phase(s) +``` + +Each stage is described in the following sections. + +--- + +## 1 · AABB Update + +The helper kernel `_func_update_aabbs()` delegates the work to `RigidSolver._func_update_geom_aabbs()`. It computes a *tight* world-space AABB per geometry and stores the result in `geoms_state[..].aabb_min / aabb_max`. + +Why do we do this every frame? + +* Rigid bodies move ⇒ their bounding boxes change. +* AABB overlap checks are the cornerstone of the broad phase. + +--- + +## 2 · Broad Phase – Sweep & Prune + +The broad phase is implemented in `_func_broad_phase()`. It is an *N·log N* insertion-sort variant of the classical Sweep-and-Prune (a.k.a. Sort-and-Sweep): + +1. Project every AABB onto a single axis (currently X) and insert its *min* and *max* endpoints into a sortable buffer. +2. **Warm-start** – the endpoints are already almost sorted from the previous frame ⇒ insertion sort is almost linear. +3. Sweep through the sorted buffer maintaining an *active set* of intervals that overlap the current endpoint. +4. Whenever `min_a` crosses inside `max_b` we have a *potential* pair `(geom_a, geom_b)`. + +Extra filtering steps remove pairs that are physically impossible or explicitly disabled: + +* Same link / adjacent link filtering. +* `contype`/`conaffinity` bitmasks. +* Pairs of links that are both fixed w.r.t. the world. +* *Hibernation* support – sleeping bodies are ignored unless colliding with awake ones. + +The surviving pairs are stored in `broad_collision_pairs` and `n_broad_pairs`. + +--- + +## 3 · Narrow Phase – Contact Manifold Generation + +The narrow phase is split into four specialised kernels: + +| Kernel | When it runs | Purpose | +|--------|--------------|---------| +| `_func_narrow_phase_convex_vs_convex` | general convex–convex & plane-convex | Default path using **MPR** (Minkowski Portal Refinement) with fall-back to signed-distance-field queries. Use **GJK** algorithm when `use_gjk_collision` option in `RigidOptions` is set to be `True`. +| `_func_narrow_phase_convex_specializations` | plane-box & box-box | Specialized handlers for a pair of convex geometries that have analytic solutions. +| `_func_narrow_phase_any_vs_terrain` | at least one geometry is a *height-field terrain* | Generate multiple contact points per supporting cell. +| `_func_narrow_phase_nonconvex_vs_nonterrain` | at least one geometry is **non-convex** | Handles mesh ↔ convex or mesh ↔ mesh collisions via SDF vertex/edge sampling. + +### 3.1  Convex–Convex + +#### 3.1.1. GJK + +GJK, along with EPA, is a widely used contact detection algorithm in many physics engines, as it has following advantages: + +* Runs entirely on the GPU thanks to branch-free support-mapping primitives. +* Requires only a *support function* per shape – no face adjacency or feature cache. +* Gives seperation distance when the geometries are not in contact. +* Verified numerical robustness in many implementations. + +In Genesis, it is enabled when `use_gjk_collision` option in `RigidOptions` is set to be `True`. Also, Genesis enhances +the robustness of GJK with following measures. + +* Thorough degeneracy check on simplex and polytope during runtime. +* Robust face normal estimation. +* Robust lower and upper bound estimation on the penetration depth. + +Genesis accelerates support queries with a **pre-computed Support Field** (see {doc}`Support Field `). + +Multi-contact generation is enabled by *small pose perturbations* around the first contact normal. At most five +contacts (`_n_contacts_per_pair = 5`) are stored per pair. + +#### 3.1.2. MPR + +MPR is another contact detection algorithm widely adopted in physics engines. Even though it shares most of the advantages +of GJK, it does not give separation distance when the geometries are not colliding, and could be susceptible to numerical +errors and degeneracies as it is not verified as much as GJK in many implementations. + +In Genesis, MPR is improved with a signed-distance-field fall-back when there is a deep penetration. + +As GJK, Genesis accelerates support queries of MPR with a pre-computed Support Field, and detect multiple contacts with +small pose perturbations around the first contact normal. Thus, at most five contacts (`_n_contacts_per_pair = 5`) are stored per pair. + +### 3.2  Non-convex Objects + +For triangle meshes or decomposed convex clusters the pipeline uses **signed-distance fields** (SDF) pre-baked offline. The algorithm samples + +* vertices (vertex–face contact), then +* edges (edge–edge contact) + +and keeps the deepest penetration. The costly edge pass is skipped if a vertex contact is already found. + +### 3.3  Plane ↔ Box Special-Case + +Mujoco's analytical plane–box and box–box routine is ported for extra stability and to avoid degeneracies when a box lies flush on a plane. + +--- + +## Contact Data Layout + +Successful contacts are pushed into the *struct-of-arrays* field `contact_data`: + +| Field | Meaning | +|-------|---------| +| `geom_a`, `geom_b` | geometry indices | +| `penetration` | positive depth (≤ 0 means separated) | +| `normal` | world-space unit vector pointing **from B to A** | +| `pos` | mid-point of inter-penetration | +| `friction` | effective Coulomb coefficient (max of the two) | +| `sol_params` | solver tuning constants | + +`n_contacts` is incremented atomically so that GPU kernels may append in parallel. + +--- + +## Warm-Start & Caching + +To improve temporal coherence we cache, for every geometry pair, the ID of the previously deepest vertex and the last known separating normal. The cache is consulted to *seed* the MPR search direction and is cleared when the pair separates in the broad phase. + +--- + +## Hibernation + +When this feature is enabled, contacts belonging exclusively to hibernated bodies are preserved but not re-evaluated every frame (`n_contacts_hibernated`). This drastically reduces GPU work for scenes with large static backgrounds. + +--- + +## Tuning Parameters + +| Option | Default | Effect | +|--------|---------|--------| +| `RigidSolver._max_collision_pairs` | 4096 | upper bound on broad-phase pairs (per environment) | +| `Collider._mc_perturbation` | `1e-2` rad | perturbation angle for multi-contact search | +| `Collider._mc_tolerance` | `1e-2` of AABB size | duplicate-contact rejection radius | +| `Collider._mpr_to_sdf_overlap_ratio` | `0.5` | threshold to switch from MPR to SDF when one shape encloses the other | + +--- + +## Further Reading + +* {doc}`Support Field ` – offline acceleration structure for support-mapping shapes. diff --git a/source/user_guide/advanced_topics/collision_representation.md b/source/user_guide/advanced_topics/collision_representation.md deleted file mode 100644 index 0794ec1..0000000 --- a/source/user_guide/advanced_topics/collision_representation.md +++ /dev/null @@ -1,3 +0,0 @@ -# 🎱 Collision Representataions - -Coming soon... diff --git a/source/user_guide/advanced_topics/concepts.md b/source/user_guide/advanced_topics/concepts.md index aeb045a..b7d0173 100644 --- a/source/user_guide/advanced_topics/concepts.md +++ b/source/user_guide/advanced_topics/concepts.md @@ -1,4 +1,76 @@ # 🧩 Concepts +## Systemat Architecture Overview + +```{figure} ../../_static/images/overview.png +``` + + + +From a user’s perspective, building an environment in Genesis involves adding `Entity` objects to a `Scene`. Each `Entity` is defined by: +- `Morph`: the geometry of the entity, such as primitive shapes (e.g., cube, sphere) or articulated models (e.g., URDF, MJCF). +- `Material`: the physical properties of the entity, such as elastic solids, liquids, or granular materials. The material type determines the underlying solver used—for example, both MPM and SPH can simulate liquids, but each exhibits different behaviors. +- `Surface`: the visual and interaction-related surface properties, such as texture, roughness, or reflectivity. + +Behind the scenes, the `Scene` is powered by a `Simulator`, which includes: +- `Solver`: the core physics solvers responsible for simulating different physical models, such as rigid body dynamics, Material Point Method (MPM), Finite Element Method (FEM), Position-Based Dynamics (PBD), and Smoothed Particle Hydrodynamics (SPH). +- `Coupler`: a module that handles interactions between solvers, ensuring consistent force coupling and inter-entity dynamics. + + +## Data Indexing + +We have been recieving a lot of questions about how to partially manipulate a rigid entity like only controling or retrieving certain attributes. Thus, we figure it would be nice to write a more in-depth explaination on index access to data. + +**Structured Data Field**. For most of the case, we are using [struct Taichi field](https://docs.taichi-lang.org/docs/type#struct-types-and-dataclass). Take MPM for an example for better illustration ([here](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/solvers/mpm_solver.py#L103C1-L107C10) and [here](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/solvers/mpm_solver.py#L123)), +``` +struct_particle_state_render = ti.types.struct( + pos=gs.ti_vec3, + vel=gs.ti_vec3, + active=gs.ti_int, +) +... +self.particles_render = struct_particle_state_render.field( + shape=self._n_particles, needs_grad=False, layout=ti.Layout.SOA +) +``` +This means we are create a huge "array" (called field in Taichi) with each entry being a structured data type that includes `pos`, `vel`, and `active`. Note that this data field is of length `n_particles`, which include __ALL__ particles in a scene. Then, suppose there are multiple entities in the scene, how do we differentiate across entities? A straightforward idea is to "tag" each entry of the data field with the corresponding entity ID. However, it may not be the best practice from the memory layout, computation, and I/O perspective. Alternatively, we use index offsets to distinguish entities. + +**Local and Global Indexing**. The index offset provides simultaneously the simple, intuitive user interface (local indexing) and the optimized low-level implementation (global indexing). Local indexing allows interfacing __WITHIN__ an entity, e.g., the 1st joint or 30th particles of a specific entity. The global indexing is the pointer directly to the data field inside the solver which consider all entities in the scene. A visual illustration looks like this + +```{figure} ../../_static/images/local_global_indexing.png +``` + +We provide some concrete examples in the following for better understanding, +- In MPM simulation, suppose `vel=torch.zeros((mpm_entity.n_particles, 3))` (which only considers all particles of __this__ entity), [`mpm_entity.set_velocity(vel)`](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/entities/particle_entity.py#L296) automatically abstract out the offseting for global indexing. Under the hood, Genesis is actually doing something conceptually like `mpm_solver.particles[start:end].vel = vel`, where `start` is the offset ([`mpm_entity.particle_start`](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/entities/particle_entity.py#L453)) and `end` is the offset plus the number of particles ([`mpm_entity.particle_end`](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/entities/particle_entity.py#L457)). +- In rigid body simulation, all `*_idx_local` mean the local indexing, with which the users interact. They will be converted to the global indexing through `entity.*_start + *_idx_local`. Suppose we want to get the 3rd dof position by [`rigid_entity.get_dofs_position(dofs_idx_local=[2])`](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/entities/rigid_entity/rigid_entity.py#L2201), this is actually accessing `rigid_solver.dofs_state[2+offset].pos` where `offset` is [`rigid_entity.dofs_start`](https://github.com/Genesis-Embodied-AI/Genesis/blob/53b475f49c025906a359bc8aff1270a3c8a1d4a8/genesis/engine/entities/rigid_entity/rigid_entity.py#L2717). + +(An interesting read of a relevant design pattern called [entity component system (ECS)](https://en.wikipedia.org/wiki/Entity_component_system)) + +## Direct Access to Data Field + +Normally, we do not encourage users to directly access the (Taichi) data field. +Instead, users should mostly use the APIs in each entity, such as `RigidEntity.get_dofs_position`. +However, if one would like to access to data field not supported via APIs and could not wait for the new API support, one could try a direct access of data field, which may be a quick and dirty (yet most likely inefficient) solution. Specifically, following the data indexing mechanism described in the previous section, suppose one would like to do +``` +entity: RigidEntity = ... +tgt = entity.get_dofs_position(...) +``` + +This is equivalent to +``` +all_dofs_pos = entity.solver.dofs_state.pos.to_torch() +tgt = all_dofs_pos[:, entity.dof_start:entity.dof_end] # the first dimension is the batch dimension +``` + +All entities are associated with a specific solver (except for hybrid entity). +Each desired physical attribute is stored somewhere in the solver (e.g., dofs position here is stored as `dofs_state.pos` in the rigid solver). +For more details of these mapping, you could check {doc}`Naming and Variables `. +Also, all the data field in the solver follows a global indexing (for all entities) where you need `entity.*_start` and `entity.*_end` to only extract the data relevant with a specific entity. -Coming soon... diff --git a/source/user_guide/advanced_topics/differentiable_simulation.md b/source/user_guide/advanced_topics/differentiable_simulation.md index e508c6b..4ecfcc3 100644 --- a/source/user_guide/advanced_topics/differentiable_simulation.md +++ b/source/user_guide/advanced_topics/differentiable_simulation.md @@ -6,8 +6,8 @@ We now have our own tensor data type: `genesis.Tensor()`, for the following reasons: - to ensure a consistent user experience :) - it enables end-to-end gradient flow from loss all the way back to action input -- it removes need for specifying datatype (though you still can) when creaing tensors. The datatype specified when calling gs.init() will be used when creating genesis tensors. -- provides additional safety checks, such as contiguous check and check if tensors from different Scene are accidently being merged into the same computation graph. +- it removes need for specifying datatype (though you still can) when creating tensors. The datatype specified when calling gs.init() will be used when creating genesis tensors. +- provides additional safety checks, such as contiguous check and check if tensors from different Scene are accidentally being merged into the same computation graph. - supports other potential customizations if we need. This is essentially a subclass of pytorch tensors, so users can simply treat it as torch tensors and apply different kinds of torch operations. diff --git a/source/user_guide/advanced_topics/drone.md b/source/user_guide/advanced_topics/drone.md deleted file mode 100644 index c741695..0000000 --- a/source/user_guide/advanced_topics/drone.md +++ /dev/null @@ -1,4 +0,0 @@ -# 🛸 Drone - - -Coming soon... diff --git a/source/user_guide/advanced_topics/naming_and_variables.md b/source/user_guide/advanced_topics/naming_and_variables.md new file mode 100644 index 0000000..0c6aa80 --- /dev/null +++ b/source/user_guide/advanced_topics/naming_and_variables.md @@ -0,0 +1,426 @@ +# 📃 Naming and Variables + +Different solvers represent physical entities using various formats, such as particles, elements, grids, and surfaces. Each data field is prefixed according to its corresponding representation. For computational efficiency and structures, data fields associated with different physical attributes are organized into the following categories (based on types of computations): +- `*_state_*`: Dynamic states updated at every solver step. These fields are typically instantiated with `requires_grad` enabled by default. Its field size is, if differentiable, (number of substeps, number of units) and, if not, (number of units), where units depend on the representation like particles, vertices, etc. There may be different suffix for further specification such as, + - `*_state_ng`: Set `requires_gradient` to False. +- `*_info`: Static attributes that remain constant throughout the simulation, typically encompassing physical properties such as mass, stiffness, viscosity, etc. Its field size is (number of units,) +- `*_render`: Fields used exclusively for visualization, not directly involved in the physics computations. Its field size is (number of units,). + + + +Overall, the naming following `_`. (We always follow plural form with an s in representation, e.g., `dofs`, `particles`, `elements`, etc.) + +Also, some useful generic data types (defined in [genesis/\_\_init\_\_.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/__init__.py)): +```python +ti_vec2 = ti.types.vector(2, ti_float) +ti_vec3 = ti.types.vector(3, ti_float) +ti_vec4 = ti.types.vector(4, ti_float) +ti_vec6 = ti.types.vector(6, ti_float) +ti_vec7 = ti.types.vector(7, ti_float) +ti_vec11 = ti.types.vector(11, ti_float) + +ti_mat3 = ti.types.matrix(3, 3, ti_float) +ti_mat4 = ti.types.matrix(4, 4, ti_float) + +ti_ivec2 = ti.types.vector(2, ti_int) +ti_ivec3 = ti.types.vector(3, ti_int) +ti_ivec4 = ti.types.vector(4, ti_int) +``` + +In the following sections, we briefly describe the variables used by each solver. + +## Rigid Solver + +The rigid solver involves links, joints, geometry, and vertex representations. The rigid solver models articulated bodies composed of links and joints, with each link potentially consisting of multiple geometric components. Each geometry, in turn, may contain numerous vertices. + +For links, +* Dynamic link state (`links_state`) + ```python + ti.types.struct( + parent_idx=gs.ti_int, # index of the parent link in the kinematic tree (-1 if root) + root_idx=gs.ti_int, # index of the root link in the articulation + q_start=gs.ti_int, # start index in the global configuration vector (q) + dof_start=gs.ti_int, # start index in the global DoF vector + joint_start=gs.ti_int, # start index for joints affecting this link + q_end=gs.ti_int, # end index in the global configuration vector + dof_end=gs.ti_int, # end index in the global DoF vector + joint_end=gs.ti_int, # end index for joints affecting this link + n_dofs=gs.ti_int, # number of degrees of freedom for this link + pos=gs.ti_vec3, # current world-space position of the link + quat=gs.ti_vec4, # current world-space orientation (quaternion) + invweight=gs.ti_vec2, # inverse mass + is_fixed=gs.ti_int, # boolean flag: 1 if link is fixed/static, 0 if dynamic + inertial_pos=gs.ti_vec3, # position of the inertial frame (CoM) in link-local coordinates + inertial_quat=gs.ti_vec4, # orientation of the inertial frame relative to the link frame + inertial_i=gs.ti_mat3, # inertia tensor in the inertial frame + inertial_mass=gs.ti_float, # mass of the link + entity_idx=gs.ti_int, # index of the entity this link belongs to + ) + ``` +* Static link information (`links_info`) + ```python + ti.types.struct( + cinr_inertial=gs.ti_mat3, # com-based body inertia + cinr_pos=gs.ti_vec3, # com-based body position + cinr_quat=gs.ti_vec4, # com-based body orientation + cinr_mass=gs.ti_float, # com-based body mass + crb_inertial=gs.ti_mat3, # com-based composite inertia + crb_pos=gs.ti_vec3, # com-based composite position + crb_quat=gs.ti_vec4, # com-based composite orientation + crb_mass=gs.ti_float, # com-based composite mass + cdd_vel=gs.ti_vec3, # com-based acceleration (linear) + cdd_ang=gs.ti_vec3, # com-based acceleration (angular) + pos=gs.ti_vec3, # current world position + quat=gs.ti_vec4, # current orientation + ang=gs.ti_vec3, # angular velocity + vel=gs.ti_vec3, # linear velocity + i_pos=gs.ti_vec3, # inertia position + i_quat=gs.ti_vec4, # inertia orientation + j_pos=gs.ti_vec3, # joint frame position + j_quat=gs.ti_vec4, # joint frame orientation + j_vel=gs.ti_vec3, # joint linear velocity + j_ang=gs.ti_vec3, # joint angular velocity + cd_ang=gs.ti_vec3, # com-based velocity (angular) + cd_vel=gs.ti_vec3, # com-based velocity (linear) + root_COM=gs.ti_vec3, # center of mass of the root link's subtree + mass_sum=gs.ti_float, # total mass of the subtree rooted at this link + mass_shift=gs.ti_float, # mass shift + i_pos_shift=gs.ti_vec3, # inertia position shift + cfrc_flat_ang=gs.ti_vec3, # com-based interaction force (angular) + cfrc_flat_vel=gs.ti_vec3, # com-based interaction force (linear) + cfrc_ext_ang=gs.ti_vec3, # com-based external force (angular) + cfrc_ext_vel=gs.ti_vec3, # com-based external force (linear) + contact_force=gs.ti_vec3, # net contact force from environment + hibernated=gs.ti_int, # 1 if the link is in a hibernated/static state + ) + ``` + +For joints, +* Dynamic DoF state (`dofs_state`) + ```python + ti.types.struct( + force=gs.ti_float, # total net force applied on this DoF after accumulation + qf_bias=gs.ti_float, # + qf_passive=gs.ti_float, # total passive forces + qf_actuator=gs.ti_float, # actuator force + qf_applied=gs.ti_float, # + act_length=gs.ti_float, # + pos=gs.ti_float, # position + vel=gs.ti_float, # velocity + acc=gs.ti_float, # acceleration + acc_smooth=gs.ti_float, # + qf_smooth=gs.ti_float, # + qf_constraint=gs.ti_float, # constraint force + cdof_ang=gs.ti_vec3, # com-based motion axis (angular) + cdof_vel=gs.ti_vec3, # com-based motion axis (linear) + cdofvel_ang=gs.ti_vec3, # + cdofvel_vel=gs.ti_vec3, # + cdofd_ang=gs.ti_vec3, # time-derivative of cdof (angular) + cdofd_vel=gs.ti_vec3, # time-derivative of cdof (linear) + f_vel=gs.ti_vec3, # + f_ang=gs.ti_vec3, # + ctrl_force=gs.ti_float, # target force from the controller + ctrl_pos=gs.ti_float, # target position from the controller + ctrl_vel=gs.ti_float, # target velocity from the controller + ctrl_mode=gs.ti_int, # control mode (e.g., position, velocity, torque) + hibernated=gs.ti_int, # indicate hibernation + ) + ``` +* Static DoF information (`dofs_info`) + ```python + ti.types.struct( + stiffness=gs.ti_float, # stiffness of the DoF + sol_params=gs.ti_vec7, # constraint solver () + invweight=gs.ti_float, # inverse mass + armature=gs.ti_float, # dof armature inertia/mass + damping=gs.ti_float, # damping coefficient + motion_ang=gs.ti_vec3, # prescribed angular motion target + motion_vel=gs.ti_vec3, # prescribed linear motion target + limit=gs.ti_vec2, # lower and upper positional limits of the DoF + dof_start=gs.ti_int, # starting index of the DoF in the global system + kp=gs.ti_float, # proportional gain for PD control + kv=gs.ti_float, # derivative gain for PD control + force_range=gs.ti_vec2, # minimum and maximum allowed control force + ) + ``` +* Static joint information (`joints_info`) + ```python + ti.types.struct( + type=gs.ti_int, # joint type ID (e.g., revolute, prismatic, fixed) + sol_params=gs.ti_vec7, # constraint solver (reference; impedance) + q_start=gs.ti_int, # start index in global configuration vector (q) + dof_start=gs.ti_int, # start index in global DoF vector + q_end=gs.ti_int, # end index in global configuration vector + dof_end=gs.ti_int, # end index in global DoF vector + n_dofs=gs.ti_int, # number of DOFs for this joint + pos=gs.ti_vec3, # joint position in world space + ) + ``` + +For geometries, +* Dynamic geometry state (`geom_state`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # current world position of the geometry + quat=gs.ti_vec4, # current world orientation (quaternion) + vel=gs.ti_vec3, # linear velocity of the geometry + ang=gs.ti_vec3, # angular velocity of the geometry + aabb_min=gs.ti_vec3, # minimum bound of the geometry's AABB (axis-aligned bounding box) + aabb_max=gs.ti_vec3, # maximum bound of the geometry's AABB + ) + ``` +* Static geometry information (`geom_info`) + ```python + ti.types.struct( + link_idx=gs.ti_int, # index of the link this geometry belongs to + type=gs.ti_int, # geometry type (e.g., box, sphere, mesh) + local_pos=gs.ti_vec3, # position in the link's local frame + local_quat=gs.ti_vec4, # orientation in the link's local frame + size=gs.ti_vec3, # dimensions or bounding volume + ) + ``` + + + + +## MPM Solver + +Material Point Method (MPM) uses particle- and grid-based representations. + +For particles, +* Dynamic particle state (`particles_state`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # position + vel=gs.ti_vec3, # velocity + C=gs.ti_mat3, # affine velocity field + F=gs.ti_mat3, # deformation gradient + F_tmp=gs.ti_mat3, # temporary deformation gradient + U=gs.ti_mat3, # left orthonormal matrix in SVD (Singular Value Decomposition) + V=gs.ti_mat3, # right orthonormal matrix in SVD + S=gs.ti_mat3, # diagonal matrix in SVD + actu=gs.ti_float, # actuation + Jp=gs.ti_float, # volume ratio + ) + ``` +* Dynamic particle state without gradient (`particles_stage_ng`) + ```python + ti.types.struct( + active=gs.ti_int, # whether the particle is active or not + ) + ``` +* Static particle information (`particles_info`) + ```python + ti.types.struct( + material_idx=gs.ti_int, # material id + mass=gs.ti_float, # mass + default_Jp=gs.ti_float, # default volume ratio + free=gs.ti_int, # whether the particle is free; non-free particles behave as boundary conditions + muscle_group=gs.ti_int, # muscle/actuation group + muscle_direction=gs.ti_vec3, # muscle/actuation direction + ) + ``` + +For grid, +* Dynamic grid state (`grid_state`) + ```python + ti.types.struct( + vel_in=gs.ti_vec3, # input momentum + mass=gs.ti_float, # mass + vel_out=gs.ti_vec3, # output velocity + ) + ``` + +For rendering, +* Particle attributes for particle-based rendering (`particles_render`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # position + vel=gs.ti_vec3, # velocity + active=gs.ti_int, # whether the particle is active + ) + ``` +* Static virtual vertex information for visual-based rendering (`vverts_info`) + ```python + ti.types.struct( + support_idxs=ti.types.vector(n_vvert_supports, gs.ti_int), # the indices of the supporting particles + support_weights=ti.types.vector(n_vvert_supports, gs.ti_float), # the interpolation weights + ) + ``` +* Dynamic virtual vertex state for visual-based rendering (`vverts_render`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # the position of the virtual vertices + active=gs.ti_int, # whether the virtual vertex is active + ) + ``` + +Check [`genesis/solvers/mpm_solver.py`](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/engine/solvers/mpm_solver.py) for more details. + +## FEM Solver + +Finite Element Method (FEM) uses element and surface representation, where some attributes in elements are stored in the associated vertices. + +For elements, +* Dynamic element state in element (`elements_el_state`) + ```python + ti.types.struct( + actu=gs.ti_float, # actuation + ) + ``` +* Dynamic element state in vertex (`elements_v_state`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # position + vel=gs.ti_vec3, # velocity + ) + ``` +* Dynamic element state without gradient (`elements_el_state_ng`) + ```python + ti.types.struct( + active=gs.ti_int, # whether the element is actice + ) + ``` +* Static element information (`elements_el_info`) + ```python + ti.types.struct( + el2v=gs.ti_ivec4, # vertex index of an element + mu=gs.ti_float, # lame parameters (1) + lam=gs.ti_float, # lame parameters (2) + mass_scaled=gs.ti_float, # scaled element mass. The real mass is mass_scaled / self._vol_scale + material_idx=gs.ti_int, # material model index + B=gs.ti_mat3, # the inverse of the undeformed shape matrix + muscle_group=gs.ti_int, # muscle/actuator group + muscle_direction=gs.ti_vec3, # muscle/actuator direction + ) + ``` + +For surfaces, +* Static surface information (`surfaces_info`) + ```python + ti.types.struct( + tri2v=gs.ti_ivec3, # vertex index of a triangle + tri2el=gs.ti_int, # element index of a triangle + active=gs.ti_int, # whether this surface unit is active + ) + ``` + +For rendering, +* Dynamic surface attribute in vertex (`surfaces_v_render`) + ```python + ti.types.struct( + vertices=gs.ti_vec3, # position + ) + ``` +* Dynamic surface attribute in face (`surfaces_f_render`) + ```python + ti.types.struct( + indices=gs.ti_int, # vertex indices corresponding to this surface unit (TODO: this is ugly as we flatten out (n_surfaces_max, 3)) + ) + ``` + +Check [`genesis/solvers/fem_solver.py`](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/engine/solvers/fem_solver.py) for more details. + + +## PBD Solver + +Position Based Dynamics (PBD) uses a particle-based representation. + +For particles, +* Dynamic particle state (`particles_state`, `particles_state_reordered`) + ```python + ti.types.struct( + free=gs.ti_int, # whether the particle is free to move. If 0, it is kinematically controlled (e.g., fixed or externally manipulated) + pos=gs.ti_vec3, # position + ipos=gs.ti_vec3, # initial position + dpos=gs.ti_vec3, # delta position + vel=gs.ti_vec3, # velocity + lam=gs.ti_float, # lagrange multiplier or constraint force scalar + rho=gs.ti_float, # estimated fluid density + ) + ``` +* Dynamic particle state without gradient (`particles_state_ng`, `particles_state_ng_reordered`) + ```python + ti.types.struct( + reordered_idx=gs.ti_int, # reordering index + active=gs.ti_int, # whether the particle is active + ) + ``` +* Static particle information (`particles_info`, `particles_info_reordered`) + ```python + ti.types.struct( + mass=gs.ti_float, # mass + pos_rest=gs.ti_vec3, # rest position + rho_rest=gs.ti_float, # rest density + material_type=gs.ti_int, # material type + mu_s=gs.ti_float, # static friction coefficient + mu_k=gs.ti_float, # dynamic friction coefficient + air_resistance=gs.ti_float, # coefficient of drag / damping due to air + density_relaxation=gs.ti_float, # parameter for density constraint solver + viscosity_relaxation=gs.ti_float, # parameter for viscosity behavior + ) + ``` + +For rendering, +* Particle attribute (`particles_render`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # position + vel=gs.ti_vec3, # velocity + active=gs.ti_int, # whether the particle is active + ) + ``` + +Check [`genesis/solvers/pbd_solver.py`](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/engine/solvers/pbd_solver.py) for more details. + +## SPH Solver + +Smoothed Particle Hydrodynamics (SPH) uses a particle-based representation. + +For particles, +* Dynamic particle state (`particles_state`, `particles_state_reordered`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # position + vel=gs.ti_vec3, # velocity + acc=gs.ti_vec3, # acceleration + rho=gs.ti_float, # density + p=gs.ti_float, # pressure + dfsph_factor=gs.ti_float, # factor used in DFSPH pressure solve + drho=gs.ti_float, # density derivative (rate of change) + ) + ``` +* Dynamic particle state without gradient (`particles_state_ng`, `particles_state_ng_reordered`) + ```python + ti.types.struct( + reordered_idx=gs.ti_int, # reordering index + active=gs.ti_int, # whether the particle is active + ) + ``` +* Static particle information (`particles_info`, `particles_info_reordered`) + ```python + ti.types.struct( + rho=gs.ti_float, # rest density + mass=gs.ti_float, # particle mass + stiffness=gs.ti_float, # equation-of-state stiffness + exponent=gs.ti_float, # equation-of-state exponent + mu=gs.ti_float, # viscosity coefficient + gamma=gs.ti_float, # surface tension coefficient + ) + ``` + +For rendering, +* Particle attributes (`particles_render`) + ```python + ti.types.struct( + pos=gs.ti_vec3, # position + vel=gs.ti_vec3, # velocity + active=gs.ti_int, # whether the particle is active + ) + ``` + +Check [`genesis/solvers/sph_solver.py`](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/engine/solvers/sph_solver.py) for more details. + + diff --git a/source/user_guide/advanced_topics/nonrigid_models.md b/source/user_guide/advanced_topics/nonrigid_models.md new file mode 100644 index 0000000..c9e9e53 --- /dev/null +++ b/source/user_guide/advanced_topics/nonrigid_models.md @@ -0,0 +1,128 @@ +# 🧩 Non-rigid Dynamics + +This page gives a compact overview of the physical models implemented by Genesis' continuum and discrete solvers. The emphasis is on *which equations are being solved and how*, rather than on the Python API. For coupling theory see the dedicated *Solvers & Coupling* chapter. + +--- + +## 1. Eulerian Stable-Fluid Solver (`SFSolver`) + +**Purpose.** Fast smoke / gas simulation on a fixed grid. + +**Governing equations** – incompressible Navier–Stokes. + +**Algorithm** – Jos Stam's *Stable Fluids*: + +1. **Advection** – velocities are back-traced with third-order RK and interpolated (`backtrace` + `trilerp`). Numerically unconditionally stable. +2. **External impulses** – jet sources inject momentum after advection. +3. **Viscosity / decay** – optional exponential damping term. +4. **Pressure projection** – solve Poisson by Jacobi iteration (`pressure_jacobi`). + +5. **Boundary conditions** – zero-normal velocity enforced by mirroring components at solid faces. + +Because all steps are explicit or diagonally implicit the method is extremely robust at large time-steps and suitable for real-time effects. + +--- + +## 2. Material Point Method Solver (`MPMSolver`) + +**Purpose.** Unified simulation of solids, liquids and granular media using particles + background grid. + +**Core idea.** The continuum momentum equation is evaluated on an Eulerian grid while material history (deformation gradient, plastic strain, etc.) is stored on Lagrangian particles. + +### 2.1 Update sequence (APIC / CPIC variant) + +| Phase | Description | +|-------|-------------| +| P2G | Transfer mass and momentum to neighbour grid nodes with B-spline weights; add stress contribution. | +| Grid solve | Divide by mass to obtain velocities, apply gravity & boundary collisions. | +| G2P | Interpolate grid velocity back, update affine matrix and position. | +| Polar-SVD | Decompose deformation graident; material law returns new deformation gradient. | + +### 2.2 Constitutive models + +Genesis ships several analytic stress functions: + +* **Neo-Hookean elastic** (chalk/snow) +* **Von Mises capped plasticity** (snow-plastic) +* **Weakly compressible liquid** (WC fluid) +* **Anisotropic muscle** adding active fibre stress + +--- + +## 3. Finite Element Method Solver (`FEMSolver`) + +**Purpose.** High-quality deformable solids with tetrahedral meshes; optional implicit integration for stiff materials. + +### 3.1 Energy formulation + +Total potential energy + +$$ \Pi(\mathbf x) = \sum_{e} V_{e}\,\psi(\mathbf F_e) - \sum_{i} m_{i}\,\mathbf g\!\cdot\!\mathbf x_i. $$ + +The first variation yields the internal force; the second variation gives the element stiffness. + +### 3.2 Implicit backward Euler + +Given current state $(\mathbf x^n, \mathbf v^n)$ solve for $\mathbf x^{n+1}$ by Newton–Raphson: + +$$ \mathbf r(\mathbf x) = \frac{m}{\Delta t^{2}}(\mathbf x - \hat{\mathbf x}) + \frac{\partial \Pi}{\partial \mathbf x} = 0,$$ +where $\hat{\mathbf x} = \mathbf x^{n} + \Delta t\,\mathbf v^{n}$ is the inertial prediction. + +Each Newton step solves $\mathbf H\,\delta \mathbf x = -\mathbf r$ with PCG; $\mathbf H$ is the consistent stiffness + mass matrix. A block-Jacobi inverse of per-vertex 3×3 blocks is used as preconditioner. Line-search (Armijo back-tracking) guarantees energy decrease. + +--- + +## 4. Position-Based Dynamics Solver (`PBDSolver`) + +**Purpose.** Real-time cloth, elastic rods, XPBD fluids and particle crowds. + +### 4.1 XPBD integration cycle + +1. **Predict** – explicit Euler: $\mathbf v^{*}\!=\!\mathbf v + \Delta t\,\mathbf f/m$ and $\mathbf x^{*}\!=\!\mathbf x + \Delta t\,\mathbf v^{*}$. +2. **Project constraints** – iterate over edges, tetrahedra, SPH density etc. + For each constraint $C(\mathbf x)\!=\!0$ solve for Lagrange multiplier λ + + $$ \Delta\mathbf x = -\frac{C + \alpha\,\lambda^{old}}{\sum w_i\,|\nabla\!C_i|^{2}+\alpha}\,\nabla\!C, \quad \alpha = \frac{\text{compliance}}{\Delta t^{2}}. $$ + +3. **Update velocities** – $\mathbf v = (\mathbf x^{new}-\mathbf x^{old})/\Delta t$. + +### 4.2 Supported constraints + +* Stretch / bending (cloth) +* Volume preservation (XPBD tetrahedra) +* Incompressible SPH density & viscosity constraints (fluid-PBD) +* Collision & friction via positional correction + Coulomb model. + +--- + +## 5. Smoothed Particle Hydrodynamics Solver (`SPHSolver`) + +**Purpose.** Particle-based fluids with either WCSPH or DFSPH pressure solvers. + +### 5.1 Kernels + +Cubic spline kernel $W(r,h)$ and gradient $\nabla W$ with support radius $h=$ `_support_radius`. + +### 5.2 Weakly Compressible SPH (WCSPH) + +* Equation of state: $p_i = k\bigl[(\rho_i/\rho_0)^{\gamma}-1\bigr]$. +* Momentum equation: + + $$ \frac{d\mathbf v_i}{dt} = -\sum_j m_j \left( \frac{p_i}{\rho_i^2} + \frac{p_j}{\rho_j^2} \right) \nabla W_{ij} + \mathbf g + \mathbf f_{visc} + \mathbf f_{surf}. $$ + +### 5.3 Divergence-free SPH (DFSPH) + +* Splits solve into **divergence pass** (enforce $\nabla\!\cdot\mathbf v = 0$) and **density pass** (enforce $\rho\!=\!\rho_0$). +* Both passes iteratively compute per-particle pressure coefficient κ with Jacobi iterations using the *DFSPh factor* field. +* Ensures incompressibility with bigger time-steps than WCSPH. + +--- + +### References + +* Stam, J. "Stable Fluids", SIGGRAPH 1999. +* Zhu, Y.⁠ & Bridson, R. "Animating Sand as a Fluid", SIGGRAPH 2005. +* Gao, T. et al. "Robust Simulation of Deformable Solids with Implicit FEM", SIGGRAPH 2015. +* Macklin, M. et al. "Position Based Fluids", SIGGRAPH 2013. +* Bender, J. et al. "Position Based Dynamics", 2014. +* Bavo et al. "Divergence-Free SPH", Eurographics 2015. diff --git a/source/user_guide/advanced_topics/rigid_constraint_model.md b/source/user_guide/advanced_topics/rigid_constraint_model.md new file mode 100644 index 0000000..d292ab8 --- /dev/null +++ b/source/user_guide/advanced_topics/rigid_constraint_model.md @@ -0,0 +1,108 @@ +# 🔗 Rigid Collision Resolution + +Genesis follows a **quadratic penalty formulation** very similar to that used by [MuJoCo](https://mujoco.readthedocs.io/) for enforcing rigid–body constraints. This document summarises the mathematics and physical interpretation of the model. + +--- + +## 1. General formulation + +Let + +* $q$ – joint configuration (generalised positions) +* **\dot q** – generalised velocities +* $a = \ddot q$ – the unknown **generalised accelerations** to be solved for each sub-step +* $M(q)$ – joint-space mass matrix (positive definite) +* $\tau_{ext}$ – all external joint forces **already known** (actuation, gravity, hydrodynamics …) +* $J $ – a *stack* of kinematic constraints linearised in acceleration space +* $D$ – diagonal matrix of *softness* / *impedance* parameters per constraint +* $a_{ref}$ – reference accelerations that try to restore penetrations or satisfy motors + +We seek the acceleration that minimises the **quadratic cost** + +$$ + \frac12 (M a \,{-}\, \tau_{ext})^{\!T} (a \,{-}\, a^{\text{prev}}) + \;{+}\; + \frac12 (J a \,{-}\, a_{ref})^{\!T} D (J a \,{-}\, a_{ref}) +$$ + + +--- + +## 2. Contact & friction model + +For every **contact pair** Genesis creates four constraints, which are the basis of the friction pyramid. Mathematically each direction **tᵢ** is + +$$ + \mathbf t\_i = \pm d_1\,\mu - \mathbf n \quad\text{or}\quad \pm d_2\,\mu - \mathbf n , +$$ + +so that a positive multiplier on **tᵢ** produces a force that lies *inside* the cone $|\mathbf f_t| \le \mu f_n$. A diagonal entry **Dᵢ** proportional to the combined inverse mass gives the familiar *soft-constraint* behaviour where larger *imp* (implicitness) values lead to stiffer contacts. + +--- + +## 3. Joint limits (inequality constraints) + +Revolute and prismatic joints optionally carry a **lower** and **upper** position limit. Whenever the signed distance to a limit becomes negative + +$$ \phi = q - q_{min} < 0 \quad\text{or}\quad \phi = q_{max} - q < 0 $$ + +a *single* 1-DOF constraint is spawned with Jacobian + +$$ J = \pm 1 $$ + +and reference acceleration + +$$ a_{ref} = k\,\phi + c \,\dot q, $$ + +obtained from the scalar `sol_params` (spring-damper style softness). The diagonal entry of **D** once again scales with the inverse joint inertia. + +--- + +## 4. Equality constraints + +Genesis supports three kinds of **holonomic equalities**: + +| Type | DOF removed | Description | +|------|-------------|-------------| +| **Connect** | 3 | Enforces that two points on different bodies share the *same world position*. Good for ball-and-socket joints. | +| **Weld** | 6 | Keeps two frames coincident in both translation **and** rotation (optionally scaled torque). | +| **Polynomial joint** | 1 | Constrains one joint as a polynomial function of another (useful for complex mechanisms). | + +Each equality writes rows into **J** so that their *relative* translational / rotational velocity vanishes. Softness and Baumgarte stabilisation again come from per-constraint `sol_params`. + +--- + +## 5. Solvers + +The solver class implements **two interchangeable algorithms**: + +### 5.1 Projected Conjugate Gradient (PCG) + +* Operates in the **reduced space** of accelerations. +* Uses the *mass matrix* as pre-conditioner. +* After each CG step a **back-tracking line search** (Armijo style) projects the new **J a** onto the feasible set (normal ≥0, friction cone). +* Requires only **matrix-vector products**, making it memory-friendly and fast for scenes with many constraints. + +### 5.2 Newton–Cholesky + +* Builds the **exact Hessian** \(H = M + J^T D J\). +* A Cholesky factorisation (with incremental rank-1 updates) yields search directions. +* Converges in very few steps (often 2-3) but is more expensive for large DOF counts. + +Both variants share **identical line-search logic** implemented in `_func_linesearch` that chooses the step length \(\alpha\) minimising the quadratic model whilst respecting inequality activation/de-activation. The algorithm stops when either + +* the gradient norm \(|\nabla f|\) drops below `tolerance · mean_inertia · n_dofs`, or +* the improvement of the cost function falls below the same threshold. + +Warm-starting is supported by initialising from the previous sub-step's smoothed accelerations `acc_smooth`. + +--- + +## 6. Practical implications + +* **Stability** – because constraints are *implicit* in acceleration space the model handles larger time-steps, similar to MuJoCo. +* **Friction anisotropy** – replacing the cone by a pyramid introduces slight anisotropy. Increasing the number of directions would reduce this but cost more. +* **Softness** – tuning `imp` and `timeconst` lets you trade constraint stiffness against numerical conditioning. Values near 1 are stiff but may slow convergence. +* **Choosing a solver** – use *CG* for scenes with thousands of DOFs or when memory is tight; switch to *Newton* when you need very high accuracy or when the DOF count is moderate (<100). + +--- diff --git a/source/user_guide/advanced_topics/solvers_and_coupling.md b/source/user_guide/advanced_topics/solvers_and_coupling.md index 5f49116..95456fd 100644 --- a/source/user_guide/advanced_topics/solvers_and_coupling.md +++ b/source/user_guide/advanced_topics/solvers_and_coupling.md @@ -1,4 +1,112 @@ -# 🧮 Solvers & Coupling +# 🧮 Non-rigid Coupling +Genesis allows you to combine multiple continuum and rigid-body solvers in the **same scene** – e.g. MPM snow interacting with SPH water, deformable FEM tissue colliding with surgical tools, or rigid props splashing into a granular bed. All cross-solver interactions are orchestrated by the `gs.engine.Coupler` class. -Coming soon... +This page explains: + +* the **architecture** of the Coupler and how it decides which solver pairs are active; +* the **impulse-based collision response** that governs momentum exchange; +* the meaning of **friction, restitution, softness** and other coupling parameters; +* a quick **reference table** of currently supported solver pairs; and +* **usage examples** showing how to enable/disable specific interactions. + +--- + +## 1. Architecture overview + +Internally the simulator owns **one Coupler instance** which keeps pointers to every solver. During each sub-step the simulator executes: + +1. `coupler.preprocess(f)`    – e.g. surfacing operations for CPIC. +2. `solver.substep_pre_coupling(f)` – advance each individual solver. +3. `coupler.couple(f)` – exchange momentum between solvers. +4. `solver.substep_post_coupling(f)` – solver postprocessing after collision. + +Because all solver fields live on Taichi data-structures the Coupler can call Taichi `@kernel`s that touch the memory of several solvers **without data copies**. + +### 1.1 Activating a coupling pair + +Whether a pair is active is determined **statically once** when `Coupler.build()` is called: + +```python +self._rigid_mpm = rigid.is_active() and mpm.is_active() and options.rigid_mpm +``` + + +## 2. Impulse-based collision response + +### 2.1 Signed distance & influence weight + +For every candidate contact the Coupler queries the signed distance function `sdf(p)` of the rigid geometry. The *softness* parameter produces a smooth blending weight + +$$ +\text{influence} = \min\bigl( \exp\!\left(-\dfrac{\;d\;}{\epsilon}\right) ,\;1 \bigr) +$$ + +where `d` is the signed distance and `ε = coup_softness`. Large softness values make the contact zone thicker and produce gentler impulses. + +### 2.2 Relative velocity decomposition + +For a particle/grid node with world velocity **v** and a rigid body velocity **vᵣ**, the **relative velocity** is + +$$ \mathbf r = \mathbf v - \mathbf v_{\text{rigid}}. $$ + +Split **r** into its normal and tangential components + +$$ + r_n = (\mathbf r \cdot \mathbf n)\,\mathbf n, \quad + r_t = \mathbf r - r_n +$$ + +with **n** the outward surface normal. + +### 2.3 Normal impulse (restitution) + +If the normal component is *inward* ($r_n<0$) an impulse is applied so that after the collision + +$$ r_n' = -e\,r_n, \quad 0 \le e \le 1, $$ + +where `e = coup_restitution` is the **restitution coefficient**. `e=0` is perfectly inelastic, `e=1` perfectly elastic. + +### 2.4 Tangential impulse (Coulomb friction) + +Friction is implemented by **scaling** the tangential component: + +$$ r_t' = \max\!\bigl( 0,\;|r_t| + \mu \, r_n\bigr) \; \dfrac{r_t}{|r_t|}\,, $$ + +with `μ = coup_friction`. This is an impulse-based variant of Coulomb friction that ensures the post-collision tangential speed never exceeds the sticking limit. + +### 2.5 Velocity update and momentum transfer + +The new particle/node velocity is then + +$$ \mathbf v' = \mathbf v_{\text{rigid}} + (r_t' + r_n') \times \text{influence} + \mathbf r\,(1-\text{influence}). $$ + +The *change of momentum* + +$$ \Delta\mathbf p = m\,(\mathbf v' - \mathbf v) $$ + +is applied as an **external force** on the rigid body + +$$ \mathbf F_{\text{rigid}} = -\dfrac{\Delta\mathbf p}{\Delta t}. $$ + +Thus Newton's third law is satisfied and the rigid body responds to fluid impacts. + +--- + +## 3. Supported solver pairs + +| Pair | Direction | Notes | +|------|-----------|-------| +| **MPM ↔ Rigid** | impulse based on grid nodes (supports CPIC) | +| **MPM ↔ SPH** | averages SPH particle velocities within an MPM cell | +| **MPM ↔ PBD** | similar to SPH but skips pinned PBD particles | +| **FEM ↔ Rigid** | collision on surface vertices only | +| **FEM ↔ MPM** | uses MPM P2G/G2P weights to exchange momentum | +| **FEM ↔ SPH** | experimental – normal projection only | +| **SPH ↔ Rigid** | robust side-flip handling of normals | +| **PBD ↔ Rigid** | positional correction then velocity projection | +| **Tool ↔ MPM** | delegated to each Tool entity's `collide()` | + +If a combination is not in the table it is currently unsupported. + +--- diff --git a/source/user_guide/advanced_topics/sparse_computation.md b/source/user_guide/advanced_topics/sparse_computation.md deleted file mode 100644 index dc6308c..0000000 --- a/source/user_guide/advanced_topics/sparse_computation.md +++ /dev/null @@ -1,3 +0,0 @@ -# 💠 Sparse Computation - -Coming soon... diff --git a/source/user_guide/advanced_topics/support_field.md b/source/user_guide/advanced_topics/support_field.md new file mode 100644 index 0000000..33632b5 --- /dev/null +++ b/source/user_guide/advanced_topics/support_field.md @@ -0,0 +1,72 @@ +# 🚀 Support Field + +Collision detection for convex shapes in Genesis relies heavily on *support functions*. Every iteration of the Minkowski Portal Refinement (MPR) algorithm asks questions of the form: + +> _"Given a direction **d**, which vertex of the shape has the maximum dot-product **v·d**?"_ + +A naïve implementation has to iterate over all vertices every time – wasteful for models containing thousands of points. To avoid this, Genesis pre-computes a **Support Field** for every convex geometry during scene initialisation. The implementation lives in `genesis/engine/solvers/rigid/support_field_decomp.py`. + +--- + +## How It Works + +1. **Uniform Direction Grid** – The sphere is discretised into `support_res × support_res` directions using longitude/latitude (`θ`, `ϕ`). By default `support_res = 180`, giving ≈32 k sample directions. +2. **Offline Projection** – For each direction we project *all* vertices and remember the index with the largest dot-product. The resulting arrays are: + * `support_v ∈ ℝ^{N_dir×3}` – the actual vertex positions in *object space*. + * `support_vid ∈ ℕ^{N_dir}` – original vertex indices (useful to warm-start SDF queries). + * `support_cell_start[i_g]` – prefix-sum offset into the flattened arrays per geometry. +3. **Taichi Fields** – The arrays are copied into GPU-resident Taichi fields so that kernels can access them without host round-trips. + +```python +v_ws, idx = support_field._func_support_world(dir_ws, i_geom, i_batch) +``` + +The above gives you the extreme point in world-space for any query direction in **O(1)**. + +--- + +## Data Layout + +| Field | Shape | Description | +|-------|-------|-------------| +| `support_v` | `(N_cells, 3)` | vertex positions (float32/64) | +| `support_vid` | `(N_cells,)` | corresponding vertex index (int32) | +| `support_cell_start`| `(n_geoms,)` | offset into flattened arrays | + +!!! info "Memory footprint" + With the default resolution each convex shape uses ≈ 32 k × (3 × 4 + 4) = 416 kB. For collections of small primitives this is significantly cheaper than building a BVH per shape. + +--- + +## Advantages + +* **Constant-time look-ups** during MPR ⇒ fewer diverging branches on the GPU. +* **GPU friendly** – the support field is a simple SOA array, no complex pointer chasing. +* **Works for *any* convex mesh** – no need for canonical-axes or bounding boxes. + +## Limitations & Future Work + +* The direction grid is isotropic but not adaptive – features smaller than the angular cell size may map to the wrong vertex. +* Preprocessing and memory consumption would be expensive if the number of geometry is large in a scene. + +--- + +## API Summary + +```python +from genesis.engine.solvers.rigid.rigid_solver_decomp import RigidSolver +solver = RigidSolver(...) +s_field = solver.collider._mpr._support # internal handle + +v_ws, idx = s_field._func_support_world(dir_ws, i_geom, i_env) +``` + +`v_ws` is the *world-space* support point while `idx` is the vertex ID in the original mesh (global index). + +--- + +## Relation to Collision Pipeline + +The Support Field is an **acceleration structure** exclusively used by the *convex–convex* narrow phase. Other collision paths – SDF, terrain, plane–box – bypass it because they either rely on analytical support functions or distance fields. + +For details on how MPR integrates this structure see {doc}`Collision, Contacts & Forces `. \ No newline at end of file diff --git a/source/user_guide/getting_started/advanced_ik.md b/source/user_guide/getting_started/advanced_ik.md index 01893bc..d4b9531 100644 --- a/source/user_guide/getting_started/advanced_ik.md +++ b/source/user_guide/getting_started/advanced_ik.md @@ -12,7 +12,7 @@ import numpy as np import genesis as gs ########################## init ########################## -gs.init(seed=0, precision='32', logging_level='debug') +gs.init(seed=0, precision='32', logging_level='info') ########################## create a scene ########################## scene = gs.Scene( diff --git a/source/user_guide/getting_started/beyond_rigid_bodies.md b/source/user_guide/getting_started/beyond_rigid_bodies.md index 9c9775e..745894b 100644 --- a/source/user_guide/getting_started/beyond_rigid_bodies.md +++ b/source/user_guide/getting_started/beyond_rigid_bodies.md @@ -78,7 +78,7 @@ Once you run this successfully, you will see the water drops and spreads over th You can get the real-time particle positions by: ``` -particles = liquid.get_particles() +particles = liquid.get_particles_pos() ``` **Changing the liquid properties:** You can also play with the physical properties of the liquid. For example, you can increase its viscosity (`mu`) and surface tension (`gamma`): @@ -139,7 +139,7 @@ for i in range(horizon): scene.step() # get particle positions -particles = liquid.get_particles() +particles = liquid.get_particles_pos() ``` ## Deformable object simulation using MPM Solver @@ -273,7 +273,7 @@ cloth_1 = scene.add_entity( morph=gs.morphs.Mesh( file='meshes/cloth.obj', scale=2.0, - pos=(0, 0, 0.5), + pos=(0, 0, 0.5), euler=(0.0, 0, 0.0), ), surface=gs.surfaces.Default( @@ -287,7 +287,7 @@ cloth_2 = scene.add_entity( morph=gs.morphs.Mesh( file='meshes/cloth.obj', scale=2.0, - pos=(0, 0, 1.0), + pos=(0, 0, 1.0), euler=(0.0, 0, 0.0), ), surface=gs.surfaces.Default( @@ -303,12 +303,11 @@ scene.build() Then, let's fix the corners (particles) we want. To do this, we provide a handy tool to locate a particle using a location in the cartesian space: ```python -cloth_1.fix_particle(cloth_1.find_closest_particle((-1, -1, 1.0))) -cloth_1.fix_particle(cloth_1.find_closest_particle((1, 1, 1.0))) -cloth_1.fix_particle(cloth_1.find_closest_particle((-1, 1, 1.0))) -cloth_1.fix_particle(cloth_1.find_closest_particle((1, -1, 1.0))) - -cloth_2.fix_particle(cloth_2.find_closest_particle((-1, -1, 1.0))) +cloth_1.fix_particles(cloth_1.find_closest_particle((-1, -1, 1.0))) +cloth_1.fix_particles(cloth_1.find_closest_particle((1, 1, 1.0))) +cloth_1.fix_particles(cloth_1.find_closest_particle((-1, 1, 1.0))) +cloth_1.fix_particles(cloth_1.find_closest_particle((1, -1, 1.0))) +cloth_2.fix_particles(cloth_2.find_closest_particle((-1, -1, 1.0))) horizon = 1000 for i in range(horizon): diff --git a/source/user_guide/getting_started/command_line_tools.md b/source/user_guide/getting_started/command_line_tools.md deleted file mode 100644 index 1d56cf7..0000000 --- a/source/user_guide/getting_started/command_line_tools.md +++ /dev/null @@ -1,7 +0,0 @@ -# 🖥️ Command Line Tools - -We provided some command line tools that you can execute in terminal once Genesis is installed. These include: - -- `gs clean`: Clean all the files cached by genesis and taichi -- `gs view *.*`: Visualize a given asset (mesh/URDF/MJCF) (can be useful if you want to quickly check if your asset can be loaded and visualized correctly) -- `gs animate 'path/*.png'`: Combine all images that matches the given pattern into a video. diff --git a/source/user_guide/getting_started/config_system.md b/source/user_guide/getting_started/config_system.md new file mode 100644 index 0000000..f6e87fc --- /dev/null +++ b/source/user_guide/getting_started/config_system.md @@ -0,0 +1,150 @@ +# 🗂 Config System + +## Overview + +The Genesis simulation framework is built around a modular and extensible configuration system. This system allows users to flexibly compose and control different aspects of a simulation—ranging from low-level physics solvers to high-level rendering options—through structured configuration objects. + +To help you understand how these components work together, we start with a high-level template of how a Genesis scene is typically initialized. This template shows how simulation settings, solver options, and entity-level configurations are orchestrated. + +```python +# Initializate Genesis +gs.init(...) + +# Initialize scene +scene = gs.Scene( + # simulation & coupling + sim_options=SimOptions(...), + coupler_options=CouplerOptions(...), + + # solvers + tool_options=ToolOptions(...), + rigid_options=RigidOptions(...), + avatar_options=AvatarOptions(...), + mpm_options=MPMOptions(...), + sph_options=SPHOptions(...), + fem_options=FEMOptions(...), + sf_options=SFOptions(...), + pbd_options=PBDOptions(...), + + # visualization & rendering + vis_options=VisOptions(...), + viewer_options=ViewerOptions(...), + renderer=Rasterizer(...), +) + +# Add entities +scene.add_entity( + morph=gs.morphs..., + material=gs.materials..., + surface=gs.surfaces...., +) +``` + +As shown above, a scene in Genesis is defined by a combination of: + +- [Simulation & Coupling](#simulation--coupling): Defines global simulation parameters and how different solvers interact. +- [Solvers](#solvers): Configure physical behaviors for different simulation methods (e.g., rigid bodies, fluids, cloth). +- [Visualization & Rendering](#visualization--rendering): Customize runtime visualization and final rendering options. +- For each entity added to the scene: + - [Morph](#morph): Defines the geometry or structure of the entity. + - [Material](#material): Specifies material properties relevant with the corresponding physics solver. + - [Surface](#surface): Controls visual appearance and surface rendering. + +## Simulation & Coupling + +This configuration defines how the simulation is globally structured and how different physics solvers are coupled. These options control the "skeleton" of the simulation loop, e.g., time-stepping, stability, and solver interoperability. + +- `SimOptions`: Sets global simulation parameters—time step size, gravity, damping, and numerical integrator. +- `CouplerOptions`: Configures multi-physics interactions - for instance, how a rigid tool interacts with a soft deformable body or how a fluid flows through a porous material. + +Defined in [genesis/options/solvers.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/options/solvers.py). + +## Solvers + +Solvers are the cores behind specific physical models. Each solver encapsulates a simulation algorithm for a particular material or system—rigid bodies, fluids, deformables, etc. Users can enable or disable solvers depending on the scenario. +- `RigidOptions`: Rigid body dynamics with contact, collision, and constraints. +- `AvatarOptions`: Simulation of animated characters. +- `MPMOptions`: Material Point Method solver for elastic, plastic, granular, fluidic materials. +- `SPHOptions`: Smoothed Particle Hydrodynamics solver for fluids and granular flows. +- `FEMOptions`: Finite Element Method solver for elastic material. +- `SFOptions`: Stable Fluid solver for eulerian-based gaseous simulation. +- `PBDOptions`: Position-Based Dynamics solver for cloth, volumetric deformable objects, liquid, and particles. +- `ToolOptions`: A temporary setup. To be deprecated. + +Defined in [genesis/options/solvers.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/options/solvers.py). + +## Visualization & Rendering + +This configuration controls both the live visualization (useful during debugging and development) and the final rendered output (useful for demos, analysis, or media). It governs how users interact with and perceive the simulation visually. +- `ViewerOptions`: Configure properties of the interactive viewer. +- `VisOptions`: Configure visualization-related properties that are independent of the viewer or camera. +- `Renderer` (Rasterizer or Raytracer): Defines the rendering backend, including lighting, shading, and post-processing effects. Support Rasterization or Raytracing. + +Defined in [genesis/options/vis.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/options/vis.py) and [genesis/options/renderers.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/options/renderers.py). + +## Morph + +Morphs define the shape and topology of an entity. This includes primitive geometries (e.g., spheres, boxes), structured assets (e.g., articulated arms). Morphs form the geometric foundation on which materials and physics operate. +- `Primitive`: For all shape-primitive morphs. + - `Box`: Morph defined by a box shape. + - `Cylinder`: Morph defined by a cylinder shape. + - `Sphere`: Morph defined by a sphere shape. + - `Plane`: Morph defined by a plane shape. +- `FileMorph`: + - `Mesh`: Morph loaded from a mesh file. + - `MeshSet`: A collection of meshes. + - `MJCF`: Morph loaded from a MJCF file. This morph only supports rigid entity. + - `URDF`: Morph loaded from a URDF file. This morph only supports rigid entity. + - `Drone`: Morph loaded from a URDF file for creating a drone entity. +- `Terrain`: Morph for creating a rigid terrain. +- `NoWhere`: Reserved for emitter. Internal use only. + +Defined in [genesis/options/morphs.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/options/morphs.py). + +## Material + +Materials define how an object responds to physical forces. This includes stiffness, friction, elasticity, damping, and solver-specific material parameters. The material also determines how an entity interacts with other objects and solvers. +- `Rigid`: Rigid-bodied and articulated. + - `Avatar`: Abstraction for avatar / animated characters. +- `MPM`: Material Point Method. + - `Elastic` + - `ElastoPlastic` + - `Liquid` + - `Muscle` + - `Sand` + - `Snow` +- `FEM`: Finite Element Method. + - `Elastic` + - `Muscle` +- `PBD`: Position Based Dynamics. + - `Cloth` + - `Elastic` + - `Liquid` + - `Particle` +- `SF`: Stable Fluid. + - `Smoke` +- `Hybrid`: Rigid skeleton actuating soft skin. +- `Tool`: Temporary and to be deprecated. + +These can be found in [genesis/engine/materials](https://github.com/Genesis-Embodied-AI/Genesis/tree/main/genesis/engine/materials). + +## Surface + +Surfaces define how an entity appears visually. They include rendering properties like color, texture, reflectance, transparency, and more. Surfaces are the interface between an entity's internal structure and the renderer. + +- `Default`: Basically `Plastic`. +- `Plastic`: Plastic surface is the most basic type of surface. + - `Rough`: Shortcut for a rough surface with proper parameters. + - `Smooth`: Shortcut for a smooth surface with proper parameters. + - `Reflective`: For collision geometry with a grey color by default. + - `Collision`: Shortcut for a rough plastic surface with proper parameters. +- `Metal` + - `Iron`: Shortcut for an metallic surface with `metal_type = 'iron'`. + - `Aluminium`: Shortcut for an metallic surface with `metal_type = 'aluminium'`. + - `Copper`: Shortcut for an metallic surface with `metal_type = 'copper'`. + - `Gold`: Shortcut for an metallic surface with `metal_type = 'gold'`. +- `Glass` + - `Water`: Shortcut for a water surface (using Glass surface with proper values). +- `Emission`: Emission surface. This surface emits light. + +Defined in [genesis/options/surfaces.py](https://github.com/Genesis-Embodied-AI/Genesis/blob/main/genesis/options/surfaces.py). diff --git a/source/user_guide/getting_started/control_your_robot.md b/source/user_guide/getting_started/control_your_robot.md index 2612d8e..b5fe073 100644 --- a/source/user_guide/getting_started/control_your_robot.md +++ b/source/user_guide/getting_started/control_your_robot.md @@ -12,15 +12,15 @@ gs.init(backend=gs.gpu) ########################## create a scene ########################## scene = gs.Scene( + sim_options = gs.options.SimOptions( + dt = 0.01, + ), viewer_options = gs.options.ViewerOptions( camera_pos = (0, -3.5, 2.5), camera_lookat = (0.0, 0.0, 0.5), camera_fov = 30, max_FPS = 60, ), - sim_options = gs.options.SimOptions( - dt = 0.01, - ), show_viewer = True, ) @@ -42,7 +42,7 @@ franka = scene.add_entity( scene.build() ``` -This robot arm will fall down due to gravity, if we don't give it any actuation force. Genesis has a built-in PD controller that takes as input target joint position or velocity. You can also directly set torque/force applied to each joint. +This robot arm will fall down due to gravity, if we don't give it any actuation force. Genesis has a built-in PD controller ([proportional–integral–derivative controller](https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller) ) that takes as input target joint position or velocity. You can also directly set torque/force applied to each joint. In the context of robotic simulation, `joint` and `dof` (degree-of-freedom) are two related but different concepts. Since we are dealing with a Franka arm, which has 7 revolute joints in the arm and 2 prismatic joints in its gripper, all the joints have 1 dof only, leading to a 9-dof articulated body. In a more general case, there will be joint types such as free joint (6 dofs) or ball joint (3 dofs) that have more than one degrees of freedom. In general, you can think of each dof as a motor and can be controlled independently. @@ -280,3 +280,71 @@ for i in range(1250): scene.step() ``` + +## Pick & Place with a Suction Cup + +In many industrial settings robots pick objects using a suction pad that behaves like an "instant" rigid grasp. In Genesis you can reproduce the same behaviour by temporarily welding two rigid bodies together. + +The *rigid solver* inside the scene gives you direct access to this functionality through +`add_weld_constraint()` and `delete_weld_constraint()`. The API takes two numpy arrays that list the +link indices to be attached / detached. + +Below is a minimal example that moves the Franka end-effector above a small cube, welds the two bodies together (imitating suction), transports the cube to another pose and finally releases it again. + +```python +import numpy as np +import genesis as gs + +# --- (scene and robot creation omitted, identical to the sections above) --- + +# Retrieve some commonly used handles +rigid = scene.sim.rigid_solver # low-level rigid body solver +end_effector = franka.get_link("hand") # Franka gripper frame +cube_link = cube.get_link("box_baselink") # the link we want to pick + +################ Reach pre-grasp pose ################ +q_pregrasp = franka.inverse_kinematics( + link = end_effector, + pos = np.array([0.65, 0.0, 0.13]), # just above the cube + quat = np.array([0, 1, 0, 0]), # down-facing orientation +) +franka.control_dofs_position(q_pregrasp[:-2], np.arange(7)) # arm joints only +for _ in range(50): + scene.step() + +################ Attach (activate suction) ################ +link_cube = np.array([cube_link.idx], dtype=gs.np_int) +link_franka = np.array([end_effector.idx], dtype=gs.np_int) +rigid.add_weld_constraint(link_cube, link_franka) + +################ Lift and transport ################ +q_lift = franka.inverse_kinematics( + link = end_effector, + pos = np.array([0.65, 0.0, 0.28]), # lift up + quat = np.array([0, 1, 0, 0]), +) +franka.control_dofs_position(q_lift[:-2], np.arange(7)) +for _ in range(50): + scene.step() + +q_place = franka.inverse_kinematics( + link = end_effector, + pos = np.array([0.4, 0.2, 0.18]), # target place pose + quat = np.array([0, 1, 0, 0]), +) +franka.control_dofs_position(q_place[:-2], np.arange(7)) +for _ in range(100): + scene.step() + +################ Detach (release suction) ################ +rigid.delete_weld_constraint(link_cube, link_franka) +for _ in range(400): + scene.step() +``` + +A few remarks: +1. The suction pad is modelled as an *ideal* weld — no compliance or force limit is enforced. If you need a more physical behaviour you can instead create a `gs.constraints.DampedSpring` or control the gripper fingers. +2. Link indices are **scene-global**, therefore we wrap them in a single-element numpy array to satisfy the API contract. +3. You can attach or detach multiple objects at once by passing arrays with more than one index. + +With just two lines of code you can now pick and place arbitrary objects with suction! Feel free to integrate this snippet into your own control pipeline. diff --git a/source/user_guide/getting_started/conventions.md b/source/user_guide/getting_started/conventions.md new file mode 100644 index 0000000..a10831a --- /dev/null +++ b/source/user_guide/getting_started/conventions.md @@ -0,0 +1,33 @@ +# Conventions + +This page outlines the coordinate system and mathematical conventions used throughout Genesis. + +## Coordinate System + +Genesis uses a right-handed coordinate system with the following conventions: + +- **+X axis**: Points out of the screen (towards the viewer) +- **+Y axis**: Points to the left +- **+Z axis**: Points upward (vertical) + +## Quaternion Representation + +Quaternions in Genesis follow the **(w, x, y, z)** convention, where: +- **w**: Scalar component (real part) +- **x, y, z**: Vector components (imaginary parts) + +This is also known as the "scalar-first" or "Hamilton" convention. When specifying rotations using quaternions, always provide them in this order. + +### Example +```python +# Quaternion representing a 90-degree rotation around the Z-axis +rotation = [0.707, 0, 0, 0.707] # [w, x, y, z] +``` + +## Gravity + +The gravitational force vector is defined as: +- **Gravity direction**: **-Z** (pointing downward) +- **Default magnitude**: 9.81 m/s² + +This means objects will naturally fall in the negative Z direction when no other forces are applied. diff --git a/source/user_guide/getting_started/hello_genesis.md b/source/user_guide/getting_started/hello_genesis.md index 65ffa2f..9ab984a 100644 --- a/source/user_guide/getting_started/hello_genesis.md +++ b/source/user_guide/getting_started/hello_genesis.md @@ -42,7 +42,7 @@ gs.init( debug = False, eps = 1e-12, logging_level = None, - backend = gs_backend.gpu, + backend = gs.gpu, theme = 'dark', logger_verbose_time = False ) @@ -108,7 +108,7 @@ In addition, for training locomotion tasks, we support various types of built-in We support loading from external files with different formats including : - `gs.morphs.MJCF`: mujoco `.xml` robot configuration files - `gs.morphs.URDF`: robot description files that end with `.urdf` (Unified Robotics Description Format) -- `gs.morphs.Mesh`: non-articulated mesh assets, supporting extensions including: `*.obj`, `*.ply`, `*.stl`, `*.glb`, `*.gltf` +- `gs.morphs.Mesh`: non-articulated mesh assets, supporting extensions including: `*.obj`, `*.ply`, `*.stl`, `*.glb`, `*.gltf`, `*.usd` When loading from external files, you need to specify the file location using the `file` parameter. When parsing this, we support both *absolute* and *relative* file path. Note that since genesis also comes with an internal asset directory (`genesis/assets`), so if a relative path is used, we search not only relative path with respect to your current working directory, but also under `genesis/assets`. Therefore, in this example, we will retrieve the franka model from: `genesis/assets/xml/franka_emika_panda/panda.xml`. diff --git a/source/user_guide/getting_started/hover_env.md b/source/user_guide/getting_started/hover_env.md new file mode 100644 index 0000000..c65b1fa --- /dev/null +++ b/source/user_guide/getting_started/hover_env.md @@ -0,0 +1,103 @@ +# 🚁 Training Drone Hovering Policies with RL + +Genesis supports parallel simulation, making it ideal for training reinforcement learning (RL) drone hovering policies efficiently. In this tutorial, we will walk you through a complete training example for obtaining a basic hovering policy that enables a drone to maintain a stable hover position by reaching randomly generated target points. + +This is a simple and minimal example that demonstrates a very basic RL training pipeline in Genesis, and with the following example you will be able to obtain a drone hovering policy that's deployable to a real drone very quickly. + +**Note**: This is *NOT* a comprehensive drone hovering policy training pipeline. It uses simplified reward terms to get you started easily, and does not exploit Genesis's speed on big batch sizes, so it only serves basic demonstration purposes. + +**Acknowledgement**: This tutorial is inspired by [Champion-level drone racing using deep reinforcement learning (Nature 2023)](https://www.nature.com/articles/s41586-023-06419-4.pdf). + +## Environment Overview +We start by creating a gym-style environment (hover-env). + +#### Initialize +The `__init__` function sets up the simulation environment with the following steps: +1. **Control Frequency**. + The simulation runs at 100 Hz, providing a high-frequency control loop for the drone. +2. **Scene Creation**. + A simulation scene is created, including the drone and a static plane. +3. **Target Initialization**. + A random target point is initialized, which the drone will attempt to reach. +4. **Reward Registration**. + Reward functions, defined in the configuration, are registered to guide the policy. These functions will be explained in the "Reward" section. +5. **Buffer Initialization**. + Buffers are initialized to store environment states, observations, and rewards. + +#### Reset +The `reset_idx` function resets the initial pose and state buffers of the specified environments. This ensures robots start from predefined configurations, crucial for consistent training. + +#### Step +The `step` function updates the environment state based on the actions taken by the policy. It includes the following steps: +1. **Action Execution**. + The input action will be clipped to a valid range, rescaled, and applied as adjustments to the default hover propeller RPMs. +2. **State Update**. + Drone states, such as position, attitude, and velocities, are retrieved and stored in buffers. +3. **Termination Checks**. + Terminated environments are reset automatically. Environments are terminated if + - Episode length exceeds the maximum allowed. + - The drone's pitch or roll angle exceeds a specified threshold. + - The drone's position exceeds specified boundaries. + - The drone is too close to the ground. +4. **Reward Computation**. + Rewards are calculated based on the drone's performance in reaching the target point and maintaining stability. +5. **Observation Computation**. + Observations are normalized and returned to the policy. Observations used for training include drone's position, attitude (quaternion), body linear velocity, body angular velocity and previous actions. + +#### Reward +In this example, we use the following reward functions to encourage the drone to reach the target point and maintain stability: +- **target**: Encourages the drone to reach the randomly generated target points. +- **smooth**: Encourages smooth actions and bridge the sim-to-real gap. +- **yaw**: Encourages the drone to maintain a stable hover yaw. +- **angular**: Encourages the drone to maintain low angular velocities. +- **crash**: Penalizes the drone for crashing or deviating too far from the target. + +These reward functions are combined to provide comprehensive feedback to the policy, guiding it to achieve stable and accurate hovering behavior. + +## Training +At this stage, we have defined the environments. To train the drone hovering policy using PPO, follow these steps: +1. **Install Dependencies**. + First, ensure you have Genesis installed, then add all required Python dependencies using `pip`: + ```bash + pip install --upgrade pip + pip install tensorboard rsl-rl-lib==2.2.4 + ``` +2. **Run Training Script**. + Use the provided training script to start training the policy. + ```bash + python hover_train.py -e drone-hovering -B 8192 --max_iterations 301 + ``` + - `-e drone-hovering`: Specifies the experiment name as "drone-hovering". + - `-B 8192`: Sets the number of environments to 8192 for parallel training. + - `--max_iterations 301`: Specifies the maximum number of training iterations to 301. + - `-v`: Optional. Enables training with visualization. + + To monitor the training process, launch TensorBoard: + ```bash + tensorboard --logdir logs + ``` + You should see a training curve similar to this: + ```{figure} ../../_static/images/hover_curve.png + ``` + When training with visualization enabled, you will see: + ```{figure} ../../_static/images/training.gif + ``` + +## Evaluation +To evaluate the trained drone hovering policy, follow these steps: +1. **Run Evaluation Script**. + Use the provided evaluation script to evaluate the trained policy. + ```bash + python hover_eval.py -e drone-hovering --ckpt 300 --record + ``` + - `-e drone-hovering`: Specifies the experiment name as "drone-hovering". + - `--ckpt 300`: Loads the trained policy from checkpoint 300. + - `--record`: Records the evaluation and saves a video of the drone's performance. +2. **Visualize Results**. + The evaluation script will visualize the drone's performance and save a video if the `--record` flag is set. + + + +By following this tutorial, you'll be able to train and evaluate a basic drone hovering policy using Genesis. Have fun and enjoy! \ No newline at end of file diff --git a/source/user_guide/getting_started/inverse_kinematics_motion_planning.md b/source/user_guide/getting_started/inverse_kinematics_motion_planning.md index 2de59d9..f589d9c 100644 --- a/source/user_guide/getting_started/inverse_kinematics_motion_planning.md +++ b/source/user_guide/getting_started/inverse_kinematics_motion_planning.md @@ -12,16 +12,15 @@ gs.init(backend=gs.gpu) ########################## create a scene ########################## scene = gs.Scene( + sim_options = gs.options.SimOptions( + dt = 0.01, + ), viewer_options = gs.options.ViewerOptions( camera_pos = (3, -1, 1.5), camera_lookat = (0.0, 0.0, 0.5), camera_fov = 30, max_FPS = 60, ), - sim_options = gs.options.SimOptions( - dt = 0.01, - substeps = 4, # for more stable grasping contact - ), show_viewer = True, ) @@ -103,7 +102,7 @@ Next, we move the robot gripper down, grasp the cube, and lift it: # reach qpos = franka.inverse_kinematics( link = end_effector, - pos = np.array([0.65, 0.0, 0.135]), + pos = np.array([0.65, 0.0, 0.130]), quat = np.array([0, 1, 0, 0]), ) franka.control_dofs_position(qpos[:-2], motors_dof) @@ -120,7 +119,7 @@ for i in range(100): # lift qpos = franka.inverse_kinematics( link=end_effector, - pos=np.array([0.65, 0.0, 0.3]), + pos=np.array([0.65, 0.0, 0.28]), quat=np.array([0, 1, 0, 0]), ) franka.control_dofs_position(qpos[:-2], motors_dof) diff --git a/source/user_guide/getting_started/locomotion.md b/source/user_guide/getting_started/locomotion.md index 17f3c4a..8ea87c1 100644 --- a/source/user_guide/getting_started/locomotion.md +++ b/source/user_guide/getting_started/locomotion.md @@ -1,6 +1,10 @@ # 🦿 Training Locomotion Policies with RL -Genesis supports parallel simulation, making it ideal for training reinforcement learning (RL) locomotion policies efficiently. In this tutorial, we will walk you through a complete training example for obtaining a basic locomotion policy that enables a Unitree Go2 Robot to walk. With Genesis, you will be able to train a locomotion policy that's **deployable in real-world in less than 26 seconds** (benchmarked on a RTX 4090). +Genesis supports parallel simulation, making it ideal for training reinforcement learning (RL) locomotion policies efficiently. In this tutorial, we will walk you through a complete training example for obtaining a basic locomotion policy that enables a Unitree Go2 Robot to walk. + +This is a simple and minimal example that demonstrates a very basic RL training pipeline in Genesis, and with the following example you will be able to obtain a quadruped locomotion policy that's deployable to a real robot very quickly. + +**Note**: This is *NOT* a comprehensive locomotion policy training pipeline. It uses simplified reward terms to get you started easily, and does not exploit Genesis's speed on big batchsizes, so it only serves basic demonstration purposes. **Acknowledgement**: This tutorial is inspired by and builds several core concepts from [Legged Gym](https://github.com/leggedrobotics/legged_gym). @@ -10,7 +14,7 @@ We start by creating a gym-style environment (go2-env). The `__init__` function sets up the simulation environment with the following steps: 1. **Control Frequency**. - The simulation runs at 50 Hz, matching the real robot's control frequency. To further bridge sim2real gap, we also manually simulate the action latecy (~20ms, one dt) shown on the real robot. + The simulation runs at 50 Hz, matching the real robot's control frequency. To further bridge sim2real gap, we also manually simulate the action latency (~20ms, one dt) shown on the real robot. 2. **Scene Creation**. A simulation scene is created, including the robot and a static plane. 3. **PD Controller Setup**. @@ -46,14 +50,9 @@ Reward functions are critical for policy guidance. In this example, we use: - **similar_to_default**: Encourage the robot pose to be similar to the default pose ## Training -At this stage, we have defined the environments. Now, we use the PPO implementation from rsl-rl to train the policy. Follow these installation steps: +At this stage, we have defined the environments. Now, we use the PPO implementation from rsl-rl to train the policy. First, install all Python dependencies via `pip`: ``` -# Install rsl_rl. -git clone https://github.com/leggedrobotics/rsl_rl -cd rsl_rl && git checkout v1.0.2 && pip install -e . - -# Install tensorboard. -pip install tensorboard +pip install tensorboard rsl-rl-lib==2.2.4 ``` After installation, start training by running: ``` diff --git a/source/user_guide/getting_started/manipulation.md b/source/user_guide/getting_started/manipulation.md new file mode 100644 index 0000000..8e6c8e3 --- /dev/null +++ b/source/user_guide/getting_started/manipulation.md @@ -0,0 +1,133 @@ +# ✍️ Manipulation with Two-Stage Training + +This example demonstrates robotic manipulation using a **two-stage training paradigm** that combines **reinforcement learning (RL)** and **imitation learning (IL)**. The central idea is to first train a **privileged teacher policy** using full state information, and then distill that knowledge into a **vision-based student policy** that relies on camera observations (and optionally robot proprioception). +This approach enables efficient learning in simulation while bridging the gap toward real-world deployment where privileged states are unavailable. + +--- + +## Environment Overview + +The manipulation environment is composed of the following elements: + +* **Robot:** A 7-DoF Franka Panda arm with a parallel-jaw gripper. +* **Object:** A box with randomized initial position and orientation, ensuring diverse training scenarios. +* **Cameras:** Two stereo RGB cameras (left and right) facing the manipulation scene. Here, we use [Madrona Enginer](https://madrona-engine.github.io/) for batch rendering. +* **Observations:** + + * **Privileged state:** End-effector pose and object pose (used only during teacher training). + * **Vision state:** Stereo RGB images (used by the student policy). +* **Actions:** 6-DoF delta end-effector pose commands (3D position + orientation). +* **Rewards:** A **keypoint alignment** reward is used. This defines reference keypoints between the gripper and the object, encouraging the gripper to align to a graspable pose. + + * This formulation avoids dense shaping terms and directly encodes task success. + * Only this reward is required for the policy to learn goal reaching. + +--- + +## RL Training (Stage 1: Teacher Policy) + +In the first stage, we train a teacher policy using **Proximal Policy Optimization (PPO)** from the [RSL-RL library](https://github.com/leggedrobotics/rsl_rl). + +**Setup:** + +```bash +pip install tensorboard rsl-rl-lib==2.2.4 +``` + +**Training:** + +```bash +python examples/manipulation/grasp_train.py --stage=rl +``` + +**Monitoring:** + +```bash +tensorboard --logdir=logs +``` + +The reward learning curve looks like the following if the training is successful: + +```{figure} ../../_static/images/manipulation_curve.png +``` + +**Key details:** + +* **Inputs:** Privileged state (no images). +* **Outputs:** End-effector action commands. +* **Parallelization:** Large vectorized rollouts (e.g., 1024–4096 envs) for fast throughput. +* **Reward design:** Keypoint alignment suffices to produce consistent grasping behavior. +* **Outcome:** A lightweight MLP policy that learns stable grasping given ground-truth state information. + +The teacher policy serves as the demonstration source for the next stage. + +--- + +## Imitation Learning (Stage 2: Student Policy) + +The second stage trains a **vision-conditioned student policy** that imitates the RL teacher. + +**Architecture:** + +* **Encoder:** Shared stereo CNN encoder extracts visual features. +* **Fusion network:** Merges image features with optional robot proprioception. +* **Heads:** + * **Action head:** Predicts 6-DoF manipulation actions. + * **Pose head:** Auxiliary task to predict object pose (xyz + quaternion). + +**Training Objective:** + +* **Loss:** + * Action MSE (student vs teacher). + * Pose loss = position MSE + quaternion distance. +* **Data Collection:** Teacher provides online supervision, optionally with **DAgger-style corrections** to mitigate covariate shift. + +**Outcome:** A vision-only policy capable of generalizing grasping behavior without access to privileged states. + +**Run training:** + +```bash +python examples/manipulation/grasp_train.py --stage=bc +``` + +--- + +## Evaluation + +Both teacher and student policies can be evaluated in simulation (with or without visualization). + +* **Teacher Policy (MLP):** + +```bash +python examples/manipulation/grasp_eval.py --stage=rl +``` + + + +* **Student Policy (CNN+MLP):** + +```bash +python examples/manipulation/grasp_eval.py --stage=bc --record +``` + +The student observes the environment via stereo cameras rendered with Mandrona. + + +**Logging & Monitoring:** + +* Metrics recorded in TensorBoard (`logs/grasp_rl/` or `logs/grasp_bc/`). +* Periodic checkpoints for both RL and BC stages. + +--- + +## Summary + +This two-stage pipeline illustrates a practical strategy for robotic manipulation: + +1. **Teacher policy (RL):** Efficient learning with full information. +2. **Student policy (IL):** Vision-based control distilled from demonstrations. + +The result is a policy that is both sample-efficient in training and robust to realistic perception inputs. + diff --git a/source/user_guide/getting_started/misc_guidelines.md b/source/user_guide/getting_started/misc_guidelines.md index 3816ec4..1c3039d 100644 --- a/source/user_guide/getting_started/misc_guidelines.md +++ b/source/user_guide/getting_started/misc_guidelines.md @@ -1,4 +1,4 @@ -# 📝 Misc Guidelines +# 📝 Guidelines (I will keep updating this) - Use genesis.tensor whenever possible. Note that when we pass genesis tensor to taichi kernels, call tensor.assert_contiguous() to check whether it's contiguous, since taichi only support contiguous external tensor. @@ -63,11 +63,11 @@ - offset value for its own children. e.g. a `geom` only stores `idx_offset_*` for `vert`, `face`, and `edge`. - root vs base - `root` is a more natural name as we use a tree structure for the links, while `base` is more informative from user's perspective - - Let's use `root` link inernally, and `base` link for docs etc. + - Let's use `root` link internally, and `base` link for docs etc. - root pose vs q (current design subject to possible change) - for both arm and single mesh, its pos and euler specified when loaded is its root pose, and q will be w.r.t to this - control interface - - root pos should be merged with joint pos of the first (fixed) joint, which connectes world to the first link + - root pose should be merged with joint pose of the first (fixed) joint, which connects world to the first link - if we want to control something, we will command velocity - thus, if it’s a free joint, it’s ok. We will override velocity - if it’s a fixed joint, there’s no dof for it, so we cannot control it diff --git a/source/user_guide/getting_started/miscellaneous.md b/source/user_guide/getting_started/miscellaneous.md new file mode 100644 index 0000000..654ee07 --- /dev/null +++ b/source/user_guide/getting_started/miscellaneous.md @@ -0,0 +1,16 @@ +# 💡 Tips + +## Running Performance Benchmarks + +* One may need to temporarily disable caching when doing profiling and/or benchmarking. The most straightforward solution would be to completely wip out the persistent local cache folder. This is not recommended because its effect will persist beyond the scope of your experiment, slowing down start up of all your future simulations until your cache is finally recovered. One should rather redirect Genesis (and Taichi) to some alternative temporary cache folder. This can be done editing any Python code, by setting a few environment variables: +```bash +XDG_CACHE_HOME="$(mktemp -d)" GS_CACHE_FILE_PATH="$XDG_CACHE_HOME/genesis" TI_OFFLINE_CACHE_FILE_PATH="$XDG_CACHE_HOME/taichi" python [...] +``` +Note that specifying `XDG_CACHE_HOME` is sufficient on Linux, but not on Windows OS and Mac OS. + +# 🖥️ Command Line Tools + +We provided some command line tools that you can execute in terminal once Genesis is installed. These include: + +- `gs view *.*`: Visualize a given asset (mesh/URDF/MJCF) (can be useful if you want to quickly check if your asset can be loaded and visualized correctly) +- `gs animate 'path/*.png'`: Combine all images that matches the given pattern into a video. diff --git a/source/user_guide/getting_started/parallel_simulation.md b/source/user_guide/getting_started/parallel_simulation.md index ac1b739..78b9f01 100644 --- a/source/user_guide/getting_started/parallel_simulation.md +++ b/source/user_guide/getting_started/parallel_simulation.md @@ -48,7 +48,7 @@ scene.build(n_envs=B, env_spacing=(1.0, 1.0)) # control all the robots franka.control_dofs_position( torch.tile( - torch.tensor([0, 0, 0, -1.0, 0, 0, 0, 0.02, 0.02], device=gs.device), (B, 1) + torch.tensor([0, 0, 0, -1.0, 0, 1.0, 0, 0.02, 0.02], device=gs.device), (B, 1) ), ) @@ -106,7 +106,7 @@ scene.build(n_envs=30000) # control all the robots franka.control_dofs_position( torch.tile( - torch.tensor([0, 0, 0, -1.0, 0, 0, 0, 0.02, 0.02], device=gs.device), (30000, 1) + torch.tensor([0, 0, 0, -1.0, 0, 1.0, 0, 0.02, 0.02], device=gs.device), (30000, 1) ), ) @@ -119,5 +119,5 @@ Running the above script on a desktop with RTX 4090 and 14900K gives you a futur ``` :::{tip} -**FPS logging:** By default, genesis logger will display real-time simulation speed in the terminal. You can disable this behavior by setting `show_FPS=False` when creating the scene. +**FPS logging:** By default, genesis logger will display real-time simulation speed in the terminal. You can disable this behavior by setting `scene.profiling_options.show_FPS=False` when creating the scene. ::: \ No newline at end of file diff --git a/source/user_guide/getting_started/recorders.md b/source/user_guide/getting_started/recorders.md new file mode 100644 index 0000000..2baec88 --- /dev/null +++ b/source/user_guide/getting_started/recorders.md @@ -0,0 +1,48 @@ +# 🎥 Saving and Visualizing Data with Recorders +Genesis also provides data recording utilities for automatically processing data without slowing down the simulation. +This can be used to stream formatted data to a file, or visualize the data live. + +```python +# 1. Start recording before building scene +sensor.start_recording( + rec_options=gs.recorders.NPZFile( + filename="sensor_data.npz" + ), +) +``` +... And that's it! Recordings will automatically stop and clean up when the scene is no longer active, and can also +be stopped with `scene.stop_recording()`. + +You can record sensor data with `sensor.start_recording(recorder_options)` or any other kind of data using `scene.start_recording(data_func, recorder_options)` with a custom data function. For example: + +``` +def imu_data_func(): + data = imu.read() + true_data = imu.read_ground_truth() + return { + "lin_acc": data.lin_acc, + "true_lin_acc": true_data.lin_acc, + "ang_vel": data.ang_vel, + "true_ang_vel": true_data.ang_vel, + } + +scene.start_recording( + imu_data_func, + gs.recorders.MPLLinePlot( + title="IMU Data", + labels={ + "lin_acc": ("x", "y", "z"), + "true_lin_acc": ("x", "y", "z"), + "ang_vel": ("x", "y", "z"), + "true_ang_vel": ("x", "y", "z"), + }, + ), +) +``` + + + +See RecorderOptions in the API reference for currently available recorders. +More example uses of recorders can also be seen in `examples/sensors/`. \ No newline at end of file diff --git a/source/user_guide/getting_started/sensors.md b/source/user_guide/getting_started/sensors.md new file mode 100644 index 0000000..ecc88fe --- /dev/null +++ b/source/user_guide/getting_started/sensors.md @@ -0,0 +1,218 @@ +# 🖲️ Sensors + +Robots need sensors to observe the world around them. +In Genesis, sensors extract information from the scene, computing values using the state of the scene but not affecting the scene itself. + +Sensors can be created with `scene.add_sensor(sensor_options)` and read with `sensor.read()` or `sensor.read_ground_truth()`. +```python +scene = ... + +# 1. Add sensors to the scene +sensor = scene.add_sensor( + gs.sensors.Contact( + ..., + draw_debug=True, # visualize the sensor data in the scene viewer + ) +) + +# 2. Build the scene +scene.build() + +for _ in range(1000): + scene.step() + + # 3. Read data from sensors + measured_data = sensor.read() + ground_truth_data = sensor.read_ground_truth() +``` + +Currently supported sensors: +- `IMU` (accelerometer and gyroscope) +- `Contact` (boolean per rigid link) +- `ContactForce` (xyz force per rigid link) +- `Raycaster` + - `Lidar` + - `DepthCamera` + + +Example usage of sensors can be found under `examples/sensors/`. + + +## IMU Example + +In this tutorial, we'll walk through how to set up an Inertial Measurement Unit (IMU) sensor on a robotic arm's end-effector. The IMU will measure linear acceleration and angular velocity as the robot traces a circular path, and we'll visualize the data in real-time with realistic noise parameters. + +The full example script is available at `examples/sensors/imu_franka.py`. + +### Scene Setup + +First, let's create our simulation scene and load the robotic arm: + +```python +import genesis as gs +import numpy as np + +gs.init(backend=gs.gpu) + +########################## create a scene ########################## +scene = gs.Scene( + viewer_options=gs.options.ViewerOptions( + camera_pos=(3.5, 0.0, 2.5), + camera_lookat=(0.0, 0.0, 0.5), + camera_fov=40, + ), + sim_options=gs.options.SimOptions( + dt=0.01, + ), + show_viewer=True, +) + +########################## entities ########################## +scene.add_entity(gs.morphs.Plane()) +franka = scene.add_entity( + gs.morphs.MJCF(file="xml/franka_emika_panda/panda.xml"), +) +end_effector = franka.get_link("hand") +motors_dof = (0, 1, 2, 3, 4, 5, 6) +``` + +Here we set up a basic scene with a Franka robotic arm. The camera is positioned to give us a good view of the robot's workspace, and we identify the end-effector link where we'll attach our IMU sensor. + +### Adding the IMU Sensor + +We "attach" the IMU sensor onto the entity at the end effector by specifying the `entity_idx` and `link_idx_local`. + +```python +imu = scene.add_sensor( + gs.sensors.IMU( + entity_idx=franka.idx, + link_idx_local=end_effector.idx_local, + pos_offset=(0.0, 0.0, 0.15), + # sensor characteristics + acc_cross_axis_coupling=(0.0, 0.01, 0.02), + gyro_cross_axis_coupling=(0.03, 0.04, 0.05), + acc_noise=(0.01, 0.01, 0.01), + gyro_noise=(0.01, 0.01, 0.01), + acc_random_walk=(0.001, 0.001, 0.001), + gyro_random_walk=(0.001, 0.001, 0.001), + delay=0.01, + jitter=0.01, + interpolate=True, + draw_debug=True, + ) +) +``` + +The `gs.sensors.IMU` constructor has options to configure the following sensor characteristics: +- `pos_offset` specifies the sensor's position relative to the link frame +- `acc_cross_axis_coupling` and `gyro_cross_axis_coupling` simulate sensor misalignment +- `acc_noise` and `gyro_noise` add Gaussian noise to measurements +- `acc_random_walk` and `gyro_random_walk` simulate gradual sensor drift over time +- `delay` and `jitter` introduce timing realism +- `interpolate` smooths delayed measurements +- `draw_debug` visualizes the sensor frame in the viewer + +### Motion Control and Simulation + +Now let's build the scene and create circular motion to generate interesting IMU readings: + +```python +########################## build and control ########################## +scene.build() + +franka.set_dofs_kp(np.array([4500, 4500, 3500, 3500, 2000, 2000, 2000, 100, 100])) +franka.set_dofs_kv(np.array([450, 450, 350, 350, 200, 200, 200, 10, 10])) + +# Create a circular path for end effector to follow +circle_center = np.array([0.4, 0.0, 0.5]) +circle_radius = 0.15 +rate = np.deg2rad(2.0) # Angular velocity in radians per step + +def control_franka_circle_path(i): + pos = circle_center + np.array([np.cos(i * rate), np.sin(i * rate), 0]) * circle_radius + qpos = franka.inverse_kinematics( + link=end_effector, + pos=pos, + quat=np.array([0, 1, 0, 0]), # Keep orientation fixed + ) + franka.control_dofs_position(qpos[:-2], motors_dof) + scene.draw_debug_sphere(pos, radius=0.01, color=(1.0, 0.0, 0.0, 0.5)) # Visualize target + +# Run simulation +for i in range(1000): + scene.step() + control_franka_circle_path(i) +``` + +The robot traces a horizontal circle while maintaining a fixed orientation. The circular motion creates centripetal acceleration that the IMU will detect, along with any gravitational effects based on the sensor's orientation. + +After building the scene, you can access both measured and ground truth IMU data: + +```python +# Access sensor readings +print("Ground truth data:") +print(imu.read_ground_truth()) +print("Measured data:") +print(imu.read()) +``` + +The IMU returns data as a **named tuple** with fields: +- `lin_acc`: Linear acceleration in m/s² (3D vector) +- `ang_vel`: Angular velocity in rad/s (3D vector) + + + +## Contact Sensors + +The contact sensors retrieve contact information per rigid link from the rigid solver. +`Contact` sensor will return a boolean, and `ContactForce` returns the net force vector in the local frame of the associated rigid link. + + +The full example script is available at `examples/sensors/contact_force_go2.py` (add flag `--force` to use force sensor). + +```{figure} ../../_static/images/contact_force_sensor.png +``` + +## Raycaster Sensors: Lidar and Depth Camera + +The `Raycaster` sensor measures distance by casting rays into the scene and detecting intersections with geometry. +The number of rays and ray directions can be specified with a `RaycastPattern`. +`SphericalPattern` supports Lidar-like specification of field of view and angular resolution, and `GridPattern` casts rays from a plane. `DepthCamera` sensors provide the `read_image()` function which formats the raycast information as a depth image. See the API reference for details on the available options. + +```python +lidar = scene.add_sensor( + gs.sensors.Lidar( + pattern=gs.sensors.Spherical(), + entity_idx=robot.idx, # attach to a rigid entity + pos_offset=(0.3, 0.0, 0.1) # offset from attached entity + return_world_frame=True, # whether to return points in world frame or local frame + ) +) + +depth_camera = scene.add_sensor( + gs.sensors.DepthCamera( + pattern=gs.sensors.DepthCameraPattern( + res=(480, 360), # image resolution in width, height + fov_horizontal=90, # field of view in degrees + fov_vertical=40, + ), + ) +) + +... + +lidar.read() # returns a NamedTuple containing points and distances +depth_camera.read_image() # returns tensor of distances as shape (height, width) + +``` + +An example script which demonstrates a raycaster sensor mounted on a robot is available at `examples/sensors/lidar_teleop.py`. +Set the flag `--pattern` to `spherical` for a Lidar like pattern, `grid` for planar grid pattern, and `depth` for depth camera. + +Here's what running `python examples/sensors/lidar_teleop.py --pattern depth` looks like: + + \ No newline at end of file diff --git a/source/user_guide/getting_started/soft_robots.md b/source/user_guide/getting_started/soft_robots.md index d4db2e5..c376900 100644 --- a/source/user_guide/getting_started/soft_robots.md +++ b/source/user_guide/getting_started/soft_robots.md @@ -10,12 +10,12 @@ import genesis as gs ########################## init ########################## -gs.init(seed=0, precision='32', logging_level='debug') +gs.init(seed=0, precision='32', logging_level='info') ########################## create a scene ########################## -dt = 5e-4 scene = gs.Scene( sim_options=gs.options.SimOptions( + dt = 5e-4, substeps=10, gravity=(0, 0, 0), ), @@ -25,13 +25,11 @@ scene = gs.Scene( camera_fov=40, ), mpm_options=gs.options.MPMOptions( - dt=dt, lower_bound=(-1.0, -1.0, -0.2), upper_bound=( 1.0, 1.0, 1.0), ), fem_options=gs.options.FEMOptions( - dt=dt, - damping=45., + damping=45.0, ), vis_options=gs.options.VisOptions( show_world_frame=False, @@ -95,7 +93,7 @@ Most of the code is pretty standard compared to instantiating regular deformable By default, there is only one muscle that spans the entire robot body with the muscle direction perpendicular to the ground `[0, 0, 1]`. -In the next example, we show how to simulate a worm crawling forward by setting muscle groups and directions, as shown in the following. (The full script can be found in [tutorials/advanced_worm.py](https://github.com/zhouxian/Genesis-dev/tree/main/examples/tutorials/advanced_worm.py).) +In the next example, we show how to simulate a worm crawling forward by setting muscle groups and directions, as shown in the following. (The full script can be found in [tutorials/advanced_worm.py](https://github.com/Genesis-Embodied-AI/Genesis/tree/main/examples/tutorials/advanced_worm.py).) ```python ########################## entities ########################## @@ -180,12 +178,12 @@ import genesis as gs ########################## init ########################## -gs.init(seed=0, precision='32', logging_level='debug') +gs.init(seed=0, precision='32', logging_level='info') ######################## create a scene ########################## -dt = 3e-3 scene = gs.Scene( sim_options=gs.options.SimOptions( + dt=3e-3, substeps=10, ), viewer_options= gs.options.ViewerOptions( @@ -194,13 +192,11 @@ scene = gs.Scene( camera_fov=40, ), rigid_options=gs.options.RigidOptions( - dt=dt, gravity=(0, 0, -9.8), enable_collision=True, enable_self_collision=False, ), mpm_options=gs.options.MPMOptions( - dt=dt, lower_bound=( 0.0, 0.0, -0.2), upper_bound=( 1.0, 1.0, 1.0), gravity=(0, 0, 0), # mimic gravity compensation @@ -224,10 +220,10 @@ robot = scene.add_entity( fixed=True, ), material=gs.materials.Hybrid( - mat_rigid=gs.materials.Rigid( + material_rigid=gs.materials.Rigid( gravity_compensation=1., ), - mat_soft=gs.materials.MPM.Muscle( # to allow setting group + material_soft=gs.materials.MPM.Muscle( # to allow setting group E=1e4, nu=0.45, rho=1000., @@ -272,6 +268,6 @@ This is what you will see: * You can specify hybrid robot with the material `gs.materials.Hybrid`, which consists of `gs.materials.Rigid` and `gs.materials.MPM.Muscle`. Note that only MPM is supported here and it must be the Muscle class since the hybrid material reuses internally the `muscle_group` implemented for `Muscle`. * When controlling the robot, given the actuation being from the inner rigid-bodied skeleton, there is a similar interface to rigid-bodied robot, e.g., `control_dofs_velocity`, `control_dofs_force`, `control_dofs_position`. Also, the control dimension is the same as the DoFs of the inner skeleton (in the above example, 2). * The skin is determined by the shape of the inner skeleton, where `thickness` determines the skin thickness when wrapping the skeleton. -* By default, we grow skin based on the shape of the skeleton, which is specified by `morph` (in this example, the `urdf/simple/two_link_arm.urdf`). The argument `func_instantiate_soft_from_rigid` of `gs.materials.Hybrid` defines concretely how skin should grow based on the rigid-bodied `morph`. There is a default implementation `default_func_instantiate_soft_from_rigid` in [genesis/engine/entities/hybrid_entity.py](https://github.com/zhouxian/Genesis-dev/blob/main/genesis/engine/entities/hybrid_entity.py). You can also implement your own function. +* By default, we grow skin based on the shape of the skeleton, which is specified by `morph` (in this example, the `urdf/simple/two_link_arm.urdf`). The argument `func_instantiate_soft_from_rigid` of `gs.materials.Hybrid` defines concretely how skin should grow based on the rigid-bodied `morph`. There is a default implementation `default_func_instantiate_soft_from_rigid` in [genesis/engine/entities/hybrid_entity.py](https://github.com/Genesis-Embodied-AI/Genesis/tree/main/genesis/engine/entities/hybrid_entity.py). You can also implement your own function. * When `morph` is `Mesh` instead of `URDF`, the mesh specifies the soft outer body and the inner skeleton is grown based on the skin shape. This is defined by `func_instantiate_rigid_from_soft`. There is also a default implementation `default_func_instantiate_rigid_from_soft`, which basically implements skeletonization of 3D meshes. * The argument `func_instantiate_rigid_soft_association` of `gs.materials.Hybrid` determines how each skeletal part is associated with skin. The default implementation is to find the closest particles of the soft skin to the rigid skeletal parts. diff --git a/source/user_guide/getting_started/terrain.md b/source/user_guide/getting_started/terrain.md new file mode 100644 index 0000000..68eceb1 --- /dev/null +++ b/source/user_guide/getting_started/terrain.md @@ -0,0 +1,147 @@ +# 🏔️ Terrain Simulation and Generation + +Genesis provides first-class support for **height-field terrains** via the `gs.morphs.Terrain` morph. A terrain is a static rigid object represented internally by a height map (for fast collision queries) and a watertight triangle mesh (for visualisation & SDF generation). + +This page introduces the three most common ways to create terrains: + +1. Pass in your own NumPy height map. +2. Procedurally generate a *sub-terrain* grid (Isaac Gym style). +3. Convert an arbitrary triangle mesh to a height map automatically. + +--- + +## 1 Use a custom height map +If you already have terrain data (for example from DEM files) you can feed it directly to Genesis. The only two numbers you need are the horizontal and vertical scales. + +```python +import numpy as np +import genesis as gs + +# 1. initialise Genesis +gs.init(seed=0, backend=gs.gpu) # use gs.cpu for CPU backend + +# 2. create a scene +scene = gs.Scene(show_viewer=True) + +# 3. prepare a height map (here a simple bump for demo) +hf = np.zeros((40, 40), dtype=np.int16) +hf[10:30, 10:30] = 200 * np.hanning(20)[:, None] * np.hanning(20)[None, :] + +horizontal_scale = 0.25 # metres between grid points +vertical_scale = 0.005 # metres per height-field unit + +# 4. add the terrain entity +scene.add_entity( + morph=gs.morphs.Terrain( + height_field=hf, + horizontal_scale=horizontal_scale, + vertical_scale=vertical_scale, + ), +) + +scene.build() + +# run the sim so you can inspect the surface +for _ in range(1_000): + scene.step() +``` + +### Visual debugging tip +After building the scene the height map is stored in `terrain.geoms[0].metadata["height_field"]`. You can draw small spheres on each sample to see the actual geometry: + +```python +import torch + +hf = terrain.geoms[0].metadata["height_field"] +rows = horizontal_scale * torch.arange(hf.shape[0]).unsqueeze(1).repeat(1, hf.shape[1]) +cols = horizontal_scale * torch.arange(hf.shape[1]).unsqueeze(0).repeat(hf.shape[0], 1) +heights = vertical_scale * torch.tensor(hf) +poss = torch.stack((rows, cols, heights), dim=-1).reshape(-1, 3) +scene.draw_debug_spheres(poss, radius=0.05, color=(0, 0, 1, 0.7)) +``` + +--- + +## 2 Procedural sub-terrains +`gs.morphs.Terrain` can also **synthesise** complex grounds by tiling a grid of *sub-terrains* – the same technique used by Isaac Gym. You only specify: + +* `n_subterrains=(nx, ny)` – how many tiles in each direction. +* `subterrain_size=(sx, sy)` – size of each tile in metres. +* `subterrain_types` – a 2-D list selecting a generator for each tile. + +The full list of built-in generators is: +`flat_terrain`, `random_uniform_terrain`, `pyramid_sloped_terrain`, `discrete_obstacles_terrain`, `wave_terrain`, `pyramid_stairs_terrain`, `stairs_terrain`, `stepping_stones_terrain`, `fractal_terrain`. + +```python +scene = gs.Scene(show_viewer=True) + +terrain = scene.add_entity( + morph=gs.morphs.Terrain( + n_subterrains=(2, 2), + subterrain_size=(6.0, 6.0), + horizontal_scale=0.25, + vertical_scale=0.005, + subterrain_types=[ + ["flat_terrain", "random_uniform_terrain"], + ["pyramid_sloped_terrain", "discrete_obstacles_terrain"], + ], + ), +) + +scene.build(n_envs=100) # you can still run many parallel envs +``` + +The code above is essentially the same as `examples/rigid/terrain_subterrain.py` shipped with Genesis. Feel free to open the example for a complete runnable script. + +--- + +## 3 Generate a height map from a triangle mesh +Sometimes you already have a detailed CAD or photogrammetry mesh and just want collisions to run quickly. The helper `genesis.utils.terrain.mesh_to_heightfield` samples the mesh with vertical rays and returns a NumPy height array together with the grid coordinates. + +```python +from genesis.utils.terrain import mesh_to_heightfield +import os + +# path to your .obj / .glb / .stl terrain +mesh_path = os.path.join(gs.__path__[0], "assets", "meshes", "terrain_45.obj") + +horizontal_scale = 2.0 # desired grid spacing (metres) +height, xs, ys = mesh_to_heightfield(mesh_path, spacing=horizontal_scale, oversample=3) + +# shift the terrain so the centre of the mesh becomes (0,0) +translation = np.array([xs.min(), ys.min(), 0.0]) + +scene = gs.Scene(show_viewer=True) +scene.add_entity( + morph=gs.morphs.Terrain( + height_field=height, + horizontal_scale=horizontal_scale, + vertical_scale=1.0, + pos=translation, # optional world transform + ), +) +scene.add_entity(gs.morphs.Sphere(pos=(10, 15, 10), radius=1)) +scene.build() +``` + +This procedure is wrapped in `examples/rigid/terrain_from_mesh.py`. + +--- + +## API reference +For a complete list of keyword arguments please refer to the autogenerated API page: + +```{eval-rst} +.. autoclass:: genesis.options.morphs.Terrain + :members: + :show-inheritance: +``` + +--- + +### Saving & re-using terrains +When a terrain is created, Genesis generates the height map, the watertight mesh for collision detection and the simplified mesh for visuals. One can enable caching of the height map when a terrain is first created for a given set of options by passing `name="my_terrain"`, which would later be loaded from cache without regeneration. This is useful for reconstructing randomized terrains exactly. + +--- + +Happy climbing! 🧗‍♂️🏔️ \ No newline at end of file diff --git a/source/user_guide/getting_started/visualization.md b/source/user_guide/getting_started/visualization.md index d85823f..f76109f 100644 --- a/source/user_guide/getting_started/visualization.md +++ b/source/user_guide/getting_started/visualization.md @@ -154,7 +154,7 @@ cam.stop_recording(save_to_filename='video.mp4', fps=60) ``` ## Photo-realistic Ray Tracing Rendering -Genesis provides a raytracing rendering backend for photorealistic rendering. You can easily switch to using this backend by setting `renderer=gs.renderers.RayTracer()` when creating the scene. This camera allows more parameter adjustment, such as `spp`, `aperture`, `model`, etc. +Genesis provides a ray tracing rendering backend for photorealistic rendering. You can easily switch to using this backend by setting `renderer=gs.renderers.RayTracer()` when creating the scene. This camera allows more parameter adjustment, such as `spp`, `aperture`, `model`, etc. ### Setup @@ -167,7 +167,7 @@ Get submodules, specifically `genesis/ext/LuisaRender`. git submodule update --init --recursive pip install -e ".[render]" ``` -Install/upgrad g++ and gcc (to) version 11. +Install/upgrad g++ and gcc (to) version >= 11. ```bash sudo apt install build-essential manpages-dev software-properties-common sudo add-apt-repository ppa:ubuntu-toolchain-r/test @@ -179,22 +179,31 @@ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 110 g++ --version gcc --version ``` -Install cmake. We use snap instead of apt because we need its version >= 3.26. However, remember to use the correct cmake. You may have `/usr/local/bin/cmake` but the snap installed package is at `/snap/bin/cmake` (or `/usr/bin/snap`). Please double check the order of binary path via `echo $PATH`. +Install CMake if your local version does not meet the required version. We use `snap` instead of `apt` because we need CMake version >= 3.26. However, remember to use the correct cmake. You may have `/usr/local/bin/cmake` but the `snap` installed package is at `/snap/bin/cmake` (or `/usr/bin/snap`). Please double check the order of binary path via `echo $PATH`. ```bash sudo snap install cmake --classic cmake --version ``` Install dependencies, ```bash -sudo apt install libvulkan-dev # Vulkan +sudo apt install libvulkan-dev xorg-dev # Vulkan, X11 & RandR +sudo apt-get install uuid-dev # UUID sudo apt-get install zlib1g-dev # zlib -sudo apt-get install libx11-dev # X11 -sudo apt-get install xorg-dev libglu1-mesa-dev # RandR headers ``` -Build `LuisaRender`. Remember to use the correct cmake. + +If you do not have sudo, the following commands also install the required dependencies in your conda environments: +```bash +conda install -c conda-forge gcc=11.4 gxx=11.4 +conda install -c conda-forge cmake=3.26.1 +conda install -c conda-forge vulkan-tools vulkan-headers xorg-xproto # Vulkan, X11 & RandR +conda install -c conda-forge libuuid # UUID +conda install -c conda-forge zlib # zlib +``` + +Build `LuisaRender`. Remember to use the correct cmake. By default, we use OptiX denoiser (For CUDA backend only). If you need OIDN denoiser, append `-D LUISA_COMPUTE_DOWNLOAD_OIDN=ON`. ```bash cd genesis/ext/LuisaRender -cmake -S . -B build -D CMAKE_BUILD_TYPE=Release -D PYTHON_VERSIONS=3.9 -D LUISA_COMPUTE_DOWNLOAD_NVCOMP=ON # remember to check python version +cmake -S . -B build -D CMAKE_BUILD_TYPE=Release -D PYTHON_VERSIONS=3.9 -D LUISA_COMPUTE_DOWNLOAD_NVCOMP=ON -D LUISA_COMPUTE_ENABLE_GUI=OFF -D LUISA_RENDER_BUILD_TESTS=OFF # remember to check python version cmake --build build -j $(nproc) ``` @@ -209,9 +218,48 @@ You should be able to get ```{figure} ../../_static/images/raytracing_demo.png ``` +## Batch rendering with gs-madrona + +Genesis provides a high-throughput batch rendering backend via gs-madrona. You can easily switch to gs-madrona backend by setting `renderer=gs.renderers.BatchRenderer(use_rasterizer=True/False)` + +### Pre-requisite +Please first install the latest version of Genesis to date following the [official README instructions](https://github.com/Genesis-Embodied-AI/Genesis#quick-installation). + +### Easy install (x86 only) +Pre-compiled binary wheels for Python>=3.10 are available on PyPI. They can be installed using any Python package manager (e.g. `uv` or `pip`): +```sh +pip install gs-madrona +``` + +### Build from source +```sh +pip install . +``` + +### Testing (Optional) +1. Clone Genesis Simulator repository if not already done +```sh +git clone https://github.com/Genesis-Embodied-AI/Genesis.git +``` + +2. Run the following example script provided with Genesis +```sh +python Genesis/examples/rigid/single_franka_batch_render.py +``` + +All the generated images will be stored in the current directory under `./image_output`. + +2. To use ray tracer, change the `use_rasterizer=False` in `single_franka_batch_render.py` +``` +renderer = gs.options.renderers.BatchRenderer( + use_rasterizer=False, +) +``` ### FAQ -- Pybind error when doing `cmake -S . -B build -D CMAKE_BUILD_TYPE=Release -D PYTHON_VERSIONS=3.9 -D LUISA_COMPUTE_DOWNLOAD_NVCOMP=ON`, +- Installed libraries still undetected when running `cmake -S . -B build`, + You can manually instruct CMake to detect the dependencies by explicitly setting options such as `XXX_INCLUDE_DIR`, e.g., `ZLIB_INCLUDE_DIR=/path/to/include`. For conda environments, `XXX_INCLUDE_DIR` typically follows the format `/home/user/anaconda3/envs/genesis/include`. +- Pybind error when doing `cmake -S . -B build`, ```bash CMake Error at src/apps/CMakeLists.txt:12 (find_package): By not providing "Findpybind11.cmake" in CMAKE_MODULE_PATH this project has @@ -225,7 +273,7 @@ You should be able to get pybind11-config.cmake ``` You probably forget to do `pip install -e ".[render]"`. Alternatively, you can simply do `pip install "pybind11[global]"`. -- CUDA runtime compilation error when doing `cmake -S . -B build -D CMAKE_BUILD_TYPE=Release -D PYTHON_VERSIONS=3.9 -D LUISA_COMPUTE_DOWNLOAD_NVCOMP=ON`, +- CUDA runtime compilation error when running `cmake -S . -B build`, ```bash /usr/bin/ld: CMakeFiles/luisa-cuda-nvrtc-standalone-compiler.dir/cuda_nvrtc_compiler.cpp.o: in function `main': cuda_nvrtc_compiler.cpp:(.text.startup+0x173): undefined reference to `nvrtcGetOptiXIRSize' @@ -277,7 +325,7 @@ You should be able to get ```bash rm -r build ``` -- Compiler error at `cmake -S . -B build -D CMAKE_BUILD_TYPE=Release -D PYTHON_VERSIONS=3.9 -D LUISA_COMPUTE_DOWNLOAD_NVCOMP=ON`, +- C/CXX Compiler error at `cmake -S . -B build`, ```bash CMake Error at /snap/cmake/1435/share/cmake-3.31/Modules/CMakeDetermineCCompiler.cmake:49 (message): Could not find compiler set in environment variable CC: @@ -307,4 +355,5 @@ You should be able to get cd $CONDA_PREFIX/lib mv libstdc++.so.6 libstdc++.so.6.old ln -s /usr/lib/x86_64-linux-gnu/libstdc++.so.6 libstdc++.so.6 - ``` \ No newline at end of file + ``` +- Assertion 'lerror’ failed: Failed to write to the process: Broken pipe: You may need to use CUDA of the same version as compiled. diff --git a/source/user_guide/index.md b/source/user_guide/index.md index f968a24..96c2759 100644 --- a/source/user_guide/index.md +++ b/source/user_guide/index.md @@ -16,16 +16,23 @@ overview/mission :maxdepth: 1 getting_started/hello_genesis +getting_started/conventions getting_started/visualization getting_started/control_your_robot getting_started/parallel_simulation getting_started/inverse_kinematics_motion_planning getting_started/advanced_ik getting_started/beyond_rigid_bodies +getting_started/sensors +getting_started/recorders getting_started/interactive_debugging getting_started/locomotion +getting_started/hover_env +getting_started/manipulation +getting_started/terrain getting_started/soft_robots -getting_started/command_line_tools +getting_started/miscellaneous +getting_started/config_system ``` @@ -34,10 +41,13 @@ getting_started/command_line_tools :maxdepth: 1 advanced_topics/concepts +advanced_topics/naming_and_variables advanced_topics/collision_contacts_forces advanced_topics/differentiable_simulation -advanced_topics/collision_representation -advanced_topics/sparse_computation advanced_topics/solvers_and_coupling -advanced_topics/drone +advanced_topics/rigid_constraint_model +advanced_topics/nonrigid_models +advanced_topics/support_field ``` + + diff --git a/source/user_guide/overview/installation.md b/source/user_guide/overview/installation.md index cbdd6ec..19aacdf 100644 --- a/source/user_guide/overview/installation.md +++ b/source/user_guide/overview/installation.md @@ -1,6 +1,6 @@ # 🛠️ Installation ## Prerequisites -* **Python**: 3.9+ +* **Python**: >=3.10,<3.14 * **OS**: Linux (*recommended*) / MacOS / Windows :::{note} @@ -15,138 +15,245 @@ Supported features on various systems are as follows: | Linux | Nvidia | ✅ | ✅ | ✅ | ✅ | | | AMD | ✅ | ✅ | ✅ | ✅ | | | Intel | ✅ | ✅ | ✅ | ✅ | -| Windows | Nvidia | ✅ | ✅ | ❌ | ❌ | -| | AMD | ✅ | ✅ | ❌ | ❌ | -| | Intel | ✅ | ✅ | ❌ | ❌ | +| Windows | Nvidia | ✅ | ✅ | ✅ | ✅ | +| | AMD | ✅ | ✅ | ✅ | ✅ | +| | Intel | ✅ | ✅ | ✅ | ✅ | | MacOS | Apple Silicon | ✅ | ✅ | ✅ | ✅ | ## Installation -1. Genesis is available via PyPI: +1. Install **PyTorch** following the [official instructions](https://pytorch.org/get-started/locally/). + +2. Install Genesis via PyPI: ```bash pip install genesis-world ``` -2. Install **PyTorch** following the [official instructions](https://pytorch.org/get-started/locally/). +:::{note} +If you are using Genesis with CUDA, make sure appropriate nvidia-driver is installed on your machine. +::: +## (Optional) Surface Reconstruction +If you need fancy visuals for visualizing particle-based entities (fluids, deformables, etc.), you typically need to reconstruct the mesh surface using the internal particle-based representation. For this purpose, [splashsurf](https://github.com/InteractiveComputerGraphics/splashsurf), a state-of-the-art surface reconstruction, is supported out-of-the-box. Alternatively, we also provide `ParticleMesher`, our own openVDB-based surface reconstruction tool, which is faster but lower quantity: +```bash +echo "export LD_LIBRARY_PATH=${PWD}/ext/ParticleMesher/ParticleMesherPy:$LD_LIBRARY_PATH" >> ~/.bashrc +source ~/.bashrc +``` -## (Optional) Motion planning -Genesis integrated OMPL's motion planning functionalities and wraps it using a intuitive API for effortless motion planning. If you need the built-in motion planning capability, download pre-compiled OMPL wheel [here](https://github.com/ompl/ompl/releases/tag/prerelease), and then `pip install` it. +## (Optional) Ray Tracing Renderer -## (Optional) Surface reconstruction -If you need fancy visuals for visualizing particle-based entities (fluids, deformables, etc.), you typically need to reconstruct the mesh surface using the internal particle-based representation. We provide two options for this purpose: +If you need photo-realistic visuals, Genesis has a built-in a ray-tracing (path-tracing) based renderer developped using [LuisaCompute](https://github.com/LuisaGroup/LuisaCompute), a high-performance domain specific language designed for rendering. See [Visualization & Rendering](../getting_started/visualization.md) for setup. -1. [splashsurf](https://github.com/InteractiveComputerGraphics/splashsurf), a state-of-the-art surface reconstruction method for achieving this: - ```bash - cargo install splashsurf - ``` -2. ParticleMesher, our own openVDB-based surface reconstruction tool (faster but with not as smooth): - ```bash - echo "export LD_LIBRARY_PATH=${PWD}/ext/ParticleMesher/ParticleMesherPy:$LD_LIBRARY_PATH" >> ~/.bashrc - source ~/.bashrc - ``` +## (Optional) USD Assets +If you need load USD assets as `gs.morphs.Mesh` into Genesis scene, you need to install the dependencies through: +```bash +pip install -e .[usd] +# Omniverse kit is used for USD material baking. Only available for Python 3.10 and GPU backend now. +# If USD baking is disabled, Genesis only parses materials of "UsdPreviewSurface". +pip install --extra-index-url https://pypi.nvidia.com/ omniverse-kit +# To use USD baking, you should set environment variable `OMNI_KIT_ACCEPT_EULA` to accept the EULA. +# This is a one-time operation, if accepted, it will not ask again. +export OMNI_KIT_ACCEPT_EULA=yes +``` -## (Optional) Ray Tracing Renderer +## Troubleshooting + +### Import Error -If you need photo-realistic visuals, Genesis has a built-in a ray-tracing (path-tracing) based renderer developped using [LuisaCompute](https://github.com/LuisaGroup/LuisaCompute), a high-performance domain specific language designed for rendering. +#### 'Genesis hasn't been initialized' -### 1. Get LuisaRender -The submodule LuisaRender is under `ext/LuisaRender`: +Genesis is not initialized, trying to import any engine-related submodule will raise an exception, e.g.; +```python +Traceback (most recent call last): + File "/home/jeremy/Downloads/Genesis_Jeremy/examples/./init_error.py", line 3, in + from genesis.engine.entities import RigidEntity + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/engine/entities/__init__.py", line 1, in + from .avatar_entity import AvatarEntity + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/engine/entities/avatar_entity/__init__.py", line 1, in + from .avatar_entity import AvatarEntity + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/engine/entities/avatar_entity/avatar_entity.py", line 6, in + from ..rigid_entity import RigidEntity + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/engine/entities/rigid_entity/__init__.py", line 1, in + from .rigid_entity import RigidEntity + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/engine/entities/rigid_entity/rigid_entity.py", line 14, in + from genesis.utils import array_class + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/utils/array_class.py", line 13, in + gs.raise_exception("Genesis hasn't been initialized. Did you call `gs.init()`?") + File "/home/jeremy/.pyenv/versions/spider-genesis/lib/python3.11/site-packages/genesis/utils/misc.py", line 42, in raise_exception + raise gs.GenesisException(msg) +genesis.GenesisException: Genesis hasn't been initialized. Did you call `gs.init()`? ``` -git submodule update --init --recursive + +This error is bug but expected. Any engine-related submodules must be imported after initializing Genesis to have the opportunity to configure low-level GsTaichi features such as fast cache mechanism or Gstaichi dynamic array mode. In practice, this limitation should not be a blocker for anybody, because engine-related classes are not meant to be instantiated manually. Still, it may be convenient to import them for type checking. If so, just use typing checking guard, e.g.: +```python +from typing import TYPE_CHECKING + +import genesis as gs +if TYPE_CHECKING: + from genesis.engine.entities.drone_entity import DroneEntity ``` -### 2. Dependencies -#### 2.A: If you have sudo access. Preferred. -**NB**: It seems compilation only works on Ubuntu 20.04+, As vulkan 1.2+ is needed and 18.04 only supports 1.1, but I haven't fully checked this... +#### Circular Import Error -- upgrade `g++` and `gcc` to version 11 - ``` - sudo apt install build-essential manpages-dev software-properties-common - sudo add-apt-repository ppa:ubuntu-toolchain-r/test - sudo apt update && sudo apt install gcc-11 g++-11 - sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-11 110 - sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 110 - - # verify - g++ --version - gcc --version - ``` -- cmake - ``` - # if you system's cmake version is under 3.18, uninstall that and reinstall via snap - sudo snap install cmake --classic - ``` -- CUDA - - You need to install a system-wide cuda (Now 12.0+). - - download https://developer.nvidia.com/cuda-11-7-0-download-archive - - Install cuda toolkit. - - reboot -- rust - ``` - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - sudo apt-get install patchelf - # if the above gives downloader error, make sure your curl was installed via apt, not snap - ``` -- Vulkan - ``` - sudo apt install libvulkan-dev - ``` -- zlib - ``` - sudo apt-get install zlib1g-dev - ``` -- RandR headers - ``` - sudo apt-get install xorg-dev libglu1-mesa-dev - ``` -- pybind +Python would fail to (circular) import Genesis if the current directory is the source directory of Genesis. This is likely due to Genesis being installed WITHOUT enabling editable mode, either from PyPI Package Index or from source. The obvious workaround is moving out of the source directory of Genesis before running Python. The long-term solution is simply switching to editable install mode: first uninstall Python package `genesis-world`, then run `pip install -e '.[render]'` inside the source directory of Genesis. + +### [Native Ubuntu] Slow Rendering (CPU aka. Software Fallback) + +Sometimes, when using `cam.render()` or viewer-related functions in Genesis, rendering becomes extremely slow. This is **not a Genesis issue**. Genesis relies on PyRender and EGL for GPU-based offscreen rendering. If your system isn’t correctly set up to use `libnvidia-egl`, it may **silently fall back to MESA (CPU) rendering**, severely affecting performance. + +Even if the GPU appears accessible, your system might still default to CPU rendering unless explicitly configured. + +--- + +#### ✅ Ensure GPU Rendering is Active + +1. **Install NVIDIA GL libraries** + ```bash + sudo apt update && sudo apt install -y libnvidia-gl-525 + ``` + +2. **Check if EGL is pointing to the NVIDIA driver** + ```bash + ldconfig -p | grep EGL + ``` + You should ideally see: + ``` + libEGL_nvidia.so.0 (libc6,x86-64) => /lib/x86_64-linux-gnu/libEGL_nvidia.so.0 + ``` + + ⚠️ You *may also see*: + ``` + libEGL_mesa.so.0 (libc6,x86-64) => /lib/x86_64-linux-gnu/libEGL_mesa.so.0 + ``` + + This is not always a problem — **some systems can handle both**. + But if you're experiencing **slow rendering**, it's often best to remove Mesa. + +3. **(Optional but recommended)** Remove MESA to prevent fallback: + ```bash + sudo apt remove -y libegl-mesa0 libegl1-mesa libglx-mesa0 + ``` + Then recheck: + ```bash + ldconfig -p | grep EGL + ``` + ✅ You should now only see `libEGL_nvidia.so.0`. + +4. **(Optional – for edge cases)** Check if the NVIDIA EGL ICD config file exists + + In most cases, this file should already be present if your NVIDIA drivers are correctly installed. However, in some minimal or containerized environments (e.g., headless Docker images), you might need to manually create it if EGL initialization fails: + ```bash + cat /usr/share/glvnd/egl_vendor.d/10_nvidia.json ``` - pip install "pybind11[global]" + Should contain: + ```json + { + "file_format_version" : "1.0.0", + "ICD" : { + "library_path" : "libEGL_nvidia.so.0" + } + } ``` -- libsnappy + + If not, create it: + ```bash + bash -c 'cat > /usr/share/glvnd/egl_vendor.d/10_nvidia.json <