svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r22625:22668
[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 #ifdef WITH_CXX_GUARDEDALLOC
46 #include "MEM_guardedalloc.h"
47 #endif
48
49 #ifndef GEN_NO_ASSERT
50 #undef  assert
51 #define assert(exp)                     ((void)NULL)
52 #endif
53
54
55 #ifndef GEN_NO_TRACE
56 #undef  trace
57 #define trace(exp)                      ((void)NULL)
58 #endif
59
60 #ifndef GEN_NO_DEBUG
61 #undef  debug
62 #define debug(exp)                      ((void)NULL)
63 #endif
64
65 #ifndef GEN_NO_ASSERTD
66 #undef  assertd
67 #define assertd(exp)                    ((void)NULL)
68 #endif
69
70
71 #ifndef USE_PRAGMA_ONCE
72 #ifdef WIN32
73         #pragma once
74
75 #endif //WIN32
76 #endif
77
78 #define EDITOR_LEVEL_VERSION 0x06
79
80 enum VALUE_OPERATOR {
81         
82         VALUE_MOD_OPERATOR,                     // %
83         VALUE_ADD_OPERATOR,                     // +
84         VALUE_SUB_OPERATOR,                     // -
85         VALUE_MUL_OPERATOR,                     // *
86         VALUE_DIV_OPERATOR,                     // /
87         VALUE_NEG_OPERATOR,                     // -
88         VALUE_POS_OPERATOR,                     // +
89         VALUE_AND_OPERATOR,                     // &&
90         VALUE_OR_OPERATOR,                      // ||
91         VALUE_EQL_OPERATOR,                     // ==
92         VALUE_NEQ_OPERATOR,                     // !=
93         VALUE_GRE_OPERATOR,                     // >
94         VALUE_LES_OPERATOR,                     // <
95         VALUE_GEQ_OPERATOR,                     // >=
96         VALUE_LEQ_OPERATOR,                     // <=
97         VALUE_NOT_OPERATOR,                     // !
98         VALUE_NO_OPERATOR                       // no operation at all
99 };
100
101 enum VALUE_DATA_TYPE {
102         VALUE_NO_TYPE,                          // abstract baseclass
103         VALUE_INT_TYPE,
104         VALUE_FLOAT_TYPE,
105         VALUE_STRING_TYPE,
106         VALUE_BOOL_TYPE,
107         VALUE_ERROR_TYPE,
108         VALUE_EMPTY_TYPE,
109         VALUE_SOLID_TYPE,
110         VALUE_COMBISOLID_TYPE,
111         VALUE_VECTOR_TYPE,
112         VALUE_MENU_TYPE,
113         VALUE_ACTOR_TYPE,
114         VALUE_MAX_TYPE                          //only here to provide number of types
115 };
116
117
118
119 #ifdef _DEBUG
120 //extern int gRefCountValue;            // debugonly variable to check if all CValue Refences are Dereferenced at programexit
121 #endif
122
123 struct HashableInt 
124 {
125         HashableInt(int id)                                                                                                                     : mData(id) { }
126
127         unsigned long                           Hash() const                                                                                    { return 0;} ////}gHash(&mData, sizeof(int));}
128         
129         bool                            operator==(HashableInt rhs)                                                             { return mData == rhs.mData; }
130         
131         int                                     mData;
132 };
133
134
135 //
136 // Bitfield that stores the flags for each CValue derived class
137 //
138 struct ValueFlags {
139         ValueFlags() :
140                 Modified(true),
141                 Selected(false),
142                 Affected(false),
143                 ReleaseRequested(false),
144                 Error(false),
145                 RefCountDisabled(false),
146                 HasProperties(false),
147                 HasName(false),
148                 Visible(true),
149                 CustomFlag1(false),
150                 CustomFlag2(false)
151         {
152         }
153
154         unsigned short Modified : 1;
155         unsigned short Selected : 1;
156         unsigned short Affected : 1;
157         unsigned short ReleaseRequested : 1;
158         unsigned short Error : 1;
159         unsigned short RefCountDisabled : 1;
160         unsigned short HasProperties : 1;
161         unsigned short HasName : 1;
162         unsigned short Visible : 1;
163         unsigned short CustomFlag1 : 1;
164         unsigned short CustomFlag2 : 1;
165
166         
167 };
168
169 /**
170  *      Base Class for all Actions performed on CValue's. Can be extended for undo/redo system in future.
171 */
172 class CAction
173 {
174 public:
175         CAction() {
176         };
177         virtual ~CAction(){
178         };
179         virtual void Execute() const =0;
180         
181         
182 #ifdef WITH_CXX_GUARDEDALLOC
183 public:
184         void *operator new( unsigned int num_bytes) { return MEM_mallocN(num_bytes, "GE:CAction"); }
185         void operator delete( void *mem ) { MEM_freeN(mem); }
186 #endif
187 };
188
189 //
190 // CValue
191 //
192 // Base class for all editor functionality, flexible object type that allows
193 // calculations and uses reference counting for memory management.
194 // 
195 //
196
197
198
199
200 #ifndef NO_EXP_PYTHON_EMBEDDING
201 #include "PyObjectPlus.h"
202 #include "object.h"
203 class CValue  : public PyObjectPlus
204 #else
205 class CValue  
206 #endif //NO_EXP_PYTHON_EMBEDDING
207
208
209 {
210 #ifndef NO_EXP_PYTHON_EMBEDDING
211 Py_Header;
212 #endif //NO_EXP_PYTHON_EMBEDDING
213 public:
214         enum AllocationTYPE {
215                 STACKVALUE              = 0,
216                 HEAPVALUE               = 1
217         };
218         
219         enum DrawTYPE {
220                 STARTFRAME              = 0,
221                 ENDFRAME                = 1,
222                 INTERFRAME              = 2
223         };
224
225
226         // Construction / Destruction
227 #ifndef NO_EXP_PYTHON_EMBEDDING
228
229         CValue();
230         //static PyObject*      PyMake(PyObject*,PyObject*);
231         virtual PyObject *py_repr(void)
232         {
233                 return PyUnicode_FromString((const char*)GetText());
234         }
235
236         virtual PyObject*       ConvertValueToPython() {
237                 return NULL;
238         }
239
240         virtual CValue* ConvertPythonToValue(PyObject* pyobj, const char *error_prefix);
241         
242         static PyObject * pyattr_get_name(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
243         
244         virtual PyObject* ConvertKeysToPython( void );
245         
246         KX_PYMETHOD_NOARGS(CValue,GetName);
247
248 #else
249         CValue();
250 #endif //NO_EXP_PYTHON_EMBEDDING
251
252         
253         
254         // Expression Calculation
255         virtual CValue*         Calc(VALUE_OPERATOR op, CValue *val) = 0;
256         virtual CValue*         CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) = 0;
257         virtual void            SetOwnerExpression(class CExpression* expr);
258
259         
260
261         void                            Execute(const CAction& a)
262         {
263                 a.Execute();
264         };
265
266         /// Reference Counting
267         int                                     GetRefCount()                                                                                   
268         { 
269                 return m_refcount; 
270         }
271
272         // Add a reference to this value
273         CValue*                         AddRef()                                                                                                
274         {
275                 // Increase global reference count, used to see at the end of the program
276                 // if all CValue-derived classes have been dereferenced to 0
277                 //debug(gRefCountValue++);
278         #ifdef _DEBUG
279                 //gRefCountValue++;
280         #endif
281                 m_refcount++; 
282                 return this;
283         }
284
285         // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
286         int                     Release()                                                               
287         {
288                 // Decrease global reference count, used to see at the end of the program
289                 // if all CValue-derived classes have been dereferenced to 0
290                 //debug(gRefCountValue--);
291         #ifdef _DEBUG
292                 //gRefCountValue--;
293         #endif
294                 // Decrease local reference count, if it reaches 0 the object should be freed
295                 if (--m_refcount > 0)
296                 {
297                         // Reference count normal, return new reference count
298                         return m_refcount;
299                 }
300                 else
301                 {
302                         // Reference count reached 0, delete ourselves and return 0
303         //              MT_assert(m_refcount==0, "Reference count reached sub-zero, object released too much");
304                         
305                         delete this;
306                         return 0;
307                 }
308         }
309
310
311         /// Property Management
312         virtual void            SetProperty(const STR_String& name,CValue* ioProperty);                                         // Set property <ioProperty>, overwrites and releases a previous property with the same name if needed
313         virtual void            SetProperty(const char* name,CValue* ioProperty);
314         virtual CValue*         GetProperty(const char* inName);                                                        // Get pointer to a property with name <inName>, returns NULL if there is no property named <inName>
315         virtual CValue*         GetProperty(const STR_String & inName);
316         const STR_String&       GetPropertyText(const STR_String & inName);                                             // Get text description of property with name <inName>, returns an empty string if there is no property named <inName>
317         float                           GetPropertyNumber(const STR_String& inName,float defnumber);
318         virtual bool            RemoveProperty(const char *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
319         virtual vector<STR_String>      GetPropertyNames();
320         virtual void            ClearProperties();                                                                              // Clear all properties
321
322         virtual void            SetPropertiesModified(bool inModified);                                 // Set all properties' modified flag to <inModified>
323         virtual bool            IsAnyPropertyModified();                                                                // Check if any of the properties in this value have been modified
324
325         virtual CValue*         GetProperty(int inIndex);                                                               // Get property number <inIndex>
326         virtual int                     GetPropertyCount();                                                                             // Get the amount of properties assiocated with this value
327
328         virtual CValue*         FindIdentifier(const STR_String& identifiername);
329         /** Set the wireframe color of this value depending on the CSG
330          * operator type <op>
331          * @attention: not implemented */
332         virtual void            SetColorOperator(VALUE_OPERATOR op);
333
334         virtual const STR_String &      GetText() = 0;
335         virtual double          GetNumber() = 0;
336         double*                         ZeroVector() { return m_sZeroVec; };
337         virtual double*         GetVector3(bool bGetTransformedVec = false);
338
339         virtual STR_String&     GetName() = 0;                                                                                  // Retrieve the name of the value
340         virtual void            SetName(const char *name) = 0;                                                          // Set the name of the value
341         /** Sets the value to this cvalue.
342          * @attention this particular function should never be called. Why not abstract? */
343         virtual void            SetValue(CValue* newval);
344         virtual CValue*         GetReplica() =0;
345         virtual void                    ProcessReplica();
346         //virtual CValue*               Copy() = 0;
347         
348         
349         STR_String                              op2str(VALUE_OPERATOR op);
350                 
351         // setting / getting flags
352         inline void                     SetSelected(bool bSelected)                                                             { m_ValFlags.Selected = bSelected; }
353         virtual void            SetModified(bool bModified)                                                             { m_ValFlags.Modified = bModified; }
354         virtual void            SetAffected(bool bAffected=true)                                                { m_ValFlags.Affected = bAffected; }
355         inline void                     SetReleaseRequested(bool bReleaseRequested)                             { m_ValFlags.ReleaseRequested=bReleaseRequested; }
356         inline void                     SetError(bool err)                                                                              { m_ValFlags.Error=err; }
357         inline void                     SetVisible (bool vis)                                                                   { m_ValFlags.Visible=vis; }
358                                                                                                                                                                 
359         virtual bool            IsModified()                                                                                    { return m_ValFlags.Modified; }
360         inline bool                     IsError()                                                                                               { return m_ValFlags.Error; }
361         virtual bool            IsAffected()                                                                                    { return m_ValFlags.Affected || m_ValFlags.Modified; }
362         virtual bool            IsSelected()                                                                                    { return m_ValFlags.Selected; }
363         inline bool                     IsReleaseRequested()                                                                    { return m_ValFlags.ReleaseRequested; }
364         virtual bool            IsVisible()                                                                                             { return m_ValFlags.Visible;}
365         virtual void            SetCustomFlag1(bool bCustomFlag)                                                { m_ValFlags.CustomFlag1 = bCustomFlag;};
366         virtual bool            IsCustomFlag1()                                                                                 { return m_ValFlags.CustomFlag1;};
367
368         virtual void            SetCustomFlag2(bool bCustomFlag)                                                { m_ValFlags.CustomFlag2 = bCustomFlag;};
369         virtual bool            IsCustomFlag2()                                                                                 { return m_ValFlags.CustomFlag2;};
370
371 protected:                                                                                                                                              
372         virtual void            DisableRefCount();                                                                              // Disable reference counting for this value
373         //virtual void          AddDataToReplica(CValue* replica);                                              
374         virtual                         ~CValue();
375 private:
376         // Member variables                                                                                                                     
377         std::map<STR_String,CValue*>*           m_pNamedPropertyArray;                                                                  // Properties for user/game etc
378         ValueFlags                      m_ValFlags;                                                                                             // Frequently used flags in a bitfield (low memoryusage)
379         int                                     m_refcount;                                                                                             // Reference Counter    
380         static  double m_sZeroVec[3];   
381
382 };
383
384
385
386 //
387 // Declare a CValue or CExpression or CWhatever to be serialized by the editor.
388 //
389 // This macro introduces the EdSerialize() function (which must be implemented by
390 // the client) and the EdIdSerialize() function (which is implemented by this macro).
391 //
392 // The generated Copy() function returns a pointer to <root_base_class_name> type
393 // of object. So, for *any* CValue-derived object this should be set to CValue,
394 // for *any* CExpression-derived object this should be set to CExpression.
395 //
396 #define PLUGIN_DECLARE_SERIAL(class_name, root_base_class_name)                                                                                 \
397 public:                                                                                                                                                                                                 \
398         virtual root_base_class_name *  Copy()                                  { return new class_name; }                                      \
399         virtual bool EdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring);    \
400         virtual bool EdIdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring)       \
401 {                                                                                                                                                                                                               \
402         if (bIsStoring)                                                                                                                                                                         \
403                 arch.StoreString(#class_name);                                                                                                                                  \
404                                                                                                                                                                                                                 \
405         return false;                                                                                                                                                                           \
406 }                                                                                                                                                                                                               \
407         
408
409 ////////////////////////////////////////////////////////////////////////////////
410 ////////////////////////////////////////////////////////////////////////////////
411 ////////////////////////////////////////////////////////////////////////////////
412
413 // CPropValue is a CValue derived class, that implements the identification (String name)
414 // SetName() / GetName(), 
415 // normal classes should derive from CPropValue, real lightweight classes straight from CValue
416
417
418 class CPropValue : public CValue
419 {
420 public:
421 #ifndef NO_EXP_PYTHON_EMBEDDING 
422         CPropValue() :
423           CValue(),
424 #else
425         CPropValue() :
426 #endif //NO_EXP_PYTHON_EMBEDDING
427                 m_strNewName()
428
429         {
430         }
431         
432         virtual ~CPropValue()
433         {
434         }
435         
436         virtual void                    SetName(const char *name) {
437                 m_strNewName = name;
438         }
439         
440         virtual STR_String&                     GetName() {
441                 //STR_String namefromprop = GetPropertyText("Name");
442                 //if (namefromprop.Length() > 0)
443                 //      return namefromprop;
444                 return m_strNewName;
445         };                                              // name of Value
446         
447 protected:
448         STR_String                                      m_strNewName;                               // Identification
449
450
451 #ifdef WITH_CXX_GUARDEDALLOC
452 public:
453         void *operator new( unsigned int num_bytes) { return MEM_mallocN(num_bytes, "GE:CPropValue"); }
454         void operator delete( void *mem ) { MEM_freeN(mem); }
455 #endif
456 };
457
458 #endif // !defined _VALUEBASECLASS_H
459