> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# LampArray 效果

> LampArray 效果

在游戏循环内调用 [ILampArray](/reference/lighting/lamparray/interfaces/ilamparray/ilamparray) 颜色函数以产生效果和动画。本页提供了一些示例。

为简单起见，这些示例将在可能的情况下使用 [ILampArray::SetColor](/reference/lighting/lamparray/interfaces/ilamparray/methods/ilamparray_setcolor) 将颜色应用于设备上的每个 Lamp。可以通过使用 [ILampArray::SetColorsForIndices](/reference/lighting/lamparray/interfaces/ilamparray/methods/ilamparray_setcolorsforindices) 在单个 Lamp 或一组 Lamp 上产生效果。

## 淡入淡出与闪烁

通过在一定时间间隔内将颜色的 RGB 值乘以一个递增或递减的百分比来淡入或淡出 Lamp。通过反复淡入和淡出 Lamp 来创建闪烁、呼吸或闪光效果。

以下示例让 LampArray 的所有 Lamp 反复亮灭：

```cpp theme={null}
uint32_t currentFrame = 0;

// The total number of frames in one blink
const float blinkFrameCount = 90;

const float blinkFadeFrameCount = blinkFrameCount / 2;

// The color to fade in and out. In this example we'll use red.
const LampArrayColor mainColor = {0xFF /* r */, 0x0 /* g */, 0x0 /* b */, 0xFF /* a */};

Microsoft::WRL::ComPtr<ILampArray> lampArray;

void BlinkUpdateFrame(ILampArray* lampArrayToUpdate)
{
    LampArrayColor currentFrameColor = mainColor;

    float colorScale = 1.0;

    if (currentFrame < blinkFadeFrameCount)
    {
        // Fade out to black
        colorScale = (blinkFadeFrameCount - currentFrame) / blinkFadeFrameCount;
    }
    else
    {
        // Fade in to full color value
        colorScale = (currentFrame - blinkFadeFrameCount) / blinkFadeFrameCount;
    }

    currentFrameColor.r = static_cast<uint8_t>(mainColor.r * colorScale);
    currentFrameColor.g = static_cast<uint8_t>(mainColor.g * colorScale);
    currentFrameColor.b = static_cast<uint8_t>(mainColor.b * colorScale);

    // Apply the color
    lampArrayToUpdate->SetColor(currentFrameColor);

    // Increment our current frame, accounting for overflow
    if (++currentFrame > blinkFrameCount)
    {
        currentFrame = 0;
    }
}

void MainLoop(
    _In_ volatile bool& terminateLoop)
{
    color.a = 0xFF;

    while (!terminateLoop)
    {
        Sleep(50);

        BlinkUpdateFrame(lampArray.Get());
    }
} 
```

## 颜色循环

通过逐渐增加和减少颜色的红、绿、蓝值来创建颜色循环。这将在 RGB 光谱上一大片颜色范围内进行混合。

以下示例在 LampArray 上执行 RGB 颜色循环。

```cpp theme={null}
uint32_t currentFrame = 0;

// The total number of frames in one cycle
const float cycleFrameCount = 180;

// The size of each "ramp" of the cycle (blending from one color to the next)
const float rampIntervalFrameCount = cycleFrameCount / 6;

// The color to set in each frame
LampArrayColor color = {};

Microsoft::WRL::ComPtr<ILampArray> lampArray;

void CycleUpdateFrame(ILampArray* lampArrayToUpdate)
{
    // Calculate the color for the current frame.
    if (currentFrame < rampIntervalFrameCount)
    {
        // Red -> yellow: increase g
        color.r = 0xFF;
        color.g = static_cast<BYTE>(0xFF * (currentFrame / rampIntervalFrameCount));
    }
    else if (currentFrame < (2 * rampIntervalFrameCount))
    {
        // Yellow -> green: decrease r
        color.r = static_cast<BYTE>(0xFF * (((2 * rampIntervalFrameCount) - currentFrame) / rampIntervalFrameCount));
        color.g = 0xFF;
    }
    else if (currentFrame < (3 * rampIntervalFrameCount))
    {
        // Green -> cyan: increase b
        color.g = 0xFF;
        color.b = static_cast<BYTE>(0xFF * ((currentFrame - (2 * rampIntervalFrameCount)) / rampIntervalFrameCount));
    }
    else if (currentFrame < (4 * rampIntervalFrameCount))
    {
        // Cyan -> blue: decrease g
        color.g = static_cast<BYTE>(0xFF * (((4 * rampIntervalFrameCount) - currentFrame) / rampIntervalFrameCount));
        color.b = 0xFF;
    }
    else if (currentFrame < (5 * rampIntervalFrameCount))
    {
        // Blue -> magenta: increase r
        color.r = static_cast<BYTE>(0xFF * ((currentFrame - (4 * rampIntervalFrameCount)) / rampIntervalFrameCount));
        color.b = 0xFF;
    }
    else
    {
        // Magenta -> red: decrease b
        color.r = 0xFF;
        color.b = static_cast<BYTE>(0xFF * ((cycleFrameCount - currentFrame) / rampIntervalFrameCount));
    }

    // Apply the color
    lampArrayToUpdate->SetColor(color);

    // Increment our current frame, accounting for overflow
    if (++currentFrame > cycleFrameCount)
    {
        currentFrame = 0;
    }
}

void MainLoop(
    _In_ volatile bool& terminateLoop)
{
    color.a = 0xFF;

    while (!terminateLoop)
    {
        Sleep(50);

        CycleUpdateFrame(lampArray.Get());
    }
}
```

## 基于位置的效果

在创建看起来在设备上移动的效果（例如涟漪或波浪）时，请使用 [ILampInfo::GetPosition](/reference/lighting/lamparray/interfaces/ilampinfo/methods/ilampinfo_getposition) 和 [ILampArray::GetBoundingBox](/reference/lighting/lamparray/interfaces/ilamparray/methods/ilamparray_getboundingbox)。

以下示例将创建一波从左向右在设备上逐渐淡出的 Lamp。请注意，我们借用了“淡入淡出与闪烁”一节中的缩放概念，但这里是基于每个 Lamp 的。

```cpp theme={null}
Microsoft::WRL::ComPtr<ILampArray> lampArray;

uint32_t currentFrame = 0;

// The total number of frames in one wave
const uint32_t waveFrameCount = 30;

// The number of frames it takes for each Lamp to fade out
const uint32_t fadeDurationInFrames = 10;

// Helper class for per-Lamp effect state information
struct LampContext
{
    uint32_t lampIndex;

    // How far to the right this Lamp is located compared to the total length of the device.
    float xPercentage;

    // The number of frames left in this Lamp's fade-out
    uint32_t fadeFramesRemaining;
};

std::vector<LampContext> lampContexts;

// The Lamp indices for the device, in sorted order by position from left to right
std::vector<uint32_t> indices;

// The colors to set in each frame
std::vector<LampArrayColor> colors;

// The index in the sorted array representing the peak of the wave
uint32_t lastUpdatedIndex = 0;

// The base color to use in the wave effect
const LampArrayColor mainColor = {0xFF /* r */, 0x0 /* g */, 0x0 /* b */, 0xFF /* a */};

void WaveUpdateFrame(ILampArray* lampArrayToUpdate)
{
    float framePercentage = (float)currentFrame / (float)myFrameCount;

    const uint32_t lampCount = lampArrayToUpdate->GetLampCount();
    for (uint32_t i = 0; i < lampCount; i++)
    {
        auto& lampContext = lampContexts[i];

        // Mark any Lamps for which we should start a new fade-out.
        // Use lastUpdatedIndex to track which Lamps we've started in this wave.
        if (i >= lastUpdatedIndex && lampContext.xPercentage <= framePercentage)
        {
            lastUpdatedIndex = i;

            // This Lamp should start at full brightness on this frame.
            lampContext.fadeFramesRemaining = fadeDurationInFrames + 1;
        }

        // Process fade-outs for any Lamps that have fade-out frames remaining
        if (lampContext.fadeFramesRemaining > 0)
        {
            lampContext.fadeFramesRemaining--;

            // Optimization: use the full strength color for the first fade-out frame (without scaling)
            if (lampContext.fadeFramesRemaining == fadeDurationInFrames)
            {
                colors[i] = mainColor;
            }
            else
            {
                // Scale the main color down based on how many fade-out frames are remaining for this Lamp.
                float scaleFactor = (float)lampContext.fadeFramesRemaining / (float)fadeDurationInFrames;

                auto& lampColor = colors[i];
                lampColor.r = static_cast<BYTE>(scaleFactor * mainColor.r);
                lampColor.g = static_cast<BYTE>(scaleFactor * mainColor.g);
                lampColor.b = static_cast<BYTE>(scaleFactor * mainColor.b);
            }
        }
    }

    // Apply the color
    lampArrayToUpdate->SetColorsForIndices(lampCount, indices.data(), colors.data());

    // Increment our current frame, accounting for overflow
    if (++currentFrame > waveFrameCount)
    {
        currentFrame = 0;

        // The peak of the wave also needs to wrap around
        lastUpdatedIndex = 0;
    }
}

HRESULT MainLoop(
    _In_ volatile bool& terminateLoop)
{
    color.a = 0xFF;

    // Set up contexts
    const uint32_t lampCount = lampArray->GetLampCount();
    for (uint32_t i = 0; i < lampCount; i++)
    {
        LampContext context = {};
        context.lampIndex = i;

        Microsoft::WRL::ComPtr<ILampInfo> lampInfo;
        RETURN_IF_FAILED(lampArray->GetLampInfo(i, &lampInfo));

        LampArrayPosition lampPosition = {};
        lampInfo->GetPosition(&lampPosition);

        // Our position values will be relative to the total length of the device.
        context.xPercentage = (float)lampPosition.xInMeters / (float)boundingBox.xInMeters;

        lampContexts.push_back(context);
    }

    // Sort the contexts by position from left to right
    std::sort(lampContexts.begin(),
        lampContexts.end(),
        [](LampContext const& a, LampContext const& b)
        {
            return a.xPercentage < b.xPercentage;
        });

    // Set up our indices buffer in sorted order
    for (uint32_t i = 0; i < lampCount; i++)
    {
        indices[i] = lampContexts[i].lampIndex;
    }

    colors.resize(lampCount);

    // Animation loop for the sample
    while (!terminateLoop)
    {
        Sleep(33);
        WaveUpdateFrame(lampArray.Get());
    }

    return S_OK;
}
```

## 另请参阅

[光照 API 概览](/build/core-features/common/lighting/gc-lighting-toc)
[ILampArray 参考](/reference/lighting/lamparray/interfaces/ilamparray/ilamparray)


## Related topics

- [光照 API 概览](/zh-CN/build/core-features/common/lighting/gc-lighting-toc.md)
- [XBOX 与 PC 上的 Lighting API 与 LampArray](/zh-CN/build/core-features/common/lighting/index.md)
- [LampArray](/zh-CN/reference/lighting/lamparray/lamparray_members.md)
- [在 LampArray 上设置颜色](/zh-CN/build/core-features/common/lighting/lighting-colors.md)
- [ILampArray::SetColorsForScanCodes](/zh-CN/reference/lighting/lamparray/interfaces/ilamparray/methods/ilamparray_setcolorsforscancodes.md)
