Fix for bugs: 1788 (forces) and 1799 (python delattr on game objects)
[blender.git] / source / gameengine / Expressions / Value.h
1 /*
2  * Value.h: interface for the CValue class.
3  * $Id$
4  * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
5  *
6  * Permission to use, copy, modify, distribute and sell this software
7  * and its documentation for any purpose is hereby granted without fee,
8  * provided that the above copyright notice appear in all copies and
9  * that both that copyright notice and this permission notice appear
10  * in supporting documentation.  Erwin Coumans makes no
11  * representations about the suitability of this software for any
12  * purpose.  It is provided "as is" without express or implied warranty.
13  *
14  */
15
16 #ifdef WIN32
17 #pragma warning (disable:4786)
18 #endif //WIN32
19
20 /////////////////////////////////////////////////////////////////////////////////////
21 //// Baseclass CValue
22 //// Together with CExpression, CValue and it's derived classes can be used to
23 //// parse expressions into a parsetree with error detecting/correcting capabilities
24 //// also expandible by a CFactory pluginsystem 
25 //// 
26 //// Features:
27 //// Reference Counting (AddRef() / Release())
28 //// Calculations (Calc() / CalcFinal())
29 //// Configuration (Configure())
30 //// Serialization (EdSerialize() / EdIdSerialize() / EdPtrSerialize() and macro PLUGIN_DECLARE_SERIAL
31 //// Property system (SetProperty() / GetProperty() / FindIdentifier())
32 //// Replication (GetReplica())
33 //// Flags (IsSelected() / IsModified() / SetSelected()...)
34 //// 
35 //// Some small editor-specific things added
36 //// A helperclass CompressorArchive handles the serialization
37 //// 
38 /////////////////////////////////////////////////////////////////////////////////////
39 #ifndef __VALUE_H__
40 #define __VALUE_H__
41
42 #include <map>          // array functionality for the propertylist
43 #include "STR_String.h" // STR_String class
44
45 #ifndef GEN_NO_ASSERT
46 #undef  assert
47 #define assert(exp)                     ((void)NULL)
48 #endif
49
50
51 #ifndef GEN_NO_TRACE
52 #undef  trace
53 #define trace(exp)                      ((void)NULL)
54 #endif
55
56 #ifndef GEN_NO_DEBUG
57 #undef  debug
58 #define debug(exp)                      ((void)NULL)
59 #endif
60
61 #ifndef GEN_NO_ASSERTD
62 #undef  assertd
63 #define assertd(exp)                    ((void)NULL)
64 #endif
65
66
67 #ifndef USE_PRAGMA_ONCE
68 #ifdef WIN32
69         #pragma once
70
71 #endif //WIN32
72 #endif
73
74 #define EDITOR_LEVEL_VERSION 0x06
75
76 enum VALUE_OPERATOR {
77         
78         VALUE_ADD_OPERATOR,                     // +
79         VALUE_SUB_OPERATOR,                     // -
80         VALUE_MUL_OPERATOR,                     // *
81         VALUE_DIV_OPERATOR,                     // /
82         VALUE_NEG_OPERATOR,                     // -
83         VALUE_POS_OPERATOR,                     // +
84         VALUE_AND_OPERATOR,                     // &&
85         VALUE_OR_OPERATOR,                      // ||
86         VALUE_EQL_OPERATOR,                     // ==
87         VALUE_NEQ_OPERATOR,                     // !=
88         VALUE_GRE_OPERATOR,                     // >
89         VALUE_LES_OPERATOR,                     // <
90         VALUE_GEQ_OPERATOR,                     // >=
91         VALUE_LEQ_OPERATOR,                     // <=
92         VALUE_NOT_OPERATOR,                     // !
93         VALUE_NO_OPERATOR                       // no operation at all
94 };
95
96 enum VALUE_DATA_TYPE {
97         VALUE_NO_TYPE,                          // abstract baseclass
98         VALUE_INT_TYPE,
99         VALUE_FLOAT_TYPE,
100         VALUE_STRING_TYPE,
101         VALUE_BOOL_TYPE,
102         VALUE_ERROR_TYPE,
103         VALUE_EMPTY_TYPE,
104         VALUE_SOLID_TYPE,
105         VALUE_COMBISOLID_TYPE,
106         VALUE_VECTOR_TYPE,
107         VALUE_MENU_TYPE,
108         VALUE_ACTOR_TYPE,
109         VALUE_MAX_TYPE                          //only here to provide number of types
110 };
111
112
113
114 #ifdef _DEBUG
115 //extern int gRefCountValue;            // debugonly variable to check if all CValue Refences are Dereferenced at programexit
116 #endif
117
118 struct HashableInt 
119 {
120         HashableInt(int id)                                                                                                                     : mData(id) { }
121
122         unsigned long                           Hash() const                                                                                    { return 0;} ////}gHash(&mData, sizeof(int));}
123         
124         bool                            operator==(HashableInt rhs)                                                             { return mData == rhs.mData; }
125         
126         int                                     mData;
127 };
128
129
130 //
131 // Bitfield that stores the flags for each CValue derived class
132 //
133 struct ValueFlags {
134         ValueFlags() :
135                 Modified(true),
136                 Selected(false),
137                 Affected(false),
138                 ReleaseRequested(false),
139                 Error(false),
140                 RefCountDisabled(false),
141                 HasProperties(false),
142                 HasName(false),
143                 Visible(true),
144                 CustomFlag1(false),
145                 CustomFlag2(false)
146         {
147         }
148
149         unsigned short Modified : 1;
150         unsigned short Selected : 1;
151         unsigned short Affected : 1;
152         unsigned short ReleaseRequested : 1;
153         unsigned short Error : 1;
154         unsigned short RefCountDisabled : 1;
155         unsigned short HasProperties : 1;
156         unsigned short HasName : 1;
157         unsigned short Visible : 1;
158         unsigned short CustomFlag1 : 1;
159         unsigned short CustomFlag2 : 1;
160
161         
162 };
163
164 /**
165  *      Base Class for all Actions performed on CValue's. Can be extended for undo/redo system in future.
166 */
167 class CAction
168 {
169 public:
170         CAction() {
171         };
172         virtual ~CAction(){
173         };
174         virtual void Execute() const =0;
175 };
176
177 //
178 // CValue
179 //
180 // Base class for all editor functionality, flexible object type that allows
181 // calculations and uses reference counting for memory management.
182 // 
183 //
184
185
186
187 #ifndef NO_EXP_PYTHON_EMBEDDING
188 #include "PyObjectPlus.h"
189 #include "object.h"
190 class CValue  : public PyObjectPlus
191 #else
192 class CValue  
193 #endif //NO_EXP_PYTHON_EMBEDDING
194
195
196 {
197 #ifndef NO_EXP_PYTHON_EMBEDDING
198 Py_Header;
199 #endif //NO_EXP_PYTHON_EMBEDDING
200 public:
201         enum AllocationTYPE {
202                 STACKVALUE              = 0,
203                 HEAPVALUE               = 1
204         };
205         
206         enum DrawTYPE {
207                 STARTFRAME              = 0,
208                 ENDFRAME                = 1,
209                 INTERFRAME              = 2
210         };
211
212
213         // Construction / Destruction
214 #ifndef NO_EXP_PYTHON_EMBEDDING
215
216         CValue(PyTypeObject *T = &Type);
217         //static PyObject*      PyMake(PyObject*,PyObject*);
218         virtual PyObject *_repr(void)
219         {
220                 return Py_BuildValue("s",(const char*)GetText());
221         }
222
223
224
225         virtual PyObject*                       _getattr(const STR_String& attr);
226
227         void    SpecialRelease()
228         {
229                 int i=0;
230                 if (ob_refcnt == 0)
231                 {
232                         _Py_NewReference(this);
233                         
234                 } else
235                 {
236                         i++;
237                 }
238                 Release();
239         }
240         static void PyDestructor(PyObject *P)                           // python wrapper
241         {
242           ((CValue*)P)->SpecialRelease();
243         };
244
245         virtual PyObject*       ConvertValueToPython() {
246                 return NULL;
247         }
248
249         virtual CValue* ConvertPythonToValue(PyObject* pyobj);
250
251
252         virtual int                             _delattr(const STR_String& attr);
253         virtual int                             _setattr(const STR_String& attr,PyObject* value);
254         
255         KX_PYMETHOD(CValue,GetName);
256
257 #else
258         CValue();
259 #endif //NO_EXP_PYTHON_EMBEDDING
260
261         
262         
263         // Expression Calculation
264         virtual CValue*         Calc(VALUE_OPERATOR op, CValue *val) = 0;
265         virtual CValue*         CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) = 0;
266         virtual void            SetOwnerExpression(class CExpression* expr);
267
268         
269
270         void                            Execute(const CAction& a)
271         {
272                 a.Execute();
273         };
274
275         /// Reference Counting
276         int                                     GetRefCount()                                                                                   { return m_refcount; }
277         virtual CValue*         AddRef();                                                                                               // Add a reference to this value
278         virtual int                     Release();                                                                                              // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
279
280         /// Property Management
281         virtual void            SetProperty(const STR_String& name,CValue* ioProperty);                                         // Set property <ioProperty>, overwrites and releases a previous property with the same name if needed
282         virtual CValue*         GetProperty(const STR_String & inName);                                                 // Get pointer to a property with name <inName>, returns NULL if there is no property named <inName>
283         STR_String                      GetPropertyText(const STR_String & inName,const STR_String& deftext="");                                                // Get text description of property with name <inName>, returns an empty string if there is no property named <inName>
284         float                           GetPropertyNumber(const STR_String& inName,float defnumber);
285         virtual bool            RemoveProperty(const STR_String & inName);                                              // Remove the property named <inName>, returns true if the property was succesfully removed, false if property was not found or could not be removed
286         virtual void            ClearProperties();                                                                              // Clear all properties
287
288         virtual void            SetPropertiesModified(bool inModified);                                 // Set all properties' modified flag to <inModified>
289         virtual bool            IsAnyPropertyModified();                                                                // Check if any of the properties in this value have been modified
290
291         virtual CValue*         GetProperty(int inIndex);                                                               // Get property number <inIndex>
292         virtual int                     GetPropertyCount();                                                                             // Get the amount of properties assiocated with this value
293
294         virtual void            CloneProperties(CValue* replica);
295         virtual CValue*         FindIdentifier(const STR_String& identifiername);
296         /** Set the wireframe color of this value depending on the CSG
297          * operator type <op>
298          * @attention: not implemented */
299         virtual void            SetColorOperator(VALUE_OPERATOR op);
300
301         virtual const STR_String &      GetText() = 0;
302         virtual float           GetNumber() = 0;
303         double*                         ZeroVector() { return m_sZeroVec; };
304         virtual double*         GetVector3(bool bGetTransformedVec = false);
305
306         virtual STR_String      GetName() = 0;                                                                                  // Retrieve the name of the value
307         virtual void            SetName(STR_String name) = 0;                                                           // Set the name of the value
308         virtual void            ReplicaSetName(STR_String name) = 0;
309         /** Sets the value to this cvalue.
310          * @attention this particular function should never be called. Why not abstract? */
311         virtual void            SetValue(CValue* newval);
312         virtual CValue*         GetReplica() =0;
313         //virtual CValue*               Copy() = 0;
314         
315         
316         STR_String                              op2str(VALUE_OPERATOR op);
317                 
318         // setting / getting flags
319         inline void                     SetSelected(bool bSelected)                                                             { m_ValFlags.Selected = bSelected; }
320         virtual void            SetModified(bool bModified)                                                             { m_ValFlags.Modified = bModified; }
321         virtual void            SetAffected(bool bAffected=true)                                                { m_ValFlags.Affected = bAffected; }
322         inline void                     SetReleaseRequested(bool bReleaseRequested)                             { m_ValFlags.ReleaseRequested=bReleaseRequested; }
323         inline void                     SetError(bool err)                                                                              { m_ValFlags.Error=err; }
324         inline void                     SetVisible (bool vis)                                                                   { m_ValFlags.Visible=vis; }
325                                                                                                                                                                 
326         virtual bool            IsModified()                                                                                    { return m_ValFlags.Modified; }
327         inline bool                     IsError()                                                                                               { return m_ValFlags.Error; }
328         virtual bool            IsAffected()                                                                                    { return m_ValFlags.Affected || m_ValFlags.Modified; }
329         virtual bool            IsSelected()                                                                                    { return m_ValFlags.Selected; }
330         inline bool                     IsReleaseRequested()                                                                    { return m_ValFlags.ReleaseRequested; }
331         virtual bool            IsVisible()                                                                                             { return m_ValFlags.Visible;}
332         virtual void            SetCustomFlag1(bool bCustomFlag)                                                { m_ValFlags.CustomFlag1 = bCustomFlag;};
333         virtual bool            IsCustomFlag1()                                                                                 { return m_ValFlags.CustomFlag1;};
334
335         virtual void            SetCustomFlag2(bool bCustomFlag)                                                { m_ValFlags.CustomFlag2 = bCustomFlag;};
336         virtual bool            IsCustomFlag2()                                                                                 { return m_ValFlags.CustomFlag2;};
337                                                                                                                                                                 
338 protected:                                                                                                                                              
339         virtual void            DisableRefCount();                                                                              // Disable reference counting for this value
340         virtual void            AddDataToReplica(CValue* replica);                                              
341         virtual                         ~CValue();
342 private:                                                                                                                                                
343         // Member variables                                                                                                                     
344         std::map<STR_String,CValue*>*           m_pNamedPropertyArray;                                                                  // Properties for user/game etc
345         ValueFlags                      m_ValFlags;                                                                                             // Frequently used flags in a bitfield (low memoryusage)
346         int                                     m_refcount;                                                                                             // Reference Counter    
347         static  double m_sZeroVec[3];   
348
349 };
350
351
352
353 //
354 // Declare a CValue or CExpression or CWhatever to be serialized by the editor.
355 //
356 // This macro introduces the EdSerialize() function (which must be implemented by
357 // the client) and the EdIdSerialize() function (which is implemented by this macro).
358 //
359 // The generated Copy() function returns a pointer to <root_base_class_name> type
360 // of object. So, for *any* CValue-derived object this should be set to CValue,
361 // for *any* CExpression-derived object this should be set to CExpression.
362 //
363 #define PLUGIN_DECLARE_SERIAL(class_name, root_base_class_name)                                                                                 \
364 public:                                                                                                                                                                                                 \
365         virtual root_base_class_name *  Copy()                                  { return new class_name; }                                      \
366         virtual bool EdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring);    \
367         virtual bool EdIdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring)       \
368 {                                                                                                                                                                                                               \
369         if (bIsStoring)                                                                                                                                                                         \
370                 arch.StoreString(#class_name);                                                                                                                                  \
371                                                                                                                                                                                                                 \
372         return false;                                                                                                                                                                           \
373 }                                                                                                                                                                                                               \
374         
375
376 ////////////////////////////////////////////////////////////////////////////////
377 ////////////////////////////////////////////////////////////////////////////////
378 ////////////////////////////////////////////////////////////////////////////////
379
380 // CPropValue is a CValue derived class, that implements the identification (String name)
381 // SetName() / GetName(), 
382 // normal classes should derive from CPropValue, real lightweight classes straight from CValue
383
384
385 class CPropValue : public CValue
386 {
387 public:
388
389 #ifndef NO_EXP_PYTHON_EMBEDDING 
390         CPropValue(PyTypeObject* T=&Type) :
391           CValue(T),
392 #else
393         CPropValue() :
394 #endif //NO_EXP_PYTHON_EMBEDDING
395                 m_pstrNewName(NULL)
396
397         {
398         }
399         
400         virtual ~CPropValue()
401         {
402                 if (m_pstrNewName)
403                 {
404                         delete m_pstrNewName;
405                         m_pstrNewName = NULL;
406                 }
407         }
408         
409         virtual void                    SetName(STR_String name) {
410                 if (m_pstrNewName)
411                 {
412                         delete m_pstrNewName;
413                         m_pstrNewName = NULL;   
414                 }
415                 if (name.Length())
416                         m_pstrNewName = new STR_String(name);
417         }
418         virtual void                    ReplicaSetName(STR_String name) {
419                 m_pstrNewName=NULL;
420                 if (name.Length())
421                         m_pstrNewName = new STR_String(name);
422         }
423         
424         virtual STR_String                      GetName() {
425                 //STR_String namefromprop = GetPropertyText("Name");
426                 //if (namefromprop.Length() > 0)
427                 //      return namefromprop;
428                 
429                 if (m_pstrNewName)
430                 {
431                         return *m_pstrNewName;
432                 }
433                 return STR_String("");
434         };                                              // name of Value
435         
436 protected:
437         STR_String*                                     m_pstrNewName;                              // Identification
438 };
439
440 #endif // !defined _VALUEBASECLASS_H
441