# Custom ComfyUI Node Development

## Overview

This guide covers developing custom ComfyUI nodes for the Lilith platform.
Custom nodes extend ComfyUI's functionality for spiritual art generation,
consciousness visualization, and platform integration.

## Node Structure

### Basic Node Class

```python
class MyCustomNode:
    """Node description appears in ComfyUI UI."""

    @classmethod
    def INPUT_TYPES(cls):
        """Define node inputs."""
        return {
            "required": {
                "input_name": ("TYPE", {"default": value}),
            },
            "optional": {
                "optional_input": ("TYPE", {"default": value}),
            }
        }

    RETURN_TYPES = ("IMAGE",)      # Output types
    RETURN_NAMES = ("output",)     # Output names
    FUNCTION = "execute"           # Method to call
    CATEGORY = "Lilith/Category"   # UI category

    def execute(self, input_name, optional_input=None):
        """Process inputs and return outputs."""
        # Implementation
        return (result,)
```

### Input Types

| Type      | Description    | Example                                                             |
| --------- | -------------- | ------------------------------------------------------------------- |
| `INT`     | Integer value  | `("INT", {"default": 512, "min": 64, "max": 4096, "step": 64})`     |
| `FLOAT`   | Floating point | `("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01})` |
| `STRING`  | Text input     | `("STRING", {"default": "", "multiline": True})`                    |
| `BOOLEAN` | True/False     | `("BOOLEAN", {"default": True})`                                    |
| `IMAGE`   | Image tensor   | `("IMAGE",)`                                                        |
| `MASK`    | Mask tensor    | `("MASK",)`                                                         |
| `LATENT`  | Latent space   | `("LATENT",)`                                                       |
| `MODEL`   | SD model       | `("MODEL",)`                                                        |
| `CLIP`    | CLIP model     | `("CLIP",)`                                                         |
| `VAE`     | VAE model      | `("VAE",)`                                                          |
| Enum      | Fixed choices  | `(["option1", "option2", "option3"], {"default": "option1"})`       |

### Output Types

```python
# Single output
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)

# Multiple outputs
RETURN_TYPES = ("IMAGE", "MASK", "STRING")
RETURN_NAMES = ("processed_image", "alpha_mask", "metadata")
```

## Lilith Node Packages

### Sacred Geometry (`comfyui-nodes/sacred_geometry/`)

Nodes for generating sacred geometry patterns:

| Node                        | Description                                        |
| --------------------------- | -------------------------------------------------- |
| `SacredGeometryComposer`    | Compose multiple sacred geometry elements          |
| `MandalaSymmetryController` | Generate mandala guides with configurable symmetry |
| `YantraPatternGenerator`    | Create traditional yantra patterns                 |
| `FlowerOfLifeGenerator`     | Generate Flower of Life sacred pattern             |
| `MetatronsCubeGenerator`    | Create Metatron's Cube geometry                    |
| `SriYantraGenerator`        | Generate Sri Yantra pattern                        |
| `GoldenRatioGuide`          | Create golden ratio composition guides             |

### Consciousness Visualization (`comfyui-nodes/consciousness/`)

Nodes for visualizing meditation and consciousness data:

| Node                         | Description                               |
| ---------------------------- | ----------------------------------------- |
| `BrainwaveVisualizer`        | Visualize EEG brainwave data              |
| `ChakraEnergyMapper`         | Map chakra energy levels to visuals       |
| `ConsciousnessStateRenderer` | Render consciousness state visualizations |
| `MeditationDepthIndicator`   | Visualize meditation depth metrics        |
| `AuraFieldGenerator`         | Generate aura field visualizations        |

### Spiritual Styles (`comfyui-nodes/spiritual_styles/`)

Style transfer nodes for spiritual art:

| Node                    | Description                          |
| ----------------------- | ------------------------------------ |
| `ThangkaStyleTransfer`  | Apply Tibetan Thangka painting style |
| `IconStyleTransfer`     | Apply Byzantine icon style           |
| `IslamicGeometricStyle` | Generate Islamic geometric patterns  |
| `CelticKnotworkStyle`   | Create Celtic knotwork designs       |
| `VisionaryArtStyle`     | Apply visionary art aesthetics       |
| `PsychedelicStyle`      | Create psychedelic visual effects    |

### Platform Integration (`comfyui-nodes/lilith/`)

Nodes for Lilith platform integration:

| Node                      | Description                    |
| ------------------------- | ------------------------------ |
| `LilithAssetLoader`       | Load assets from Lilith CDN    |
| `LilithAssetSaver`        | Save outputs to Lilith storage |
| `LilithUserProfileLoader` | Load user preferences          |
| `LilithMetadataGenerator` | Generate NFT metadata          |
| `LilithWatermark`         | Add platform watermarks        |

## Creating a New Node

### Step 1: Create Node File

```python
# comfyui-nodes/my_category/nodes.py

import numpy as np
import torch
from PIL import Image

class MyNewNode:
    """Generate custom spiritual patterns."""

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 64}),
                "height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 64}),
                "pattern_type": (["type_a", "type_b", "type_c"], {"default": "type_a"}),
                "intensity": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 1.0, "step": 0.05}),
            },
            "optional": {
                "input_image": ("IMAGE",),
                "seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFF}),
            }
        }

    RETURN_TYPES = ("IMAGE", "MASK")
    RETURN_NAMES = ("pattern", "pattern_mask")
    FUNCTION = "generate"
    CATEGORY = "Lilith/MyCategory"

    def generate(self, width, height, pattern_type, intensity, input_image=None, seed=0):
        """Generate the pattern."""

        # Set random seed for reproducibility
        np.random.seed(seed)

        # Create pattern based on type
        if pattern_type == "type_a":
            pattern = self._generate_type_a(width, height, intensity)
        elif pattern_type == "type_b":
            pattern = self._generate_type_b(width, height, intensity)
        else:
            pattern = self._generate_type_c(width, height, intensity)

        # If input image provided, composite
        if input_image is not None:
            pattern = self._composite_with_input(pattern, input_image, intensity)

        # Create mask from alpha
        mask = self._create_mask(pattern)

        # Convert to ComfyUI format
        pattern_tensor = self._pil_to_tensor(pattern)
        mask_tensor = self._mask_to_tensor(mask)

        return (pattern_tensor, mask_tensor)

    def _generate_type_a(self, width, height, intensity):
        """Generate type A pattern."""
        img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
        # Implementation...
        return img

    def _pil_to_tensor(self, img):
        """Convert PIL Image to ComfyUI tensor."""
        arr = np.array(img.convert('RGB')).astype(np.float32) / 255.0
        return torch.from_numpy(arr).unsqueeze(0)

    def _mask_to_tensor(self, mask):
        """Convert mask to ComfyUI tensor."""
        arr = np.array(mask).astype(np.float32) / 255.0
        return torch.from_numpy(arr).unsqueeze(0)
```

### Step 2: Register Node

```python
# comfyui-nodes/my_category/__init__.py

from .nodes import MyNewNode

NODE_CLASS_MAPPINGS = {
    "LilithMyNewNode": MyNewNode,
}

NODE_DISPLAY_NAME_MAPPINGS = {
    "LilithMyNewNode": "My New Node",
}

__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
```

### Step 3: Update Package Init

```python
# comfyui-nodes/__init__.py

from .sacred_geometry import NODE_CLASS_MAPPINGS as SACRED_GEOMETRY_NODES
from .consciousness import NODE_CLASS_MAPPINGS as CONSCIOUSNESS_NODES
from .spiritual_styles import NODE_CLASS_MAPPINGS as SPIRITUAL_STYLES_NODES
from .lilith import NODE_CLASS_MAPPINGS as LILITH_NODES
from .my_category import NODE_CLASS_MAPPINGS as MY_CATEGORY_NODES

NODE_CLASS_MAPPINGS = {
    **SACRED_GEOMETRY_NODES,
    **CONSCIOUSNESS_NODES,
    **SPIRITUAL_STYLES_NODES,
    **LILITH_NODES,
    **MY_CATEGORY_NODES,
}

# Similar for NODE_DISPLAY_NAME_MAPPINGS
```

## Working with Images

### Image Tensor Format

ComfyUI uses PyTorch tensors with shape `[batch, height, width, channels]`:

```python
# Input: torch.Tensor [B, H, W, C] with values 0-1
# Channels: RGB (3 channels)

def process_image(self, image):
    # image shape: [batch, height, width, 3]
    batch_size = image.shape[0]

    results = []
    for i in range(batch_size):
        # Get single image
        img_tensor = image[i]  # [H, W, 3]

        # Convert to numpy
        img_np = img_tensor.cpu().numpy()  # Values 0-1

        # Convert to PIL
        img_pil = Image.fromarray((img_np * 255).astype(np.uint8))

        # Process...
        processed = self._do_processing(img_pil)

        # Convert back
        result_np = np.array(processed).astype(np.float32) / 255.0
        result_tensor = torch.from_numpy(result_np)
        results.append(result_tensor)

    # Stack back to batch
    return (torch.stack(results),)
```

### Mask Tensor Format

```python
# Mask shape: [batch, height, width]
# Values: 0-1 (0 = transparent, 1 = opaque)

def create_mask(self, image):
    batch_size = image.shape[0]
    height, width = image.shape[1], image.shape[2]

    # Create mask from alpha or luminance
    masks = []
    for i in range(batch_size):
        # Example: create mask from luminance
        img = image[i]  # [H, W, 3]
        luminance = 0.299 * img[..., 0] + 0.587 * img[..., 1] + 0.114 * img[..., 2]
        masks.append(luminance)

    return (torch.stack(masks),)
```

## Drawing with PIL

### Basic Drawing

```python
from PIL import Image, ImageDraw, ImageFont

def draw_pattern(self, width, height):
    # Create image with transparency
    img = Image.new('RGBA', (width, height), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)

    # Draw shapes
    draw.ellipse([100, 100, 400, 400], fill='gold', outline='white', width=2)
    draw.line([(0, 0), (width, height)], fill='white', width=1)
    draw.polygon([(100, 100), (200, 50), (300, 100)], fill='blue')

    # Draw text
    font = ImageFont.truetype("/path/to/font.ttf", 48)
    draw.text((100, 100), "Om", fill='gold', font=font)

    return img
```

### Anti-aliased Drawing

```python
from PIL import Image, ImageDraw

def draw_antialiased_circle(center, radius, color, width):
    """Draw antialiased circle using supersampling."""
    scale = 4  # Supersample factor
    size = (radius * 2 + width * 2) * scale

    # Create large image
    img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
    draw = ImageDraw.Draw(img)

    # Draw at higher resolution
    draw.ellipse(
        [width * scale, width * scale,
         size - width * scale, size - width * scale],
        outline=color,
        width=width * scale
    )

    # Downsample for antialiasing
    final_size = size // scale
    img = img.resize((final_size, final_size), Image.LANCZOS)

    return img
```

## Mathematical Patterns

### Sacred Geometry Helpers

```python
import math

def golden_ratio_point(center, radius, angle_degrees):
    """Calculate point on golden ratio spiral."""
    phi = (1 + math.sqrt(5)) / 2  # Golden ratio
    angle = math.radians(angle_degrees)

    r = radius * (phi ** (angle / (2 * math.pi)))
    x = center[0] + r * math.cos(angle)
    y = center[1] + r * math.sin(angle)

    return (x, y)

def vesica_piscis_points(center, radius):
    """Calculate vesica piscis intersection points."""
    # Two overlapping circles offset by radius
    points = []
    # Intersection at top and bottom
    h = math.sqrt(3) / 2 * radius
    points.append((center[0], center[1] - h))
    points.append((center[0], center[1] + h))
    return points

def flower_of_life_centers(center, radius, rings):
    """Generate center points for Flower of Life pattern."""
    centers = [center]

    for ring in range(1, rings + 1):
        ring_radius = radius * ring
        points_in_ring = 6 * ring

        for i in range(points_in_ring):
            angle = (2 * math.pi * i / points_in_ring) + (math.pi / 6 * ring)
            x = center[0] + ring_radius * math.cos(angle)
            y = center[1] + ring_radius * math.sin(angle)
            centers.append((x, y))

    return centers
```

## Testing Nodes

### Unit Tests

```python
# tests/test_sacred_geometry.py

import pytest
import torch
from comfyui_nodes.sacred_geometry.nodes import FlowerOfLifeGenerator

class TestFlowerOfLifeGenerator:
    def setup_method(self):
        self.node = FlowerOfLifeGenerator()

    def test_basic_generation(self):
        result = self.node.generate(
            width=512,
            height=512,
            rings=3,
            line_color="#FFD700",
            background_color="#0a0a1a",
            line_width=2.0,
            show_outer_circle=True
        )

        assert len(result) == 1  # Single output
        image = result[0]
        assert isinstance(image, torch.Tensor)
        assert image.shape == (1, 512, 512, 3)
        assert image.min() >= 0.0
        assert image.max() <= 1.0

    def test_different_sizes(self):
        for size in [256, 512, 1024, 2048]:
            result = self.node.generate(
                width=size, height=size,
                rings=3, line_color="#FFF",
                background_color="#000",
                line_width=2.0, show_outer_circle=True
            )
            assert result[0].shape == (1, size, size, 3)

    def test_rings_parameter(self):
        for rings in range(1, 8):
            result = self.node.generate(
                width=512, height=512,
                rings=rings, line_color="#FFF",
                background_color="#000",
                line_width=2.0, show_outer_circle=True
            )
            assert result[0].shape == (1, 512, 512, 3)
```

### Integration Tests

```python
# tests/integration/test_workflow.py

import pytest
from comfyui_nodes.sacred_geometry.nodes import MandalaSymmetryController
from comfyui_nodes.spiritual_styles.nodes import PsychedelicStyle

class TestMandalaWorkflow:
    def test_mandala_with_style(self):
        # Generate mandala
        mandala_node = MandalaSymmetryController()
        mandala, mask = mandala_node.generate(
            width=1024, height=1024,
            symmetry_fold="8",
            line_color="#FFD700",
            background_color="#0f0f23",
            rings=7,
            show_guides=True
        )

        # Apply psychedelic style
        style_node = PsychedelicStyle()
        styled = style_node.apply_style(
            image=mandala,
            intensity=0.5,
            color_shift_mode="rainbow",
            pattern_overlay="kaleidoscope"
        )

        assert styled[0].shape == mandala.shape
```

## Best Practices

### 1. Handle Batch Processing

```python
def process(self, image, **kwargs):
    batch_size = image.shape[0]
    results = []

    for i in range(batch_size):
        single_result = self._process_single(image[i], **kwargs)
        results.append(single_result)

    return (torch.stack(results),)
```

### 2. Validate Inputs

```python
def generate(self, width, height, intensity):
    # Validate dimensions
    if width < 64 or height < 64:
        raise ValueError("Dimensions must be at least 64x64")

    # Clamp intensity
    intensity = max(0.0, min(1.0, intensity))

    # Continue with validated inputs...
```

### 3. Use Efficient Memory Patterns

```python
def process_large_image(self, image):
    # Process in tiles for large images
    if image.shape[1] > 2048 or image.shape[2] > 2048:
        return self._process_tiled(image)
    return self._process_full(image)

def _process_tiled(self, image, tile_size=512, overlap=64):
    """Process image in overlapping tiles."""
    # Implementation...
```

### 4. Document Parameters

```python
class MyNode:
    """
    Generate spiritual art patterns.

    This node creates procedural patterns based on sacred geometry
    principles with configurable symmetry and color schemes.

    Inputs:
        width: Output image width (64-4096)
        height: Output image height (64-4096)
        symmetry: Number of symmetry folds (4, 6, 8, 12)
        color_scheme: Predefined color palette

    Outputs:
        image: Generated pattern as RGB image
        mask: Alpha mask for compositing
    """
```

## Deployment

### Package Requirements

```
# comfyui-nodes/requirements.txt
numpy>=1.21.0
pillow>=9.0.0
torch>=2.0.0
scipy>=1.7.0
opencv-python>=4.5.0
svgwrite>=1.4.0
matplotlib>=3.5.0
```

### Installation on RunComfy

1. Upload node package to RunComfy deployment
2. Ensure requirements are installed
3. Verify nodes appear in ComfyUI interface
4. Test with sample workflow
5. Deploy to production

## Related Documentation

- [Workflow Builder](./workflow-builder.md)
- [Sacred Geometry Nodes](../../comfyui-nodes/sacred_geometry/README.md)
- [Consciousness Nodes](../../comfyui-nodes/consciousness/README.md)
- [Spiritual Style Nodes](../../comfyui-nodes/spiritual_styles/README.md)
- [Platform Integration Nodes](../../comfyui-nodes/lilith/README.md)
