switch (GetNearestControlPoint(evt.GetPosition()))
   {
   case none:
      SetCursor(wxNullCursor);
      break;
   case innerFadeDown:
   case innerFadeUp:
   case outerFadeDown:
   case outerFadeUp:
      SetCursor(wxCursor(wxCURSOR_SIZEWE));
      break;
   case duckAmount:
      SetCursor(wxCursor(wxCURSOR_SIZENS));
      break;
   }

/**********************************************************************

  Audacity: A Digital Audio Editor

  AutoDuck.cpp

  Markus Meyer

*******************************************************************//**

\class EffectAutoDuck
\brief Implements the Auto Ducking effect

\class AutoDuckRegion
\brief a struct that holds a start and end time.

*******************************************************************/

#include "AutoDuck.h"
#include "LoadEffects.h"

#include <math.h>
#include <float.h>

#include <wx/dcclient.h>
#include <wx/dcmemory.h>
#include <wx/intl.h>

#include "../AColor.h"
#include "../AllThemeResources.h"
#include "../Prefs.h"
#include "../Shuttle.h"
#include "../ShuttleGui.h"
#include "../Theme.h"
#include "../widgets/valnum.h"

#include "../WaveTrack.h"
#include "../widgets/AudacityMessageBox.h"

// Define keys, defaults, minimums, and maximums for the effect parameters
//     Name                Type     Key                     Def      Min      Max      Scale
Param( DuckAmountDb,       double,  wxT("DuckAmountDb"),     -12.0,   -24.0,   0.0,     1  );
Param( InnerFadeDownLen,   double,  wxT("InnerFadeDownLen"), 0.0,     0.0,     3.0,     1  );
Param( InnerFadeUpLen,     double,  wxT("InnerFadeUpLen"),   0.0,     0.0,     3.0,     1  );
Param( OuterFadeDownLen,   double,  wxT("OuterFadeDownLen"), 0.5,     0.0,     3.0,     1  );
Param( OuterFadeUpLen,     double,  wxT("OuterFadeUpLen"),   0.5,     0.0,     3.0,     1  );
Param( ThresholdDb,        double,  wxT("ThresholdDb"),      -30.0,   -100.0,  0.0,     1  );
Param( MaximumPause,       double,  wxT("MaximumPause"),     1.0,     0.0,     DBL_MAX, 1  );

/*
 * Common constants
 */

static const size_t kBufSize = 131072u;     // number of samples to process at once
static const size_t kRMSWindowSize = 100u;  // samples in circular RMS window buffer

/*
 * A auto duck region and an array of auto duck regions
 */

struct AutoDuckRegion
{
   AutoDuckRegion(double t0, double t1)
   {
      this->t0 = t0;
      this->t1 = t1;
   }

   double t0;
   double t1;
};

/*
 * Effect implementation
 */

const ComponentInterfaceSymbol EffectAutoDuck::Symbol
{ XO("Auto Duck") };

namespace{ BuiltinEffectsModule::Registration< EffectAutoDuck > reg; }

BEGIN_EVENT_TABLE(EffectAutoDuck, wxEvtHandler)
   EVT_TEXT(wxID_ANY, EffectAutoDuck::OnValueChanged)
END_EVENT_TABLE()

EffectAutoDuck::EffectAutoDuck()
{
   mDuckAmountDb = DEF_DuckAmountDb;
   mInnerFadeDownLen = DEF_InnerFadeDownLen;
   mInnerFadeUpLen = DEF_InnerFadeUpLen;
   mOuterFadeDownLen = DEF_OuterFadeDownLen;
   mOuterFadeUpLen = DEF_OuterFadeUpLen;
   mThresholdDb = DEF_ThresholdDb;
   mMaximumPause = DEF_MaximumPause;

   SetLinearEffectFlag(true);

   mControlTrack = NULL;

   mPanel = NULL;
}

EffectAutoDuck::~EffectAutoDuck()
{
}

// ComponentInterface implementation

ComponentInterfaceSymbol EffectAutoDuck::GetSymbol()
{
   return Symbol;
}

TranslatableString EffectAutoDuck::GetDescription()
{
   return XO("Reduces (ducks) the volume of one or more tracks whenever the volume of a specified \"control\" track reaches a particular level");
}

ManualPageID EffectAutoDuck::ManualPage()
{
   return L"Auto_Duck";
}

// EffectDefinitionInterface implementation

EffectType EffectAutoDuck::GetType()
{
   return EffectTypeProcess;
}

// EffectClientInterface implementation
bool EffectAutoDuck::DefineParams( ShuttleParams & S ){
   S.SHUTTLE_PARAM(  mDuckAmountDb, DuckAmountDb);
   S.SHUTTLE_PARAM(  mInnerFadeDownLen, InnerFadeDownLen);
   S.SHUTTLE_PARAM(  mInnerFadeUpLen, InnerFadeUpLen);
   S.SHUTTLE_PARAM(  mOuterFadeDownLen, OuterFadeDownLen);
   S.SHUTTLE_PARAM(  mOuterFadeUpLen, OuterFadeUpLen);
   S.SHUTTLE_PARAM(  mThresholdDb, ThresholdDb);
   S.SHUTTLE_PARAM(  mMaximumPause, MaximumPause);
   return true;
}

bool EffectAutoDuck::GetAutomationParameters(CommandParameters & parms)
{
   parms.Write(KEY_DuckAmountDb, mDuckAmountDb);
   parms.Write(KEY_InnerFadeDownLen, mInnerFadeDownLen);
   parms.Write(KEY_InnerFadeUpLen, mInnerFadeUpLen);
   parms.Write(KEY_OuterFadeDownLen, mOuterFadeDownLen);
   parms.Write(KEY_OuterFadeUpLen, mOuterFadeUpLen);
   parms.Write(KEY_ThresholdDb, mThresholdDb);
   parms.Write(KEY_MaximumPause, mMaximumPause);

   return true;
}

bool EffectAutoDuck::SetAutomationParameters(CommandParameters & parms)
{
   ReadAndVerifyDouble(DuckAmountDb);
   ReadAndVerifyDouble(InnerFadeDownLen);
   ReadAndVerifyDouble(InnerFadeUpLen);
   ReadAndVerifyDouble(OuterFadeDownLen);
   ReadAndVerifyDouble(OuterFadeUpLen);
   ReadAndVerifyDouble(ThresholdDb);
   ReadAndVerifyDouble(MaximumPause);

   mDuckAmountDb = DuckAmountDb;
   mInnerFadeDownLen = InnerFadeDownLen;
   mInnerFadeUpLen = InnerFadeUpLen;
   mOuterFadeDownLen = OuterFadeDownLen;
   mOuterFadeUpLen = OuterFadeUpLen;
   mThresholdDb = ThresholdDb;
   mMaximumPause = MaximumPause;

   return true;
}

// Effect implementation

bool EffectAutoDuck::Startup()
{
   wxString base = wxT("/Effects/AutoDuck/");

   // Migrate settings from 2.1.0 or before

   // Already migrated, so bail
   if (gPrefs->Exists(base + wxT("Migrated")))
   {
      return true;
   }

   // Load the old "current" settings
   if (gPrefs->Exists(base))
   {
      gPrefs->Read(base + wxT("DuckAmountDb"), &mDuckAmountDb, DEF_DuckAmountDb);
      gPrefs->Read(base + wxT("InnerFadeDownLen"), &mInnerFadeDownLen, DEF_InnerFadeDownLen);
      gPrefs->Read(base + wxT("InnerFadeUpLen"), &mInnerFadeUpLen, DEF_InnerFadeUpLen);
      gPrefs->Read(base + wxT("OuterFadeDownLen"), &mOuterFadeDownLen, DEF_OuterFadeDownLen);
      gPrefs->Read(base + wxT("OuterFadeUpLen"), &mOuterFadeUpLen, DEF_OuterFadeUpLen);
      gPrefs->Read(base + wxT("ThresholdDb"), &mThresholdDb, DEF_ThresholdDb);
      gPrefs->Read(base + wxT("MaximumPause"), &mMaximumPause, DEF_MaximumPause);

      SaveUserPreset(GetCurrentSettingsGroup());

      // Do not migrate again
      gPrefs->Write(base + wxT("Migrated"), true);
      gPrefs->Flush();
   }

   return true;
}

bool EffectAutoDuck::Init()
{
   mControlTrack = NULL;

   bool lastWasSelectedWaveTrack = false;
   const WaveTrack *controlTrackCandidate = NULL;

   for (auto t : inputTracks()->Any())
   {
      if (lastWasSelectedWaveTrack && !t->GetSelected()) {
         // This could be the control track, so remember it
         controlTrackCandidate = track_cast<const WaveTrack *>(t);
      }

      lastWasSelectedWaveTrack = false;

      if (t->GetSelected()) {
         bool ok = t->TypeSwitch<bool>(
            [&](const WaveTrack *) {
               lastWasSelectedWaveTrack = true;
               return true;
            },
            [&](const Track *) {
               Effect::MessageBox(
                  /* i18n-hint: Auto duck is the name of an effect that 'ducks' (reduces the volume)
                   * of the audio automatically when there is sound on another track.  Not as
                   * in 'Donald-Duck'!*/
                  XO("You selected a track which does not contain audio. AutoDuck can only process audio tracks."),
                  wxICON_ERROR );
               return false;
            }
         );
         if (!ok)
            return false;
      }
   }

   if (!controlTrackCandidate)
   {
      Effect::MessageBox(
         /* i18n-hint: Auto duck is the name of an effect that 'ducks' (reduces the volume)
          * of the audio automatically when there is sound on another track.  Not as
          * in 'Donald-Duck'!*/
         XO("Auto Duck needs a control track which must be placed below the selected track(s)."),
         wxICON_ERROR );
      return false;
   }

   mControlTrack = controlTrackCandidate;

   return true;
}

void EffectAutoDuck::End()
{
   mControlTrack = NULL;
}

bool EffectAutoDuck::Process()
{
   if (GetNumWaveTracks() == 0 || !mControlTrack)
      return false;

   bool cancel = false;

   auto start =
      mControlTrack->TimeToLongSamples(mT0 + mOuterFadeDownLen);
   auto end =
      mControlTrack->TimeToLongSamples(mT1 - mOuterFadeUpLen);

   if (end <= start)
      return false;

   // the minimum number of samples we have to wait until the maximum
   // pause has been exceeded
   double maxPause = mMaximumPause;

   // We don't fade in until we have time enough to actually fade out again
   if (maxPause < mOuterFadeDownLen + mOuterFadeUpLen)
      maxPause = mOuterFadeDownLen + mOuterFadeUpLen;

   auto minSamplesPause =
      mControlTrack->TimeToLongSamples(maxPause);

   double threshold = DB_TO_LINEAR(mThresholdDb);

   // adjust the threshold so we can compare it to the rmsSum value
   threshold = threshold * threshold * kRMSWindowSize;

   int rmsPos = 0;
   float rmsSum = 0;
   // to make the progress bar appear more natural, we first look for all
   // duck regions and apply them all at once afterwards
   std::vector<AutoDuckRegion> regions;
   bool inDuckRegion = false;
   {
      Floats rmsWindow{ kRMSWindowSize, true };

      Floats buf{ kBufSize };

      // initialize the following two variables to prevent compiler warning
      double duckRegionStart = 0;
      sampleCount curSamplesPause = 0;

      auto pos = start;

      while (pos < end)
      {
         const auto len = limitSampleBufferSize( kBufSize, end - pos );

         mControlTrack->GetFloats(buf.get(), pos, len);

         for (auto i = pos; i < pos + len; i++)
         {
            rmsSum -= rmsWindow[rmsPos];
            // i - pos is bounded by len:
            auto index = ( i - pos ).as_size_t();
            rmsWindow[rmsPos] = buf[ index ] * buf[ index ];
            rmsSum += rmsWindow[rmsPos];
            rmsPos = (rmsPos + 1) % kRMSWindowSize;

            bool thresholdExceeded = rmsSum > threshold;

            if (thresholdExceeded)
            {
               // everytime the threshold is exceeded, reset our count for
               // the number of pause samples
               curSamplesPause = 0;

               if (!inDuckRegion)
               {
                  // the threshold has been exceeded for the first time, so
                  // let the duck region begin here
                  inDuckRegion = true;
                  duckRegionStart = mControlTrack->LongSamplesToTime(i);
               }
            }

            if (!thresholdExceeded && inDuckRegion)
            {
               // the threshold has not been exceeded and we are in a duck
               // region, but only fade in if the maximum pause has been
               // exceeded
               curSamplesPause += 1;

               if (curSamplesPause >= minSamplesPause)
               {
                  // do the actual duck fade and reset all values
                  double duckRegionEnd =
                     mControlTrack->LongSamplesToTime(i - curSamplesPause);

                  regions.push_back(AutoDuckRegion(
                     duckRegionStart - mOuterFadeDownLen,
                     duckRegionEnd + mOuterFadeUpLen));

                  inDuckRegion = false;
               }
            }
         }

         pos += len;

         if (TotalProgress(
            (pos - start).as_double() /
            (end - start).as_double() /
            (GetNumWaveTracks() + 1)
         ))
         {
            cancel = true;
            break;
         }
      }

      // apply last duck fade, if any
      if (inDuckRegion)
      {
         double duckRegionEnd =
            mControlTrack->LongSamplesToTime(end - curSamplesPause);
         regions.push_back(AutoDuckRegion(
            duckRegionStart - mOuterFadeDownLen,
            duckRegionEnd + mOuterFadeUpLen));
      }
   }

   if (!cancel)
   {
      CopyInputTracks(); // Set up mOutputTracks.

      int trackNum = 0;

      for( auto iterTrack : mOutputTracks->Selected< WaveTrack >() )
      {
         for (size_t i = 0; i < regions.size(); i++)
         {
            const AutoDuckRegion& region = regions[i];
            if (ApplyDuckFade(trackNum, iterTrack, region.t0, region.t1))
            {
               cancel = true;
               break;
            }
         }

         if (cancel)
            break;

         trackNum++;
      }
   }

   ReplaceProcessedTracks(!cancel);
   return !cancel;
}

void EffectAutoDuck::PopulateOrExchange(ShuttleGui & S)
{
   S.SetBorder(5);
   S.StartVerticalLay(true);
   {
      S.AddSpace(0, 5);

      mPanel = safenew EffectAutoDuckPanel(S.GetParent(), wxID_ANY, this);
      S.AddWindow(mPanel);

      S.AddSpace(0, 5);

      S.StartMultiColumn(6, wxCENTER);
      {
         mDuckAmountDbBox = S.Validator<FloatingPointValidator<double>>(
               1, &mDuckAmountDb, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_DuckAmountDb, MAX_DuckAmountDb
            )
            .NameSuffix(XO("db"))
            .AddTextBox(XXO("Duck &amount:"), wxT(""), 10);
         S.AddUnits(XO("dB"));

         mMaximumPauseBox = S.Validator<FloatingPointValidator<double>>(
               2, &mMaximumPause, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_MaximumPause, MAX_MaximumPause
            )
            .NameSuffix(XO("seconds"))
            .AddTextBox(XXO("Ma&ximum pause:"), wxT(""), 10);
         S.AddUnits(XO("seconds"));

         mOuterFadeDownLenBox = S.Validator<FloatingPointValidator<double>>(
               2, &mOuterFadeDownLen, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_OuterFadeDownLen, MAX_OuterFadeDownLen
            )
            .NameSuffix(XO("seconds"))
            .AddTextBox(XXO("Outer fade &down length:"), wxT(""), 10);
         S.AddUnits(XO("seconds"));

         mOuterFadeUpLenBox = S.Validator<FloatingPointValidator<double>>(
               2, &mOuterFadeUpLen, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_OuterFadeUpLen, MAX_OuterFadeUpLen
            )
            .NameSuffix(XO("seconds"))
            .AddTextBox(XXO("Outer fade &up length:"), wxT(""), 10);
         S.AddUnits(XO("seconds"));

         mInnerFadeDownLenBox = S.Validator<FloatingPointValidator<double>>(
               2, &mInnerFadeDownLen, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_InnerFadeDownLen, MAX_InnerFadeDownLen
            )
            .NameSuffix(XO("seconds"))
            .AddTextBox(XXO("Inner fade d&own length:"), wxT(""), 10);
         S.AddUnits(XO("seconds"));

         mInnerFadeUpLenBox = S.Validator<FloatingPointValidator<double>>(
               2, &mInnerFadeUpLen, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_InnerFadeUpLen, MAX_InnerFadeUpLen
            )
            .NameSuffix(XO("seconds"))
            .AddTextBox(XXO("Inner &fade up length:"), wxT(""), 10);
         S.AddUnits(XO("seconds"));
      }
      S.EndMultiColumn();

      S.StartMultiColumn(3, wxCENTER);
      {
         mThresholdDbBox = S.Validator<FloatingPointValidator<double>>(
               2, &mThresholdDb, NumValidatorStyle::NO_TRAILING_ZEROES,
               MIN_ThresholdDb, MAX_ThresholdDb
            )
            .NameSuffix(XO("db"))
            .AddTextBox(XXO("&Threshold:"), wxT(""), 10);
         S.AddUnits(XO("dB"));
      }
      S.EndMultiColumn();

   }
   S.EndVerticalLay();

   return;
}

bool EffectAutoDuck::TransferDataToWindow()
{
   if (!mUIParent->TransferDataToWindow())
   {
      return false;
   }

   mPanel->Refresh(false);

   return true;
}

bool EffectAutoDuck::TransferDataFromWindow()
{
   if (!mUIParent->Validate() || !mUIParent->TransferDataFromWindow())
   {
      return false;
   }

   return true;
}

// EffectAutoDuck implementation

// this currently does an exponential fade
bool EffectAutoDuck::ApplyDuckFade(int trackNum, WaveTrack* t,
                                   double t0, double t1)
{
   bool cancel = false;

   auto start = t->TimeToLongSamples(t0);
   auto end = t->TimeToLongSamples(t1);

   Floats buf{ kBufSize };
   auto pos = start;

   auto fadeDownSamples = t->TimeToLongSamples(
      mOuterFadeDownLen + mInnerFadeDownLen);
   if (fadeDownSamples < 1)
      fadeDownSamples = 1;

   auto fadeUpSamples = t->TimeToLongSamples(
      mOuterFadeUpLen + mInnerFadeUpLen);
   if (fadeUpSamples < 1)
      fadeUpSamples = 1;

   float fadeDownStep = mDuckAmountDb / fadeDownSamples.as_double();
   float fadeUpStep = mDuckAmountDb / fadeUpSamples.as_double();

   while (pos < end)
   {
      const auto len = limitSampleBufferSize( kBufSize, end - pos );

      t->GetFloats(buf.get(), pos, len);

      for (auto i = pos; i < pos + len; i++)
      {
         float gainDown = fadeDownStep * (i - start).as_float();
         float gainUp = fadeUpStep * (end - i).as_float();

         float gain;
         if (gainDown > gainUp)
            gain = gainDown;
         else
            gain = gainUp;
         if (gain < mDuckAmountDb)
            gain = mDuckAmountDb;

         // i - pos is bounded by len:
         buf[ ( i - pos ).as_size_t() ] *= DB_TO_LINEAR(gain);
      }

      t->Set((samplePtr)buf.get(), floatSample, pos, len);

      pos += len;

      float curTime = t->LongSamplesToTime(pos);
      float fractionFinished = (curTime - mT0) / (mT1 - mT0);
      if (TotalProgress( (trackNum + 1 + fractionFinished) /
                         (GetNumWaveTracks() + 1) ))
      {
         cancel = true;
         break;
      }
   }

   return cancel;
}

void EffectAutoDuck::OnValueChanged(wxCommandEvent & WXUNUSED(evt))
{
   mPanel->Refresh(false);
}

/*
 * EffectAutoDuckPanel implementation
 */

#define CONTROL_POINT_REGION 10 // pixel distance to click on a control point
#define CONTROL_POINT_MIN_MOVE 5 // min mouse move until value is changed

#define TEXT_DISTANCE 15 // pixel distance text <-> center of control point

#define FADE_DOWN_START 150 // x coordinate
#define FADE_UP_START 450 // x coordinate
#define DUCK_AMOUNT_START 50 // y coordinate

#define FADE_SCALE 40 // scale factor for second -> pixel conversion
#define DUCK_AMOUNT_SCALE 8 // scale factor for db -> pixel conversion

static int GetDistance(const wxPoint& first, const wxPoint& second)
{
   int distanceX = abs(first.x - second.x);
   int distanceY = abs(first.y - second.y);
   if (distanceX > distanceY)
      return distanceX;
   else
      return distanceY;
}

BEGIN_EVENT_TABLE(EffectAutoDuckPanel, wxPanelWrapper)
   EVT_PAINT(EffectAutoDuckPanel::OnPaint)
   EVT_MOUSE_CAPTURE_CHANGED(EffectAutoDuckPanel::OnMouseCaptureChanged)
   EVT_MOUSE_CAPTURE_LOST(EffectAutoDuckPanel::OnMouseCaptureLost)
   EVT_LEFT_DOWN(EffectAutoDuckPanel::OnLeftDown)
   EVT_LEFT_UP(EffectAutoDuckPanel::OnLeftUp)
   EVT_MOTION(EffectAutoDuckPanel::OnMotion)
END_EVENT_TABLE()

EffectAutoDuckPanel::EffectAutoDuckPanel(
   wxWindow *parent, wxWindowID winid, EffectAutoDuck *effect)
:  wxPanelWrapper(parent, winid, wxDefaultPosition, wxSize(600, 300))
{
   mParent = parent;
   mEffect = effect;
   mCurrentControlPoint = none;
   mBackgroundBitmap = NULL;

   ResetControlPoints();
}

EffectAutoDuckPanel::~EffectAutoDuckPanel()
{
   if(HasCapture())
      ReleaseMouse();
}

void EffectAutoDuckPanel::ResetControlPoints()
{
   mControlPoints[innerFadeDown] = wxPoint(-100,-100);
   mControlPoints[innerFadeUp] = wxPoint(-100,-100);
   mControlPoints[outerFadeDown] = wxPoint(-100,-100);
   mControlPoints[outerFadeUp] = wxPoint(-100,-100);
   mControlPoints[duckAmount] = wxPoint(-100,-100);
}

void EffectAutoDuckPanel::OnPaint(wxPaintEvent & WXUNUSED(evt))
{
   int clientWidth, clientHeight;
   GetSize(&clientWidth, &clientHeight);

   if (!mBackgroundBitmap || mBackgroundBitmap->GetWidth() != clientWidth ||
       mBackgroundBitmap->GetHeight() != clientHeight)
   {
      mBackgroundBitmap = std::make_unique<wxBitmap>(clientWidth, clientHeight,24);
   }

   wxMemoryDC dc;
   dc.SelectObject(*mBackgroundBitmap);

   dc.SetBrush(*wxWHITE_BRUSH);
   dc.SetPen(*wxBLACK_PEN);
   dc.DrawRectangle(0, 0, clientWidth, clientHeight);

   dc.SetFont(wxFont(10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL,
                     wxFONTWEIGHT_NORMAL));
   dc.SetTextForeground(*wxBLACK);
   dc.SetTextBackground(*wxWHITE);

   double duckAmountDb = 0;
   double innerFadeDownLen = 0;
   double innerFadeUpLen = 0;
   double outerFadeDownLen = 0;
   double outerFadeUpLen = 0;
   mEffect->mDuckAmountDbBox->GetValue().ToDouble(&duckAmountDb);
   mEffect->mInnerFadeDownLenBox->GetValue().ToDouble(&innerFadeDownLen);
   mEffect->mInnerFadeUpLenBox->GetValue().ToDouble(&innerFadeUpLen);
   mEffect->mOuterFadeDownLenBox->GetValue().ToDouble(&outerFadeDownLen);
   mEffect->mOuterFadeUpLenBox->GetValue().ToDouble(&outerFadeUpLen);

   if (innerFadeDownLen < MIN_InnerFadeDownLen || innerFadeDownLen > MAX_InnerFadeDownLen ||
       innerFadeUpLen < MIN_InnerFadeUpLen     || innerFadeUpLen > MAX_InnerFadeUpLen     ||
       outerFadeDownLen < MIN_OuterFadeDownLen || outerFadeDownLen > MAX_OuterFadeDownLen ||
       outerFadeUpLen < MIN_OuterFadeUpLen     || outerFadeUpLen > MAX_OuterFadeUpLen     ||
       duckAmountDb < MIN_DuckAmountDb         || duckAmountDb > MAX_DuckAmountDb)
   {
      // values are out of range, no preview available
      wxString message = _("Preview not available");
      int textWidth = 0, textHeight = 0;
      dc.GetTextExtent(message, &textWidth, &textHeight);
      dc.DrawText(message, (clientWidth - textWidth) / 2,
                           (clientHeight - textHeight) / 2);

      ResetControlPoints();
   } else
   {
      // draw preview
      dc.SetBrush(*wxTRANSPARENT_BRUSH);
      dc.SetPen(wxPen(theTheme.Colour(clrGraphLines), 3, wxPENSTYLE_SOLID));

      wxPoint points[6];

      points[0].x = 10;
      points[0].y = DUCK_AMOUNT_START;

      points[1].x = FADE_DOWN_START - (int)(outerFadeDownLen * FADE_SCALE);
      points[1].y = DUCK_AMOUNT_START;

      points[2].x = FADE_DOWN_START + (int)(innerFadeDownLen * FADE_SCALE);
      points[2].y = DUCK_AMOUNT_START -
         (int)(duckAmountDb * DUCK_AMOUNT_SCALE);

      points[3].x = FADE_UP_START - (int)(innerFadeUpLen * FADE_SCALE);
      points[3].y = DUCK_AMOUNT_START -
         (int)(duckAmountDb * DUCK_AMOUNT_SCALE);

      points[4].x = FADE_UP_START + (int)(outerFadeUpLen * FADE_SCALE);
      points[4].y = DUCK_AMOUNT_START;

      points[5].x = clientWidth - 10;
      points[5].y = DUCK_AMOUNT_START;

      AColor::Lines(dc, 6, points);

      dc.SetPen(wxPen(*wxBLACK, 1, wxPENSTYLE_DOT));

      AColor::Line(dc, FADE_DOWN_START, 10, FADE_DOWN_START, clientHeight - 10);
      AColor::Line(dc, FADE_UP_START, 10, FADE_UP_START, clientHeight - 10);

      dc.SetPen(AColor::envelopePen);
      dc.SetBrush(*wxWHITE_BRUSH);

      mControlPoints[outerFadeDown] = points[1];
      mControlPoints[innerFadeDown] = points[2];
      mControlPoints[innerFadeUp] = points[3];
      mControlPoints[outerFadeUp] = points[4];
      mControlPoints[duckAmount] = wxPoint(
         (points[2].x + points[3].x) / 2, points[2].y);

      for (int i = 0; i < AUTO_DUCK_PANEL_NUM_CONTROL_POINTS; i++)
      {
         EControlPoint cp = (EControlPoint)i;
         int digits;
         float value;

         if (cp == innerFadeDown)
         {
            value = innerFadeDownLen;
            digits = 2;
         }
         else if (cp == innerFadeUp)
         {
            value = innerFadeUpLen;
            digits = 2;
         }
         else if (cp == outerFadeDown)
         {
            value = outerFadeDownLen;
            digits = 2;
         } else if (cp == outerFadeUp)
         {
            value = outerFadeUpLen;
            digits = 2;
         }
         else
         {
            value = duckAmountDb;
            digits = 1;
         }

         wxString valueStr = Internat::ToDisplayString(value, digits);
         valueStr += wxT(" ");

         if (cp == duckAmount)
            /* i18n-hint: short form of 'decibels'.*/
            valueStr += _("dB");
         else
            /* i18n-hint: short form of 'seconds'.*/
            valueStr += _("s");

         int textWidth = 0, textHeight = 0;
         GetTextExtent(valueStr, &textWidth, &textHeight);

         int textPosX = mControlPoints[i].x - textWidth / 2;
         int textPosY = mControlPoints[i].y;

         if (cp == duckAmount || cp == outerFadeDown || cp == outerFadeUp)
            textPosY -= TEXT_DISTANCE + textHeight;
         else
            textPosY += TEXT_DISTANCE;

         dc.DrawText(valueStr, textPosX, textPosY);

         dc.DrawEllipse(mControlPoints[i].x - 3,
                        mControlPoints[i].y - 3, 6, 6);
      }
   }

   // copy background buffer to paint dc
   wxPaintDC paintDC(this);
   paintDC.Blit(0, 0, clientWidth, clientHeight, &dc, 0, 0);

   // clean up: necessary to free resources on Windows
   dc.SetPen(wxNullPen);
   dc.SetBrush(wxNullBrush);
   dc.SetFont(wxNullFont);
   dc.SelectObject(wxNullBitmap);
}

void EffectAutoDuckPanel::OnMouseCaptureChanged(
   wxMouseCaptureChangedEvent & WXUNUSED(evt))
{
   SetCursor(wxNullCursor);
   mCurrentControlPoint = none;
}

void EffectAutoDuckPanel::OnMouseCaptureLost(
   wxMouseCaptureLostEvent & WXUNUSED(evt))
{
   mCurrentControlPoint = none;

   if (HasCapture())
   {
      ReleaseMouse();
   }
}

EffectAutoDuckPanel::EControlPoint
   EffectAutoDuckPanel::GetNearestControlPoint(const wxPoint & pt)
{
   int dist[AUTO_DUCK_PANEL_NUM_CONTROL_POINTS];
   int i;

   for (i = 0; i < AUTO_DUCK_PANEL_NUM_CONTROL_POINTS; i++)
      dist[i] = GetDistance(pt, mControlPoints[i]);

   int curMinimum = 0;
   for (i = 0; i < AUTO_DUCK_PANEL_NUM_CONTROL_POINTS; i++)
      if (dist[i] < dist[curMinimum])
         curMinimum = i;

   if (dist[curMinimum] <= CONTROL_POINT_REGION)
      return (EControlPoint)curMinimum;
   else
      return none;
}

void EffectAutoDuckPanel::OnLeftDown(wxMouseEvent & evt)
{
   EControlPoint nearest = GetNearestControlPoint(evt.GetPosition());

   if (nearest != none)
   {
      // this control point has been clicked
      mMouseDownPoint = evt.GetPosition();

      mCurrentControlPoint = nearest;
      mControlPointMoveActivated = false;

      for (int i = 0; i < AUTO_DUCK_PANEL_NUM_CONTROL_POINTS; i++)
         mMoveStartControlPoints[i] = mControlPoints[i];

      if( !HasCapture() )
         CaptureMouse();
   }
}

void EffectAutoDuckPanel::OnLeftUp(wxMouseEvent & WXUNUSED(evt))
{
   if (mCurrentControlPoint != none)
   {
      mCurrentControlPoint = none;
      ReleaseMouse();
   }
}

void EffectAutoDuckPanel::OnMotion(wxMouseEvent & evt)
{

   if (mCurrentControlPoint != none)
   {
      if (!mControlPointMoveActivated)
      {
         int dist;

         if (mCurrentControlPoint == duckAmount)
            dist = abs(evt.GetY() - mMouseDownPoint.y);
         else
            dist = abs(evt.GetX() - mMouseDownPoint.x);

         if (dist >= CONTROL_POINT_MIN_MOVE)
            mControlPointMoveActivated = true;
      }

      if (mControlPointMoveActivated)
      {
         float newValue;

         switch (mCurrentControlPoint)
         {
         case outerFadeDown:
            newValue = ((double)(FADE_DOWN_START - evt.GetX())) / FADE_SCALE;
            mEffect->mOuterFadeDownLen = TrapDouble(newValue, MIN_OuterFadeDownLen, MAX_OuterFadeDownLen);
            break;
         case outerFadeUp:
            newValue = ((double)(evt.GetX() - FADE_UP_START)) / FADE_SCALE;
            mEffect->mOuterFadeUpLen = TrapDouble(newValue, MIN_OuterFadeUpLen, MAX_OuterFadeUpLen);
            break;
         case innerFadeDown:
            newValue = ((double)(evt.GetX() - FADE_DOWN_START)) / FADE_SCALE;
            mEffect->mInnerFadeDownLen = TrapDouble(newValue, MIN_InnerFadeDownLen, MAX_InnerFadeDownLen);
            break;
         case innerFadeUp:
            newValue = ((double)(FADE_UP_START - evt.GetX())) / FADE_SCALE;
            mEffect->mInnerFadeUpLen = TrapDouble(newValue, MIN_InnerFadeUpLen, MAX_InnerFadeUpLen);
            break;
         case duckAmount:
            newValue = ((double)(DUCK_AMOUNT_START - evt.GetY())) / DUCK_AMOUNT_SCALE;
            mEffect->mDuckAmountDb = TrapDouble(newValue, MIN_DuckAmountDb, MAX_DuckAmountDb);
            break;
         case none:
            wxASSERT(false); // should not happen
         }
         mEffect->TransferDataToWindow();
         Refresh(false);
      }
   }
}


int EntityData::get_integer(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::INTEGER,
      "Field '" + key + "' is not a string");

  return it->second.int_value;
}

/*
 *
 */
#include "solarus/core/Debug.h"
#include "solarus/entities/EntityData.h"
#include "solarus/entities/EntityTypeInfo.h"
#include "solarus/lua/LuaTools.h"
#include <ostream>

namespace Solarus {

namespace {

using EntityTypeDescription = EntityData::EntityTypeDescription;
using OptionalFlag = EntityData::OptionalFlag;
using FieldValue = EntityData::FieldValue;

/**
 * \brief Definition of the format of entity types in map data files and Lua API.
 */
const std::map<EntityType, const EntityTypeDescription> entity_type_descriptions = {

    {
        EntityType::TILE, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "pattern", OptionalFlag::MANDATORY, FieldValue("") },
            { "tileset", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::DYNAMIC_TILE, {
            { "pattern", OptionalFlag::MANDATORY, FieldValue("") },
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "enabled_at_start", OptionalFlag::MANDATORY, FieldValue(true) },
            { "tileset", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::TELETRANSPORTER, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "transition", OptionalFlag::OPTIONAL, FieldValue("fade") },
            { "destination_map", OptionalFlag::MANDATORY, FieldValue("") },
            { "destination", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sound", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::DESTINATION, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(1) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "starting_location_mode", OptionalFlag::OPTIONAL, FieldValue("when_world_changes") },
            { "default", OptionalFlag::OPTIONAL, FieldValue(false) }
        }
    },

    {
        EntityType::PICKABLE, {
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::DESTRUCTIBLE, {
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("") },
            { "destruction_sound", OptionalFlag::OPTIONAL, FieldValue("") },
            { "weight", OptionalFlag::OPTIONAL, FieldValue(0) },
            { "can_be_cut", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "can_explode", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "can_regenerate", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "damage_on_enemies", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "ground", OptionalFlag::OPTIONAL, FieldValue("wall") }
        }
    },

    {
        EntityType::CHEST, {
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("entities/chest") },
            { "opening_method", OptionalFlag::OPTIONAL, FieldValue("interaction") },
            { "opening_condition", OptionalFlag::OPTIONAL, FieldValue("") },
            { "opening_condition_consumed", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "cannot_open_dialog", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::SHOP_TREASURE, {
            { "treasure_name", OptionalFlag::MANDATORY, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "price", OptionalFlag::MANDATORY, FieldValue(0) },
            { "font", OptionalFlag::OPTIONAL, FieldValue("") },
            { "dialog", OptionalFlag::MANDATORY, FieldValue("") }
        }
    },

    {
        EntityType::ENEMY, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(0) },
            { "breed", OptionalFlag::MANDATORY, FieldValue("") },
            { "rank", OptionalFlag::OPTIONAL, FieldValue(0) },
            { "savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::NPC, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(3) },
            { "subtype", OptionalFlag::MANDATORY, FieldValue(1) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "behavior", OptionalFlag::OPTIONAL, FieldValue("map") },
        }
    },

    {
        EntityType::BLOCK, {
            { "direction", OptionalFlag::OPTIONAL, FieldValue(-1) },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("entities/block") },
            { "pushable", OptionalFlag::MANDATORY, FieldValue(true) },
            { "pullable", OptionalFlag::MANDATORY, FieldValue(false) },
            { "maximum_moves", OptionalFlag::MANDATORY, FieldValue(1) },
        }
    },

    {
        EntityType::JUMPER, {
            { "width", OptionalFlag::MANDATORY, FieldValue(32) },
            { "height", OptionalFlag::MANDATORY, FieldValue(8) },
            { "direction", OptionalFlag::MANDATORY, FieldValue(6) },
            { "jump_length", OptionalFlag::MANDATORY, FieldValue(40) }
        }
    },

    {
        EntityType::SWITCH, {
            { "subtype", OptionalFlag::MANDATORY, FieldValue("walkable") },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sound", OptionalFlag::OPTIONAL, FieldValue("") },
            { "needs_block", OptionalFlag::MANDATORY, FieldValue(false) },
            { "inactivate_when_leaving", OptionalFlag::MANDATORY, FieldValue(false) },
        }
    },

    {
        EntityType::SENSOR, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
        }
    },

    {
        EntityType::WALL, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "stops_hero", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_npcs", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_enemies", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_blocks", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_projectiles", OptionalFlag::OPTIONAL, FieldValue(false) },
        }
    },

    {
        EntityType::CRYSTAL, {
            // No additional fields.
        }
    },

    {
        EntityType::CRYSTAL_BLOCK, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "subtype", OptionalFlag::MANDATORY, FieldValue(0) },
        }
    },

    {
        EntityType::STREAM, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(6) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "speed", OptionalFlag::OPTIONAL, FieldValue(64) },
            { "allow_movement", OptionalFlag::OPTIONAL, FieldValue(true) },
            { "allow_attack", OptionalFlag::OPTIONAL, FieldValue(true) },
            { "allow_item", OptionalFlag::OPTIONAL, FieldValue(true) },
        }
    },

    {
        EntityType::DOOR, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(3) },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("") },
            { "savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "opening_method", OptionalFlag::OPTIONAL, FieldValue("none") },
            { "opening_condition", OptionalFlag::OPTIONAL, FieldValue("") },
            { "opening_condition_consumed", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "cannot_open_dialog", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::STAIRS, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(1) },
            { "subtype", OptionalFlag::MANDATORY, FieldValue(0) },
        }
    },

    {
        EntityType::SEPARATOR, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
        }
    },

    {
        EntityType::CUSTOM, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "direction", OptionalFlag::MANDATORY, FieldValue(0) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "model", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::EXPLOSION, {
            // No additional fields.
        }
    },

    {
        EntityType::BOMB, {
            // No additional fields.
        }
    },

    {
        EntityType::FIRE, {
            // No additional fields.
        }
    }
};

/**
 * \brief Implementation of all entity data creation functions.
 * \param l The Lua context that is calling this function.
 * \return Number of values to return to Lua.
 */
int l_create_entity_data(lua_State* l) {

  return LuaTools::exception_boundary_handle(l, [&] {

    // Retrieve the entity data instance to build.
    lua_getfield(l, LUA_REGISTRYINDEX, "entity");
    EntityData& entity = *static_cast<EntityData*>(lua_touserdata(l, -1));
    lua_pop(l, 1);

    // Get the type of entity, it should have been passed as an upvalue.
    EntityType type = LuaTools::check_enum<EntityType>(
        l, lua_upvalueindex(1)
    );

    entity = EntityData::check_entity_data(l, 1, type);

    return 0;
  });
}

}  // Anonymous namespace.

/**
 * \brief Creates a nil value.
 */
FieldValue::FieldValue():
    value_type(EntityFieldType::NIL),
    string_value(),
    int_value(0) {

}

/**
 * \brief Creates a value of type string.
 * \param value The value.
 */
FieldValue::FieldValue(const std::string& value):
    value_type(EntityFieldType::STRING),
    string_value(value),
    int_value(0) {

}

/**
 * \brief Creates a value of type string.
 *
 * This overload makes sure that string literal parameters
 * won't get converted to bool.
 *
 * \param value The value.
 */
FieldValue::FieldValue(const char* value):
    FieldValue(std::string(value)) {

}

/**
 * \brief Creates a value of type integer.
 * \param value The value.
 */
FieldValue::FieldValue(int value):
    value_type(EntityFieldType::INTEGER),
    string_value(),
    int_value(value) {

}

/**
 * \brief Creates a value of type boolean.
 * \param value The value.
 */
FieldValue::FieldValue(bool value):
    value_type(EntityFieldType::BOOLEAN),
    string_value(),
    int_value(value ? 1 : 0) {

}

/**
 * \brief Returns whether two values are equal.
 */
bool FieldValue::operator==(const FieldValue& other) const {

  return value_type == other.value_type &&
      string_value == other.string_value &&
      int_value == other.int_value;
}

/**
 * \brief Returns whether two values are different.
 */
bool FieldValue::operator!=(const FieldValue& other) const {

  return !(*this == other);
}

/**
 * \brief Creates data for an entity of a default-constructed type.
 */
EntityData::EntityData() :
    type(),
    name(),
    layer(0),
    xy(),
    user_properties() ,
    specific_properties() {

  initialize_specific_properties();
}

/**
 * \brief Creates data for an entity of the given type.
 * \param type A type of entity.
 */
EntityData::EntityData(EntityType type) :
    type(type),
    name(),
    layer(0),
    xy(),
    user_properties(),
    specific_properties() {

  initialize_specific_properties();
}

/**
 * \brief Returns the type of entity.
 * \return The type of entity.
 */
EntityType EntityData::get_type() const {
  return type;
}

/**
 * \brief Sets the type of this entity.
 *
 * When the type changes, all fields are reset to their default value.
 *
 * \param type The new type.
 */
void EntityData::set_type(EntityType type) {

  if (type == this->type) {
    return;
  }

  this->type = type;
  initialize_specific_properties();
}

/**
 * \brief Returns whether this entity is a dynamic one.
 * \return \c true if this is a dynamic entity, \c false if this is a tile.
 */
bool EntityData::is_dynamic() const {
  return type != EntityType::TILE;
}

/**
 * \brief Returns the name of the type of entity.
 * \return The type name of entity.
 */
const std::string& EntityData::get_type_name() const {
  return enum_to_name(get_type());
}

/**
 * \brief Returns whether the entity has a name.
 */
bool EntityData::has_name() const {
  return !name.empty();
}

/**
 * \brief Returns the name of this entity.
 * \return The entity name or an empty string.
 */
std::string EntityData::get_name() const {
  return name;
}

/**
 * \brief Changes the name of this entity.
 * \param name The entity name or an empty string.
 */
void EntityData::set_name(const std::string& name) {
  this->name = name;
}

/**
 * \brief Returns the layer of this entity on the map.
 * \return The layer.
 */
int EntityData::get_layer() const {
  return layer;
}

/**
 * \brief Sets the layer of this entity on the map.
 * \param layer The layer.
 */
void EntityData::set_layer(int layer) {
  this->layer = layer;
}

/**
 * \brief Returns the coordinates of this entity on the map.
 * \return The coordinates of the entity.
 */
Point EntityData::get_xy() const {
  return xy;
}

/**
 * \brief Sets the coordinates of this entity on the map.
 * \param xy The coordinates of the entity.
 */
void EntityData::set_xy(const Point& xy) {
  this->xy = xy;
}

/**
 * \brief Returns whether a string is a valid key for a user property.
 *
 * It should only contain alphanumeric characters or '_' and
 * not start with a digit.
 *
 * \param key The string to check.
 * \return \c true if this is a valid user property key.
 */
bool EntityData::is_user_property_key_valid(const std::string& key) {

  // Same rules as Lua identifiers.
  return LuaTools::is_valid_lua_identifier(key);
}

/**
 * \brief Returns the user-defined properties of this entity.
 * \return The user-defined properties.
 */
const std::vector<EntityData::UserProperty>& EntityData::get_user_properties() const {
  return user_properties;
}

/**
 * \brief Returns the number of user-defined properties of this entity.
 * \return The number of user-defined properties.
 */
int EntityData::get_user_property_count() const {
  return static_cast<int>(user_properties.size());
}

/**
 * \brief Returns the user property at the given index.
 * \param index An index between \c 0 and <tt>get_user_property_count() - 1</tt>.
 * \return The user property at this index.
 */
const EntityData::UserProperty& EntityData::get_user_property(int index) const {

  Debug::check_assertion(index >= 0 && index < get_user_property_count(),
      "Invalid user property index");
  return user_properties.at(index);
}

/**
 * \brief Sets the user property at the given index.
 * \param index An index between \c 0 and <tt>get_user_property_count() - 1</tt>.
 * \param user_property The new key and value to set.
 */
void EntityData::set_user_property(int index, const UserProperty& user_property) {

  Debug::check_assertion(index >= 0 && index < get_user_property_count(),
      "Invalid user property index");

  Debug::check_assertion(is_user_property_key_valid(user_property.first),
      "Invalid user property key");

  int existing_index = get_user_property_index(user_property.first);
  Debug::check_assertion(existing_index == -1 || existing_index == index,
      "This user property already exists");

  user_properties[index] = user_property;
}

/**
 * \brief Sets all user-defined properties.
 * \param user_properties The properties to set. Keys must be unique.
 */
void EntityData::set_user_properties(const std::vector<UserProperty>& user_properties) {

  for (const UserProperty& user_property : user_properties) {
    Debug::check_assertion(is_user_property_key_valid(user_property.first),
        "Invalid user property key");
  }

  this->user_properties = user_properties;
}

/**
 * \brief Adds a user property.
 *
 * The key of the property should not already exist.
 *
 * \param user_property The new key and value to add.
 */
void EntityData::add_user_property(const UserProperty& user_property) {

  Debug::check_assertion(is_user_property_key_valid(user_property.first),
      "Invalid user property key");

  Debug::check_assertion(!has_user_property(user_property.first),
      "This user property already exists");

  user_properties.emplace_back(user_property);
}

/**
 * \brief Returns a user property.
 * \param index An index between \c 0 and <tt>get_user_property_count() - 1</tt>.
 */
void EntityData::remove_user_property(int index) {

  Debug::check_assertion(index >= 0 && index < get_user_property_count(),
      "Invalid user property index");

  user_properties.erase(user_properties.begin() + index);
}

/**
 * \brief Returns the index of a user property in the user property list.
 * \param key Key of the property to get.
 * \return The corresponding index, or -1 if there is no such property.
 */
int EntityData::get_user_property_index(const std::string& key) const {

  int index = 0;
  for (const UserProperty& user_property : user_properties) {
    if (user_property.first == key) {
      return index;
    }
    ++index;
  }
  return -1;
}

/**
 * \brief Returns whether a user property exists with the given key.
 * \param key Key of the property to get.
 * \return \c true if the entity has such a property.
 */
bool EntityData::has_user_property(const std::string& key) const {
  return get_user_property_index(key) != -1;
}

/**
 * \brief Initializes specific properties with their default values for the type.
 */
void EntityData::initialize_specific_properties() {

  specific_properties.clear();
  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {
    specific_properties.emplace(field_description.key, field_description.default_value);
  }
}

/**
 * \brief Returns all specific properties of this entity.
 * \return The entity properties that are specific to its type.
 */
const std::map<std::string, FieldValue>& EntityData::get_specific_properties() const {
  return specific_properties;
}

/**
 * \brief Returns a specific property of this entity if it exists.
 * \param key Key of the specific property to get.
 * \return The corresponding specific property or a nil field.
 */
FieldValue EntityData::get_specific_property(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return FieldValue();
  }

  return it->second;
}

/**
 * \brief Returns whether a specific property of this entity is a string.
 * \param key Key of the specific property to get.
 * \return \c true if the specific property exists and is a string.
 */
bool EntityData::is_string(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return false;
  }
  return it->second.value_type == EntityFieldType::STRING;
}

/**
 * \brief Returns the value of a string specific property of this entity.
 * \param key Key of the specific property to get.
 * It must exist and be a string.
 * \return The string value.
 */
const std::string& EntityData::get_string(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::STRING,
      "Field '" + key + "' is not a string");

  return it->second.string_value;
}

/**
 * \brief Sets the value of a string specific property of this entity.
 * \param key Key of the specific property to set.
 * It must exist and be a string.
 * \param value The string value.
 */
void EntityData::set_string(const std::string& key, const std::string& value) {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::STRING,
      "Field '" + key + "' is not a string");

  it->second.string_value = value;
}

/**
 * \brief Returns whether a specific property of this entity is an integer.
 * \param key Key of the specific property to get.
 * \return \c true if the specific property exists and is an integer.
 */
bool EntityData::is_integer(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return false;
  }
  return it->second.value_type == EntityFieldType::INTEGER;
}

/**
 * \brief Returns the value of an integer specific property of this entity.
 * \param key Key of the specific property to get.
 * It must exist and be an integer.
 * \return The integer value.
 */

/**
 * \brief Sets the value of an integer specific property of this entity.
 * \param key Key of the specific property to set.
 * It must exist and be an integer.
 * \param value The integer value.
 */
void EntityData::set_integer(const std::string& key, int value) {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::INTEGER,
      "Field '" + key + "' is not an integer");

  it->second.int_value = value;
}

/**
 * \brief Returns whether a specific property of this entity is a boolean.
 * \param key Key of the specific property to get.
 * \return \c true if the specific property exists and is a boolean.
 */
bool EntityData::is_boolean(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return false;
  }
  return it->second.value_type == EntityFieldType::BOOLEAN;
}

/**
 * \brief Returns the value of a boolean specific property of this entity.
 * \param key Key of the specific property to get.
 * It must exist and be a boolean.
 * \return The boolean value.
 */
bool EntityData::get_boolean(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::BOOLEAN,
      "Field '" + key + "' is not a boolean");

  return it->second.int_value != 0;
}

/**
 * \brief Sets the value of a boolean specific property of this entity.
 * \param key Key of the specific property to set.
 * It must exist and be a boolean.
 * \param value The boolean value.
 */
void EntityData::set_boolean(const std::string& key, bool value) {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::BOOLEAN,
      "Field '" + key + "' is not an boolean");

  it->second.int_value = value ? 1 : 0;
}

/**
 * \brief Returns whether a specific property exists for this type of entity.
 * \param key Key of the specific property to check.
 * \return \c true if such a specific property exists.
 */
bool EntityData::has_specific_property(const std::string& key) const {

  return get_specific_property(key).value_type != EntityData::EntityFieldType::NIL;
}

/**
 * \brief Returns whether a specific property is optional.
 * \param key Key of the specific property to check.
 * \return \c true if the specific property exists and is optional.
 */
bool EntityData::is_specific_property_optional(const std::string& key) const {

  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {
    if (field_description.key == key) {
      return field_description.optional == OptionalFlag::OPTIONAL;
    }
  }

  return false;
}

/**
 * \brief Returns whether a specific property is unset.
 *
 * A specific property can only be unset if it is optional.
 *
 * \param key Key of the specific property to check.
 * \return \c true if the specific property exists, is optional and is equal to its
 * default value.
 */
bool EntityData::is_specific_property_unset(const std::string& key) const {

  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {
    if (field_description.key != key) {
      continue;
    }

    if (field_description.optional != OptionalFlag::OPTIONAL) {
      // Mandatory specific property: always set.
      return false;
    }

    const FieldValue& default_value = field_description.default_value;
    switch (default_value.value_type) {

    case EntityFieldType::STRING:
      return get_string(key) == default_value.string_value;

    case EntityFieldType::INTEGER:
      return get_integer(key) == default_value.int_value;

    case EntityFieldType::BOOLEAN:
      return get_boolean(key) == (default_value.int_value != 0);

    case EntityFieldType::NIL:
      Debug::die("Nil entity field");
      break;
    }
  }

  // The specific property does not exist.
  return false;
}

/**
 * \brief Reads an EntityData from the Lua table at the specified index.
 * \param l A Lua state.
 * \param index Index of the table in the Lua stack.
 * \param type Type of entity to read.
 * \return The EntityData created.
 */
EntityData EntityData::check_entity_data(lua_State* l, int index, EntityType type) {

  LuaTools::check_type(l, index, LUA_TTABLE);
  const std::string& name = LuaTools::opt_string_field(l, index, "name", "");
  int layer = LuaTools::check_int_field(l, index, "layer");
  int x = LuaTools::check_int_field(l, index, "x");
  int y = LuaTools::check_int_field(l, index, "y");

  EntityData entity(type);
  entity.set_name(name);
  entity.set_layer(layer);
  entity.set_xy({ x, y });

  // User-defined properties.
  lua_getfield(l, index, "properties");
  if (!lua_isnil(l, -1)) {
    LuaTools::check_type(l, -1, LUA_TTABLE);
    lua_pushnil(l);
    while (lua_next(l, -2) != 0) {
      LuaTools::check_type(l, -1, LUA_TTABLE);
      const std::string& key = LuaTools::check_string_field(l, -1, "key");
      const std::string& value = LuaTools::check_string_field(l, -1, "value");
      if (entity.has_user_property(key)) {
        LuaTools::error(l, "Duplicate property '" + key + "'");
      }
      if (!EntityData::is_user_property_key_valid(key)) {
        LuaTools::error(l, "Invalid property key: '" + key + "'");
      }
      entity.add_user_property(std::make_pair(key, value));
      lua_pop(l, 1);
    }
  }
  lua_pop(l, 1);

  // Additional properties specific to the entity type.
  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {

    const std::string& key = field_description.key;
    const FieldValue& default_value = field_description.default_value;
    switch (default_value.value_type) {

      case EntityFieldType::STRING:
      {
        std::string value;
        if (field_description.optional == OptionalFlag::OPTIONAL) {
          value = LuaTools::opt_string_field(l, index, key, default_value.string_value);
        }
        else {
          value = LuaTools::check_string_field(l, index, key);
        }
        entity.set_string(key, value);
        break;
      }

      case EntityFieldType::INTEGER:
      {
        int value;
        if (field_description.optional == OptionalFlag::OPTIONAL) {
          value = LuaTools::opt_int_field(l, index, key, default_value.int_value);
        }
        else {
          value = LuaTools::check_int_field(l, index, key);
        }
        entity.set_integer(key, value);
        break;
      }

      case EntityFieldType::BOOLEAN:
      {
        bool value;
        if (field_description.optional == OptionalFlag::OPTIONAL) {
          value = LuaTools::opt_boolean_field(l, index, key, default_value.int_value != 0);
        }
        else {
          value = LuaTools::check_boolean_field(l, index, key);
        }
        entity.set_boolean(key, value);
        break;
      }

      case EntityFieldType::NIL:
        Debug::die("Nil entity field");
        break;
    }
  }

  return entity;
}

/**
 * \brief Returns the definition of the format of all entity types in map data files.
 *
 * Note: entities whose type is not in this map can only be created
 * by the engine.
 * This is the case of HERO, CARRIED_OBJECT, BOOMERANG, ARROW and HOOKHOT.
 * The ones in the map can be created either by declaring them in a map
 * data file or by the Lua API, or both.
 *
 * \return The format description of entity types.
 */
const std::map<EntityType, const EntityTypeDescription> EntityData::get_entity_type_descriptions() {
  return entity_type_descriptions;
}

/**
 * \copydoc LuaData::import_from_lua
 */
bool EntityData::import_from_lua(lua_State* l) {

  lua_pushlightuserdata(l, this);
  lua_setfield(l, LUA_REGISTRYINDEX, "entity");
  for (const auto& kvp : EnumInfoTraits<EntityType>::names) {
    EntityType type = kvp.first;
    const std::string& type_name = kvp.second;
    if (!EntityTypeInfo::can_be_stored_in_map_file(type)) {
      continue;
    }
    std::string function_name = type_name;
    lua_pushstring(l, function_name.c_str());
    lua_pushcclosure(l, l_create_entity_data, 1);
    lua_setglobal(l, function_name.c_str());
  }

  if (lua_pcall(l, 0, 0, 0) != 0) {
    Debug::error(std::string("Failed to load entity: ") + lua_tostring(l, -1));
    lua_pop(l, 1);
    return false;
  }

  return true;
}

/**
 * \copydoc LuaData::export_to_lua
 */
bool EntityData::export_to_lua(std::ostream& out) const {

  // Entity type.
  out << get_type_name() << "{\n";

  if (has_name()) {
    out << "  name = \"" << escape_string(get_name()) << "\",\n";
  }

  // Position on the map.
  out << "  layer = " << get_layer() << ",\n"
      << "  x = " << get_xy().x << ",\n"
      << "  y = " << get_xy().y << ",\n";

  // User-defined properties.
  export_user_properties(out);

  // Properties specific to the type of entity.
  export_specific_properties(out);

  out << "}\n\n";

  return true;
}

/**
 * \brief Exports the user-defined properties to a stream.
 * \param out Output stream to write.
 */
void EntityData::export_user_properties(std::ostream& out) const {

  const std::vector<UserProperty>& user_properties = get_user_properties();
  if (user_properties.empty()) {
    return;
  }

  out << "  properties = {\n";
  for (const UserProperty& user_property : user_properties) {
    out << "    {\n";
    out << "      key = \"" << escape_string(user_property.first) << "\",\n";
    out << "      value = \"" << escape_string(user_property.second) << "\",\n";
    out << "    },\n";
  }
  out << "  },\n";
}

/**
 * \brief Exports the properties to the entity type to a stream.
 * \param out Output stream to write.
 */
void EntityData::export_specific_properties(std::ostream& out) const {

  // Properties specific to the type of entity.
  const EntityTypeDescription& type_description = entity_type_descriptions.at(get_type());

  for (const EntityFieldDescription& field_description : type_description) {

    const std::string& key = field_description.key;
    const bool optional = field_description.optional == OptionalFlag::OPTIONAL;
    switch (field_description.default_value.value_type) {

      case EntityFieldType::STRING:
      {
        const std::string& value = get_string(key);
        const std::string& default_value = field_description.default_value.string_value;
        if (optional && value == default_value) {
          // No need to write the value.
          continue;
        }
        out << "  " << key << " = \"" << escape_string(value) << "\",\n";
        break;
      }

      case EntityFieldType::INTEGER:
      {
        int value = get_integer(key);
        int default_value = field_description.default_value.int_value;
        if (optional && value == default_value) {
          // No need to write the value.
          continue;
        }
        out << "  " << key << " = " << value << ",\n";
        break;
      }

      case EntityFieldType::BOOLEAN:
      {
        bool value = get_boolean(key);
        bool default_value = field_description.default_value.int_value != 0;
        if (optional && value == default_value) {
          // No need to write the value.
          continue;
        }
        out << "  " << key << " = " << (value ? "true" : "false") << ",\n";

        break;
      }

      case EntityFieldType::NIL:
        Debug::die("Nil entity field");
        break;
    }
  }
}

}  // namespace Solarus


switch (default_value.value_type) {

    case EntityFieldType::STRING:
      return get_string(key) == default_value.string_value;

    case EntityFieldType::INTEGER:
      return get_integer(key) == default_value.int_value;

    case EntityFieldType::BOOLEAN:
      return get_boolean(key) == (default_value.int_value != 0);

    case EntityFieldType::NIL:
      Debug::die("Nil entity field");
      break;
    }

/*
 *
 */
#include "solarus/core/Debug.h"
#include "solarus/entities/EntityData.h"
#include "solarus/entities/EntityTypeInfo.h"
#include "solarus/lua/LuaTools.h"
#include <ostream>

namespace Solarus {

namespace {

using EntityTypeDescription = EntityData::EntityTypeDescription;
using OptionalFlag = EntityData::OptionalFlag;
using FieldValue = EntityData::FieldValue;

/**
 * \brief Definition of the format of entity types in map data files and Lua API.
 */
const std::map<EntityType, const EntityTypeDescription> entity_type_descriptions = {

    {
        EntityType::TILE, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "pattern", OptionalFlag::MANDATORY, FieldValue("") },
            { "tileset", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::DYNAMIC_TILE, {
            { "pattern", OptionalFlag::MANDATORY, FieldValue("") },
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "enabled_at_start", OptionalFlag::MANDATORY, FieldValue(true) },
            { "tileset", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::TELETRANSPORTER, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "transition", OptionalFlag::OPTIONAL, FieldValue("fade") },
            { "destination_map", OptionalFlag::MANDATORY, FieldValue("") },
            { "destination", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sound", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::DESTINATION, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(1) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "starting_location_mode", OptionalFlag::OPTIONAL, FieldValue("when_world_changes") },
            { "default", OptionalFlag::OPTIONAL, FieldValue(false) }
        }
    },

    {
        EntityType::PICKABLE, {
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") }
        }
    },

    {
        EntityType::DESTRUCTIBLE, {
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("") },
            { "destruction_sound", OptionalFlag::OPTIONAL, FieldValue("") },
            { "weight", OptionalFlag::OPTIONAL, FieldValue(0) },
            { "can_be_cut", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "can_explode", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "can_regenerate", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "damage_on_enemies", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "ground", OptionalFlag::OPTIONAL, FieldValue("wall") }
        }
    },

    {
        EntityType::CHEST, {
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("entities/chest") },
            { "opening_method", OptionalFlag::OPTIONAL, FieldValue("interaction") },
            { "opening_condition", OptionalFlag::OPTIONAL, FieldValue("") },
            { "opening_condition_consumed", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "cannot_open_dialog", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::SHOP_TREASURE, {
            { "treasure_name", OptionalFlag::MANDATORY, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "price", OptionalFlag::MANDATORY, FieldValue(0) },
            { "font", OptionalFlag::OPTIONAL, FieldValue("") },
            { "dialog", OptionalFlag::MANDATORY, FieldValue("") }
        }
    },

    {
        EntityType::ENEMY, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(0) },
            { "breed", OptionalFlag::MANDATORY, FieldValue("") },
            { "rank", OptionalFlag::OPTIONAL, FieldValue(0) },
            { "savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_name", OptionalFlag::OPTIONAL, FieldValue("") },
            { "treasure_variant", OptionalFlag::OPTIONAL, FieldValue(1) },
            { "treasure_savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::NPC, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(3) },
            { "subtype", OptionalFlag::MANDATORY, FieldValue(1) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "behavior", OptionalFlag::OPTIONAL, FieldValue("map") },
        }
    },

    {
        EntityType::BLOCK, {
            { "direction", OptionalFlag::OPTIONAL, FieldValue(-1) },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("entities/block") },
            { "pushable", OptionalFlag::MANDATORY, FieldValue(true) },
            { "pullable", OptionalFlag::MANDATORY, FieldValue(false) },
            { "maximum_moves", OptionalFlag::MANDATORY, FieldValue(1) },
        }
    },

    {
        EntityType::JUMPER, {
            { "width", OptionalFlag::MANDATORY, FieldValue(32) },
            { "height", OptionalFlag::MANDATORY, FieldValue(8) },
            { "direction", OptionalFlag::MANDATORY, FieldValue(6) },
            { "jump_length", OptionalFlag::MANDATORY, FieldValue(40) }
        }
    },

    {
        EntityType::SWITCH, {
            { "subtype", OptionalFlag::MANDATORY, FieldValue("walkable") },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "sound", OptionalFlag::OPTIONAL, FieldValue("") },
            { "needs_block", OptionalFlag::MANDATORY, FieldValue(false) },
            { "inactivate_when_leaving", OptionalFlag::MANDATORY, FieldValue(false) },
        }
    },

    {
        EntityType::SENSOR, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
        }
    },

    {
        EntityType::WALL, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "stops_hero", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_npcs", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_enemies", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_blocks", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "stops_projectiles", OptionalFlag::OPTIONAL, FieldValue(false) },
        }
    },

    {
        EntityType::CRYSTAL, {
            // No additional fields.
        }
    },

    {
        EntityType::CRYSTAL_BLOCK, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "subtype", OptionalFlag::MANDATORY, FieldValue(0) },
        }
    },

    {
        EntityType::STREAM, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(6) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "speed", OptionalFlag::OPTIONAL, FieldValue(64) },
            { "allow_movement", OptionalFlag::OPTIONAL, FieldValue(true) },
            { "allow_attack", OptionalFlag::OPTIONAL, FieldValue(true) },
            { "allow_item", OptionalFlag::OPTIONAL, FieldValue(true) },
        }
    },

    {
        EntityType::DOOR, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(3) },
            { "sprite", OptionalFlag::MANDATORY, FieldValue("") },
            { "savegame_variable", OptionalFlag::OPTIONAL, FieldValue("") },
            { "opening_method", OptionalFlag::OPTIONAL, FieldValue("none") },
            { "opening_condition", OptionalFlag::OPTIONAL, FieldValue("") },
            { "opening_condition_consumed", OptionalFlag::OPTIONAL, FieldValue(false) },
            { "cannot_open_dialog", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::STAIRS, {
            { "direction", OptionalFlag::MANDATORY, FieldValue(1) },
            { "subtype", OptionalFlag::MANDATORY, FieldValue(0) },
        }
    },

    {
        EntityType::SEPARATOR, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
        }
    },

    {
        EntityType::CUSTOM, {
            { "width", OptionalFlag::MANDATORY, FieldValue(16) },
            { "height", OptionalFlag::MANDATORY, FieldValue(16) },
            { "direction", OptionalFlag::MANDATORY, FieldValue(0) },
            { "sprite", OptionalFlag::OPTIONAL, FieldValue("") },
            { "model", OptionalFlag::OPTIONAL, FieldValue("") },
        }
    },

    {
        EntityType::EXPLOSION, {
            // No additional fields.
        }
    },

    {
        EntityType::BOMB, {
            // No additional fields.
        }
    },

    {
        EntityType::FIRE, {
            // No additional fields.
        }
    }
};

/**
 * \brief Implementation of all entity data creation functions.
 * \param l The Lua context that is calling this function.
 * \return Number of values to return to Lua.
 */
int l_create_entity_data(lua_State* l) {

  return LuaTools::exception_boundary_handle(l, [&] {

    // Retrieve the entity data instance to build.
    lua_getfield(l, LUA_REGISTRYINDEX, "entity");
    EntityData& entity = *static_cast<EntityData*>(lua_touserdata(l, -1));
    lua_pop(l, 1);

    // Get the type of entity, it should have been passed as an upvalue.
    EntityType type = LuaTools::check_enum<EntityType>(
        l, lua_upvalueindex(1)
    );

    entity = EntityData::check_entity_data(l, 1, type);

    return 0;
  });
}

}  // Anonymous namespace.

/**
 * \brief Creates a nil value.
 */
FieldValue::FieldValue():
    value_type(EntityFieldType::NIL),
    string_value(),
    int_value(0) {

}

/**
 * \brief Creates a value of type string.
 * \param value The value.
 */
FieldValue::FieldValue(const std::string& value):
    value_type(EntityFieldType::STRING),
    string_value(value),
    int_value(0) {

}

/**
 * \brief Creates a value of type string.
 *
 * This overload makes sure that string literal parameters
 * won't get converted to bool.
 *
 * \param value The value.
 */
FieldValue::FieldValue(const char* value):
    FieldValue(std::string(value)) {

}

/**
 * \brief Creates a value of type integer.
 * \param value The value.
 */
FieldValue::FieldValue(int value):
    value_type(EntityFieldType::INTEGER),
    string_value(),
    int_value(value) {

}

/**
 * \brief Creates a value of type boolean.
 * \param value The value.
 */
FieldValue::FieldValue(bool value):
    value_type(EntityFieldType::BOOLEAN),
    string_value(),
    int_value(value ? 1 : 0) {

}

/**
 * \brief Returns whether two values are equal.
 */
bool FieldValue::operator==(const FieldValue& other) const {

  return value_type == other.value_type &&
      string_value == other.string_value &&
      int_value == other.int_value;
}

/**
 * \brief Returns whether two values are different.
 */
bool FieldValue::operator!=(const FieldValue& other) const {

  return !(*this == other);
}

/**
 * \brief Creates data for an entity of a default-constructed type.
 */
EntityData::EntityData() :
    type(),
    name(),
    layer(0),
    xy(),
    user_properties() ,
    specific_properties() {

  initialize_specific_properties();
}

/**
 * \brief Creates data for an entity of the given type.
 * \param type A type of entity.
 */
EntityData::EntityData(EntityType type) :
    type(type),
    name(),
    layer(0),
    xy(),
    user_properties(),
    specific_properties() {

  initialize_specific_properties();
}

/**
 * \brief Returns the type of entity.
 * \return The type of entity.
 */
EntityType EntityData::get_type() const {
  return type;
}

/**
 * \brief Sets the type of this entity.
 *
 * When the type changes, all fields are reset to their default value.
 *
 * \param type The new type.
 */
void EntityData::set_type(EntityType type) {

  if (type == this->type) {
    return;
  }

  this->type = type;
  initialize_specific_properties();
}

/**
 * \brief Returns whether this entity is a dynamic one.
 * \return \c true if this is a dynamic entity, \c false if this is a tile.
 */
bool EntityData::is_dynamic() const {
  return type != EntityType::TILE;
}

/**
 * \brief Returns the name of the type of entity.
 * \return The type name of entity.
 */
const std::string& EntityData::get_type_name() const {
  return enum_to_name(get_type());
}

/**
 * \brief Returns whether the entity has a name.
 */
bool EntityData::has_name() const {
  return !name.empty();
}

/**
 * \brief Returns the name of this entity.
 * \return The entity name or an empty string.
 */
std::string EntityData::get_name() const {
  return name;
}

/**
 * \brief Changes the name of this entity.
 * \param name The entity name or an empty string.
 */
void EntityData::set_name(const std::string& name) {
  this->name = name;
}

/**
 * \brief Returns the layer of this entity on the map.
 * \return The layer.
 */
int EntityData::get_layer() const {
  return layer;
}

/**
 * \brief Sets the layer of this entity on the map.
 * \param layer The layer.
 */
void EntityData::set_layer(int layer) {
  this->layer = layer;
}

/**
 * \brief Returns the coordinates of this entity on the map.
 * \return The coordinates of the entity.
 */
Point EntityData::get_xy() const {
  return xy;
}

/**
 * \brief Sets the coordinates of this entity on the map.
 * \param xy The coordinates of the entity.
 */
void EntityData::set_xy(const Point& xy) {
  this->xy = xy;
}

/**
 * \brief Returns whether a string is a valid key for a user property.
 *
 * It should only contain alphanumeric characters or '_' and
 * not start with a digit.
 *
 * \param key The string to check.
 * \return \c true if this is a valid user property key.
 */
bool EntityData::is_user_property_key_valid(const std::string& key) {

  // Same rules as Lua identifiers.
  return LuaTools::is_valid_lua_identifier(key);
}

/**
 * \brief Returns the user-defined properties of this entity.
 * \return The user-defined properties.
 */
const std::vector<EntityData::UserProperty>& EntityData::get_user_properties() const {
  return user_properties;
}

/**
 * \brief Returns the number of user-defined properties of this entity.
 * \return The number of user-defined properties.
 */
int EntityData::get_user_property_count() const {
  return static_cast<int>(user_properties.size());
}

/**
 * \brief Returns the user property at the given index.
 * \param index An index between \c 0 and <tt>get_user_property_count() - 1</tt>.
 * \return The user property at this index.
 */
const EntityData::UserProperty& EntityData::get_user_property(int index) const {

  Debug::check_assertion(index >= 0 && index < get_user_property_count(),
      "Invalid user property index");
  return user_properties.at(index);
}

/**
 * \brief Sets the user property at the given index.
 * \param index An index between \c 0 and <tt>get_user_property_count() - 1</tt>.
 * \param user_property The new key and value to set.
 */
void EntityData::set_user_property(int index, const UserProperty& user_property) {

  Debug::check_assertion(index >= 0 && index < get_user_property_count(),
      "Invalid user property index");

  Debug::check_assertion(is_user_property_key_valid(user_property.first),
      "Invalid user property key");

  int existing_index = get_user_property_index(user_property.first);
  Debug::check_assertion(existing_index == -1 || existing_index == index,
      "This user property already exists");

  user_properties[index] = user_property;
}

/**
 * \brief Sets all user-defined properties.
 * \param user_properties The properties to set. Keys must be unique.
 */
void EntityData::set_user_properties(const std::vector<UserProperty>& user_properties) {

  for (const UserProperty& user_property : user_properties) {
    Debug::check_assertion(is_user_property_key_valid(user_property.first),
        "Invalid user property key");
  }

  this->user_properties = user_properties;
}

/**
 * \brief Adds a user property.
 *
 * The key of the property should not already exist.
 *
 * \param user_property The new key and value to add.
 */
void EntityData::add_user_property(const UserProperty& user_property) {

  Debug::check_assertion(is_user_property_key_valid(user_property.first),
      "Invalid user property key");

  Debug::check_assertion(!has_user_property(user_property.first),
      "This user property already exists");

  user_properties.emplace_back(user_property);
}

/**
 * \brief Returns a user property.
 * \param index An index between \c 0 and <tt>get_user_property_count() - 1</tt>.
 */
void EntityData::remove_user_property(int index) {

  Debug::check_assertion(index >= 0 && index < get_user_property_count(),
      "Invalid user property index");

  user_properties.erase(user_properties.begin() + index);
}

/**
 * \brief Returns the index of a user property in the user property list.
 * \param key Key of the property to get.
 * \return The corresponding index, or -1 if there is no such property.
 */
int EntityData::get_user_property_index(const std::string& key) const {

  int index = 0;
  for (const UserProperty& user_property : user_properties) {
    if (user_property.first == key) {
      return index;
    }
    ++index;
  }
  return -1;
}

/**
 * \brief Returns whether a user property exists with the given key.
 * \param key Key of the property to get.
 * \return \c true if the entity has such a property.
 */
bool EntityData::has_user_property(const std::string& key) const {
  return get_user_property_index(key) != -1;
}

/**
 * \brief Initializes specific properties with their default values for the type.
 */
void EntityData::initialize_specific_properties() {

  specific_properties.clear();
  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {
    specific_properties.emplace(field_description.key, field_description.default_value);
  }
}

/**
 * \brief Returns all specific properties of this entity.
 * \return The entity properties that are specific to its type.
 */
const std::map<std::string, FieldValue>& EntityData::get_specific_properties() const {
  return specific_properties;
}

/**
 * \brief Returns a specific property of this entity if it exists.
 * \param key Key of the specific property to get.
 * \return The corresponding specific property or a nil field.
 */
FieldValue EntityData::get_specific_property(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return FieldValue();
  }

  return it->second;
}

/**
 * \brief Returns whether a specific property of this entity is a string.
 * \param key Key of the specific property to get.
 * \return \c true if the specific property exists and is a string.
 */
bool EntityData::is_string(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return false;
  }
  return it->second.value_type == EntityFieldType::STRING;
}

/**
 * \brief Returns the value of a string specific property of this entity.
 * \param key Key of the specific property to get.
 * It must exist and be a string.
 * \return The string value.
 */
const std::string& EntityData::get_string(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::STRING,
      "Field '" + key + "' is not a string");

  return it->second.string_value;
}

/**
 * \brief Sets the value of a string specific property of this entity.
 * \param key Key of the specific property to set.
 * It must exist and be a string.
 * \param value The string value.
 */
void EntityData::set_string(const std::string& key, const std::string& value) {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::STRING,
      "Field '" + key + "' is not a string");

  it->second.string_value = value;
}

/**
 * \brief Returns whether a specific property of this entity is an integer.
 * \param key Key of the specific property to get.
 * \return \c true if the specific property exists and is an integer.
 */
bool EntityData::is_integer(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return false;
  }
  return it->second.value_type == EntityFieldType::INTEGER;
}

/**
 * \brief Returns the value of an integer specific property of this entity.
 * \param key Key of the specific property to get.
 * It must exist and be an integer.
 * \return The integer value.
 */
int EntityData::get_integer(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::INTEGER,
      "Field '" + key + "' is not a string");

  return it->second.int_value;
}

/**
 * \brief Sets the value of an integer specific property of this entity.
 * \param key Key of the specific property to set.
 * It must exist and be an integer.
 * \param value The integer value.
 */
void EntityData::set_integer(const std::string& key, int value) {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::INTEGER,
      "Field '" + key + "' is not an integer");

  it->second.int_value = value;
}

/**
 * \brief Returns whether a specific property of this entity is a boolean.
 * \param key Key of the specific property to get.
 * \return \c true if the specific property exists and is a boolean.
 */
bool EntityData::is_boolean(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  if (it == specific_properties.end()) {
    return false;
  }
  return it->second.value_type == EntityFieldType::BOOLEAN;
}

/**
 * \brief Returns the value of a boolean specific property of this entity.
 * \param key Key of the specific property to get.
 * It must exist and be a boolean.
 * \return The boolean value.
 */
bool EntityData::get_boolean(const std::string& key) const {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::BOOLEAN,
      "Field '" + key + "' is not a boolean");

  return it->second.int_value != 0;
}

/**
 * \brief Sets the value of a boolean specific property of this entity.
 * \param key Key of the specific property to set.
 * It must exist and be a boolean.
 * \param value The boolean value.
 */
void EntityData::set_boolean(const std::string& key, bool value) {

  const auto& it = specific_properties.find(key);
  Debug::check_assertion(it != specific_properties.end(),
      "No such entity field in " + get_type_name() + ": '" + key + "'");

  Debug::check_assertion(it->second.value_type == EntityFieldType::BOOLEAN,
      "Field '" + key + "' is not an boolean");

  it->second.int_value = value ? 1 : 0;
}

/**
 * \brief Returns whether a specific property exists for this type of entity.
 * \param key Key of the specific property to check.
 * \return \c true if such a specific property exists.
 */
bool EntityData::has_specific_property(const std::string& key) const {

  return get_specific_property(key).value_type != EntityData::EntityFieldType::NIL;
}

/**
 * \brief Returns whether a specific property is optional.
 * \param key Key of the specific property to check.
 * \return \c true if the specific property exists and is optional.
 */
bool EntityData::is_specific_property_optional(const std::string& key) const {

  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {
    if (field_description.key == key) {
      return field_description.optional == OptionalFlag::OPTIONAL;
    }
  }

  return false;
}

/**
 * \brief Returns whether a specific property is unset.
 *
 * A specific property can only be unset if it is optional.
 *
 * \param key Key of the specific property to check.
 * \return \c true if the specific property exists, is optional and is equal to its
 * default value.
 */
bool EntityData::is_specific_property_unset(const std::string& key) const {

  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {
    if (field_description.key != key) {
      continue;
    }

    if (field_description.optional != OptionalFlag::OPTIONAL) {
      // Mandatory specific property: always set.
      return false;
    }

    const FieldValue& default_value = field_description.default_value;

  }

  // The specific property does not exist.
  return false;
}

/**
 * \brief Reads an EntityData from the Lua table at the specified index.
 * \param l A Lua state.
 * \param index Index of the table in the Lua stack.
 * \param type Type of entity to read.
 * \return The EntityData created.
 */
EntityData EntityData::check_entity_data(lua_State* l, int index, EntityType type) {

  LuaTools::check_type(l, index, LUA_TTABLE);
  const std::string& name = LuaTools::opt_string_field(l, index, "name", "");
  int layer = LuaTools::check_int_field(l, index, "layer");
  int x = LuaTools::check_int_field(l, index, "x");
  int y = LuaTools::check_int_field(l, index, "y");

  EntityData entity(type);
  entity.set_name(name);
  entity.set_layer(layer);
  entity.set_xy({ x, y });

  // User-defined properties.
  lua_getfield(l, index, "properties");
  if (!lua_isnil(l, -1)) {
    LuaTools::check_type(l, -1, LUA_TTABLE);
    lua_pushnil(l);
    while (lua_next(l, -2) != 0) {
      LuaTools::check_type(l, -1, LUA_TTABLE);
      const std::string& key = LuaTools::check_string_field(l, -1, "key");
      const std::string& value = LuaTools::check_string_field(l, -1, "value");
      if (entity.has_user_property(key)) {
        LuaTools::error(l, "Duplicate property '" + key + "'");
      }
      if (!EntityData::is_user_property_key_valid(key)) {
        LuaTools::error(l, "Invalid property key: '" + key + "'");
      }
      entity.add_user_property(std::make_pair(key, value));
      lua_pop(l, 1);
    }
  }
  lua_pop(l, 1);

  // Additional properties specific to the entity type.
  const EntityTypeDescription& type_description = entity_type_descriptions.at(type);
  for (const EntityFieldDescription& field_description : type_description) {

    const std::string& key = field_description.key;
    const FieldValue& default_value = field_description.default_value;
    switch (default_value.value_type) {

      case EntityFieldType::STRING:
      {
        std::string value;
        if (field_description.optional == OptionalFlag::OPTIONAL) {
          value = LuaTools::opt_string_field(l, index, key, default_value.string_value);
        }
        else {
          value = LuaTools::check_string_field(l, index, key);
        }
        entity.set_string(key, value);
        break;
      }

      case EntityFieldType::INTEGER:
      {
        int value;
        if (field_description.optional == OptionalFlag::OPTIONAL) {
          value = LuaTools::opt_int_field(l, index, key, default_value.int_value);
        }
        else {
          value = LuaTools::check_int_field(l, index, key);
        }
        entity.set_integer(key, value);
        break;
      }

      case EntityFieldType::BOOLEAN:
      {
        bool value;
        if (field_description.optional == OptionalFlag::OPTIONAL) {
          value = LuaTools::opt_boolean_field(l, index, key, default_value.int_value != 0);
        }
        else {
          value = LuaTools::check_boolean_field(l, index, key);
        }
        entity.set_boolean(key, value);
        break;
      }

      case EntityFieldType::NIL:
        Debug::die("Nil entity field");
        break;
    }
  }

  return entity;
}

/**
 * \brief Returns the definition of the format of all entity types in map data files.
 *
 * Note: entities whose type is not in this map can only be created
 * by the engine.
 * This is the case of HERO, CARRIED_OBJECT, BOOMERANG, ARROW and HOOKHOT.
 * The ones in the map can be created either by declaring them in a map
 * data file or by the Lua API, or both.
 *
 * \return The format description of entity types.
 */
const std::map<EntityType, const EntityTypeDescription> EntityData::get_entity_type_descriptions() {
  return entity_type_descriptions;
}

/**
 * \copydoc LuaData::import_from_lua
 */
bool EntityData::import_from_lua(lua_State* l) {

  lua_pushlightuserdata(l, this);
  lua_setfield(l, LUA_REGISTRYINDEX, "entity");
  for (const auto& kvp : EnumInfoTraits<EntityType>::names) {
    EntityType type = kvp.first;
    const std::string& type_name = kvp.second;
    if (!EntityTypeInfo::can_be_stored_in_map_file(type)) {
      continue;
    }
    std::string function_name = type_name;
    lua_pushstring(l, function_name.c_str());
    lua_pushcclosure(l, l_create_entity_data, 1);
    lua_setglobal(l, function_name.c_str());
  }

  if (lua_pcall(l, 0, 0, 0) != 0) {
    Debug::error(std::string("Failed to load entity: ") + lua_tostring(l, -1));
    lua_pop(l, 1);
    return false;
  }

  return true;
}

/**
 * \copydoc LuaData::export_to_lua
 */
bool EntityData::export_to_lua(std::ostream& out) const {

  // Entity type.
  out << get_type_name() << "{\n";

  if (has_name()) {
    out << "  name = \"" << escape_string(get_name()) << "\",\n";
  }

  // Position on the map.
  out << "  layer = " << get_layer() << ",\n"
      << "  x = " << get_xy().x << ",\n"
      << "  y = " << get_xy().y << ",\n";

  // User-defined properties.
  export_user_properties(out);

  // Properties specific to the type of entity.
  export_specific_properties(out);

  out << "}\n\n";

  return true;
}

/**
 * \brief Exports the user-defined properties to a stream.
 * \param out Output stream to write.
 */
void EntityData::export_user_properties(std::ostream& out) const {

  const std::vector<UserProperty>& user_properties = get_user_properties();
  if (user_properties.empty()) {
    return;
  }

  out << "  properties = {\n";
  for (const UserProperty& user_property : user_properties) {
    out << "    {\n";
    out << "      key = \"" << escape_string(user_property.first) << "\",\n";
    out << "      value = \"" << escape_string(user_property.second) << "\",\n";
    out << "    },\n";
  }
  out << "  },\n";
}

/**
 * \brief Exports the properties to the entity type to a stream.
 * \param out Output stream to write.
 */
void EntityData::export_specific_properties(std::ostream& out) const {

  // Properties specific to the type of entity.
  const EntityTypeDescription& type_description = entity_type_descriptions.at(get_type());

  for (const EntityFieldDescription& field_description : type_description) {

    const std::string& key = field_description.key;
    const bool optional = field_description.optional == OptionalFlag::OPTIONAL;
    switch (field_description.default_value.value_type) {

      case EntityFieldType::STRING:
      {
        const std::string& value = get_string(key);
        const std::string& default_value = field_description.default_value.string_value;
        if (optional && value == default_value) {
          // No need to write the value.
          continue;
        }
        out << "  " << key << " = \"" << escape_string(value) << "\",\n";
        break;
      }

      case EntityFieldType::INTEGER:
      {
        int value = get_integer(key);
        int default_value = field_description.default_value.int_value;
        if (optional && value == default_value) {
          // No need to write the value.
          continue;
        }
        out << "  " << key << " = " << value << ",\n";
        break;
      }

      case EntityFieldType::BOOLEAN:
      {
        bool value = get_boolean(key);
        bool default_value = field_description.default_value.int_value != 0;
        if (optional && value == default_value) {
          // No need to write the value.
          continue;
        }
        out << "  " << key << " = " << (value ? "true" : "false") << ",\n";

        break;
      }

      case EntityFieldType::NIL:
        Debug::die("Nil entity field");
        break;
    }
  }
}

}  // namespace Solarus