python api for ID property access by Joseph Eager, copied from blender 2.4x.
[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 #include "PyObjectPlus.h"
201 #ifndef DISABLE_PYTHON
202 #include "object.h"
203 #endif
204 class CValue  : public PyObjectPlus
205
206 {
207 Py_Header;
208 public:
209         enum AllocationTYPE {
210                 STACKVALUE              = 0,
211                 HEAPVALUE               = 1
212         };
213         
214         enum DrawTYPE {
215                 STARTFRAME              = 0,
216                 ENDFRAME                = 1,
217                 INTERFRAME              = 2
218         };
219
220
221         // Construction / Destruction
222         CValue();
223
224 #ifndef DISABLE_PYTHON
225         //static PyObject*      PyMake(PyObject*,PyObject*);
226         virtual PyObject *py_repr(void)
227         {
228                 return PyUnicode_FromString((const char*)GetText());
229         }
230
231         virtual PyObject*       ConvertValueToPython() {
232                 return NULL;
233         }
234
235         virtual CValue* ConvertPythonToValue(PyObject* pyobj, const char *error_prefix);
236         
237         static PyObject * pyattr_get_name(void * self, const KX_PYATTRIBUTE_DEF * attrdef);
238         
239         virtual PyObject* ConvertKeysToPython( void );
240 #endif // DISABLE_PYTHON
241
242         
243         
244         // Expression Calculation
245         virtual CValue*         Calc(VALUE_OPERATOR op, CValue *val) = 0;
246         virtual CValue*         CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) = 0;
247         virtual void            SetOwnerExpression(class CExpression* expr);
248
249         
250
251         void                            Execute(const CAction& a)
252         {
253                 a.Execute();
254         };
255
256         /// Reference Counting
257         int                                     GetRefCount()                                                                                   
258         { 
259                 return m_refcount; 
260         }
261
262         // Add a reference to this value
263         CValue*                         AddRef()                                                                                                
264         {
265                 // Increase global reference count, used to see at the end of the program
266                 // if all CValue-derived classes have been dereferenced to 0
267                 //debug(gRefCountValue++);
268         #ifdef _DEBUG
269                 //gRefCountValue++;
270         #endif
271                 m_refcount++; 
272                 return this;
273         }
274
275         // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
276         int                     Release()                                                               
277         {
278                 // Decrease global reference count, used to see at the end of the program
279                 // if all CValue-derived classes have been dereferenced to 0
280                 //debug(gRefCountValue--);
281         #ifdef _DEBUG
282                 //gRefCountValue--;
283         #endif
284                 // Decrease local reference count, if it reaches 0 the object should be freed
285                 if (--m_refcount > 0)
286                 {
287                         // Reference count normal, return new reference count
288                         return m_refcount;
289                 }
290                 else
291                 {
292                         // Reference count reached 0, delete ourselves and return 0
293         //              MT_assert(m_refcount==0, "Reference count reached sub-zero, object released too much");
294                         
295                         delete this;
296                         return 0;
297                 }
298         }
299
300
301         /// Property Management
302         virtual void            SetProperty(const STR_String& name,CValue* ioProperty);                                         // Set property <ioProperty>, overwrites and releases a previous property with the same name if needed
303         virtual void            SetProperty(const char* name,CValue* ioProperty);
304         virtual CValue*         GetProperty(const char* inName);                                                        // Get pointer to a property with name <inName>, returns NULL if there is no property named <inName>
305         virtual CValue*         GetProperty(const STR_String & inName);
306         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>
307         float                           GetPropertyNumber(const STR_String& inName,float defnumber);
308         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
309         virtual vector<STR_String>      GetPropertyNames();
310         virtual void            ClearProperties();                                                                              // Clear all properties
311
312         virtual void            SetPropertiesModified(bool inModified);                                 // Set all properties' modified flag to <inModified>
313         virtual bool            IsAnyPropertyModified();                                                                // Check if any of the properties in this value have been modified
314
315         virtual CValue*         GetProperty(int inIndex);                                                               // Get property number <inIndex>
316         virtual int                     GetPropertyCount();                                                                             // Get the amount of properties assiocated with this value
317
318         virtual CValue*         FindIdentifier(const STR_String& identifiername);
319         /** Set the wireframe color of this value depending on the CSG
320          * operator type <op>
321          * @attention: not implemented */
322         virtual void            SetColorOperator(VALUE_OPERATOR op);
323
324         virtual const STR_String &      GetText() = 0;
325         virtual double          GetNumber() = 0;
326         double*                         ZeroVector() { return m_sZeroVec; };
327         virtual double*         GetVector3(bool bGetTransformedVec = false);
328
329         virtual STR_String&     GetName() = 0;                                                                                  // Retrieve the name of the value
330         virtual void            SetName(const char *name) = 0;                                                          // Set the name of the value
331         /** Sets the value to this cvalue.
332          * @attention this particular function should never be called. Why not abstract? */
333         virtual void            SetValue(CValue* newval);
334         virtual CValue*         GetReplica() =0;
335         virtual void                    ProcessReplica();
336         //virtual CValue*               Copy() = 0;
337         
338         
339         STR_String                              op2str(VALUE_OPERATOR op);
340                 
341         // setting / getting flags
342         inline void                     SetSelected(bool bSelected)                                                             { m_ValFlags.Selected = bSelected; }
343         virtual void            SetModified(bool bModified)                                                             { m_ValFlags.Modified = bModified; }
344         virtual void            SetAffected(bool bAffected=true)                                                { m_ValFlags.Affected = bAffected; }
345         inline void                     SetReleaseRequested(bool bReleaseRequested)                             { m_ValFlags.ReleaseRequested=bReleaseRequested; }
346         inline void                     SetError(bool err)                                                                              { m_ValFlags.Error=err; }
347         inline void                     SetVisible (bool vis)                                                                   { m_ValFlags.Visible=vis; }
348                                                                                                                                                                 
349         virtual bool            IsModified()                                                                                    { return m_ValFlags.Modified; }
350         inline bool                     IsError()                                                                                               { return m_ValFlags.Error; }
351         virtual bool            IsAffected()                                                                                    { return m_ValFlags.Affected || m_ValFlags.Modified; }
352         virtual bool            IsSelected()                                                                                    { return m_ValFlags.Selected; }
353         inline bool                     IsReleaseRequested()                                                                    { return m_ValFlags.ReleaseRequested; }
354         virtual bool            IsVisible()                                                                                             { return m_ValFlags.Visible;}
355         virtual void            SetCustomFlag1(bool bCustomFlag)                                                { m_ValFlags.CustomFlag1 = bCustomFlag;};
356         virtual bool            IsCustomFlag1()                                                                                 { return m_ValFlags.CustomFlag1;};
357
358         virtual void            SetCustomFlag2(bool bCustomFlag)                                                { m_ValFlags.CustomFlag2 = bCustomFlag;};
359         virtual bool            IsCustomFlag2()                                                                                 { return m_ValFlags.CustomFlag2;};
360
361 protected:                                                                                                                                              
362         virtual void            DisableRefCount();                                                                              // Disable reference counting for this value
363         //virtual void          AddDataToReplica(CValue* replica);                                              
364         virtual                         ~CValue();
365 private:
366         // Member variables                                                                                                                     
367         std::map<STR_String,CValue*>*           m_pNamedPropertyArray;                                                                  // Properties for user/game etc
368         ValueFlags                      m_ValFlags;                                                                                             // Frequently used flags in a bitfield (low memoryusage)
369         int                                     m_refcount;                                                                                             // Reference Counter    
370         static  double m_sZeroVec[3];   
371
372 };
373
374
375
376 //
377 // Declare a CValue or CExpression or CWhatever to be serialized by the editor.
378 //
379 // This macro introduces the EdSerialize() function (which must be implemented by
380 // the client) and the EdIdSerialize() function (which is implemented by this macro).
381 //
382 // The generated Copy() function returns a pointer to <root_base_class_name> type
383 // of object. So, for *any* CValue-derived object this should be set to CValue,
384 // for *any* CExpression-derived object this should be set to CExpression.
385 //
386 #define PLUGIN_DECLARE_SERIAL(class_name, root_base_class_name)                                                                                 \
387 public:                                                                                                                                                                                                 \
388         virtual root_base_class_name *  Copy()                                  { return new class_name; }                                      \
389         virtual bool EdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring);    \
390         virtual bool EdIdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring)       \
391 {                                                                                                                                                                                                               \
392         if (bIsStoring)                                                                                                                                                                         \
393                 arch.StoreString(#class_name);                                                                                                                                  \
394                                                                                                                                                                                                                 \
395         return false;                                                                                                                                                                           \
396 }                                                                                                                                                                                                               \
397         
398
399 ////////////////////////////////////////////////////////////////////////////////
400 ////////////////////////////////////////////////////////////////////////////////
401 ////////////////////////////////////////////////////////////////////////////////
402
403 // CPropValue is a CValue derived class, that implements the identification (String name)
404 // SetName() / GetName(), 
405 // normal classes should derive from CPropValue, real lightweight classes straight from CValue
406
407
408 class CPropValue : public CValue
409 {
410 public:
411         CPropValue() :
412           CValue(),
413                 m_strNewName()
414
415         {
416         }
417         
418         virtual ~CPropValue()
419         {
420         }
421         
422         virtual void                    SetName(const char *name) {
423                 m_strNewName = name;
424         }
425         
426         virtual STR_String&                     GetName() {
427                 //STR_String namefromprop = GetPropertyText("Name");
428                 //if (namefromprop.Length() > 0)
429                 //      return namefromprop;
430                 return m_strNewName;
431         };                                              // name of Value
432         
433 protected:
434         STR_String                                      m_strNewName;                               // Identification
435
436
437 #ifdef WITH_CXX_GUARDEDALLOC
438 public:
439         void *operator new( unsigned int num_bytes) { return MEM_mallocN(num_bytes, "GE:CPropValue"); }
440         void operator delete( void *mem ) { MEM_freeN(mem); }
441 #endif
442 };
443
444 #endif // !defined _VALUEBASECLASS_H
445