// Copyright 2009 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include "common/ISPCMessages.h"
#include "rkcommon/math/LinearSpace.ih"

OSPRAY_BEGIN_ISPC_NAMESPACE

#define SHADINGCONTEXT_SIZE (programCount * programCount * 1024)
#define SHADINGCONTEXT_ALIGNMENT 64

struct ShadingContext
{
  /*! Data storage. Has to be at the beginning of the class due to alignment. */
  uniform int8 data[SHADINGCONTEXT_SIZE]; //!< Storage for BSDFs
  uniform uint32 size; //!< Number of bytes occupied in storage

  varying int dummy; // FIXME: needed to force correct alignment
};

inline void ShadingContext_Constructor(uniform ShadingContext *uniform self)
{
  self->size = 0;
}

/*! Allocates aligned data. */
inline void *uniform ShadingContext_alloc(
    uniform ShadingContext *uniform self, uniform uint32 size)
{
  // print("ShadingContext_alloc: %, %\n", this->size, size);
  void *uniform ptr = &self->data[self->size];
  self->size = (self->size + size + SHADINGCONTEXT_ALIGNMENT - 1)
      & ((uint32)(-SHADINGCONTEXT_ALIGNMENT));
#ifndef OSPRAY_TARGET_SYCL
  if (self->size > SHADINGCONTEXT_SIZE)
    postStatusMsg(ISPC_MSG_SHADING_CONTEXT, OSP_LOG_ERROR);
#endif
  return ptr;
}

inline varying linear3f *uniform LinearSpace3f_create(
    uniform ShadingContext *uniform ctx, const linear3f &l)
{
  varying linear3f *uniform ptr =
      (varying linear3f * uniform) ShadingContext_alloc(ctx, sizeof(linear3f));
  *ptr = l;
  return ptr;
}

OSPRAY_END_ISPC_NAMESPACE
