Merge branch 'master' into astron-master

Conflicts:
	contrib/src/ai/aiNode.h
This commit is contained in:
Sam Edwards 2015-03-28 11:22:45 -07:00
commit db2d31bf4c
505 changed files with 48699 additions and 18222 deletions

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
/built_x64
/built
/samples
/thirdparty
/targetroot

View File

@ -70,7 +70,7 @@ If you are on Ubuntu, this command should cover the most frequently
used third-party packages:
```bash
sudo apt-get install python-dev libpng-dev zlib1g-dev libssl-dev libx11-dev libgl1-mesa-dev libxrandr-dev libxxf86dga-dev libxcursor-dev bison flex libfreetype6-dev libvorbis-dev libjpeg-dev libeigen3-dev libopenal-dev libode-dev libbullet-dev nvidia-cg-toolkit
sudo apt-get install build-essential pkg-config python-dev libpng-dev libjpeg-dev libtiff-dev zlib1g-dev libssl-dev libx11-dev libgl1-mesa-dev libxrandr-dev libxxf86dga-dev libxcursor-dev bison flex libfreetype6-dev libvorbis-dev libeigen3-dev libopenal-dev libode-dev libbullet-dev nvidia-cg-toolkit libgtk2.0-dev
```
Once Panda3D has built, you can either install the .deb or .rpm package that

View File

@ -18,7 +18,7 @@
static const float _PI = 3.14;
AIBehaviors::AIBehaviors() {
_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_steering_force = LVecBase3(0.0, 0.0, 0.0);
_behaviors_flags = _behaviors_flags & _none;
_previous_conflict = false;
_conflict = false;
@ -67,7 +67,7 @@ bool AIBehaviors::is_conflict() {
}
if(is_on(_flee)) {
LVecBase3f dirn = _flee_force;
LVecBase3 dirn = _flee_force;
dirn.normalize();
_flee_force = _steering_force.length() * dirn * _flee_obj->_flee_weight;
}
@ -77,7 +77,7 @@ bool AIBehaviors::is_conflict() {
}
if(is_on(_evade)) {
LVecBase3f dirn = _evade_force;
LVecBase3 dirn = _evade_force;
dirn.normalize();
_evade_force = _steering_force.length() * dirn * _evade_obj->_evade_weight;
}
@ -111,9 +111,9 @@ bool AIBehaviors::is_conflict() {
/////////////////////////////////////////////////////////////////////////////////////////////////////
void AIBehaviors::accumulate_force(string force_type, LVecBase3f force) {
void AIBehaviors::accumulate_force(string force_type, LVecBase3 force) {
LVecBase3f old_force;
LVecBase3 old_force;
if(force_type == "seek") {
old_force = _seek_force;
@ -169,8 +169,8 @@ void AIBehaviors::accumulate_force(string force_type, LVecBase3f force) {
//////////////////////////////////////////////////////////////////////////////////////////////
LVecBase3f AIBehaviors::calculate_prioritized() {
LVecBase3f force;
LVecBase3 AIBehaviors::calculate_prioritized() {
LVecBase3 force;
if(is_on(_seek)) {
if(_conflict) {
@ -299,13 +299,13 @@ LVecBase3f AIBehaviors::calculate_prioritized() {
if(is_on(_arrival)) {
if(_seek_obj != NULL) {
LVecBase3f dirn = _steering_force;
LVecBase3 dirn = _steering_force;
dirn.normalize();
_steering_force = ((_steering_force.length() - _arrival_force.length()) * dirn);
}
if(_pursue_obj != NULL) {
LVecBase3f dirn = _steering_force;
LVecBase3 dirn = _steering_force;
dirn.normalize();
_steering_force = ((_steering_force.length() - _arrival_force.length()) * _arrival_obj->_arrival_direction);
}
@ -639,7 +639,7 @@ void AIBehaviors::resume_ai(string ai_type) {
// Function : seek
// Description : This function activates seek and makes an object of the Seek class.
// This is the function we want the user to call for seek to be done.
// This function is overloaded to accept a NodePath or an LVecBase3f.
// This function is overloaded to accept a NodePath or an LVecBase3.
/////////////////////////////////////////////////////////////////////////////////
@ -648,7 +648,7 @@ void AIBehaviors::seek(NodePath target_object, float seek_wt) {
turn_on("seek");
}
void AIBehaviors::seek(LVecBase3f pos, float seek_wt) {
void AIBehaviors::seek(LVecBase3 pos, float seek_wt) {
_seek_obj = new Seek(_ai_char, pos, seek_wt);
turn_on("seek");
}
@ -657,7 +657,7 @@ void AIBehaviors::seek(LVecBase3f pos, float seek_wt) {
//
// Function : flee
// Description : This function activates flee_activate and creates an object of the Flee class.
// This function is overloaded to accept a NodePath or an LVecBase3f.
// This function is overloaded to accept a NodePath or an LVecBase3.
//////////////////////////////////////////////////////////////////////////////////////////////////
@ -668,7 +668,7 @@ void AIBehaviors::flee(NodePath target_object, double panic_distance, double rel
turn_on("flee_activate");
}
void AIBehaviors::flee(LVecBase3f pos, double panic_distance, double relax_distance, float flee_wt) {
void AIBehaviors::flee(LVecBase3 pos, double panic_distance, double relax_distance, float flee_wt) {
_flee_obj = new Flee(_ai_char, pos, panic_distance, relax_distance, flee_wt);
_flee_list.insert(_flee_list.end(), *_flee_obj);
@ -769,38 +769,38 @@ void AIBehaviors::flock_activate() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f AIBehaviors::do_flock() {
LVecBase3 AIBehaviors::do_flock() {
//! Initialize variables required to compute the flocking force on the ai char.
unsigned int neighbor_count = 0;
LVecBase3f separation_force = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3f alignment_force = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3f cohesion_force = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3f avg_neighbor_heading = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3f total_neighbor_heading = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3f avg_center_of_mass = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3f total_center_of_mass = LVecBase3f(0.0, 0.0, 0.0);
LVecBase3 separation_force = LVecBase3(0.0, 0.0, 0.0);
LVecBase3 alignment_force = LVecBase3(0.0, 0.0, 0.0);
LVecBase3 cohesion_force = LVecBase3(0.0, 0.0, 0.0);
LVecBase3 avg_neighbor_heading = LVecBase3(0.0, 0.0, 0.0);
LVecBase3 total_neighbor_heading = LVecBase3(0.0, 0.0, 0.0);
LVecBase3 avg_center_of_mass = LVecBase3(0.0, 0.0, 0.0);
LVecBase3 total_center_of_mass = LVecBase3(0.0, 0.0, 0.0);
//! Loop through all the other AI units in the flock to check if they are neigbours.
for(unsigned int i = 0; i < _flock_group->_ai_char_list.size(); i++) {
if(_flock_group->_ai_char_list[i]->_name != _ai_char->_name) {
//! Using visibilty cone to detect neighbors.
LVecBase3f dist_vect = _flock_group->_ai_char_list[i]->_ai_char_np.get_pos() - _ai_char->_ai_char_np.get_pos();
LVecBase3f ai_char_heading = _ai_char->get_velocity();
LVecBase3 dist_vect = _flock_group->_ai_char_list[i]->_ai_char_np.get_pos() - _ai_char->_ai_char_np.get_pos();
LVecBase3 ai_char_heading = _ai_char->get_velocity();
ai_char_heading.normalize();
//! Check if the current unit is a neighbor.
if(dist_vect.dot(ai_char_heading) > ((dist_vect.length()) * (ai_char_heading.length()) * cos(_flock_group->_flock_vcone_angle * (_PI / 180)))
&& (dist_vect.length() < _flock_group->_flock_vcone_radius)) {
//! Separation force calculation.
LVecBase3f ai_char_to_units = _ai_char->_ai_char_np.get_pos() - _flock_group->_ai_char_list[i]->_ai_char_np.get_pos();
LVecBase3 ai_char_to_units = _ai_char->_ai_char_np.get_pos() - _flock_group->_ai_char_list[i]->_ai_char_np.get_pos();
float to_units_dist = ai_char_to_units.length();
ai_char_to_units.normalize();
separation_force += (ai_char_to_units / to_units_dist);
//! Calculating the total heading and center of mass of all the neighbors.
LVecBase3f neighbor_heading = _flock_group->_ai_char_list[i]->get_velocity();
LVecBase3 neighbor_heading = _flock_group->_ai_char_list[i]->get_velocity();
neighbor_heading.normalize();
total_neighbor_heading += neighbor_heading;
total_center_of_mass += _flock_group->_ai_char_list[i]->_ai_char_np.get_pos();
@ -814,7 +814,7 @@ LVecBase3f AIBehaviors::do_flock() {
if(neighbor_count > 0) {
//! Alignment force calculation
avg_neighbor_heading = total_neighbor_heading / neighbor_count;
LVector3f ai_char_heading = _ai_char->get_velocity();
LVector3 ai_char_heading = _ai_char->get_velocity();
ai_char_heading.normalize();
avg_neighbor_heading -= ai_char_heading;
avg_neighbor_heading.normalize();
@ -822,7 +822,7 @@ LVecBase3f AIBehaviors::do_flock() {
//! Cohesion force calculation
avg_center_of_mass = total_center_of_mass / neighbor_count;
LVecBase3f cohesion_dir = avg_center_of_mass - _ai_char->_ai_char_np.get_pos();
LVecBase3 cohesion_dir = avg_center_of_mass - _ai_char->_ai_char_np.get_pos();
cohesion_dir.normalize();
cohesion_force = cohesion_dir * _ai_char->_movt_force;
}
@ -830,7 +830,7 @@ LVecBase3f AIBehaviors::do_flock() {
_flock_done = true;
turn_off("flock");
turn_on("flock_activate");
return(LVecBase3f(0.0, 0.0, 0.0));
return(LVecBase3(0.0, 0.0, 0.0));
}
//! Calculate the resultant force on the ai character by taking into account the separation, alignment and cohesion
@ -885,7 +885,7 @@ void AIBehaviors::path_follow(float follow_wt) {
/////////////////////////////////////////////////////////////////////////////////
void AIBehaviors::add_to_path(LVecBase3f pos) {
void AIBehaviors::add_to_path(LVecBase3 pos) {
_path_follow_obj->add_to_path(pos);
}
@ -923,7 +923,7 @@ void AIBehaviors::init_path_find(const char* navmesh_filename) {
///////////////////////////////////////////////////////////////////////////////////////
void AIBehaviors::path_find_to(LVecBase3f pos, string type) {
void AIBehaviors::path_find_to(LVecBase3 pos, string type) {
_path_find_obj->path_find(pos, type);
}
@ -1330,56 +1330,56 @@ switch(char_to_int(ai_type)) {
if (is_on(_seek)) {
_behaviors_flags ^= _seek;
}
_seek_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_seek_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 2: {
if (is_on(_flee)) {
_behaviors_flags ^= _flee;
}
_flee_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_flee_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 3: {
if(is_on(_pursue)) {
_behaviors_flags ^= _pursue;
}
_pursue_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_pursue_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 4: {
if(is_on(_evade)) {
_behaviors_flags ^= _evade;
}
_evade_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_evade_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 5: {
if (is_on(_arrival)) {
_behaviors_flags ^= _arrival;
}
_arrival_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_arrival_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 6: {
if(is_on(_flock)) {
_behaviors_flags ^= _flock;
}
_flock_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_flock_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 7: {
if(is_on(_wander)) {
_behaviors_flags ^= _wander;
}
_wander_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_wander_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 8: {
if(is_on(_obstacle_avoidance)) {
_behaviors_flags ^= _obstacle_avoidance;
}
_obstacle_avoidance_force = LVecBase3f(0.0f, 0.0f, 0.0f);
_obstacle_avoidance_force = LVecBase3(0.0f, 0.0f, 0.0f);
break;
}
case 9:{

View File

@ -73,41 +73,41 @@ public:
Flock *_flock_group;
int _behaviors_flags;
LVecBase3f _steering_force;
LVecBase3 _steering_force;
Seek *_seek_obj;
LVecBase3f _seek_force;
LVecBase3 _seek_force;
Flee *_flee_obj;
LVecBase3f _flee_force;
LVecBase3 _flee_force;
//! This list is used if the ai character needs to flee from multiple onjects.
ListFlee _flee_list;
ListFlee::iterator _flee_itr;
Pursue *_pursue_obj;
LVecBase3f _pursue_force;
LVecBase3 _pursue_force;
Evade *_evade_obj;
LVecBase3f _evade_force;
LVecBase3 _evade_force;
//! This list is used if the ai character needs to evade from multiple onjects.
ListEvade _evade_list;
ListEvade::iterator _evade_itr;
Arrival *_arrival_obj;
LVecBase3f _arrival_force;
LVecBase3 _arrival_force;
//! Since Flock is a collective behavior the variables are declared within the AIBehaviors class.
float _flock_weight;
LVecBase3f _flock_force;
LVecBase3 _flock_force;
bool _flock_done;
Wander * _wander_obj;
LVecBase3f _wander_force;
LVecBase3 _wander_force;
ObstacleAvoidance *_obstacle_avoidance_obj;
LVecBase3f _obstacle_avoidance_force;
LVecBase3 _obstacle_avoidance_force;
PathFollow *_path_follow_obj;
@ -127,20 +127,20 @@ public:
bool is_conflict();
void accumulate_force(string force_type, LVecBase3f force);
LVecBase3f calculate_prioritized();
void accumulate_force(string force_type, LVecBase3 force);
LVecBase3 calculate_prioritized();
void flock_activate();
LVecBase3f do_flock();
LVecBase3 do_flock();
int char_to_int(string ai_type);
PUBLISHED:
void seek(NodePath target_object, float seek_wt = 1.0);
void seek(LVecBase3f pos, float seek_wt = 1.0);
void seek(LVecBase3 pos, float seek_wt = 1.0);
void flee(NodePath target_object, double panic_distance = 10.0, double relax_distance = 10.0, float flee_wt = 1.0);
void flee(LVecBase3f pos, double panic_distance = 10.0, double relax_distance = 10.0, float flee_wt = 1.0);
void flee(LVecBase3 pos, double panic_distance = 10.0, double relax_distance = 10.0, float flee_wt = 1.0);
void pursue(NodePath target_object, float pursue_wt = 1.0);
@ -155,12 +155,12 @@ PUBLISHED:
void obstacle_avoidance(float feeler_length = 1.0);
void path_follow(float follow_wt);
void add_to_path(LVecBase3f pos);
void add_to_path(LVecBase3 pos);
void start_follow(string type = "normal");
// should have different function names.
void init_path_find(const char* navmesh_filename);
void path_find_to(LVecBase3f pos, string type = "normal");
void path_find_to(LVecBase3 pos, string type = "normal");
void path_find_to(NodePath target, string type = "normal");
void add_static_obstacle(NodePath obstacle);
void add_dynamic_obstacle(NodePath obstacle);

View File

@ -23,8 +23,8 @@ AICharacter::AICharacter(string model_name, NodePath model_np, double mass, doub
_max_force = max_force;
_movt_force = movt_force;
_velocity = LVecBase3f(0.0, 0.0, 0.0);
_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_velocity = LVecBase3(0.0, 0.0, 0.0);
_steering_force = LVecBase3(0.0, 0.0, 0.0);
_steering = new AIBehaviors();
_steering->_ai_char = this;
@ -43,48 +43,43 @@ AICharacter::~AICharacter() {
// This also makes the character look at the direction of the force.
/////////////////////////////////////////////////////////////////////////////////////////
void AICharacter::update() {
if(!_steering->is_off(_steering->_none)) {
LVecBase3f old_pos = _ai_char_np.get_pos();
LVecBase3f steering_force = _steering->calculate_prioritized();
LVecBase3f acceleration = steering_force / _mass;
void AICharacter::
update() {
if (!_steering->is_off(_steering->_none)) {
LVecBase3 old_pos = _ai_char_np.get_pos();
LVecBase3 steering_force = _steering->calculate_prioritized();
LVecBase3 acceleration = steering_force / _mass;
_velocity = acceleration;
LVecBase3f direction = _steering->_steering_force;
LVecBase3 direction = _steering->_steering_force;
direction.normalize();
_ai_char_np.set_pos(old_pos + _velocity) ;
if(steering_force.length() > 0) {
if (steering_force.length() > 0) {
_ai_char_np.look_at(old_pos + (direction * 5));
_ai_char_np.set_h(_ai_char_np.get_h() + 180);
_ai_char_np.set_p(-_ai_char_np.get_p());
_ai_char_np.set_r(-_ai_char_np.get_r());
}
}
else {
_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_seek_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_flee_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_pursue_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_evade_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_arrival_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_flock_force = LVecBase3f(0.0, 0.0, 0.0);
_steering->_wander_force = LVecBase3f(0.0, 0.0, 0.0);
} else {
_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_seek_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_flee_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_pursue_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_evade_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_arrival_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_flock_force = LVecBase3(0.0, 0.0, 0.0);
_steering->_wander_force = LVecBase3(0.0, 0.0, 0.0);
}
}
LVecBase3f AICharacter::get_velocity() {
LVecBase3 AICharacter::get_velocity() {
return _velocity;
}
void AICharacter::set_velocity(LVecBase3f velocity) {
void AICharacter::set_velocity(LVecBase3 velocity) {
_velocity = velocity;
}

View File

@ -39,8 +39,8 @@ class EXPCL_PANDAAI AICharacter {
public:
double _mass;
double _max_force;
LVecBase3f _velocity;
LVecBase3f _steering_force;
LVecBase3 _velocity;
LVecBase3 _steering_force;
string _name;
double _movt_force;
unsigned int _ai_char_flock_id;
@ -51,7 +51,7 @@ class EXPCL_PANDAAI AICharacter {
bool _pf_guide;
void update();
void set_velocity(LVecBase3f vel);
void set_velocity(LVecBase3 vel);
void set_char_render(NodePath render);
NodePath get_char_render();
@ -59,7 +59,7 @@ PUBLISHED:
double get_mass();
void set_mass(double m);
LVecBase3f get_velocity();
LVecBase3 get_velocity();
double get_max_force();
void set_max_force(double max_force);

View File

@ -14,7 +14,7 @@
#include "aiNode.h"
AINode::AINode(int grid_x, int grid_y, LVecBase3f pos, float w, float l, float h) {
AINode::AINode(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h) {
for (int i = 0; i < 8; ++i) {
_neighbours[i] = NULL;
}

View File

@ -29,13 +29,7 @@
// on the mesh.
////////////////////////////////////////////////////////////////////
class EXPCL_PANDAAI AINode {
PUBLISHED:
// This variable specifies whether the node is an obtacle or not.
// Used for dynamic obstacle addition to the environment.
// obstacle = false
// navigational = true
bool _type;
public:
// This variable specifies the node status whether open, close
// or neutral.
// open = belongs to _open_list.
@ -48,6 +42,12 @@ PUBLISHED:
};
Status _status;
// This variable specifies whether the node is an obtacle or not.
// Used for dynamic obstacle addition to the environment.
// obstacle = false
// navigational = true
bool _type;
// The score is used to compute the traversal expense to nodes
// when using A*.
// _score = _cost + heuristic
@ -62,7 +62,7 @@ PUBLISHED:
int _grid_x, _grid_y;
// Position of the node in 3D space.
LVecBase3f _position;
LVecBase3 _position;
// Dimensions of each face / cell on the mesh.
// Height is given in case of expansion to a 3d mesh. Currently
@ -76,7 +76,8 @@ PUBLISHED:
// is written into navmesh.csv file.
AINode *_next;
AINode(int grid_x, int grid_y, LVecBase3f pos, float w, float l, float h);
PUBLISHED:
AINode(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h);
~AINode();
bool contains(float x, float y);

View File

@ -36,7 +36,7 @@ void PathFinder::find_path(Node *src_node, Node *dest_node) {
// Add a dummy node as the first element of the open list with score = -1.
// Inorder to implement a binary heap the index of the elements should never be 0.
Node *_dummy_node = new Node(-1, -1, LVecBase3f(0.0, 0.0, 0.0), 0, 0, 0);
Node *_dummy_node = new Node(-1, -1, LVecBase3(0.0, 0.0, 0.0), 0, 0, 0);
_dummy_node->_status = _dummy_node->open;
_dummy_node->_score = -1;
_open_list.push_back(_dummy_node);
@ -379,7 +379,7 @@ void PathFinder::remove_from_clist(int r, int c) {
/////////////////////////////////////////////////////////////////////////////////////////
Node* find_in_mesh(NavMesh nav_mesh, LVecBase3f pos, int grid_size) {
Node* find_in_mesh(NavMesh nav_mesh, LVecBase3 pos, int grid_size) {
int size = grid_size;
float x = pos[0];
float y = pos[1];

View File

@ -23,7 +23,7 @@
typedef vector<Node *> NodeArray;
typedef vector<NodeArray> NavMesh;
Node* find_in_mesh(NavMesh nav_mesh, LVecBase3f pos, int grid_size);
Node* find_in_mesh(NavMesh nav_mesh, LVecBase3 pos, int grid_size);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//

View File

@ -36,8 +36,8 @@ Arrival::~Arrival() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f Arrival::do_arrival() {
LVecBase3f direction_to_target;
LVecBase3 Arrival::do_arrival() {
LVecBase3 direction_to_target;
double distance;
if(_arrival_type) {
@ -52,22 +52,22 @@ LVecBase3f Arrival::do_arrival() {
_arrival_direction.normalize();
if(int(distance) == 0) {
_ai_char->_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_arrival_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
_ai_char->_steering->_arrival_force = LVecBase3(0.0, 0.0, 0.0);
if(_ai_char->_steering->_seek_obj != NULL) {
_ai_char->_steering->turn_off("arrival");
_ai_char->_steering->turn_on("arrival_activate");
}
_arrival_done = true;
return(LVecBase3f(0.0, 0.0, 0.0));
return(LVecBase3(0.0, 0.0, 0.0));
}
else {
_arrival_done = false;
}
double u = _ai_char->get_velocity().length();
LVecBase3f desired_force = ((u * u) / (2 * distance)) * _ai_char->get_mass();
LVecBase3 desired_force = ((u * u) / (2 * distance)) * _ai_char->get_mass();
if(_ai_char->_steering->_seek_obj != NULL) {
return(desired_force);
@ -85,7 +85,7 @@ LVecBase3f Arrival::do_arrival() {
}
cout<<"Arrival works only with seek and pursue"<<endl;
return(LVecBase3f(0.0, 0.0, 0.0));
return(LVecBase3(0.0, 0.0, 0.0));
}
/////////////////////////////////////////////////////////////////////////////////
@ -98,7 +98,7 @@ LVecBase3f Arrival::do_arrival() {
/////////////////////////////////////////////////////////////////////////////////
void Arrival::arrival_activate() {
LVecBase3f dirn;
LVecBase3 dirn;
if(_arrival_type) {
dirn = (_ai_char->_ai_char_np.get_pos(_ai_char->_window_render) - _ai_char->get_ai_behaviors()->_pursue_obj->_pursue_target.get_pos(_ai_char->_window_render));
}

View File

@ -27,9 +27,9 @@ public:
AICharacter *_ai_char;
NodePath _arrival_target;
LVecBase3f _arrival_target_pos;
LVecBase3 _arrival_target_pos;
double _arrival_distance;
LVecBase3f _arrival_direction;
LVecBase3 _arrival_direction;
bool _arrival_done;
// This flag specifies if the arrival behavior is being used with seek or pursue behavior.
@ -39,7 +39,7 @@ public:
Arrival(AICharacter *ai_ch, double distance = 10.0);
~Arrival();
LVecBase3f do_arrival();
LVecBase3 do_arrival();
void arrival_activate();
};

View File

@ -42,23 +42,23 @@ Evade::~Evade() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f Evade::do_evade() {
LVecBase3 Evade::do_evade() {
assert(_evade_target && "evade target not assigned");
_evade_direction = _ai_char->_ai_char_np.get_pos(_ai_char->_window_render) - _evade_target.get_pos(_ai_char->_window_render);
double distance = _evade_direction.length();
_evade_direction.normalize();
LVecBase3f desired_force = _evade_direction * _ai_char->_movt_force;
LVecBase3 desired_force = _evade_direction * _ai_char->_movt_force;
if(distance > (_evade_distance + _evade_relax_distance)) {
if((_ai_char->_steering->_behaviors_flags | _ai_char->_steering->_evade) == _ai_char->_steering->_evade) {
_ai_char->_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
}
_ai_char->_steering->turn_off("evade");
_ai_char->_steering->turn_on("evade_activate");
_evade_done = true;
return(LVecBase3f(0.0, 0.0, 0.0));
return(LVecBase3(0.0, 0.0, 0.0));
}
else {
_evade_done = false;

View File

@ -28,7 +28,7 @@ public:
NodePath _evade_target;
float _evade_weight;
LVecBase3f _evade_direction;
LVecBase3 _evade_direction;
double _evade_distance;
double _evade_relax_distance;
bool _evade_done;
@ -38,7 +38,7 @@ public:
double relax_distance, float evade_wt);
~Evade();
LVecBase3f do_evade();
LVecBase3 do_evade();
void evade_activate();
};

View File

@ -29,7 +29,7 @@ Flee::Flee(AICharacter *ai_ch, NodePath target_object, double panic_distance,
_flee_activate_done = false;
}
Flee::Flee(AICharacter *ai_ch, LVecBase3f pos, double panic_distance,
Flee::Flee(AICharacter *ai_ch, LVecBase3 pos, double panic_distance,
double relax_distance, float flee_wt){
_ai_char = ai_ch;
@ -57,10 +57,10 @@ Flee::~Flee() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f Flee::do_flee() {
LVecBase3f dirn;
LVecBase3 Flee::do_flee() {
LVecBase3 dirn;
double distance;
LVecBase3f desired_force;
LVecBase3 desired_force;
dirn = _ai_char->_ai_char_np.get_pos(_ai_char->_window_render) - _flee_present_pos;
distance = dirn.length();
@ -68,12 +68,12 @@ LVecBase3f Flee::do_flee() {
if(distance > (_flee_distance + _flee_relax_distance)) {
if((_ai_char->_steering->_behaviors_flags | _ai_char->_steering->_flee) == _ai_char->_steering->_flee) {
_ai_char->_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
}
_flee_done = true;
_ai_char->_steering->turn_off("flee");
_ai_char->_steering->turn_on("flee_activate");
return(LVecBase3f(0.0, 0.0, 0.0));
return(LVecBase3(0.0, 0.0, 0.0));
}
else {
return(desired_force);
@ -90,7 +90,7 @@ LVecBase3f Flee::do_flee() {
/////////////////////////////////////////////////////////////////////////////////
void Flee::flee_activate() {
LVecBase3f dirn;
LVecBase3 dirn;
double distance;
_flee_activate_done = false;

View File

@ -26,23 +26,23 @@ class EXPCL_PANDAAI Flee {
public:
AICharacter *_ai_char;
LVecBase3f _flee_position;
LVecBase3 _flee_position;
float _flee_weight;
LVecBase3f _flee_direction;
LVecBase3 _flee_direction;
double _flee_distance;
double _flee_relax_distance;
LVecBase3f _flee_present_pos;
LVecBase3 _flee_present_pos;
bool _flee_done;
bool _flee_activate_done;
Flee(AICharacter *ai_ch, NodePath target_object, double panic_distance = 10.0,
double relax_distance = 10.0, float flee_wt = 1.0);
Flee(AICharacter *ai_ch, LVecBase3f pos, double panic_distance = 10.0,
Flee(AICharacter *ai_ch, LVecBase3 pos, double panic_distance = 10.0,
double relax_distance = 10.0, float flee_wt = 1.0);
~Flee();
LVecBase3f do_flee();
LVecBase3 do_flee();
void flee_activate();
};

View File

@ -1,7 +1,7 @@
#include "meshNode.h"
Node::Node(int grid_x, int grid_y, LVecBase3f pos, float w, float l, float h) {
Node::Node(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h) {
for(int i = 0; i < 8; ++i) {
_neighbours[i] = NULL;
}

View File

@ -47,7 +47,7 @@ public:
int _grid_x, _grid_y;
// Position of the node in 3D space.
LVecBase3f _position;
LVecBase3 _position;
// Dimensions of each face / cell on the mesh.
// Height is given in case of expansion to a 3d mesh. Currently not used.
@ -58,7 +58,7 @@ public:
// Note: The data in this member is discarded when mesh data is written into navmesh.csv file.
Node *_next;
Node(int grid_x, int grid_y, LVecBase3f pos, float w, float l, float h);
Node(int grid_x, int grid_y, LVecBase3 pos, float w, float l, float h);
~Node();
bool contains(float x, float y);

View File

@ -35,15 +35,15 @@ bool ObstacleAvoidance::obstacle_detection() {
// Calculate the volume of the AICharacter with respect to render
PT(BoundingVolume) np_bounds = _ai_char->get_node_path().get_bounds();
CPT(BoundingSphere) np_sphere = np_bounds->as_bounding_sphere();
LVecBase3f avoidance(0.0, 0.0, 0.0);
LVecBase3 avoidance(0.0, 0.0, 0.0);
double distance = 0x7fff ;
double expanded_radius;
LVecBase3f to_obstacle;
LVecBase3f prev_avoidance;
LVecBase3 to_obstacle;
LVecBase3 prev_avoidance;
for(unsigned int i = 0; i < _ai_char->_world->_obstacles.size(); ++i) {
PT(BoundingVolume) bounds = _ai_char->_world->_obstacles[i].get_bounds();
CPT(BoundingSphere) bsphere = bounds->as_bounding_sphere();
LVecBase3f near_obstacle = _ai_char->_world->_obstacles[i].get_pos() - _ai_char->get_node_path().get_pos();
LVecBase3 near_obstacle = _ai_char->_world->_obstacles[i].get_pos() - _ai_char->get_node_path().get_pos();
// Check if it's the nearest obstacle, If so initialize as the nearest obstacle
if((near_obstacle.length() < distance) && (_ai_char->_world->_obstacles[i].get_pos() != _ai_char->get_node_path().get_pos())) {
_nearest_obstacle = _ai_char->_world->_obstacles[i];
@ -51,13 +51,13 @@ bool ObstacleAvoidance::obstacle_detection() {
expanded_radius = bsphere->get_radius() + np_sphere->get_radius();
}
}
LVecBase3f feeler = _feeler * _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3f::forward());
LVecBase3 feeler = _feeler * _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3::forward());
feeler.normalize();
feeler *= (expanded_radius + np_sphere->get_radius()) ;
to_obstacle = _nearest_obstacle.get_pos() - _ai_char->get_node_path().get_pos();
LVector3f line_vector = _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3f::forward());
LVecBase3f project = (to_obstacle.dot(line_vector) * line_vector) / line_vector.length_squared();
LVecBase3f perp = project - to_obstacle;
LVector3 line_vector = _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3::forward());
LVecBase3 project = (to_obstacle.dot(line_vector) * line_vector) / line_vector.length_squared();
LVecBase3 perp = project - to_obstacle;
// If the nearest obstacle will collide with our AICharacter then send obstacle detection as true
if((_nearest_obstacle) && (perp.length() < expanded_radius - np_sphere->get_radius()) && (project.length() < feeler.length())) {
return true;
@ -90,27 +90,27 @@ void ObstacleAvoidance::obstacle_avoidance_activate() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f ObstacleAvoidance::do_obstacle_avoidance() {
LVecBase3f offset = _ai_char->get_node_path().get_pos() - _nearest_obstacle.get_pos();
LVecBase3 ObstacleAvoidance::do_obstacle_avoidance() {
LVecBase3 offset = _ai_char->get_node_path().get_pos() - _nearest_obstacle.get_pos();
PT(BoundingVolume) bounds =_nearest_obstacle.get_bounds();
CPT(BoundingSphere) bsphere = bounds->as_bounding_sphere();
PT(BoundingVolume) np_bounds = _ai_char->get_node_path().get_bounds();
CPT(BoundingSphere) np_sphere = np_bounds->as_bounding_sphere();
double distance_needed = offset.length() - bsphere->get_radius() - np_sphere->get_radius();
if((obstacle_detection())) {
LVecBase3f direction = _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3f::forward());
LVecBase3 direction = _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3::forward());
direction.normalize();
float forward_component = offset.dot(direction);
LVecBase3f projection = forward_component * direction;
LVecBase3f perpendicular_component = offset - projection;
LVecBase3 projection = forward_component * direction;
LVecBase3 perpendicular_component = offset - projection;
double p = perpendicular_component.length();
perpendicular_component.normalize();
LVecBase3f avoidance = perpendicular_component;
LVecBase3 avoidance = perpendicular_component;
// The more closer the obstacle, the more force it generates
avoidance = (avoidance * _ai_char->get_max_force() * _ai_char->_movt_force) / (p + 0.01);
return avoidance;
}
_ai_char->_steering->turn_on("obstacle_avoidance_activate");
_ai_char->_steering->turn_off("obstacle_avoidance");
return LVecBase3f(0, 0, 0);
return LVecBase3(0, 0, 0);
}

View File

@ -30,7 +30,7 @@ class EXPCL_PANDAAI ObstacleAvoidance {
float _feeler;
ObstacleAvoidance(AICharacter *ai_char, float feeler_length);
LVecBase3f do_obstacle_avoidance();
LVecBase3 do_obstacle_avoidance();
~ObstacleAvoidance();
void obstacle_avoidance_activate();
bool obstacle_detection();

View File

@ -29,7 +29,7 @@ void PathFind::create_nav_mesh(const char* navmesh_filename) {
// Stage variables.
int grid_x, grid_y;
float l, w, h;
LVecBase3f position;
LVecBase3 position;
// Variable to hold line data read from file.
string line;
@ -75,7 +75,7 @@ void PathFind::create_nav_mesh(const char* navmesh_filename) {
l = atof(fields[4].c_str());
w = atof(fields[5].c_str());
h = atof(fields[6].c_str());
position = LVecBase3f(atof(fields[7].c_str()), atof(fields[8].c_str()), atof(fields[9].c_str()));
position = LVecBase3(atof(fields[7].c_str()), atof(fields[8].c_str()), atof(fields[9].c_str()));
Node *stage_node = new Node(grid_x, grid_y, position, w, l, h);
@ -197,7 +197,7 @@ void PathFind::set_path_find(const char* navmesh_filename) {
///////////////////////////////////////////////////////////////////////////////////////
void PathFind::path_find(LVecBase3f pos, string type) {
void PathFind::path_find(LVecBase3 pos, string type) {
if(type == "addPath") {
if(_ai_char->_steering->_path_follow_obj) {
_ai_char->_steering->remove_ai("pathfollow");

View File

@ -43,7 +43,7 @@ public:
int _grid_size;
NodePath _path_find_target;
LVecBase3f _prev_position;
LVecBase3 _prev_position;
PT(GeomNode) _parent;
LineSegs *_pen;
vector<int> _previous_obstacles;
@ -62,7 +62,7 @@ public:
void clear_previous_obstacles();
void set_path_find(const char* navmesh_filename);
void path_find(LVecBase3f pos, string type = "normal");
void path_find(LVecBase3 pos, string type = "normal");
void path_find(NodePath target, string type = "normal");
void add_obstacle_to_mesh(NodePath obstacle);
void dynamic_avoid(NodePath obstacle);

View File

@ -20,7 +20,7 @@ PathFollow::~PathFollow() {
/////////////////////////////////////////////////////////////////////////////////////////
void PathFollow::add_to_path(LVecBase3f pos) {
void PathFollow::add_to_path(LVecBase3 pos) {
_path.push_back(pos);
}
@ -119,7 +119,7 @@ void PathFollow::do_follow() {
bool PathFollow::check_if_possible() {
Node* src = find_in_mesh(_ai_char->_steering->_path_find_obj->_nav_mesh, _ai_char->_ai_char_np.get_pos(_ai_char->_window_render), _ai_char->_steering->_path_find_obj->_grid_size);
LVecBase3f _prev_position = _ai_char->_steering->_path_find_obj->_path_find_target.get_pos(_ai_char->_window_render);
LVecBase3 _prev_position = _ai_char->_steering->_path_find_obj->_path_find_target.get_pos(_ai_char->_window_render);
Node* dst = find_in_mesh(_ai_char->_steering->_path_find_obj->_nav_mesh, _prev_position, _ai_char->_steering->_path_find_obj->_grid_size);
if(src && dst) {

View File

@ -13,7 +13,7 @@ class EXPCL_PANDAAI PathFollow {
public:
AICharacter *_ai_char;
float _follow_weight;
vector<LVecBase3f> _path;
vector<LVecBase3> _path;
int _curr_path_waypoint;
bool _start;
NodePath _dummy;
@ -23,7 +23,7 @@ public:
PathFollow(AICharacter *ai_ch, float follow_wt);
~PathFollow();
void add_to_path(LVecBase3f pos);
void add_to_path(LVecBase3 pos);
void start(string type);
void do_follow();
bool check_if_possible();

View File

@ -37,17 +37,17 @@ Pursue::~Pursue() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f Pursue::do_pursue() {
LVecBase3 Pursue::do_pursue() {
assert(_pursue_target && "pursue target not assigned");
LVecBase3f present_pos = _ai_char->_ai_char_np.get_pos(_ai_char->_window_render);
LVecBase3 present_pos = _ai_char->_ai_char_np.get_pos(_ai_char->_window_render);
double target_distance = (_pursue_target.get_pos(_ai_char->_window_render) - present_pos).length();
if(int(target_distance) == 0) {
_pursue_done = true;
_ai_char->_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_pursue_force = LVecBase3f(0.0, 0.0, 0.0);
return(LVecBase3f(0.0, 0.0, 0.0));
_ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
_ai_char->_steering->_pursue_force = LVecBase3(0.0, 0.0, 0.0);
return(LVecBase3(0.0, 0.0, 0.0));
}
else {
_pursue_done = false;
@ -56,6 +56,6 @@ LVecBase3f Pursue::do_pursue() {
_pursue_direction = _pursue_target.get_pos(_ai_char->_window_render) - present_pos;
_pursue_direction.normalize();
LVecBase3f desired_force = _pursue_direction * _ai_char->_movt_force;
LVecBase3 desired_force = _pursue_direction * _ai_char->_movt_force;
return(desired_force);
}

View File

@ -28,12 +28,12 @@ public:
NodePath _pursue_target;
float _pursue_weight;
LVecBase3f _pursue_direction;
LVecBase3 _pursue_direction;
bool _pursue_done;
Pursue(AICharacter *ai_ch, NodePath target_object, float pursue_wt);
~Pursue();
LVecBase3f do_pursue();
LVecBase3 do_pursue();
};
#endif

View File

@ -27,7 +27,7 @@ Seek::Seek(AICharacter *ai_ch, NodePath target_object, float seek_wt) {
_seek_done = false;
}
Seek::Seek(AICharacter *ai_ch, LVecBase3f pos, float seek_wt) {
Seek::Seek(AICharacter *ai_ch, LVecBase3 pos, float seek_wt) {
_ai_char = ai_ch;
_seek_position = pos;
@ -51,16 +51,16 @@ Seek::~Seek() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f Seek::do_seek() {
LVecBase3 Seek::do_seek() {
double target_distance = (_seek_position - _ai_char->_ai_char_np.get_pos(_ai_char->_window_render)).length();
if(int(target_distance) == 0) {
_seek_done = true;
_ai_char->_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
_ai_char->_steering->turn_off("seek");
return(LVecBase3f(0.0, 0.0, 0.0));
return(LVecBase3(0.0, 0.0, 0.0));
}
LVecBase3f desired_force = _seek_direction * _ai_char->_movt_force;
LVecBase3 desired_force = _seek_direction * _ai_char->_movt_force;
return(desired_force);
}

View File

@ -26,16 +26,16 @@ class EXPCL_PANDAAI Seek {
public:
AICharacter *_ai_char;
LVecBase3f _seek_position;
LVecBase3 _seek_position;
float _seek_weight;
LVecBase3f _seek_direction;
LVecBase3 _seek_direction;
bool _seek_done;
LVecBase3f _seek_accum_force;
LVecBase3 _seek_accum_force;
Seek(AICharacter *ai_ch, NodePath target_object, float seek_wt = 1.0);
Seek(AICharacter *ai_ch, LVecBase3f pos, float seek_wt = 1.0);
Seek(AICharacter *ai_ch, LVecBase3 pos, float seek_wt = 1.0);
~Seek();
LVecBase3f do_seek();
LVecBase3 do_seek();
};
#endif

View File

@ -57,23 +57,23 @@ Wander::Wander(AICharacter *ai_ch, double wander_radius,int flag, double aoe, fl
// default is XY axes
switch(_flag) {
case 0: {
_wander_target = LVecBase3f(_wander_radius * cos(theta), _wander_radius * sin(theta),0);
_wander_target = LVecBase3(_wander_radius * cos(theta), _wander_radius * sin(theta),0);
break;
}
case 1: {
_wander_target = LVecBase3f(0, _wander_radius * cos(theta), _wander_radius * sin(theta));
_wander_target = LVecBase3(0, _wander_radius * cos(theta), _wander_radius * sin(theta));
break;
}
case 2: {
_wander_target = LVecBase3f(_wander_radius * cos(theta), 0, _wander_radius * sin(theta));
_wander_target = LVecBase3(_wander_radius * cos(theta), 0, _wander_radius * sin(theta));
break;
}
case 3: {
_wander_target = LVecBase3f(_wander_radius * sin(theta) * cos(si), _wander_radius * sin(theta) * sin(si), _wander_radius * cos(theta));
_wander_target = LVecBase3(_wander_radius * sin(theta) * cos(si), _wander_radius * sin(theta) * sin(si), _wander_radius * cos(theta));
break;
}
default: {
_wander_target = LVecBase3f(_wander_radius * cos(theta), _wander_radius * sin(theta),0);
_wander_target = LVecBase3(_wander_radius * cos(theta), _wander_radius * sin(theta),0);
break;
}
}
@ -91,52 +91,52 @@ Wander::~Wander() {
/////////////////////////////////////////////////////////////////////////////////
LVecBase3f Wander::do_wander() {
LVecBase3f present_pos = _ai_char->get_node_path().get_pos(_ai_char->get_char_render());
LVecBase3 Wander::do_wander() {
LVecBase3 present_pos = _ai_char->get_node_path().get_pos(_ai_char->get_char_render());
// Create the random slices to enable random movement of wander for x,y,z respectively
double time_slice_1 = random_clamped() * 1.5;
double time_slice_2 = random_clamped() * 1.5;
double time_slice_3 = random_clamped() * 1.5;
switch(_flag) {
case 0: {
_wander_target += LVecBase3f(time_slice_1, time_slice_2, 0);
_wander_target += LVecBase3(time_slice_1, time_slice_2, 0);
break;
}
case 1: {
_wander_target += LVecBase3f(0, time_slice_1, time_slice_2);
_wander_target += LVecBase3(0, time_slice_1, time_slice_2);
break;
}
case 2: {
_wander_target += LVecBase3f(time_slice_1, 0, time_slice_2);
_wander_target += LVecBase3(time_slice_1, 0, time_slice_2);
break;
}
case 3: {
_wander_target += LVecBase3f(time_slice_1, time_slice_2, time_slice_3);
_wander_target += LVecBase3(time_slice_1, time_slice_2, time_slice_3);
break;
}
default: {
_wander_target = LVecBase3f(time_slice_1, time_slice_2, 0);
_wander_target = LVecBase3(time_slice_1, time_slice_2, 0);
}
}
_wander_target.normalize();
_wander_target *= _wander_radius;
LVecBase3f target = _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3f::forward());
LVecBase3 target = _ai_char->get_char_render().get_relative_vector(_ai_char->get_node_path(), LVector3::forward());
target.normalize();
// Project wander target onto global space
target = _wander_target + target;
LVecBase3f desired_target = present_pos + target;
LVecBase3f desired_force = desired_target - _ai_char->get_node_path().get_pos() ;
LVecBase3 desired_target = present_pos + target;
LVecBase3 desired_force = desired_target - _ai_char->get_node_path().get_pos() ;
desired_force.normalize();
desired_force *= _ai_char->_movt_force;
double distance = (present_pos - _init_pos).length();
if(_area_of_effect > 0 && distance > _area_of_effect) {
LVecBase3f direction = present_pos - _init_pos;
LVecBase3 direction = present_pos - _init_pos;
direction.normalize();
desired_force = - direction * _ai_char->_movt_force;
LVecBase3f dirn = _ai_char->_steering->_steering_force;
LVecBase3 dirn = _ai_char->_steering->_steering_force;
dirn.normalize();
_ai_char->_steering->_steering_force = LVecBase3f(0.0, 0.0, 0.0);
_ai_char->_steering->_steering_force = LVecBase3(0.0, 0.0, 0.0);
}
return desired_force;
}

View File

@ -24,14 +24,14 @@ class EXPCL_PANDAAI Wander {
public:
AICharacter *_ai_char;
double _wander_radius;
LVecBase3f _wander_target;
LVecBase3 _wander_target;
float _wander_weight;
int _flag;
LVecBase3f _init_pos;
LVecBase3 _init_pos;
double _area_of_effect;
Wander(AICharacter *ai_ch, double wander_radius, int flag, double aoe, float wander_weight);
LVecBase3f do_wander();
LVecBase3 do_wander();
~Wander();
};

View File

@ -1019,11 +1019,6 @@ class Actor(DirectObject, NodePath):
if (partName in partDict):
del(partDict[partName])
# remove the bundle handle, in case this part is ever
# loaded again in the future
if partName in self.__commonBundleHandles:
del self.__commonBundleHandles[partName]
def hidePart(self, partName, lodName="lodRoot"):
"""
Make the given part of the optionally given lod not render,

View File

@ -1,4 +1,5 @@
print 'DirectStart: Starting the game.'
__all__ = []
print('Using deprecated DirectStart interface.')
from direct.showbase import ShowBase
base = ShowBase.ShowBase()

View File

@ -1,5 +1,7 @@
"""instantiate global DirectNotify used in Direct"""
__all__ = ['directNotify', 'giveNotify']
import DirectNotify
directNotify = DirectNotify.DirectNotify()

View File

@ -760,13 +760,13 @@ STRIP_CODE_COMMENTS = YES
# then for each documented function all documented
# functions referencing it will be listed.
REFERENCED_BY_RELATION = YES
REFERENCED_BY_RELATION = NO
# If the REFERENCES_RELATION tag is set to YES
# then for each documented function all documented entities
# called/used by that function will be listed.
REFERENCES_RELATION = YES
REFERENCES_RELATION = NO
# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from

View File

@ -30,6 +30,7 @@ def comment(code):
if empty_line:
# New paragraph.
comment += '\n\n'
empty_line = False
elif comment:
comment += '\n'
comment += '/// ' + line
@ -56,15 +57,29 @@ def block_comment(code):
line = line.rstrip()
strline = line.lstrip('/ \t')
if reading_desc:
newlines.append('/// ' + line[min(indent, len(line) - len(strline)):])
else:
# A "Description:" text starts the description.
if strline.startswith("Description"):
strline = strline[11:].lstrip(': \t')
indent = len(line) - len(strline)
reading_desc = True
newlines.append('/// ' + strline)
if ':' in strline:
pre, post = strline.split(':', 1)
pre = pre.rstrip()
if pre == "Description":
strline = post.lstrip()
elif pre in ("Class", "Access", "Function", "Created by", "Enum"):
continue
if strline or len(newlines) > 0:
newlines.append('/// ' + strline)
#if reading_desc:
# newlines.append('/// ' + line[min(indent, len(line) - len(strline)):])
#else:
# # A "Description:" text starts the description.
# if strline.startswith("Description"):
# strline = strline[11:].lstrip(': \t')
# indent = len(line) - len(strline)
# reading_desc = True
# newlines.append('/// ' + strline)
# else:
# print line
newcode = '\n'.join(newlines)
if len(newcode) > 0:
@ -73,6 +88,9 @@ def block_comment(code):
return ""
def translateFunctionName(name):
if name.startswith("__"):
return name
new = ""
for i in name.split("_"):
if new == "":
@ -85,32 +103,58 @@ def translateFunctionName(name):
new += i[0].upper() + i[1:]
return new
def translated_type_name(type):
def translateTypeName(name, mangle=True):
# Equivalent to C++ classNameFromCppName
class_name = ""
bad_chars = "!@#$%^&*()<>,.-=+~{}? "
next_cap = False
first_char = mangle
for chr in name:
if (chr == '_' or chr == ' ') and mangle:
next_cap = True
elif chr in bad_chars:
if not mangle:
class_name += '_'
elif next_cap or first_char:
class_name += chr.upper()
next_cap = False
first_char = False
else:
class_name += chr
return class_name
def translated_type_name(type, scoped=True):
while interrogate_type_is_wrapped(type):
if interrogate_type_is_const(type):
return 'const ' + translated_type_name(interrogate_type_wrapped_type(type))
else:
type = interrogate_type_wrapped_type(type)
typename = interrogate_type_name(type)
if typename in ("PyObject", "_object"):
return "object"
if interrogate_type_is_atomic(type):
token = interrogate_type_atomic_token(type)
if token == 7:
return 'str'
else:
return typename
typename = interrogate_type_name(type)
typename = typename.replace("< ", "").replace(" >", "")
return typename
typename = translateTypeName(typename)
def translateTypeSpec(name):
name = name.strip("* ")
name = name.replace("BitMask< unsigned int, 32 >", "BitMask32")
name = name.replace("atomic ", "")
name = name.replace("< ", "").replace(" >", "")
if name == '_object':
name = 'object'
elif name == '_typeobject':
name = 'type'
return name
if scoped and interrogate_type_is_nested(type):
return translated_type_name(interrogate_type_outer_class(type)) + '::' + typename
else:
return typename
def processElement(handle, element):
if interrogate_element_has_comment(element):
print >>handle, comment(interrogate_element_comment(element))
print >>handle, translateTypeSpec(translated_type_name(interrogate_element_type(element))),
print >>handle, translated_type_name(interrogate_element_type(element)),
print >>handle, interrogate_element_name(element) + ';'
def processFunction(handle, function, isConstructor = False):
@ -120,11 +164,12 @@ def processFunction(handle, function, isConstructor = False):
print >>handle, block_comment(interrogate_wrapper_comment(wrapper))
if not isConstructor:
if not interrogate_wrapper_number_of_parameters(wrapper) > 0 or not interrogate_wrapper_parameter_is_this(wrapper, 0):
print >>handle, "static",
if interrogate_function_is_method(function):
if not interrogate_wrapper_number_of_parameters(wrapper) > 0 or not interrogate_wrapper_parameter_is_this(wrapper, 0):
print >>handle, "static",
if interrogate_wrapper_has_return_value(wrapper):
print >>handle, translateTypeSpec(translated_type_name(interrogate_wrapper_return_type(wrapper))),
print >>handle, translated_type_name(interrogate_wrapper_return_type(wrapper)),
else:
pass#print >>handle, "void",
@ -137,7 +182,7 @@ def processFunction(handle, function, isConstructor = False):
if not interrogate_wrapper_parameter_is_this(wrapper, i_param):
if not first:
print >>handle, ",",
print >>handle, translateTypeSpec(translated_type_name(interrogate_wrapper_parameter_type(wrapper, i_param))),
print >>handle, translated_type_name(interrogate_wrapper_parameter_type(wrapper, i_param)),
if interrogate_wrapper_parameter_has_name(wrapper, i_param):
print >>handle, interrogate_wrapper_parameter_name(wrapper, i_param),
first = False
@ -145,7 +190,7 @@ def processFunction(handle, function, isConstructor = False):
print >>handle, ");"
def processType(handle, type):
typename = translated_type_name(type)
typename = translated_type_name(type, scoped=False)
derivations = [ translated_type_name(interrogate_type_get_derivation(type, n)) for n in range(interrogate_type_number_of_derivations(type)) ]
if interrogate_type_has_comment(type):
@ -157,7 +202,7 @@ def processType(handle, type):
docstring = comment(interrogate_type_enum_value_comment(type, i_value))
if docstring:
print >>handle, docstring
print >>handle, translateFunctionName(interrogate_type_enum_value_name(type, i_value)), "=", interrogate_type_enum_value(type, i_value), ","
print >>handle, interrogate_type_enum_value_name(type, i_value), "=", interrogate_type_enum_value(type, i_value), ","
else:
if interrogate_type_is_struct(type):
classtype = "struct"
@ -192,38 +237,54 @@ def processType(handle, type):
print >>handle, "};"
def processModule(handle, package):
print >>handle, "namespace %s {" % package
if package != "core":
print >>handle, "using namespace core;"
for i_type in xrange(interrogate_number_of_global_types()):
type = interrogate_get_global_type(i_type)
if interrogate_type_has_module_name(type):
module_name = interrogate_type_module_name(type)
if "panda3d." + package == module_name:
processType(handle, type)
else:
print "Type %s has no module name" % typename
for i_func in xrange(interrogate_number_of_global_functions()):
func = interrogate_get_global_function(i_func)
if interrogate_function_has_module_name(func):
module_name = interrogate_function_module_name(func)
if "panda3d." + package == module_name:
processFunction(handle, func)
else:
print "Type %s has no module name" % typename
print >>handle, "}"
if __name__ == "__main__":
handle = open("pandadoc.hpp", "w")
print >>handle, comment("Panda3D modules that are implemented in C++.")
print >>handle, "namespace panda3d {}"
print >>handle, "namespace panda3d {"
# Determine the path to the interrogatedb files
interrogate_add_search_directory(os.path.join(os.path.dirname(pandac.__file__), "..", "..", "etc"))
interrogate_add_search_directory(os.path.join(os.path.dirname(pandac.__file__), "input"))
import panda3d.core
processModule(handle, "core")
for lib in os.listdir(os.path.dirname(panda3d.__file__)):
if lib.endswith(('.pyd', '.so')) and not lib.startswith('core.'):
__import__('panda3d.' + os.path.splitext(lib)[0])
module_name = os.path.splitext(lib)[0]
__import__("panda3d." + module_name)
processModule(handle, module_name)
lastpkg = None
for i_type in xrange(interrogate_number_of_global_types()):
type = interrogate_get_global_type(i_type)
if interrogate_type_has_module_name(type):
package = interrogate_type_module_name(type)
if lastpkg != package:
if lastpkg is not None:
print >>handle, "}"
print >>handle, "namespace %s {" % package
lastpkg = package
processType(handle, type)
else:
print "Type %s has no module name" % typename
if lastpkg is not None:
print >>handle, "}"
print >>handle, "}"
handle.close()

View File

@ -494,7 +494,7 @@ class ConnectionRepository(
elif self.connectMethod == self.CM_NET or (not hasattr(self,"connectNative")):
# Try each of the servers in turn.
for url in serverList:
self.notify.info("Connecting to %s via NET interface." % (url.cStr()))
self.notify.info("Connecting to %s via NET interface." % (url))
if self.tryConnectNet(url):
self.startReaderPollTask()
if successCallback:
@ -506,7 +506,7 @@ class ConnectionRepository(
failureCallback(0, '', *failureArgs)
elif self.connectMethod == self.CM_NATIVE:
for url in serverList:
self.notify.info("Connecting to %s via Native interface." % (url.cStr()))
self.notify.info("Connecting to %s via Native interface." % (url))
if self.connectNative(url):
self.startReaderPollTask()
if successCallback:
@ -539,7 +539,7 @@ class ConnectionRepository(
if ch.isConnectionReady():
self.setConnectionHttp(ch)
self._serverAddress = serverList[serverIndex-1]
self.notify.info("Successfully connected to %s." % (self._serverAddress.cStr()))
self.notify.info("Successfully connected to %s." % (self._serverAddress))
## if self.recorder:
## # If we have a recorder, we wrap the connect inside a
@ -565,7 +565,7 @@ class ConnectionRepository(
# No connection yet, but keep trying.
url = serverList[serverIndex]
self.notify.info("Connecting to %s via HTTP interface." % (url.cStr()))
self.notify.info("Connecting to %s via HTTP interface." % (url))
ch.preserveStatus()
ch.beginConnectTo(DocumentSpec(url))

View File

@ -250,7 +250,7 @@ class DistributedCartesianGrid(DistributedNode, CartesianGridBase):
assert self.notify.debug("removeObjectFromGrid %s" % av)
# TODO: WHAT LOCATION SHOULD WE SET THIS TO?
#av.reparentTo(hidden)
if (av.getParent().compareTo(self) == 0):
if av.getParent() == self:
# only detach if object is directly parented
av.detachNode()
#av.b_setLocation(0, 0)

View File

@ -1,9 +0,0 @@
def __str__(self):
return self.cStr()
def __len__(self):
return self.length()
def __getitem__(self, n):
return self.cStr().__getitem__(n)

View File

@ -14,7 +14,7 @@
Returns the newly-spawned task.
"""
if not name:
name = self.getUrl().cStr()
name = str(self.getUrl())
from direct.task import Task
task = Task.Task(self.doTask)
task.callback = callback

View File

@ -18,7 +18,7 @@ def spawnTask(self, name = None, callback = None, extraArgs = []):
Returns the newly-spawned task.
"""
if not name:
name = self.getUrl().cStr()
name = str(self.getUrl())
from direct.task import Task
task = Task.Task(self.doTask)
task.callback = callback

View File

@ -16,11 +16,10 @@ clunky approach. - Josh
"""
from FilterManager import FilterManager
from pandac.PandaModules import Point3, Vec3, Vec4, Point2
from pandac.PandaModules import NodePath, PandaNode
from pandac.PandaModules import Filename
from pandac.PandaModules import AuxBitplaneAttrib
from pandac.PandaModules import RenderState, Texture, Shader, ATSNone
from panda3d.core import LVecBase4, LPoint2
from panda3d.core import Filename
from panda3d.core import AuxBitplaneAttrib
from panda3d.core import RenderState, Texture, Shader, ATSNone
import sys,os
CARTOON_BODY="""
@ -348,13 +347,13 @@ class CommonFilters:
if (changed == "CartoonInk") or fullrebuild:
if ("CartoonInk" in configuration):
c = configuration["CartoonInk"]
self.finalQuad.setShaderInput("cartoonseparation", Vec4(c.separation, 0, c.separation, 0))
self.finalQuad.setShaderInput("cartoonseparation", LVecBase4(c.separation, 0, c.separation, 0))
self.finalQuad.setShaderInput("cartooncolor", c.color)
if (changed == "BlurSharpen") or fullrebuild:
if ("BlurSharpen" in configuration):
blurval = configuration["BlurSharpen"]
self.finalQuad.setShaderInput("blurval", Vec4(blurval, blurval, blurval, blurval))
self.finalQuad.setShaderInput("blurval", LVecBase4(blurval, blurval, blurval, blurval))
if (changed == "Bloom") or fullrebuild:
if ("Bloom" in configuration):
@ -386,9 +385,9 @@ class CommonFilters:
if "VolumetricLighting" in self.configuration:
caster = self.configuration["VolumetricLighting"].caster
casterpos = Point2()
casterpos = LPoint2()
self.manager.camera.node().getLens().project(caster.getPos(self.manager.camera), casterpos)
self.finalQuad.setShaderInput("casterpos", Vec4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))
self.finalQuad.setShaderInput("casterpos", LVecBase4(casterpos.getX() * 0.5 + 0.5, (casterpos.getY() * 0.5 + 0.5), 0, 0))
if task != None:
return task.cont

View File

@ -14,16 +14,15 @@ Still need to implement:
"""
from pandac.PandaModules import Point3, Vec3, Vec4
from pandac.PandaModules import NodePath, PandaNode
from pandac.PandaModules import RenderState, Texture, Shader
from pandac.PandaModules import CardMaker
from pandac.PandaModules import TextureStage
from pandac.PandaModules import GraphicsPipe, GraphicsOutput
from pandac.PandaModules import WindowProperties, FrameBufferProperties
from pandac.PandaModules import Camera, DisplayRegion
from pandac.PandaModules import OrthographicLens
from pandac.PandaModules import AuxBitplaneAttrib
from panda3d.core import NodePath, PandaNode
from panda3d.core import RenderState, Texture, Shader
from panda3d.core import CardMaker
from panda3d.core import TextureStage
from panda3d.core import GraphicsPipe, GraphicsOutput
from panda3d.core import WindowProperties, FrameBufferProperties
from panda3d.core import Camera, DisplayRegion
from panda3d.core import OrthographicLens
from panda3d.core import AuxBitplaneAttrib
from direct.directnotify.DirectNotifyGlobal import *
from direct.showbase.DirectObject import DirectObject
@ -111,16 +110,16 @@ class FilterManager(DirectObject):
winx = self.forcex
winy = self.forcey
if (winx == 0): winx = self.win.getXSize()
if (winy == 0): winy = self.win.getYSize()
if winx == 0: winx = self.win.getXSize()
if winy == 0: winy = self.win.getYSize()
if (div != 1):
winx = ((winx+align-1) / align) * align
winy = ((winy+align-1) / align) * align
winx = winx / div
winy = winy / div
if div != 1:
winx = ((winx+align-1) // align) * align
winy = ((winy+align-1) // align) * align
winx = winx // div
winy = winy // div
if (mul != 1):
if mul != 1:
winx = winx * mul
winy = winy * mul
@ -198,7 +197,7 @@ class FilterManager(DirectObject):
quad.setDepthTest(0)
quad.setDepthWrite(0)
quad.setTexture(colortex)
quad.setColor(Vec4(1,0.5,0.5,1))
quad.setColor(1, 0.5, 0.5, 1)
cs = NodePath("dummy")
cs.setState(self.camstate)
@ -221,7 +220,7 @@ class FilterManager(DirectObject):
self.setStackedClears(buffer, self.rclears, self.wclears)
if (auxtex0):
buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)
buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, Vec4(0.5, 0.5, 1.0, 0.0))
buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))
if (auxtex1):
buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)
self.region.disableClears()
@ -262,7 +261,7 @@ class FilterManager(DirectObject):
quad = NodePath(cm.generate())
quad.setDepthTest(0)
quad.setDepthWrite(0)
quad.setColor(Vec4(1,0.5,0.5,1))
quad.setColor(1, 0.5, 0.5, 1)
quadcamnode = Camera("filter-quad-cam")
lens = OrthographicLens()
@ -294,7 +293,7 @@ class FilterManager(DirectObject):
winprops = WindowProperties()
winprops.setSize(xsize, ysize)
props = FrameBufferProperties(self.win.getFbProperties())
props = FrameBufferProperties(FrameBufferProperties.getDefault())
props.setBackBuffers(0)
props.setRgbColor(1)
props.setDepthBits(depthbits)

View File

@ -111,7 +111,7 @@ class LevelEditorBase(DirectObject):
base.direct.deselect(nodePath)
self.objectMgr.removeObjectByNodePath(nodePath)
if (base.direct.selected.last != None and nodePath.compareTo(base.direct.selected.last)==0):
if base.direct.selected.last is not None and nodePath == base.direct.selected.last:
# if base.direct.selected.last is refering to this
# removed obj, clear the reference
if (hasattr(__builtins__,'last')):

View File

@ -175,7 +175,7 @@ class AppRunner(DirectObject):
# the current working directory, for convenience; but when we
# move to multiple-instance sessions, it may have to be
# different for each instance.
self.multifileRoot = ExecutionEnvironment.getCwd().cStr()
self.multifileRoot = str(ExecutionEnvironment.getCwd())
# The "main" object will be exposed to the DOM as a property
# of the plugin object; that is, document.pluginobject.main in
@ -554,7 +554,7 @@ class AppRunner(DirectObject):
# Write the file to a temporary filename, then atomically move
# it to its actual filename, to avoid race conditions when
# updating this file.
tfile = Filename.temporary(self.rootDir.cStr(), '.xml')
tfile = Filename.temporary(str(self.rootDir), '.xml')
if doc.SaveFile(tfile.toOsSpecific()):
tfile.renameTo(filename)

View File

@ -25,7 +25,7 @@ class FileSpec:
if pathname is None:
pathname = Filename(packageDir, filename)
self.filename = filename.cStr()
self.filename = str(filename)
self.basename = filename.getBasename()
if st is None:

View File

@ -646,7 +646,7 @@ class HostInfo:
if hostDirBasename:
# If the contents.xml specified a host_dir parameter, use
# it.
hostDir = self.rootDir.cStr() + '/hosts'
hostDir = str(self.rootDir) + '/hosts'
for component in hostDirBasename.split('/'):
if component:
if component[0] == '.':

View File

@ -1066,7 +1066,7 @@ class PackageInfo:
return False
# We mount it under its actual location on disk.
root = self.getPackageDir().cStr()
root = self.getPackageDir()
vfs = VirtualFileSystem.getGlobalPtr()
vfs.mount(mf, root, vfs.MFReadOnly)
@ -1210,7 +1210,7 @@ class PackageInfo:
# Write the file to a temporary filename, then atomically move
# it to its actual filename, to avoid race conditions when
# updating this file.
tfile = Filename.temporary(self.getPackageDir().cStr(), '.xml')
tfile = Filename.temporary(str(self.getPackageDir()), '.xml')
if doc.SaveFile(tfile.toOsSpecific()):
tfile.renameTo(filename)

View File

@ -2263,7 +2263,7 @@ class Packager:
self.executablePath.appendDirectory('/usr/lib')
self.executablePath.appendDirectory('/usr/local/lib')
if os.uname()[1] == "pcbsd":
if self.platform.startswith('freebsd') and os.uname()[1] == "pcbsd":
self.executablePath.appendDirectory('/usr/PCBSD/local/lib')
# Set this flag true to automatically add allow_python_dev to

View File

@ -526,7 +526,7 @@ class PatchMaker:
# Also copy the seq to the import desc file, for
# documentation purposes.
importDescFilename = self.packageDesc.cStr()[:-3] + 'import.xml'
importDescFilename = str(self.packageDesc)[:-3] + 'import.xml'
importDescFullpath = Filename(self.patchMaker.installDir, importDescFilename)
doc = TiXmlDocument(importDescFullpath.toOsSpecific())
if doc.LoadFile():

View File

@ -58,7 +58,7 @@ class ScanDirectoryNode:
# Now update the usage.xml file with the newly-determined
# disk space.
xusage.SetAttribute('disk_space', str(self.getTotalSize()))
tfile = Filename.temporary(pathname.cStr(), '.xml')
tfile = Filename.temporary(str(pathname), '.xml')
if doc.SaveFile(tfile.toOsSpecific()):
tfile.renameTo(usageFilename)

View File

@ -18,8 +18,7 @@
// /MD. This links the plugin with the static C runtime library,
// instead of the dynamic runtime library, which is much better for
// distributing the plugin with the XPI and CAB interfaces. This
// requires that special /MT versions of OpenSSL, libjpeg, libpng,
// and zlib are available.
// requires that special /MT versions of OpenSSL and zlib are available.
#define _MT $[if $[P3D_PLUGIN_MT],_mt]
@ -114,8 +113,8 @@
// p3d_plugin.dll, the main entry point to the Core API.
//
#define BUILD_TARGET $[and $[HAVE_P3D_PLUGIN],$[HAVE_OPENSSL],$[HAVE_ZLIB],$[HAVE_JPEG],$[HAVE_PNG]]
#define USE_PACKAGES openssl$[_MT] zlib$[_MT] jpeg$[_MT] png$[_MT] x11
#define BUILD_TARGET $[and $[HAVE_P3D_PLUGIN],$[HAVE_OPENSSL],$[HAVE_ZLIB]]
#define USE_PACKAGES openssl$[_MT] zlib$[_MT] x11
#define TARGET p3d_plugin
#define LIB_PREFIX
#define BUILDING_DLL BUILDING_P3D_PLUGIN
@ -141,8 +140,8 @@
// libp3d_plugin_static.lib, the Core API as a static library (for p3dembed).
//
#define BUILD_TARGET $[and $[HAVE_P3D_PLUGIN],$[HAVE_OPENSSL],$[HAVE_ZLIB],$[HAVE_JPEG],$[HAVE_PNG]]
#define USE_PACKAGES openssl zlib jpeg png x11
#define BUILD_TARGET $[and $[HAVE_P3D_PLUGIN],$[HAVE_OPENSSL],$[HAVE_ZLIB]]
#define USE_PACKAGES openssl zlib x11
#define TARGET p3d_plugin_static
#define BUILDING_DLL BUILDING_P3D_PLUGIN

View File

@ -16,10 +16,10 @@
#include "wstring_encode.h"
#include "mkdir_complete.h"
#include <Fl/Fl_Box.H>
#include <Fl/Fl_Button.H>
#include <Fl/Fl_Return_Button.H>
#include <Fl/Fl_Text_Display.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Return_Button.H>
#include <FL/Fl_Text_Display.H>
#include <cassert>
#include <sys/types.h>
@ -557,7 +557,7 @@ get_text(char *header, size_t hlen, char *text, size_t tlen) {
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
strncpy(header, "Unverified signature!", hlen);
snprintf(text, tlen, unknown_auth_cert_text, _friendly_name.c_str());
snprintf(text, tlen, unknown_auth_cert_text);
break;
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:

View File

@ -15,8 +15,8 @@
#ifndef P3DCERT_H
#define P3DCERT_H
#include <Fl/Fl.H>
#include <Fl/Fl_Window.H>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#define OPENSSL_NO_KRB5
#include "openssl/x509.h"

View File

@ -52,7 +52,7 @@ enum {
#ifdef _WIN32
typedef P3DWinSplashWindow SplashWindowType;
#elif defined(__APPLE__)
#elif defined(__APPLE__) && !__LP64__
typedef P3DOsxSplashWindow SplashWindowType;
#elif defined(HAVE_X11)
typedef P3DX11SplashWindow SplashWindowType;
@ -740,7 +740,7 @@ get_request() {
// to shutdown.
_main_object->set_pyobj(NULL);
_main_object->set_string_property("status", "stopped");
string message = "onpythonstop";
string expression = _fparams.lookup_token(message);
nout << "notify: " << message << " " << expression << "\n";
@ -782,9 +782,12 @@ get_request() {
}
}
break;
default:
break;
}
}
return request;
}
@ -935,6 +938,9 @@ finish_request(P3D_request *request, bool handled) {
request->_request._forget_package._package_version = NULL;
}
break;
default:
break;
}
p3d_unref_delete(((P3DInstance *)request->_instance));
@ -3449,7 +3455,9 @@ paint_window() {
#ifdef __APPLE__
const P3D_window_handle &handle = _wparams.get_parent_window();
if (handle._window_handle_type == P3D_WHT_osx_port) {
#if !__LP64__
paint_window_osx_port();
#endif
} else if (handle._window_handle_type == P3D_WHT_osx_cgcontext) {
const P3D_window_handle &handle = _wparams.get_parent_window();
@ -3461,7 +3469,7 @@ paint_window() {
#endif // __APPLE__
}
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
////////////////////////////////////////////////////////////////////
// Function: P3DInstance::get_framebuffer_osx_port
// Access: Private
@ -3584,7 +3592,7 @@ get_framebuffer_osx_cgcontext() {
}
#endif // __APPLE__
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
////////////////////////////////////////////////////////////////////
// Function: P3DInstance::paint_window_osx_port
// Access: Private
@ -3674,7 +3682,7 @@ bool P3DInstance::
handle_event_osx_event_record(const P3D_event_data &event) {
bool retval = false;
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
assert(event._event_type == P3D_ET_osx_event_record);
EventRecord *er = event._event._osx_event_record._event;
@ -3889,7 +3897,7 @@ handle_event_osx_cocoa(const P3D_event_data &event) {
////////////////////////////////////////////////////////////////////
void P3DInstance::
add_carbon_modifier_flags(unsigned int &swb_flags, int modifiers) {
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
if (modifiers & cmdKey) {
swb_flags |= SubprocessWindowBuffer::EF_meta_held;
}

View File

@ -575,14 +575,14 @@ read_log(const string &log_pathname, P3D_object *params[], int num_params) {
// Read matching files
vector<string> all_logs;
int log_matches_found = 0;
int log_matches_found = 0;
string log_matching_pathname;
inst_mgr->scan_directory(log_directory, all_logs);
for (int i=(int)all_logs.size()-1; i>=0; --i) {
if ((all_logs[i] == log_leafname_primary) ||
(all_logs[i].find(log_basename) == 0) &&
(all_logs[i].size() > 4) &&
(all_logs[i].substr(all_logs[i].size() - 4) == string(".log"))) {
for (int i = (int)all_logs.size() - 1; i >= 0; --i) {
if (all_logs[i] == log_leafname_primary ||
(all_logs[i].find(log_basename) == 0 &&
all_logs[i].size() > 4 &&
all_logs[i].substr(all_logs[i].size() - 4) == string(".log"))) {
log_matches_found++;
log_matching_pathname = (log_directory + all_logs[i]);
read_log_file(log_matching_pathname, tail_bytes, head_bytes, log_data);
@ -606,10 +606,10 @@ read_log(const string &log_pathname, P3D_object *params[], int num_params) {
// Description: The generic log-reader function.
////////////////////////////////////////////////////////////////////
void P3DMainObject::
read_log_file(const string &log_pathname,
size_t tail_bytes, size_t head_bytes,
read_log_file(const string &log_pathname,
size_t tail_bytes, size_t head_bytes,
ostringstream &log_data) {
// Get leaf name
string log_leafname = log_pathname;
size_t slash = log_leafname.rfind('/');

View File

@ -14,7 +14,7 @@
#include "p3dOsxSplashWindow.h"
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
#include <Carbon/Carbon.h>
#include <ApplicationServices/ApplicationServices.h>

View File

@ -17,7 +17,7 @@
#include "p3d_plugin_common.h"
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
#include "p3dSplashWindow.h"

View File

@ -1539,6 +1539,10 @@ download_progress() {
assert(_package->_active_download == this);
switch (_dtype) {
case DT_contents_file:
case DT_redownload_contents_file:
break;
case DT_desc_file:
break;
@ -1581,7 +1585,7 @@ download_finished(bool success) {
_file_spec.get_actual_file()->output_hash(nout);
nout << "\n";
}
success = false;
}
}

View File

@ -19,10 +19,7 @@
#include "virtualFileSystem.h"
#include "nativeWindowHandle.h"
#ifndef CPPPARSER
#include "py_panda.h"
IMPORT_THIS struct Dtool_PyTypedObject Dtool_WindowHandle;
#endif
// There is only one P3DPythonRun object in any given process space.
// Makes the statics easier to deal with, and we don't need multiple
@ -298,14 +295,12 @@ run_python() {
// Now pass that func pointer back to our AppRunner instance, so it
// can call up to us.
result = PyObject_CallMethod(_runner, (char *)"setRequestFunc", (char *)"O", request_func);
result = PyObject_CallMethod(_runner, (char *)"setRequestFunc", (char *)"N", request_func);
if (result == NULL) {
PyErr_Print();
return false;
}
Py_DECREF(result);
Py_DECREF(request_func);
// Now add check_comm() as a task. It can be a threaded task, but
// this does mean that application programmers will have to be alert
@ -326,14 +321,14 @@ run_python() {
return false;
}
// We have to make it a PythonTask, not just a GenericAsyncTask,
// because we need the code in PythonTask that supports calling into
// Python from a separate thread.
_check_comm_task = new PythonTask(check_comm, "check_comm");
_check_comm_task->set_task_chain("JavaScript");
task_mgr->add(_check_comm_task);
Py_DECREF(check_comm);
// Add it to the task manager. We do this instead of constructing a
// PythonTask because linking p3dpython with core.pyd is problematic.
result = PyObject_CallMethod(_taskMgr, (char *)"add", (char *)"Ns", check_comm, "check_comm");
if (result == NULL) {
PyErr_Print();
return false;
}
Py_DECREF(result);
// Finally, get lost in AppRunner.run() (which is really a call to
// taskMgr.run()).
@ -603,10 +598,8 @@ handle_pyobj_command(TiXmlElement *xcommand, bool needs_response,
Py_INCREF(obj);
}
PyObject *result = PyObject_CallMethod
(_runner, (char *)"setBrowserScriptObject", (char *)"O", obj);
Py_DECREF(obj);
Py_XDECREF(result);
Py_XDECREF(PyObject_CallMethod
(_runner, (char *)"setBrowserScriptObject", (char *)"N", obj));
} else if (strcmp(op, "call") == 0) {
// Call the named method on the indicated object, or the object
@ -1215,9 +1208,8 @@ set_instance_info(P3DCInstance *inst, TiXmlElement *xinstance) {
xinstance->Attribute("respect_per_platform", &respect_per_platform);
PyObject *result = PyObject_CallMethod
(_runner, (char *)"setInstanceInfo", (char *)"sssiOi", root_dir,
(_runner, (char *)"setInstanceInfo", (char *)"sssiNi", root_dir,
log_directory, super_mirror, verify_contents, main, respect_per_platform);
Py_DECREF(main);
if (result == NULL) {
PyErr_Print();
@ -1331,11 +1323,9 @@ set_p3d_filename(P3DCInstance *inst, TiXmlElement *xfparams) {
}
PyObject *result = PyObject_CallMethod
(_runner, (char *)"setP3DFilename", (char *)"sOOiiis", p3d_filename.c_str(),
(_runner, (char *)"setP3DFilename", (char *)"sNNiiis", p3d_filename.c_str(),
token_list, arg_list, inst->get_instance_id(), _interactive_console, p3d_offset,
p3d_url.c_str());
Py_DECREF(token_list);
Py_DECREF(arg_list);
if (result == NULL) {
PyErr_Print();
@ -1425,18 +1415,16 @@ setup_window(P3DCInstance *inst, TiXmlElement *xwparams) {
// setupWindow() call. For this, we need to create a Python
// wrapper objcet.
parent_window_handle->ref();
py_handle = DTool_CreatePyInstanceTyped(parent_window_handle, Dtool_WindowHandle, true, false, parent_window_handle->get_type_index());
py_handle = DTool_CreatePyInstanceTyped(parent_window_handle.p(), true);
}
Py_INCREF(py_handle);
// TODO: direct this into the particular instance. This will
// require a specialized ShowBase replacement.
PyObject *result = PyObject_CallMethod
(_runner, (char *)"setupWindow", (char *)"siiiiO", window_type.c_str(),
(_runner, (char *)"setupWindow", (char *)"siiiiN", window_type.c_str(),
win_x, win_y, win_width, win_height, py_handle);
Py_DECREF(py_handle);
if (result == NULL) {
PyErr_Print();
if (_interactive_console) {

View File

@ -27,7 +27,6 @@
#include "handleStream.h"
#include "p3dCInstance.h"
#include "pandaFileStreamBuf.h"
#include "pythonTask.h"
#include "pmap.h"
#include "pdeque.h"
#include "pmutex.h"
@ -173,8 +172,6 @@ private:
PyObject *_browser_object_class;
PyObject *_taskMgr;
PT(PythonTask) _check_comm_task;
// This map keeps track of the PyObject pointers we have delivered
// to the parent process. We have to hold the reference count on
// each of these until the parent process tells us it's safe to

View File

@ -15,30 +15,11 @@
#include "p3dSplashWindow.h"
#include "wstring_encode.h"
// Stuff to use libpng.
#include <png.h>
// Stuff to use libjpeg.
extern "C" {
#include <jpeglib.h>
#include <jerror.h>
}
#include <setjmp.h>
struct my_error_mgr {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
typedef struct my_error_mgr *my_error_ptr;
METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
// cinfo->err really points to a my_error_mgr struct, so coerce pointer
my_error_ptr myerr = (my_error_ptr) cinfo->err;
// Return control to the setjmp point
longjmp(myerr->setjmp_buffer, 1);
}
// We use the public domain stb_image library for loading images.
// Define the stb_image implementation. We only use it in this unit.
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
// The number of pixels to move the block per byte downloaded, when we
// don't know the actual file size we're downloading.
@ -52,7 +33,7 @@ const double P3DSplashWindow::_unknown_progress_rate = 1.0 / 4096;
// them both into this class for reference.
////////////////////////////////////////////////////////////////////
P3DSplashWindow::
P3DSplashWindow(P3DInstance *inst, bool make_visible) :
P3DSplashWindow(P3DInstance *inst, bool make_visible) :
_inst(inst),
_fparams(inst->get_fparams()),
_wparams(inst->get_wparams())
@ -82,7 +63,7 @@ P3DSplashWindow(P3DInstance *inst, bool make_visible) :
////////////////////////////////////////////////////////////////////
// Function: P3DSplashWindow::Destructor
// Access: Public, Virtual
// Description:
// Description:
////////////////////////////////////////////////////////////////////
P3DSplashWindow::
~P3DSplashWindow() {
@ -259,191 +240,25 @@ read_image_data(ImageData &image, string &data,
return false;
}
// We only support JPEG or PNG images.
FILE *fp = NULL;
#ifdef _WIN32
wstring image_filename_w;
if (string_to_wstring(image_filename_w, image_filename)) {
fp = _wfopen(image_filename_w.c_str(), L"rb");
}
#else // _WIN32
fp = fopen(image_filename.c_str(), "rb");
#endif // _WIN32
nout << "Reading splash file image: " << image_filename << "\n";
if (fp == NULL) {
nout << "Couldn't open splash file image: " << image_filename << "\n";
return false;
}
unsigned char *imgdata = stbi_load(image_filename.c_str(), &image._width,
&image._height, &image._num_channels, 0);
// Check the magic number to determine which image type we have.
static const size_t magic_number_len = 2;
char magic_number[magic_number_len];
if (fread(magic_number, 1, magic_number_len, fp) != magic_number_len) {
nout << "Empty file: " << image_filename << "\n";
return false;
}
// Rewind to re-read the magic number below.
fseek(fp, 0, SEEK_SET);
bool result = false;
if ((char)magic_number[0] == (char)0xff &&
(char)magic_number[1] == (char)0xd8) {
// It's a jpeg image.
result = read_image_data_jpeg(image, data, fp, image_filename);
} else if (png_sig_cmp((png_bytep)magic_number, 0, magic_number_len) == 0) {
// It's a PNG image.
result = read_image_data_png(image, data, fp, image_filename);
} else {
nout << "Neither a JPEG nor a PNG image: " << image_filename << "\n";
result = false;
}
fclose(fp);
return result;
}
////////////////////////////////////////////////////////////////////
// Function: P3DSplashWindow::read_image_data_jpeg
// Access: Protected
// Description: Reads the image filename and sets image parameters
// width, height, num_channels, and data. Returns true
// on success, false on failure.
////////////////////////////////////////////////////////////////////
bool P3DSplashWindow::
read_image_data_jpeg(ImageData &image, string &data,
FILE *fp, const string &image_filename) {
// We set up the normal JPEG error routines, then override error_exit.
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
JSAMPLE *buffer = NULL;
// Establish the setjmp return context for my_error_exit to use
if (setjmp(jerr.setjmp_buffer)) {
// If we get here, the JPEG code has signaled an error.
nout << "JPEG error decoding " << image_filename << "\n";
// We need to clean up the JPEG object, close the input file, and return.
jpeg_destroy_decompress(&cinfo);
if (buffer != NULL) {
delete[] buffer;
if (imgdata == NULL) {
nout << "Couldn't read splash file image: " << image_filename << "\n";
const char *reason = stbi_failure_reason();
if (reason != NULL) {
nout << "stbi_failure_reason: " << reason << "\n";
}
return false;
}
/* Now we can initialize the JPEG decompression object. */
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, fp);
size_t data_size = image._width * image._height * image._num_channels;
data.resize(data_size);
memcpy(&data[0], imgdata, data_size);
jpeg_read_header(&cinfo, true);
cinfo.scale_num = 1;
cinfo.scale_denom = 1;
jpeg_start_decompress(&cinfo);
image._width = cinfo.output_width;
image._height = cinfo.output_height;
image._num_channels = cinfo.output_components;
int row_stride = image._width * image._num_channels;
size_t buffer_size = image._height * row_stride;
buffer = new JSAMPLE[buffer_size];
JSAMPLE *buffer_end = buffer + buffer_size;
JSAMPLE *rowptr = buffer;
while (cinfo.output_scanline < cinfo.output_height) {
assert(rowptr + row_stride <= buffer_end);
jpeg_read_scanlines(&cinfo, &rowptr, 1);
rowptr += row_stride;
}
jpeg_finish_decompress(&cinfo);
data.append((const char *)buffer, buffer_size);
delete[] buffer;
return true;
}
////////////////////////////////////////////////////////////////////
// Function: P3DSplashWindow::read_image_data_png
// Access: Protected
// Description: Reads the image filename and sets image parameters
// width, height, num_channels, and data. Returns true
// on success, false on failure.
////////////////////////////////////////////////////////////////////
bool P3DSplashWindow::
read_image_data_png(ImageData &image, string &data,
FILE *fp, const string &image_filename) {
png_structp png;
png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png == NULL) {
return false;
}
png_infop info;
info = png_create_info_struct(png);
if (info == NULL) {
png_destroy_read_struct(&png, NULL, NULL);
return false;
}
jmp_buf jmpbuf;
if (setjmp(jmpbuf)) {
// This is the ANSI C way to handle exceptions. If setjmp(),
// above, returns true, it means that libpng detected an exception
// while executing the code that reads the header info, below.
png_destroy_read_struct(&png, &info, NULL);
return false;
}
png_init_io(png, fp);
int transforms = PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_SHIFT;
// transforms |= PNG_TRANSFORM_STRIP_ALPHA;
png_read_png(png, info, transforms, NULL);
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int color_type;
png_get_IHDR(png, info, &width, &height,
&bit_depth, &color_type, NULL, NULL, NULL);
image._width = width;
image._height = height;
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
image._num_channels = 3;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
image._num_channels = 4;
break;
default:
nout << "Unsupported color type: " << color_type << "\n";
png_destroy_read_struct(&png, &info, NULL);
return false;
}
int row_stride = image._width * image._num_channels;
png_bytep *row_pointers = png_get_rows(png, info);
for (int yi = 0; yi < image._height; ++yi) {
data.append((const char *)row_pointers[yi], row_stride);
}
png_destroy_read_struct(&png, &info, NULL);
stbi_image_free(imgdata);
return true;
}
@ -479,7 +294,7 @@ set_button_range(const ImageData &image) {
// But it can't be larger than the window itself.
_button_width = min(_button_width, _win_width);
_button_height = min(_button_height, _win_height);
// Compute the top-left corner of the button image in window
// coordinates.
_button_x = (_win_width - _button_width) / 2;

View File

@ -78,10 +78,6 @@ protected:
bool read_image_data(ImageData &image, string &data,
const string &image_filename);
bool read_image_data_jpeg(ImageData &image, string &data,
FILE *fp, const string &image_filename);
bool read_image_data_png(ImageData &image, string &data,
FILE *fp, const string &image_filename);
void get_bar_placement(int &bar_x, int &bar_y,
int &bar_width, int &bar_height);
void set_button_range(const ImageData &image);

View File

@ -1060,7 +1060,6 @@ update_image(X11ImageData &image) {
_needs_new_composite = true;
// Go read the image.
string data;
if (!read_image_data(image, image._data, image._filename)) {
return;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,928 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef npapi_h_
#define npapi_h_
#if defined(__OS2__)
#pragma pack(1)
#endif
#include "nptypes.h"
#if defined(__OS2__) || defined(OS2)
#ifndef XP_OS2
#define XP_OS2 1
#endif
#endif
#if defined(_WIN32) && !defined(__SYMBIAN32__)
#include <windef.h>
#ifndef XP_WIN
#define XP_WIN 1
#endif
#endif
#if defined(__SYMBIAN32__)
#ifndef XP_SYMBIAN
#define XP_SYMBIAN 1
#undef XP_WIN
#endif
#endif
#if defined(__APPLE_CC__) && !defined(XP_UNIX)
#ifndef XP_MACOSX
#define XP_MACOSX 1
#endif
#endif
#if defined(XP_MACOSX)
#if !defined(NP_NO_OPENGL)
#define NP_NO_OPENGL 1
#endif /* !defined(NP_NO_OPENGL) */
#if defined(__LP64__)
#define NP_NO_QUICKDRAW
#define NP_NO_CARBON
#endif /* defined(__LP64__) */
#endif
#if defined(XP_MACOSX)
#include <ApplicationServices/ApplicationServices.h>
#if !NP_NO_OPENGL
#include <OpenGL/OpenGL.h>
#endif /* !NP_NO_OPENGL */
#ifndef NP_NO_CARBON
#include <Carbon/Carbon.h>
#endif
#endif
#if defined(XP_UNIX)
#include <stdio.h>
#if defined(MOZ_X11)
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#endif
#endif
#if defined(XP_SYMBIAN)
#include <QEvent>
#include <QRegion>
#endif
/*----------------------------------------------------------------------*/
/* Plugin Version Constants */
/*----------------------------------------------------------------------*/
#define NP_VERSION_MAJOR 0
#define NP_VERSION_MINOR 28
/* The OS/2 version of Netscape uses RC_DATA to define the
mime types, file extensions, etc that are required.
Use a vertical bar to separate types, end types with \0.
FileVersion and ProductVersion are 32bit ints, all other
entries are strings that MUST be terminated with a \0.
AN EXAMPLE:
RCDATA NP_INFO_ProductVersion { 1,0,0,1,}
RCDATA NP_INFO_MIMEType { "video/x-video|",
"video/x-flick\0" }
RCDATA NP_INFO_FileExtents { "avi|",
"flc\0" }
RCDATA NP_INFO_FileOpenName{ "MMOS2 video player(*.avi)|",
"MMOS2 Flc/Fli player(*.flc)\0" }
RCDATA NP_INFO_FileVersion { 1,0,0,1 }
RCDATA NP_INFO_CompanyName { "Netscape Communications\0" }
RCDATA NP_INFO_FileDescription { "NPAVI32 Extension DLL\0"
RCDATA NP_INFO_InternalName { "NPAVI32\0" )
RCDATA NP_INFO_LegalCopyright { "Copyright Netscape Communications \251 1996\0"
RCDATA NP_INFO_OriginalFilename { "NVAPI32.DLL" }
RCDATA NP_INFO_ProductName { "NPAVI32 Dynamic Link Library\0" }
*/
/* RC_DATA types for version info - required */
#define NP_INFO_ProductVersion 1
#define NP_INFO_MIMEType 2
#define NP_INFO_FileOpenName 3
#define NP_INFO_FileExtents 4
/* RC_DATA types for version info - used if found */
#define NP_INFO_FileDescription 5
#define NP_INFO_ProductName 6
/* RC_DATA types for version info - optional */
#define NP_INFO_CompanyName 7
#define NP_INFO_FileVersion 8
#define NP_INFO_InternalName 9
#define NP_INFO_LegalCopyright 10
#define NP_INFO_OriginalFilename 11
#ifndef RC_INVOKED
/*----------------------------------------------------------------------*/
/* Definition of Basic Types */
/*----------------------------------------------------------------------*/
typedef unsigned char NPBool;
typedef int16_t NPError;
typedef int16_t NPReason;
typedef char* NPMIMEType;
/*----------------------------------------------------------------------*/
/* Structures and definitions */
/*----------------------------------------------------------------------*/
#if !defined(__LP64__)
#if defined(XP_MACOSX)
#pragma options align=mac68k
#endif
#endif /* __LP64__ */
/*
* NPP is a plug-in's opaque instance handle
*/
typedef struct _NPP
{
void* pdata; /* plug-in private data */
void* ndata; /* netscape private data */
} NPP_t;
typedef NPP_t* NPP;
typedef struct _NPStream
{
void* pdata; /* plug-in private data */
void* ndata; /* netscape private data */
const char* url;
uint32_t end;
uint32_t lastmodified;
void* notifyData;
const char* headers; /* Response headers from host.
* Exists only for >= NPVERS_HAS_RESPONSE_HEADERS.
* Used for HTTP only; NULL for non-HTTP.
* Available from NPP_NewStream onwards.
* Plugin should copy this data before storing it.
* Includes HTTP status line and all headers,
* preferably verbatim as received from server,
* headers formatted as in HTTP ("Header: Value"),
* and newlines (\n, NOT \r\n) separating lines.
* Terminated by \n\0 (NOT \n\n\0). */
} NPStream;
typedef struct _NPByteRange
{
int32_t offset; /* negative offset means from the end */
uint32_t length;
struct _NPByteRange* next;
} NPByteRange;
typedef struct _NPSavedData
{
int32_t len;
void* buf;
} NPSavedData;
typedef struct _NPRect
{
uint16_t top;
uint16_t left;
uint16_t bottom;
uint16_t right;
} NPRect;
typedef struct _NPSize
{
int32_t width;
int32_t height;
} NPSize;
typedef enum {
NPFocusNext = 0,
NPFocusPrevious = 1
} NPFocusDirection;
/* Return values for NPP_HandleEvent */
#define kNPEventNotHandled 0
#define kNPEventHandled 1
/* Exact meaning must be spec'd in event model. */
#define kNPEventStartIME 2
#if defined(XP_UNIX)
/*
* Unix specific structures and definitions
*/
/*
* Callback Structures.
*
* These are used to pass additional platform specific information.
*/
enum {
NP_SETWINDOW = 1,
NP_PRINT
};
typedef struct
{
int32_t type;
} NPAnyCallbackStruct;
typedef struct
{
int32_t type;
#if defined(MOZ_X11)
Display* display;
Visual* visual;
Colormap colormap;
unsigned int depth;
#endif
} NPSetWindowCallbackStruct;
typedef struct
{
int32_t type;
FILE* fp;
} NPPrintCallbackStruct;
#endif /* XP_UNIX */
typedef enum {
NPDrawingModelDUMMY
#if defined(XP_MACOSX)
#ifndef NP_NO_QUICKDRAW
, NPDrawingModelQuickDraw = 0
#endif
, NPDrawingModelCoreGraphics = 1
, NPDrawingModelOpenGL = 2
, NPDrawingModelCoreAnimation = 3
, NPDrawingModelInvalidatingCoreAnimation = 4
#endif
#if defined(XP_WIN)
, NPDrawingModelSyncWin = 5
#endif
#if defined(MOZ_X11)
, NPDrawingModelSyncX = 6
#endif
#if 0 /* OBSOLETE */
, NPDrawingModelAsyncBitmapSurfaceOBSOLETE = 7
#if defined(XP_WIN)
, NPDrawingModelAsyncWindowsDXGISurfaceOBSOLETE = 8
#endif
#endif
} NPDrawingModel;
#ifdef XP_MACOSX
typedef enum {
#ifndef NP_NO_CARBON
NPEventModelCarbon = 0,
#endif
NPEventModelCocoa = 1
} NPEventModel;
#endif
/*
* The following masks are applied on certain platforms to NPNV and
* NPPV selectors that pass around pointers to COM interfaces. Newer
* compilers on some platforms may generate vtables that are not
* compatible with older compilers. To prevent older plugins from
* not understanding a new browser's ABI, these masks change the
* values of those selectors on those platforms. To remain backwards
* compatible with different versions of the browser, plugins can
* use these masks to dynamically determine and use the correct C++
* ABI that the browser is expecting. This does not apply to Windows
* as Microsoft's COM ABI will likely not change.
*/
#define NP_ABI_GCC3_MASK 0x10000000
/*
* gcc 3.x generated vtables on UNIX and OSX are incompatible with
* previous compilers.
*/
#if (defined(XP_UNIX) && defined(__GNUC__) && (__GNUC__ >= 3))
#define _NP_ABI_MIXIN_FOR_GCC3 NP_ABI_GCC3_MASK
#else
#define _NP_ABI_MIXIN_FOR_GCC3 0
#endif
#if defined(XP_MACOSX)
#define NP_ABI_MACHO_MASK 0x01000000
#define _NP_ABI_MIXIN_FOR_MACHO NP_ABI_MACHO_MASK
#else
#define _NP_ABI_MIXIN_FOR_MACHO 0
#endif
#define NP_ABI_MASK (_NP_ABI_MIXIN_FOR_GCC3 | _NP_ABI_MIXIN_FOR_MACHO)
/*
* List of variable names for which NPP_GetValue shall be implemented
*/
typedef enum {
NPPVpluginNameString = 1,
NPPVpluginDescriptionString,
NPPVpluginWindowBool,
NPPVpluginTransparentBool,
NPPVjavaClass,
NPPVpluginWindowSize,
NPPVpluginTimerInterval,
NPPVpluginScriptableInstance = (10 | NP_ABI_MASK),
NPPVpluginScriptableIID = 11,
NPPVjavascriptPushCallerBool = 12,
NPPVpluginKeepLibraryInMemory = 13,
NPPVpluginNeedsXEmbed = 14,
/* Get the NPObject for scripting the plugin. Introduced in NPAPI minor version 14.
*/
NPPVpluginScriptableNPObject = 15,
/* Get the plugin value (as \0-terminated UTF-8 string data) for
* form submission if the plugin is part of a form. Use
* NPN_MemAlloc() to allocate memory for the string data. Introduced
* in NPAPI minor version 15.
*/
NPPVformValue = 16,
NPPVpluginUrlRequestsDisplayedBool = 17,
/* Checks if the plugin is interested in receiving the http body of
* all http requests (including failed ones, http status != 200).
*/
NPPVpluginWantsAllNetworkStreams = 18,
/* Browsers can retrieve a native ATK accessibility plug ID via this variable. */
NPPVpluginNativeAccessibleAtkPlugId = 19,
/* Checks to see if the plug-in would like the browser to load the "src" attribute. */
NPPVpluginCancelSrcStream = 20,
NPPVsupportsAdvancedKeyHandling = 21,
NPPVpluginUsesDOMForCursorBool = 22,
/* Used for negotiating drawing models */
NPPVpluginDrawingModel = 1000
#if defined(XP_MACOSX)
/* Used for negotiating event models */
, NPPVpluginEventModel = 1001
/* In the NPDrawingModelCoreAnimation drawing model, the browser asks the plug-in for a Core Animation layer. */
, NPPVpluginCoreAnimationLayer = 1003
#endif
#if defined(MOZ_PLATFORM_MAEMO) && ((MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6))
, NPPVpluginWindowlessLocalBool = 2002
#endif
} NPPVariable;
/*
* List of variable names for which NPN_GetValue should be implemented.
*/
typedef enum {
NPNVxDisplay = 1,
NPNVxtAppContext,
NPNVnetscapeWindow,
NPNVjavascriptEnabledBool,
NPNVasdEnabledBool,
NPNVisOfflineBool,
NPNVserviceManager = (10 | NP_ABI_MASK),
NPNVDOMElement = (11 | NP_ABI_MASK),
NPNVDOMWindow = (12 | NP_ABI_MASK),
NPNVToolkit = (13 | NP_ABI_MASK),
NPNVSupportsXEmbedBool = 14,
/* Get the NPObject wrapper for the browser window. */
NPNVWindowNPObject = 15,
/* Get the NPObject wrapper for the plugins DOM element. */
NPNVPluginElementNPObject = 16,
NPNVSupportsWindowless = 17,
NPNVprivateModeBool = 18,
NPNVsupportsAdvancedKeyHandling = 21,
NPNVdocumentOrigin = 22,
NPNVpluginDrawingModel = 1000 /* Get the current drawing model (NPDrawingModel) */
#if defined(XP_MACOSX)
, NPNVcontentsScaleFactor = 1001
#ifndef NP_NO_QUICKDRAW
, NPNVsupportsQuickDrawBool = 2000
#endif
, NPNVsupportsCoreGraphicsBool = 2001
, NPNVsupportsOpenGLBool = 2002
, NPNVsupportsCoreAnimationBool = 2003
, NPNVsupportsInvalidatingCoreAnimationBool = 2004
#endif
#if 0 /* OBSOLETE */
, NPNVsupportsAsyncBitmapSurfaceBoolOBSOLETE = 2007
#if defined(XP_WIN)
, NPNVsupportsAsyncWindowsDXGISurfaceBoolOBSOLETE = 2008
#endif
#endif
#if defined(XP_MACOSX)
#ifndef NP_NO_CARBON
, NPNVsupportsCarbonBool = 3000 /* TRUE if the browser supports the Carbon event model */
#endif
, NPNVsupportsCocoaBool = 3001 /* TRUE if the browser supports the Cocoa event model */
, NPNVsupportsUpdatedCocoaTextInputBool = 3002 /* TRUE if the browser supports the updated
Cocoa text input specification. */
, NPNVsupportsCompositingCoreAnimationPluginsBool = 74656 /* TRUE if the browser supports
CA model compositing */
#endif
#if defined(MOZ_PLATFORM_MAEMO) && ((MOZ_PLATFORM_MAEMO == 5) || (MOZ_PLATFORM_MAEMO == 6))
, NPNVSupportsWindowlessLocal = 2002
#endif
} NPNVariable;
typedef enum {
NPNURLVCookie = 501,
NPNURLVProxy
} NPNURLVariable;
/*
* The type of Toolkit the widgets use
*/
typedef enum {
NPNVGtk12 = 1,
NPNVGtk2
} NPNToolkitType;
/*
* The type of a NPWindow - it specifies the type of the data structure
* returned in the window field.
*/
typedef enum {
NPWindowTypeWindow = 1,
NPWindowTypeDrawable
} NPWindowType;
typedef struct _NPWindow
{
void* window; /* Platform specific window handle */
/* OS/2: x - Position of bottom left corner */
/* OS/2: y - relative to visible netscape window */
int32_t x; /* Position of top left corner relative */
int32_t y; /* to a netscape page. */
uint32_t width; /* Maximum window size */
uint32_t height;
NPRect clipRect; /* Clipping rectangle in port coordinates */
#if (defined(XP_UNIX) || defined(XP_SYMBIAN)) && !defined(XP_MACOSX)
void * ws_info; /* Platform-dependent additional data */
#endif /* XP_UNIX */
NPWindowType type; /* Is this a window or a drawable? */
} NPWindow;
typedef struct _NPImageExpose
{
char* data; /* image pointer */
int32_t stride; /* Stride of data image pointer */
int32_t depth; /* Depth of image pointer */
int32_t x; /* Expose x */
int32_t y; /* Expose y */
uint32_t width; /* Expose width */
uint32_t height; /* Expose height */
NPSize dataSize; /* Data buffer size */
float translateX; /* translate X matrix value */
float translateY; /* translate Y matrix value */
float scaleX; /* scale X matrix value */
float scaleY; /* scale Y matrix value */
} NPImageExpose;
typedef struct _NPFullPrint
{
NPBool pluginPrinted;/* Set TRUE if plugin handled fullscreen printing */
NPBool printOne; /* TRUE if plugin should print one copy to default
printer */
void* platformPrint; /* Platform-specific printing info */
} NPFullPrint;
typedef struct _NPEmbedPrint
{
NPWindow window;
void* platformPrint; /* Platform-specific printing info */
} NPEmbedPrint;
typedef struct _NPPrint
{
uint16_t mode; /* NP_FULL or NP_EMBED */
union
{
NPFullPrint fullPrint; /* if mode is NP_FULL */
NPEmbedPrint embedPrint; /* if mode is NP_EMBED */
} print;
} NPPrint;
#if defined(XP_MACOSX)
#ifndef NP_NO_CARBON
typedef EventRecord NPEvent;
#endif
#elif defined(XP_SYMBIAN)
typedef QEvent NPEvent;
#elif defined(XP_WIN)
typedef struct _NPEvent
{
uint16_t event;
uintptr_t wParam;
uintptr_t lParam;
} NPEvent;
#elif defined(XP_OS2)
typedef struct _NPEvent
{
uint32_t event;
uint32_t wParam;
uint32_t lParam;
} NPEvent;
#elif defined(XP_UNIX) && defined(MOZ_X11)
typedef XEvent NPEvent;
#else
typedef void* NPEvent;
#endif
#if defined(XP_MACOSX)
typedef void* NPRegion;
#ifndef NP_NO_QUICKDRAW
typedef RgnHandle NPQDRegion;
#endif
typedef CGPathRef NPCGRegion;
#elif defined(XP_WIN)
typedef HRGN NPRegion;
#elif defined(XP_UNIX) && defined(MOZ_X11)
typedef Region NPRegion;
#elif defined(XP_SYMBIAN)
typedef QRegion* NPRegion;
#else
typedef void *NPRegion;
#endif
typedef struct _NPNSString NPNSString;
typedef struct _NPNSWindow NPNSWindow;
typedef struct _NPNSMenu NPNSMenu;
#if defined(XP_MACOSX)
typedef NPNSMenu NPMenu;
#else
typedef void *NPMenu;
#endif
typedef enum {
NPCoordinateSpacePlugin = 1,
NPCoordinateSpaceWindow,
NPCoordinateSpaceFlippedWindow,
NPCoordinateSpaceScreen,
NPCoordinateSpaceFlippedScreen
} NPCoordinateSpace;
#if defined(XP_MACOSX)
#ifndef NP_NO_QUICKDRAW
typedef struct NP_Port
{
CGrafPtr port;
int32_t portx; /* position inside the topmost window */
int32_t porty;
} NP_Port;
#endif /* NP_NO_QUICKDRAW */
/*
* NP_CGContext is the type of the NPWindow's 'window' when the plugin specifies NPDrawingModelCoreGraphics
* as its drawing model.
*/
typedef struct NP_CGContext
{
CGContextRef context;
void *window; /* A WindowRef under the Carbon event model. */
} NP_CGContext;
/*
* NP_GLContext is the type of the NPWindow's 'window' when the plugin specifies NPDrawingModelOpenGL as its
* drawing model.
*/
#if !NP_NO_OPENGL
typedef struct NP_GLContext
{
CGLContextObj context;
#ifdef NP_NO_CARBON
NPNSWindow *window;
#else
void *window; /* Can be either an NSWindow or a WindowRef depending on the event model */
#endif
} NP_GLContext;
#endif /* !NP_NO_OPENGL */
typedef enum {
NPCocoaEventDrawRect = 1,
NPCocoaEventMouseDown,
NPCocoaEventMouseUp,
NPCocoaEventMouseMoved,
NPCocoaEventMouseEntered,
NPCocoaEventMouseExited,
NPCocoaEventMouseDragged,
NPCocoaEventKeyDown,
NPCocoaEventKeyUp,
NPCocoaEventFlagsChanged,
NPCocoaEventFocusChanged,
NPCocoaEventWindowFocusChanged,
NPCocoaEventScrollWheel,
NPCocoaEventTextInput
} NPCocoaEventType;
typedef struct _NPCocoaEvent {
NPCocoaEventType type;
uint32_t version;
union {
struct {
uint32_t modifierFlags;
double pluginX;
double pluginY;
int32_t buttonNumber;
int32_t clickCount;
double deltaX;
double deltaY;
double deltaZ;
} mouse;
struct {
uint32_t modifierFlags;
NPNSString *characters;
NPNSString *charactersIgnoringModifiers;
NPBool isARepeat;
uint16_t keyCode;
} key;
struct {
CGContextRef context;
double x;
double y;
double width;
double height;
} draw;
struct {
NPBool hasFocus;
} focus;
struct {
NPNSString *text;
} text;
} data;
} NPCocoaEvent;
#ifndef NP_NO_CARBON
/* Non-standard event types that can be passed to HandleEvent */
enum NPEventType {
NPEventType_GetFocusEvent = (osEvt + 16),
NPEventType_LoseFocusEvent,
NPEventType_AdjustCursorEvent,
NPEventType_MenuCommandEvent,
NPEventType_ClippingChangedEvent,
NPEventType_ScrollingBeginsEvent = 1000,
NPEventType_ScrollingEndsEvent
};
#endif /* NP_NO_CARBON */
#endif /* XP_MACOSX */
/*
* Values for mode passed to NPP_New:
*/
#define NP_EMBED 1
#define NP_FULL 2
/*
* Values for stream type passed to NPP_NewStream:
*/
#define NP_NORMAL 1
#define NP_SEEK 2
#define NP_ASFILE 3
#define NP_ASFILEONLY 4
#define NP_MAXREADY (((unsigned)(~0)<<1)>>1)
/*
* Flags for NPP_ClearSiteData.
*/
#define NP_CLEAR_ALL 0
#define NP_CLEAR_CACHE (1 << 0)
#if !defined(__LP64__)
#if defined(XP_MACOSX)
#pragma options align=reset
#endif
#endif /* __LP64__ */
/*----------------------------------------------------------------------*/
/* Error and Reason Code definitions */
/*----------------------------------------------------------------------*/
/*
* Values of type NPError:
*/
#define NPERR_BASE 0
#define NPERR_NO_ERROR (NPERR_BASE + 0)
#define NPERR_GENERIC_ERROR (NPERR_BASE + 1)
#define NPERR_INVALID_INSTANCE_ERROR (NPERR_BASE + 2)
#define NPERR_INVALID_FUNCTABLE_ERROR (NPERR_BASE + 3)
#define NPERR_MODULE_LOAD_FAILED_ERROR (NPERR_BASE + 4)
#define NPERR_OUT_OF_MEMORY_ERROR (NPERR_BASE + 5)
#define NPERR_INVALID_PLUGIN_ERROR (NPERR_BASE + 6)
#define NPERR_INVALID_PLUGIN_DIR_ERROR (NPERR_BASE + 7)
#define NPERR_INCOMPATIBLE_VERSION_ERROR (NPERR_BASE + 8)
#define NPERR_INVALID_PARAM (NPERR_BASE + 9)
#define NPERR_INVALID_URL (NPERR_BASE + 10)
#define NPERR_FILE_NOT_FOUND (NPERR_BASE + 11)
#define NPERR_NO_DATA (NPERR_BASE + 12)
#define NPERR_STREAM_NOT_SEEKABLE (NPERR_BASE + 13)
#define NPERR_TIME_RANGE_NOT_SUPPORTED (NPERR_BASE + 14)
#define NPERR_MALFORMED_SITE (NPERR_BASE + 15)
/*
* Values of type NPReason:
*/
#define NPRES_BASE 0
#define NPRES_DONE (NPRES_BASE + 0)
#define NPRES_NETWORK_ERR (NPRES_BASE + 1)
#define NPRES_USER_BREAK (NPRES_BASE + 2)
/*
* Don't use these obsolete error codes any more.
*/
#define NP_NOERR NP_NOERR_is_obsolete_use_NPERR_NO_ERROR
#define NP_EINVAL NP_EINVAL_is_obsolete_use_NPERR_GENERIC_ERROR
#define NP_EABORT NP_EABORT_is_obsolete_use_NPRES_USER_BREAK
/*
* Version feature information
*/
#define NPVERS_HAS_STREAMOUTPUT 8
#define NPVERS_HAS_NOTIFICATION 9
#define NPVERS_HAS_LIVECONNECT 9
#define NPVERS_68K_HAS_LIVECONNECT 11
#define NPVERS_HAS_WINDOWLESS 11
#define NPVERS_HAS_XPCONNECT_SCRIPTING 13
#define NPVERS_HAS_NPRUNTIME_SCRIPTING 14
#define NPVERS_HAS_FORM_VALUES 15
#define NPVERS_HAS_POPUPS_ENABLED_STATE 16
#define NPVERS_HAS_RESPONSE_HEADERS 17
#define NPVERS_HAS_NPOBJECT_ENUM 18
#define NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL 19
#define NPVERS_HAS_ALL_NETWORK_STREAMS 20
#define NPVERS_HAS_URL_AND_AUTH_INFO 21
#define NPVERS_HAS_PRIVATE_MODE 22
#define NPVERS_MACOSX_HAS_COCOA_EVENTS 23
#define NPVERS_HAS_ADVANCED_KEY_HANDLING 25
#define NPVERS_HAS_URL_REDIRECT_HANDLING 26
#define NPVERS_HAS_CLEAR_SITE_DATA 27
/*----------------------------------------------------------------------*/
/* Function Prototypes */
/*----------------------------------------------------------------------*/
#if defined(__OS2__)
#define NP_LOADDS _System
#else
#define NP_LOADDS
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* NPP_* functions are provided by the plugin and called by the navigator. */
#if defined(XP_UNIX)
const char* NPP_GetMIMEDescription(void);
#endif
NPError NP_LOADDS NPP_New(NPMIMEType pluginType, NPP instance,
uint16_t mode, int16_t argc, char* argn[],
char* argv[], NPSavedData* saved);
NPError NP_LOADDS NPP_Destroy(NPP instance, NPSavedData** save);
NPError NP_LOADDS NPP_SetWindow(NPP instance, NPWindow* window);
NPError NP_LOADDS NPP_NewStream(NPP instance, NPMIMEType type,
NPStream* stream, NPBool seekable,
uint16_t* stype);
NPError NP_LOADDS NPP_DestroyStream(NPP instance, NPStream* stream,
NPReason reason);
int32_t NP_LOADDS NPP_WriteReady(NPP instance, NPStream* stream);
int32_t NP_LOADDS NPP_Write(NPP instance, NPStream* stream, int32_t offset,
int32_t len, void* buffer);
void NP_LOADDS NPP_StreamAsFile(NPP instance, NPStream* stream,
const char* fname);
void NP_LOADDS NPP_Print(NPP instance, NPPrint* platformPrint);
int16_t NP_LOADDS NPP_HandleEvent(NPP instance, void* event);
void NP_LOADDS NPP_URLNotify(NPP instance, const char* url,
NPReason reason, void* notifyData);
NPError NP_LOADDS NPP_GetValue(NPP instance, NPPVariable variable, void *value);
NPError NP_LOADDS NPP_SetValue(NPP instance, NPNVariable variable, void *value);
NPBool NP_LOADDS NPP_GotFocus(NPP instance, NPFocusDirection direction);
void NP_LOADDS NPP_LostFocus(NPP instance);
void NP_LOADDS NPP_URLRedirectNotify(NPP instance, const char* url, int32_t status, void* notifyData);
NPError NP_LOADDS NPP_ClearSiteData(const char* site, uint64_t flags, uint64_t maxAge);
char** NP_LOADDS NPP_GetSitesWithData(void);
void NP_LOADDS NPP_DidComposite(NPP instance);
/* NPN_* functions are provided by the navigator and called by the plugin. */
void NP_LOADDS NPN_Version(int* plugin_major, int* plugin_minor,
int* netscape_major, int* netscape_minor);
NPError NP_LOADDS NPN_GetURLNotify(NPP instance, const char* url,
const char* target, void* notifyData);
NPError NP_LOADDS NPN_GetURL(NPP instance, const char* url,
const char* target);
NPError NP_LOADDS NPN_PostURLNotify(NPP instance, const char* url,
const char* target, uint32_t len,
const char* buf, NPBool file,
void* notifyData);
NPError NP_LOADDS NPN_PostURL(NPP instance, const char* url,
const char* target, uint32_t len,
const char* buf, NPBool file);
NPError NP_LOADDS NPN_RequestRead(NPStream* stream, NPByteRange* rangeList);
NPError NP_LOADDS NPN_NewStream(NPP instance, NPMIMEType type,
const char* target, NPStream** stream);
int32_t NP_LOADDS NPN_Write(NPP instance, NPStream* stream, int32_t len,
void* buffer);
NPError NP_LOADDS NPN_DestroyStream(NPP instance, NPStream* stream,
NPReason reason);
void NP_LOADDS NPN_Status(NPP instance, const char* message);
const char* NP_LOADDS NPN_UserAgent(NPP instance);
void* NP_LOADDS NPN_MemAlloc(uint32_t size);
void NP_LOADDS NPN_MemFree(void* ptr);
uint32_t NP_LOADDS NPN_MemFlush(uint32_t size);
void NP_LOADDS NPN_ReloadPlugins(NPBool reloadPages);
NPError NP_LOADDS NPN_GetValue(NPP instance, NPNVariable variable,
void *value);
NPError NP_LOADDS NPN_SetValue(NPP instance, NPPVariable variable,
void *value);
void NP_LOADDS NPN_InvalidateRect(NPP instance, NPRect *invalidRect);
void NP_LOADDS NPN_InvalidateRegion(NPP instance,
NPRegion invalidRegion);
void NP_LOADDS NPN_ForceRedraw(NPP instance);
void NP_LOADDS NPN_PushPopupsEnabledState(NPP instance, NPBool enabled);
void NP_LOADDS NPN_PopPopupsEnabledState(NPP instance);
void NP_LOADDS NPN_PluginThreadAsyncCall(NPP instance,
void (*func) (void *),
void *userData);
NPError NP_LOADDS NPN_GetValueForURL(NPP instance, NPNURLVariable variable,
const char *url, char **value,
uint32_t *len);
NPError NP_LOADDS NPN_SetValueForURL(NPP instance, NPNURLVariable variable,
const char *url, const char *value,
uint32_t len);
NPError NP_LOADDS NPN_GetAuthenticationInfo(NPP instance,
const char *protocol,
const char *host, int32_t port,
const char *scheme,
const char *realm,
char **username, uint32_t *ulen,
char **password,
uint32_t *plen);
uint32_t NP_LOADDS NPN_ScheduleTimer(NPP instance, uint32_t interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32_t timerID));
void NP_LOADDS NPN_UnscheduleTimer(NPP instance, uint32_t timerID);
NPError NP_LOADDS NPN_PopUpContextMenu(NPP instance, NPMenu* menu);
NPBool NP_LOADDS NPN_ConvertPoint(NPP instance, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double *destX, double *destY, NPCoordinateSpace destSpace);
NPBool NP_LOADDS NPN_HandleEvent(NPP instance, void *event, NPBool handled);
NPBool NP_LOADDS NPN_UnfocusInstance(NPP instance, NPFocusDirection direction);
void NP_LOADDS NPN_URLRedirectResponse(NPP instance, void* notifyData, NPBool allow);
#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif /* RC_INVOKED */
#if defined(__OS2__)
#pragma pack()
#endif
#endif /* npapi_h_ */

View File

@ -0,0 +1,329 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef npfunctions_h_
#define npfunctions_h_
#ifdef __OS2__
#pragma pack(1)
#define NP_LOADDS _System
#else
#define NP_LOADDS
#endif
#include "npapi.h"
#include "npruntime.h"
typedef NPError (* NP_LOADDS NPP_NewProcPtr)(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved);
typedef NPError (* NP_LOADDS NPP_DestroyProcPtr)(NPP instance, NPSavedData** save);
typedef NPError (* NP_LOADDS NPP_SetWindowProcPtr)(NPP instance, NPWindow* window);
typedef NPError (* NP_LOADDS NPP_NewStreamProcPtr)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype);
typedef NPError (* NP_LOADDS NPP_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason);
typedef int32_t (* NP_LOADDS NPP_WriteReadyProcPtr)(NPP instance, NPStream* stream);
typedef int32_t (* NP_LOADDS NPP_WriteProcPtr)(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buffer);
typedef void (* NP_LOADDS NPP_StreamAsFileProcPtr)(NPP instance, NPStream* stream, const char* fname);
typedef void (* NP_LOADDS NPP_PrintProcPtr)(NPP instance, NPPrint* platformPrint);
typedef int16_t (* NP_LOADDS NPP_HandleEventProcPtr)(NPP instance, void* event);
typedef void (* NP_LOADDS NPP_URLNotifyProcPtr)(NPP instance, const char* url, NPReason reason, void* notifyData);
/* Any NPObjects returned to the browser via NPP_GetValue should be retained
by the plugin on the way out. The browser is responsible for releasing. */
typedef NPError (* NP_LOADDS NPP_GetValueProcPtr)(NPP instance, NPPVariable variable, void *ret_value);
typedef NPError (* NP_LOADDS NPP_SetValueProcPtr)(NPP instance, NPNVariable variable, void *value);
typedef NPBool (* NP_LOADDS NPP_GotFocusPtr)(NPP instance, NPFocusDirection direction);
typedef void (* NP_LOADDS NPP_LostFocusPtr)(NPP instance);
typedef void (* NP_LOADDS NPP_URLRedirectNotifyPtr)(NPP instance, const char* url, int32_t status, void* notifyData);
typedef NPError (* NP_LOADDS NPP_ClearSiteDataPtr)(const char* site, uint64_t flags, uint64_t maxAge);
typedef char** (* NP_LOADDS NPP_GetSitesWithDataPtr)(void);
typedef void (* NP_LOADDS NPP_DidCompositePtr)(NPP instance);
typedef NPError (* NP_LOADDS NPN_GetValueProcPtr)(NPP instance, NPNVariable variable, void *ret_value);
typedef NPError (* NP_LOADDS NPN_SetValueProcPtr)(NPP instance, NPPVariable variable, void *value);
typedef NPError (* NP_LOADDS NPN_GetURLNotifyProcPtr)(NPP instance, const char* url, const char* window, void* notifyData);
typedef NPError (* NP_LOADDS NPN_PostURLNotifyProcPtr)(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file, void* notifyData);
typedef NPError (* NP_LOADDS NPN_GetURLProcPtr)(NPP instance, const char* url, const char* window);
typedef NPError (* NP_LOADDS NPN_PostURLProcPtr)(NPP instance, const char* url, const char* window, uint32_t len, const char* buf, NPBool file);
typedef NPError (* NP_LOADDS NPN_RequestReadProcPtr)(NPStream* stream, NPByteRange* rangeList);
typedef NPError (* NP_LOADDS NPN_NewStreamProcPtr)(NPP instance, NPMIMEType type, const char* window, NPStream** stream);
typedef int32_t (* NP_LOADDS NPN_WriteProcPtr)(NPP instance, NPStream* stream, int32_t len, void* buffer);
typedef NPError (* NP_LOADDS NPN_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason);
typedef void (* NP_LOADDS NPN_StatusProcPtr)(NPP instance, const char* message);
/* Browser manages the lifetime of the buffer returned by NPN_UserAgent, don't
depend on it sticking around and don't free it. */
typedef const char* (* NP_LOADDS NPN_UserAgentProcPtr)(NPP instance);
typedef void* (* NP_LOADDS NPN_MemAllocProcPtr)(uint32_t size);
typedef void (* NP_LOADDS NPN_MemFreeProcPtr)(void* ptr);
typedef uint32_t (* NP_LOADDS NPN_MemFlushProcPtr)(uint32_t size);
typedef void (* NP_LOADDS NPN_ReloadPluginsProcPtr)(NPBool reloadPages);
typedef void* (* NP_LOADDS NPN_GetJavaEnvProcPtr)(void);
typedef void* (* NP_LOADDS NPN_GetJavaPeerProcPtr)(NPP instance);
typedef void (* NP_LOADDS NPN_InvalidateRectProcPtr)(NPP instance, NPRect *rect);
typedef void (* NP_LOADDS NPN_InvalidateRegionProcPtr)(NPP instance, NPRegion region);
typedef void (* NP_LOADDS NPN_ForceRedrawProcPtr)(NPP instance);
typedef NPIdentifier (* NP_LOADDS NPN_GetStringIdentifierProcPtr)(const NPUTF8* name);
typedef void (* NP_LOADDS NPN_GetStringIdentifiersProcPtr)(const NPUTF8** names, int32_t nameCount, NPIdentifier* identifiers);
typedef NPIdentifier (* NP_LOADDS NPN_GetIntIdentifierProcPtr)(int32_t intid);
typedef bool (* NP_LOADDS NPN_IdentifierIsStringProcPtr)(NPIdentifier identifier);
typedef NPUTF8* (* NP_LOADDS NPN_UTF8FromIdentifierProcPtr)(NPIdentifier identifier);
typedef int32_t (* NP_LOADDS NPN_IntFromIdentifierProcPtr)(NPIdentifier identifier);
typedef NPObject* (* NP_LOADDS NPN_CreateObjectProcPtr)(NPP npp, NPClass *aClass);
typedef NPObject* (* NP_LOADDS NPN_RetainObjectProcPtr)(NPObject *obj);
typedef void (* NP_LOADDS NPN_ReleaseObjectProcPtr)(NPObject *obj);
typedef bool (* NP_LOADDS NPN_InvokeProcPtr)(NPP npp, NPObject* obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result);
typedef bool (* NP_LOADDS NPN_InvokeDefaultProcPtr)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result);
typedef bool (* NP_LOADDS NPN_EvaluateProcPtr)(NPP npp, NPObject *obj, NPString *script, NPVariant *result);
typedef bool (* NP_LOADDS NPN_GetPropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName, NPVariant *result);
typedef bool (* NP_LOADDS NPN_SetPropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName, const NPVariant *value);
typedef bool (* NP_LOADDS NPN_RemovePropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName);
typedef bool (* NP_LOADDS NPN_HasPropertyProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName);
typedef bool (* NP_LOADDS NPN_HasMethodProcPtr)(NPP npp, NPObject *obj, NPIdentifier propertyName);
typedef void (* NP_LOADDS NPN_ReleaseVariantValueProcPtr)(NPVariant *variant);
typedef void (* NP_LOADDS NPN_SetExceptionProcPtr)(NPObject *obj, const NPUTF8 *message);
typedef void (* NP_LOADDS NPN_PushPopupsEnabledStateProcPtr)(NPP npp, NPBool enabled);
typedef void (* NP_LOADDS NPN_PopPopupsEnabledStateProcPtr)(NPP npp);
typedef bool (* NP_LOADDS NPN_EnumerateProcPtr)(NPP npp, NPObject *obj, NPIdentifier **identifier, uint32_t *count);
typedef void (* NP_LOADDS NPN_PluginThreadAsyncCallProcPtr)(NPP instance, void (*func)(void *), void *userData);
typedef bool (* NP_LOADDS NPN_ConstructProcPtr)(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result);
typedef NPError (* NP_LOADDS NPN_GetValueForURLPtr)(NPP npp, NPNURLVariable variable, const char *url, char **value, uint32_t *len);
typedef NPError (* NP_LOADDS NPN_SetValueForURLPtr)(NPP npp, NPNURLVariable variable, const char *url, const char *value, uint32_t len);
typedef NPError (* NP_LOADDS NPN_GetAuthenticationInfoPtr)(NPP npp, const char *protocol, const char *host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen);
typedef uint32_t (* NP_LOADDS NPN_ScheduleTimerPtr)(NPP instance, uint32_t interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32_t timerID));
typedef void (* NP_LOADDS NPN_UnscheduleTimerPtr)(NPP instance, uint32_t timerID);
typedef NPError (* NP_LOADDS NPN_PopUpContextMenuPtr)(NPP instance, NPMenu* menu);
typedef NPBool (* NP_LOADDS NPN_ConvertPointPtr)(NPP instance, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double *destX, double *destY, NPCoordinateSpace destSpace);
typedef NPBool (* NP_LOADDS NPN_HandleEventPtr)(NPP instance, void *event, NPBool handled);
typedef NPBool (* NP_LOADDS NPN_UnfocusInstancePtr)(NPP instance, NPFocusDirection direction);
typedef void (* NP_LOADDS NPN_URLRedirectResponsePtr)(NPP instance, void* notifyData, NPBool allow);
typedef void (* NP_LOADDS NPN_DummyPtr)(void);
typedef struct _NPPluginFuncs {
uint16_t size;
uint16_t version;
NPP_NewProcPtr newp;
NPP_DestroyProcPtr destroy;
NPP_SetWindowProcPtr setwindow;
NPP_NewStreamProcPtr newstream;
NPP_DestroyStreamProcPtr destroystream;
NPP_StreamAsFileProcPtr asfile;
NPP_WriteReadyProcPtr writeready;
NPP_WriteProcPtr write;
NPP_PrintProcPtr print;
NPP_HandleEventProcPtr event;
NPP_URLNotifyProcPtr urlnotify;
void* javaClass;
NPP_GetValueProcPtr getvalue;
NPP_SetValueProcPtr setvalue;
NPP_GotFocusPtr gotfocus;
NPP_LostFocusPtr lostfocus;
NPP_URLRedirectNotifyPtr urlredirectnotify;
NPP_ClearSiteDataPtr clearsitedata;
NPP_GetSitesWithDataPtr getsiteswithdata;
NPP_DidCompositePtr didComposite;
} NPPluginFuncs;
typedef struct _NPNetscapeFuncs {
uint16_t size;
uint16_t version;
NPN_GetURLProcPtr geturl;
NPN_PostURLProcPtr posturl;
NPN_RequestReadProcPtr requestread;
NPN_NewStreamProcPtr newstream;
NPN_WriteProcPtr write;
NPN_DestroyStreamProcPtr destroystream;
NPN_StatusProcPtr status;
NPN_UserAgentProcPtr uagent;
NPN_MemAllocProcPtr memalloc;
NPN_MemFreeProcPtr memfree;
NPN_MemFlushProcPtr memflush;
NPN_ReloadPluginsProcPtr reloadplugins;
NPN_GetJavaEnvProcPtr getJavaEnv;
NPN_GetJavaPeerProcPtr getJavaPeer;
NPN_GetURLNotifyProcPtr geturlnotify;
NPN_PostURLNotifyProcPtr posturlnotify;
NPN_GetValueProcPtr getvalue;
NPN_SetValueProcPtr setvalue;
NPN_InvalidateRectProcPtr invalidaterect;
NPN_InvalidateRegionProcPtr invalidateregion;
NPN_ForceRedrawProcPtr forceredraw;
NPN_GetStringIdentifierProcPtr getstringidentifier;
NPN_GetStringIdentifiersProcPtr getstringidentifiers;
NPN_GetIntIdentifierProcPtr getintidentifier;
NPN_IdentifierIsStringProcPtr identifierisstring;
NPN_UTF8FromIdentifierProcPtr utf8fromidentifier;
NPN_IntFromIdentifierProcPtr intfromidentifier;
NPN_CreateObjectProcPtr createobject;
NPN_RetainObjectProcPtr retainobject;
NPN_ReleaseObjectProcPtr releaseobject;
NPN_InvokeProcPtr invoke;
NPN_InvokeDefaultProcPtr invokeDefault;
NPN_EvaluateProcPtr evaluate;
NPN_GetPropertyProcPtr getproperty;
NPN_SetPropertyProcPtr setproperty;
NPN_RemovePropertyProcPtr removeproperty;
NPN_HasPropertyProcPtr hasproperty;
NPN_HasMethodProcPtr hasmethod;
NPN_ReleaseVariantValueProcPtr releasevariantvalue;
NPN_SetExceptionProcPtr setexception;
NPN_PushPopupsEnabledStateProcPtr pushpopupsenabledstate;
NPN_PopPopupsEnabledStateProcPtr poppopupsenabledstate;
NPN_EnumerateProcPtr enumerate;
NPN_PluginThreadAsyncCallProcPtr pluginthreadasynccall;
NPN_ConstructProcPtr construct;
NPN_GetValueForURLPtr getvalueforurl;
NPN_SetValueForURLPtr setvalueforurl;
NPN_GetAuthenticationInfoPtr getauthenticationinfo;
NPN_ScheduleTimerPtr scheduletimer;
NPN_UnscheduleTimerPtr unscheduletimer;
NPN_PopUpContextMenuPtr popupcontextmenu;
NPN_ConvertPointPtr convertpoint;
NPN_HandleEventPtr handleevent;
NPN_UnfocusInstancePtr unfocusinstance;
NPN_URLRedirectResponsePtr urlredirectresponse;
NPN_DummyPtr initasyncsurfaceOBSOLETE;
NPN_DummyPtr finalizeasyncsurfaceOBSOLETE;
NPN_DummyPtr setcurrentasyncsurfaceOBSOLETE;
} NPNetscapeFuncs;
#ifdef XP_MACOSX
/*
* Mac OS X version(s) of NP_GetMIMEDescription(const char *)
* These can be called to retreive MIME information from the plugin dynamically
*
* Note: For compatibility with Quicktime, BPSupportedMIMEtypes is another way
* to get mime info from the plugin only on OSX and may not be supported
* in furture version -- use NP_GetMIMEDescription instead
*/
enum
{
kBPSupportedMIMETypesStructVers_1 = 1
};
typedef struct _BPSupportedMIMETypes
{
SInt32 structVersion; /* struct version */
Handle typeStrings; /* STR# formated handle, allocated by plug-in */
Handle infoStrings; /* STR# formated handle, allocated by plug-in */
} BPSupportedMIMETypes;
OSErr BP_GetSupportedMIMETypes(BPSupportedMIMETypes *mimeInfo, UInt32 flags);
#define NP_GETMIMEDESCRIPTION_NAME "NP_GetMIMEDescription"
typedef const char* (*NP_GetMIMEDescriptionProcPtr)(void);
typedef OSErr (*BP_GetSupportedMIMETypesProcPtr)(BPSupportedMIMETypes*, UInt32);
#endif
#if defined(_WIN32)
#define OSCALL WINAPI
#else
#if defined(__OS2__)
#define OSCALL _System
#else
#define OSCALL
#endif
#endif
#if defined(XP_UNIX)
/* GCC 3.3 and later support the visibility attribute. */
#if defined(__GNUC__) && ((__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))
#define NP_VISIBILITY_DEFAULT __attribute__((visibility("default")))
#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC)
#define NP_VISIBILITY_DEFAULT __global
#else
#define NP_VISIBILITY_DEFAULT
#endif
#define NP_EXPORT(__type) NP_VISIBILITY_DEFAULT __type
#endif
#if defined(_WIN32) || defined (__OS2__)
#ifdef __cplusplus
extern "C" {
#endif
/* plugin meta member functions */
#if defined(__OS2__)
typedef struct _NPPluginData { /* Alternate OS2 Plugin interface */
char *pMimeTypes;
char *pFileExtents;
char *pFileOpenTemplate;
char *pProductName;
char *pProductDescription;
unsigned long dwProductVersionMS;
unsigned long dwProductVersionLS;
} NPPluginData;
typedef NPError (OSCALL *NP_GetPluginDataFunc)(NPPluginData*);
NPError OSCALL NP_GetPluginData(NPPluginData * pPluginData);
#endif
typedef NPError (OSCALL *NP_GetEntryPointsFunc)(NPPluginFuncs*);
NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs);
typedef NPError (OSCALL *NP_InitializeFunc)(NPNetscapeFuncs*);
NPError OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs);
typedef NPError (OSCALL *NP_ShutdownFunc)(void);
NPError OSCALL NP_Shutdown(void);
typedef const char* (*NP_GetMIMEDescriptionFunc)(void);
const char* NP_GetMIMEDescription(void);
#ifdef __cplusplus
}
#endif
#endif
#if defined(__OS2__)
#pragma pack()
#endif
#ifdef XP_UNIX
#ifdef __cplusplus
extern "C" {
#endif
typedef char* (*NP_GetPluginVersionFunc)(void);
NP_EXPORT(char*) NP_GetPluginVersion(void);
typedef const char* (*NP_GetMIMEDescriptionFunc)(void);
NP_EXPORT(const char*) NP_GetMIMEDescription(void);
#ifdef XP_MACOSX
typedef NPError (*NP_InitializeFunc)(NPNetscapeFuncs*);
NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs);
typedef NPError (*NP_GetEntryPointsFunc)(NPPluginFuncs*);
NP_EXPORT(NPError) NP_GetEntryPoints(NPPluginFuncs* pFuncs);
#else
typedef NPError (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*);
NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs);
#endif
typedef NPError (*NP_ShutdownFunc)(void);
NP_EXPORT(NPError) NP_Shutdown(void);
typedef NPError (*NP_GetValueFunc)(void *, NPPVariable, void *);
NP_EXPORT(NPError) NP_GetValue(void *future, NPPVariable aVariable, void *aValue);
#ifdef __cplusplus
}
#endif
#endif
#endif /* npfunctions_h_ */

View File

@ -0,0 +1,393 @@
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Copyright (c) 2004, Apple Computer, Inc. and The Mozilla Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the names of Apple Computer, Inc. ("Apple") or The Mozilla
* Foundation ("Mozilla") nor the names of their contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE, MOZILLA AND THEIR CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE, MOZILLA OR
* THEIR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef _NP_RUNTIME_H_
#define _NP_RUNTIME_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "nptypes.h"
/*
This API is used to facilitate binding code written in C to script
objects. The API in this header does not assume the presence of a
user agent. That is, it can be used to bind C code to scripting
environments outside of the context of a user agent.
However, the normal use of the this API is in the context of a
scripting environment running in a browser or other user agent.
In particular it is used to support the extended Netscape
script-ability API for plugins (NP-SAP). NP-SAP is an extension
of the Netscape plugin API. As such we have adopted the use of
the "NP" prefix for this API.
The following NP{N|P}Variables were added to the Netscape plugin
API (in npapi.h):
NPNVWindowNPObject
NPNVPluginElementNPObject
NPPVpluginScriptableNPObject
These variables are exposed through NPN_GetValue() and
NPP_GetValue() (respectively) and are used to establish the
initial binding between the user agent and native code. The DOM
objects in the user agent can be examined and manipulated using
the NPN_ functions that operate on NPObjects described in this
header.
To the extent possible the assumptions about the scripting
language used by the scripting environment have been minimized.
*/
#define NP_BEGIN_MACRO do {
#define NP_END_MACRO } while (0)
/*
Objects (non-primitive data) passed between 'C' and script is
always wrapped in an NPObject. The 'interface' of an NPObject is
described by an NPClass.
*/
typedef struct NPObject NPObject;
typedef struct NPClass NPClass;
typedef char NPUTF8;
typedef struct _NPString {
const NPUTF8 *UTF8Characters;
uint32_t UTF8Length;
} NPString;
typedef enum {
NPVariantType_Void,
NPVariantType_Null,
NPVariantType_Bool,
NPVariantType_Int32,
NPVariantType_Double,
NPVariantType_String,
NPVariantType_Object
} NPVariantType;
typedef struct _NPVariant {
NPVariantType type;
union {
bool boolValue;
int32_t intValue;
double doubleValue;
NPString stringValue;
NPObject *objectValue;
} value;
} NPVariant;
/*
NPN_ReleaseVariantValue is called on all 'out' parameters
references. Specifically it is to be called on variants that own
their value, as is the case with all non-const NPVariant*
arguments after a successful call to any methods (except this one)
in this API.
After calling NPN_ReleaseVariantValue, the type of the variant
will be NPVariantType_Void.
*/
void NPN_ReleaseVariantValue(NPVariant *variant);
#define NPVARIANT_IS_VOID(_v) ((_v).type == NPVariantType_Void)
#define NPVARIANT_IS_NULL(_v) ((_v).type == NPVariantType_Null)
#define NPVARIANT_IS_BOOLEAN(_v) ((_v).type == NPVariantType_Bool)
#define NPVARIANT_IS_INT32(_v) ((_v).type == NPVariantType_Int32)
#define NPVARIANT_IS_DOUBLE(_v) ((_v).type == NPVariantType_Double)
#define NPVARIANT_IS_STRING(_v) ((_v).type == NPVariantType_String)
#define NPVARIANT_IS_OBJECT(_v) ((_v).type == NPVariantType_Object)
#define NPVARIANT_TO_BOOLEAN(_v) ((_v).value.boolValue)
#define NPVARIANT_TO_INT32(_v) ((_v).value.intValue)
#define NPVARIANT_TO_DOUBLE(_v) ((_v).value.doubleValue)
#define NPVARIANT_TO_STRING(_v) ((_v).value.stringValue)
#define NPVARIANT_TO_OBJECT(_v) ((_v).value.objectValue)
#define VOID_TO_NPVARIANT(_v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_Void; \
(_v).value.objectValue = NULL; \
NP_END_MACRO
#define NULL_TO_NPVARIANT(_v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_Null; \
(_v).value.objectValue = NULL; \
NP_END_MACRO
#define BOOLEAN_TO_NPVARIANT(_val, _v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_Bool; \
(_v).value.boolValue = !!(_val); \
NP_END_MACRO
#define INT32_TO_NPVARIANT(_val, _v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_Int32; \
(_v).value.intValue = _val; \
NP_END_MACRO
#define DOUBLE_TO_NPVARIANT(_val, _v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_Double; \
(_v).value.doubleValue = _val; \
NP_END_MACRO
#define STRINGZ_TO_NPVARIANT(_val, _v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_String; \
NPString str = { _val, (uint32_t)(strlen(_val)) }; \
(_v).value.stringValue = str; \
NP_END_MACRO
#define STRINGN_TO_NPVARIANT(_val, _len, _v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_String; \
NPString str = { _val, (uint32_t)(_len) }; \
(_v).value.stringValue = str; \
NP_END_MACRO
#define OBJECT_TO_NPVARIANT(_val, _v) \
NP_BEGIN_MACRO \
(_v).type = NPVariantType_Object; \
(_v).value.objectValue = _val; \
NP_END_MACRO
/*
Type mappings (JavaScript types have been used for illustration
purposes):
JavaScript to C (NPVariant with type:)
undefined NPVariantType_Void
null NPVariantType_Null
Boolean NPVariantType_Bool
Number NPVariantType_Double or NPVariantType_Int32
String NPVariantType_String
Object NPVariantType_Object
C (NPVariant with type:) to JavaScript
NPVariantType_Void undefined
NPVariantType_Null null
NPVariantType_Bool Boolean
NPVariantType_Int32 Number
NPVariantType_Double Number
NPVariantType_String String
NPVariantType_Object Object
*/
typedef void *NPIdentifier;
/*
NPObjects have methods and properties. Methods and properties are
identified with NPIdentifiers. These identifiers may be reflected
in script. NPIdentifiers can be either strings or integers, IOW,
methods and properties can be identified by either strings or
integers (i.e. foo["bar"] vs foo[1]). NPIdentifiers can be
compared using ==. In case of any errors, the requested
NPIdentifier(s) will be NULL. NPIdentifier lifetime is controlled
by the browser. Plugins do not need to worry about memory management
with regards to NPIdentifiers.
*/
NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name);
void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount,
NPIdentifier *identifiers);
NPIdentifier NPN_GetIntIdentifier(int32_t intid);
bool NPN_IdentifierIsString(NPIdentifier identifier);
/*
The NPUTF8 returned from NPN_UTF8FromIdentifier SHOULD be freed.
*/
NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier);
/*
Get the integer represented by identifier. If identifier is not an
integer identifier, the behaviour is undefined.
*/
int32_t NPN_IntFromIdentifier(NPIdentifier identifier);
/*
NPObject behavior is implemented using the following set of
callback functions.
The NPVariant *result argument of these functions (where
applicable) should be released using NPN_ReleaseVariantValue().
*/
typedef NPObject *(*NPAllocateFunctionPtr)(NPP npp, NPClass *aClass);
typedef void (*NPDeallocateFunctionPtr)(NPObject *npobj);
typedef void (*NPInvalidateFunctionPtr)(NPObject *npobj);
typedef bool (*NPHasMethodFunctionPtr)(NPObject *npobj, NPIdentifier name);
typedef bool (*NPInvokeFunctionPtr)(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result);
typedef bool (*NPInvokeDefaultFunctionPtr)(NPObject *npobj,
const NPVariant *args,
uint32_t argCount,
NPVariant *result);
typedef bool (*NPHasPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name);
typedef bool (*NPGetPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name,
NPVariant *result);
typedef bool (*NPSetPropertyFunctionPtr)(NPObject *npobj, NPIdentifier name,
const NPVariant *value);
typedef bool (*NPRemovePropertyFunctionPtr)(NPObject *npobj,
NPIdentifier name);
typedef bool (*NPEnumerationFunctionPtr)(NPObject *npobj, NPIdentifier **value,
uint32_t *count);
typedef bool (*NPConstructFunctionPtr)(NPObject *npobj,
const NPVariant *args,
uint32_t argCount,
NPVariant *result);
/*
NPObjects returned by create, retain, invoke, and getProperty pass
a reference count to the caller. That is, the callee adds a
reference count which passes to the caller. It is the caller's
responsibility to release the returned object.
NPInvokeFunctionPtr function may return 0 to indicate a void
result.
NPInvalidateFunctionPtr is called by the scripting environment
when the native code is shutdown. Any attempt to message a
NPObject instance after the invalidate callback has been
called will result in undefined behavior, even if the native code
is still retaining those NPObject instances. (The runtime
will typically return immediately, with 0 or NULL, from an attempt
to dispatch to a NPObject, but this behavior should not be
depended upon.)
The NPEnumerationFunctionPtr function may pass an array of
NPIdentifiers back to the caller. The callee allocs the memory of
the array using NPN_MemAlloc(), and it's the caller's responsibility
to release it using NPN_MemFree().
*/
struct NPClass
{
uint32_t structVersion;
NPAllocateFunctionPtr allocate;
NPDeallocateFunctionPtr deallocate;
NPInvalidateFunctionPtr invalidate;
NPHasMethodFunctionPtr hasMethod;
NPInvokeFunctionPtr invoke;
NPInvokeDefaultFunctionPtr invokeDefault;
NPHasPropertyFunctionPtr hasProperty;
NPGetPropertyFunctionPtr getProperty;
NPSetPropertyFunctionPtr setProperty;
NPRemovePropertyFunctionPtr removeProperty;
NPEnumerationFunctionPtr enumerate;
NPConstructFunctionPtr construct;
};
#define NP_CLASS_STRUCT_VERSION 3
#define NP_CLASS_STRUCT_VERSION_ENUM 2
#define NP_CLASS_STRUCT_VERSION_CTOR 3
#define NP_CLASS_STRUCT_VERSION_HAS_ENUM(npclass) \
((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_ENUM)
#define NP_CLASS_STRUCT_VERSION_HAS_CTOR(npclass) \
((npclass)->structVersion >= NP_CLASS_STRUCT_VERSION_CTOR)
struct NPObject {
NPClass *_class;
uint32_t referenceCount;
/*
* Additional space may be allocated here by types of NPObjects
*/
};
/*
If the class has an allocate function, NPN_CreateObject invokes
that function, otherwise a NPObject is allocated and
returned. This method will initialize the referenceCount member of
the NPObject to 1.
*/
NPObject *NPN_CreateObject(NPP npp, NPClass *aClass);
/*
Increment the NPObject's reference count.
*/
NPObject *NPN_RetainObject(NPObject *npobj);
/*
Decremented the NPObject's reference count. If the reference
count goes to zero, the class's destroy function is invoke if
specified, otherwise the object is freed directly.
*/
void NPN_ReleaseObject(NPObject *npobj);
/*
Functions to access script objects represented by NPObject.
Calls to script objects are synchronous. If a function returns a
value, it will be supplied via the result NPVariant
argument. Successful calls will return true, false will be
returned in case of an error.
Calls made from plugin code to script must be made from the thread
on which the plugin was initialized.
*/
bool NPN_Invoke(NPP npp, NPObject *npobj, NPIdentifier methodName,
const NPVariant *args, uint32_t argCount, NPVariant *result);
bool NPN_InvokeDefault(NPP npp, NPObject *npobj, const NPVariant *args,
uint32_t argCount, NPVariant *result);
bool NPN_Evaluate(NPP npp, NPObject *npobj, NPString *script,
NPVariant *result);
bool NPN_GetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
NPVariant *result);
bool NPN_SetProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName,
const NPVariant *value);
bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName);
bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName);
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName);
bool NPN_Enumerate(NPP npp, NPObject *npobj, NPIdentifier **identifier,
uint32_t *count);
bool NPN_Construct(NPP npp, NPObject *npobj, const NPVariant *args,
uint32_t argCount, NPVariant *result);
/*
NPN_SetException may be called to trigger a script exception upon
return from entry points into NPObjects. Typical usage:
NPN_SetException (npobj, message);
*/
void NPN_SetException(NPObject *npobj, const NPUTF8 *message);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,121 @@
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* mozilla.org.
* Portions created by the Initial Developer are Copyright (C) 2004
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Johnny Stenback <jst@mozilla.org> (Original author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nptypes_h_
#define nptypes_h_
/*
* Header file for ensuring that C99 types ([u]int32_t, [u]int64_t and bool) and
* true/false macros are available.
*/
#if (defined(WIN32) && !defined(__GNUC__)) || defined(OS2)
/*
* Win32 and OS/2 don't know C99, so define [u]int_16/32/64 here. The bool
* is predefined tho, both in C and C++.
*/
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
#elif defined(_AIX) || defined(__sun) || defined(__osf__) || defined(IRIX) || defined(HPUX)
/*
* AIX and SunOS ship a inttypes.h header that defines [u]int32_t,
* but not bool for C.
*/
#include <inttypes.h>
#ifndef __cplusplus
typedef int bool;
#define true 1
#define false 0
#endif
#elif defined(bsdi) || defined(FREEBSD) || defined(OPENBSD)
/*
* BSD/OS, FreeBSD, and OpenBSD ship sys/types.h that define int32_t and
* u_int32_t.
*/
#include <sys/types.h>
/*
* BSD/OS ships no header that defines uint32_t, nor bool (for C)
*/
#if defined(bsdi)
typedef u_int32_t uint32_t;
typedef u_int64_t uint64_t;
#if !defined(__cplusplus)
typedef int bool;
#define true 1
#define false 0
#endif
#else
/*
* FreeBSD and OpenBSD define uint32_t and bool.
*/
#include <inttypes.h>
#include <stdbool.h>
#endif
#elif defined(BEOS)
#include <inttypes.h>
#else
/*
* For those that ship a standard C99 stdint.h header file, include
* it. Can't do the same for stdbool.h tho, since some systems ship
* with a stdbool.h file that doesn't compile!
*/
#include <stdint.h>
#ifndef __cplusplus
#if !defined(__GNUC__) || (__GNUC__ > 2 || __GNUC_MINOR__ > 95)
#include <stdbool.h>
#else
/*
* GCC 2.91 can't deal with a typedef for bool, but a #define
* works.
*/
#define bool int
#define true 1
#define false 0
#endif
#endif
#endif
#endif /* nptypes_h_ */

View File

@ -230,10 +230,10 @@ call(const string &method_name, P3D_object *params[], int num_params) const {
////////////////////////////////////////////////////////////////////
P3D_object *PPBrowserObject::
eval(const string &expression) const {
NPString npexpr = { expression.c_str(), expression.length() };
NPString npexpr = { expression.c_str(), (uint32_t)expression.length() };
NPVariant result;
if (!browser->evaluate(_instance->get_npp_instance(), _npobj,
if (!browser->evaluate(_instance->get_npp_instance(), _npobj,
&npexpr, &result)) {
// Failed to eval.
return NULL;

View File

@ -1882,8 +1882,10 @@ send_window() {
assert(!_use_xembed);
parent_window._window_handle_type = _window_handle_type;
if (_window_handle_type == P3D_WHT_osx_port) {
#if !__LP64__
NP_Port *port = (NP_Port *)_window.window;
parent_window._handle._osx_port._port = port->port;
#endif
} else if (_window_handle_type == P3D_WHT_osx_cgcontext) {
NP_CGContext *context = (NP_CGContext *)_window.window;
if (context != NULL) {
@ -1929,8 +1931,10 @@ send_window() {
#elif defined(__APPLE__)
parent_window._window_handle_type = _window_handle_type;
if (_window_handle_type == P3D_WHT_osx_port) {
#if !__LP64__
NP_Port *port = (NP_Port *)_window.window;
parent_window._handle._osx_port._port = port->port;
#endif
} else if (_window_handle_type == P3D_WHT_osx_cgcontext) {
NP_CGContext *context = (NP_CGContext *)_window.window;
if (context != NULL) {
@ -2173,16 +2177,16 @@ set_failed() {
NPObject *window_object = NULL;
if (browser->getvalue(_npp_instance, NPNVWindowNPObject,
&window_object) == NPERR_NO_ERROR) {
NPString npexpr = { expression.c_str(), expression.length() };
NPString npexpr = { expression.c_str(), (uint32_t)expression.length() };
NPVariant result;
if (browser->evaluate(_npp_instance, window_object,
if (browser->evaluate(_npp_instance, window_object,
&npexpr, &result)) {
nout << "Eval " << expression << "\n";
browser->releasevariantvalue(&result);
} else {
nout << "Unable to eval " << expression << "\n";
}
browser->releaseobject(window_object);
}
}

View File

@ -187,7 +187,7 @@ NP_Initialize(NPNetscapeFuncs *browserFuncs,
}
#endif
int browser_major = (browser->version >> 8) && 0xff;
int browser_major = (browser->version >> 8) & 0xff;
int browser_minor = browser->version & 0xff;
nout << "Browser NPAPI version " << browser_major << "." << browser_minor << "\n";

View File

@ -83,7 +83,6 @@
#end bin_target
#begin bin_target
#define BUILD_TARGET $[and $[HAVE_JPEG],$[HAVE_PNG]]
#define USE_PACKAGES openssl zlib
#define TARGET p3dembed
#define LOCAL_LIBS plugin_common p3d_plugin_static
@ -115,7 +114,7 @@
// On Windows, we also need to build p3dembedw.exe, the non-console
// version of p3dembed.exe.
#define BUILD_TARGET $[and $[HAVE_JPEG],$[HAVE_PNG],$[WINDOWS_PLATFORM]]
#define BUILD_TARGET $[WINDOWS_PLATFORM]
#define USE_PACKAGES openssl zlib
#define TARGET p3dembedw
#define LOCAL_LIBS plugin_common p3d_plugin_static

View File

@ -147,7 +147,7 @@ run_main_loop() {
}
}
#elif defined(__APPLE__)
#elif defined(__APPLE__) && !__LP64__
// OSX really prefers to own the main loop, so we install a timer to
// call out to our instances and getters, rather than polling within
// the event loop as we do in the Windows case, above.
@ -699,7 +699,7 @@ report_download_complete(P3D_instance *instance) {
}
}
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
////////////////////////////////////////////////////////////////////
// Function: Panda3DBase::st_timer_callback
// Access: Protected, Static
@ -712,7 +712,7 @@ st_timer_callback(EventLoopTimerRef timer, void *user_data) {
}
#endif // __APPLE__
#ifdef __APPLE__
#if defined(__APPLE__) && !__LP64__
////////////////////////////////////////////////////////////////////
// Function: Panda3DBase::timer_callback
// Access: Protected

View File

@ -63,7 +63,7 @@ open_p3d_file(FSRef *ref) {
static pascal OSErr
open_documents_handler(const AppleEvent *theAppleEvent, AppleEvent *reply,
long handlerRefcon) {
SRefCon handlerRefcon) {
AEDescList docList;
FSRef theFSRef;
long index;

View File

@ -187,3 +187,8 @@ class EventManager:
def shutdown(self):
taskMgr.remove('eventManager')
# Flush the event queue. We do this after removing the task
# since the task removal itself might also fire off an event.
if self.eventQueue is not None:
self.eventQueue.clear()

View File

@ -11,15 +11,15 @@ from panda3d.core import *
from panda3d.direct import get_config_showbase, throw_new_frame, init_app_for_gui
# This needs to be available early for DirectGUI imports
import __builtin__
__builtin__.config = get_config_showbase()
import __builtin__ as builtins
builtins.config = get_config_showbase()
from direct.directnotify.DirectNotifyGlobal import *
from MessengerGlobal import *
from BulletinBoardGlobal import *
from direct.task.TaskManagerGlobal import *
from JobManagerGlobal import *
from EventManagerGlobal import *
from direct.directnotify.DirectNotifyGlobal import directNotify, giveNotify
from MessengerGlobal import messenger
from BulletinBoardGlobal import bulletinBoard
from direct.task.TaskManagerGlobal import taskMgr
from JobManagerGlobal import jobMgr
from EventManagerGlobal import eventMgr
from PythonUtil import *
from direct.showbase import PythonUtil
#from direct.interval.IntervalManager import ivalMgr
@ -29,11 +29,11 @@ from direct.showbase.BufferViewer import BufferViewer
from direct.task import Task
from direct.directutil import Verify
from direct.showbase import GarbageReport
import EventManager
import math,sys,os
import Loader
import time
import gc
import atexit
from direct.fsm import ClassicFSM
from direct.fsm import State
from direct.showbase import ExceptionVarDump
@ -44,9 +44,17 @@ if __debug__:
import OnScreenDebug
import AppRunnerGlobal
__builtin__.FADE_SORT_INDEX = 1000
__builtin__.NO_FADE_SORT_INDEX = 2000
builtins.FADE_SORT_INDEX = 1000
builtins.NO_FADE_SORT_INDEX = 2000
def legacyRun():
builtins.base.notify.warning("run() is deprecated, use base.run() instead")
builtins.base.run()
@atexit.register
def exitfunc():
if getattr(builtins, 'base', None) is not None:
builtins.base.destroy()
# Now ShowBase is a DirectObject. We need this so ShowBase can hang
# hooks on messages, particularly on window-event. This doesn't
@ -57,7 +65,7 @@ class ShowBase(DirectObject.DirectObject):
def __init__(self, fStartDirect = True, windowType = None):
self.__dev__ = config.GetBool('want-dev', __debug__)
__builtin__.__dev__ = self.__dev__
builtins.__dev__ = self.__dev__
logStackDump = (config.GetBool('log-stack-dump', False) or
config.GetBool('client-log-stack-dump', False))
@ -65,11 +73,12 @@ class ShowBase(DirectObject.DirectObject):
if logStackDump or uploadStackDump:
ExceptionVarDump.install(logStackDump, uploadStackDump)
# Locate the directory containing the main program
## The directory containing the main Python file of this application.
self.mainDir = ExecutionEnvironment.getEnvironmentVariable("MAIN_DIR")
# The appRunner should have been created by the time ShowBase
# has been.
## This contains the global appRunner instance, as imported from
## AppRunnerGlobal. This will be None if we are not running in the
## runtime environment (ie. from a .p3d file).
self.appRunner = AppRunnerGlobal.appRunner
#debug running multiplier
@ -108,13 +117,13 @@ class ShowBase(DirectObject.DirectObject):
self.wantTk = False
self.wantWx = False
# Fill this in with a function to invoke when the user "exits"
# the program by closing the main window.
## Fill this in with a function to invoke when the user "exits"
## the program by closing the main window.
self.exitFunc = None
# Add final-exit callbacks to this list. These will be called
# when sys.exit() is called, after Panda has unloaded, and
# just before Python is about to shut down.
## Add final-exit callbacks to this list. These will be called
## when sys.exit() is called, after Panda has unloaded, and
## just before Python is about to shut down.
self.finalExitCallbacks = []
Task.TaskManager.taskTimerVerbose = self.config.GetBool('task-timer-verbose', 0)
@ -139,13 +148,15 @@ class ShowBase(DirectObject.DirectObject):
# we get a window-event.
self.__oldAspectRatio = None
## This is set to the value of the window-type config variable, but may
## optionally be overridden in the Showbase constructor. Should either be
## 'onscreen' (the default), 'offscreen' or 'none'.
self.windowType = windowType
if self.windowType is None:
self.windowType = self.config.GetString('window-type', 'onscreen')
self.requireWindow = self.config.GetBool('require-window', 1)
# base.win is the main, or only window; base.winList is a list of
# *all* windows. Similarly with base.camList.
## This is the main, or only window; see winList for a list of *all* windows.
self.win = None
self.frameRateMeter = None
self.sceneGraphAnalyzerMeter = None
@ -165,17 +176,29 @@ class ShowBase(DirectObject.DirectObject):
self.trackball = None
self.texmem = None
self.showVertices = None
## This is a NodePath pointing to the Camera object set up for the 3D scene.
## This is usually a child of self.camera.
self.cam = None
self.cam2d = None
self.cam2dp = None
## This is the NodePath that should be used to manipulate the camera. This
## is the node to which the default camera is attached.
self.camera = None
self.camera2d = None
self.camera2dp = None
## This is a list of all cameras created with makeCamera, including base.cam.
self.camList = []
## Convenience accessor for base.cam.node()
self.camNode = None
## Convenience accessor for base.camNode.get_lens()
self.camLens = None
self.camFrustumVis = None
self.direct = None
## This is used to store the wx.Application object used when want-wx is
## set or base.startWx() is called.
self.wxApp = None
self.tkRoot = None
@ -189,6 +212,7 @@ class ShowBase(DirectObject.DirectObject):
self.hidden = NodePath('hidden')
## The global graphics engine, ie. GraphicsEngine.getGlobalPtr()
self.graphicsEngine = GraphicsEngine.getGlobalPtr()
self.setupRender()
self.setupRender2d()
@ -198,11 +222,11 @@ class ShowBase(DirectObject.DirectObject):
self.setupRender2dp()
# This is a placeholder for a CollisionTraverser. If someone
# stores a CollisionTraverser pointer here, we'll traverse it
# in the collisionLoop task.
self.shadowTrav = 0
## This is a placeholder for a CollisionTraverser. If someone
## stores a CollisionTraverser pointer here, we'll traverse it
## in the collisionLoop task.
self.cTrav = 0
self.shadowTrav = 0
self.cTravStack = Stack()
# Ditto for an AppTraverser.
self.appTrav = 0
@ -233,10 +257,6 @@ class ShowBase(DirectObject.DirectObject):
random.seed(seed)
#whrandom.seed(seed & 0xff, (seed >> 8) & 0xff, (seed >> 16) & 0xff)
# Now that we've set up the window structures, assign an exitfunc.
self.oldexitfunc = getattr(sys, 'exitfunc', None)
sys.exitfunc = self.exitfunc
# Open the default rendering window.
if self.windowType != 'none':
props = WindowProperties.getDefault()
@ -254,17 +274,22 @@ class ShowBase(DirectObject.DirectObject):
self.loader = Loader.Loader(self)
self.graphicsEngine.setDefaultLoader(self.loader.loader)
## The global event manager, as imported from EventManagerGlobal.
self.eventMgr = eventMgr
## The global messenger, as imported from MessengerGlobal.
self.messenger = messenger
## The global bulletin board, as imported from BulletinBoardGlobal.
self.bboard = bulletinBoard
## The global task manager, as imported from TaskManagerGlobal.
self.taskMgr = taskMgr
## The global job manager, as imported from JobManagerGlobal.
self.jobMgr = jobMgr
# Particle manager
## Particle manager
self.particleMgr = None
self.particleMgrEnabled = 0
# Physics manager
## Physics manager
self.physicsMgr = None
self.physicsMgrEnabled = 0
self.physicsMgrAngular = 0
@ -302,8 +327,8 @@ class ShowBase(DirectObject.DirectObject):
# assigned to a single CPU
autoAffinity = self.config.GetBool('auto-single-cpu-affinity', 0)
affinity = None
if autoAffinity and ('clientIndex' in __builtin__.__dict__):
affinity = abs(int(__builtin__.clientIndex))
if autoAffinity and ('clientIndex' in builtins.__dict__):
affinity = abs(int(builtins.clientIndex))
else:
affinity = self.config.GetInt('client-cpu-affinity', -1)
if (affinity in (None, -1)) and autoAffinity:
@ -313,42 +338,44 @@ class ShowBase(DirectObject.DirectObject):
TrueClock.getGlobalPtr().setCpuAffinity(1 << (affinity % 32))
# Make sure we're not making more than one ShowBase.
if 'base' in __builtin__.__dict__:
if 'base' in builtins.__dict__:
raise StandardError, "Attempt to spawn multiple ShowBase instances!"
__builtin__.base = self
__builtin__.render2d = self.render2d
__builtin__.aspect2d = self.aspect2d
__builtin__.pixel2d = self.pixel2d
__builtin__.render = self.render
__builtin__.hidden = self.hidden
__builtin__.camera = self.camera
__builtin__.loader = self.loader
__builtin__.taskMgr = self.taskMgr
__builtin__.jobMgr = self.jobMgr
__builtin__.eventMgr = self.eventMgr
__builtin__.messenger = self.messenger
__builtin__.bboard = self.bboard
# DO NOT ADD TO THIS LIST. We're trying to phase out the use of
# built-in variables by ShowBase. Use a Global module if necessary.
builtins.base = self
builtins.render2d = self.render2d
builtins.aspect2d = self.aspect2d
builtins.pixel2d = self.pixel2d
builtins.render = self.render
builtins.hidden = self.hidden
builtins.camera = self.camera
builtins.loader = self.loader
builtins.taskMgr = self.taskMgr
builtins.jobMgr = self.jobMgr
builtins.eventMgr = self.eventMgr
builtins.messenger = self.messenger
builtins.bboard = self.bboard
# Config needs to be defined before ShowBase is constructed
#__builtin__.config = self.config
__builtin__.run = self.run
__builtin__.ostream = Notify.out()
__builtin__.directNotify = directNotify
__builtin__.giveNotify = giveNotify
__builtin__.globalClock = globalClock
__builtin__.vfs = vfs
__builtin__.cpMgr = ConfigPageManager.getGlobalPtr()
__builtin__.cvMgr = ConfigVariableManager.getGlobalPtr()
__builtin__.pandaSystem = PandaSystem.getGlobalPtr()
__builtin__.wantUberdog = base.config.GetBool('want-uberdog', 1)
#builtins.config = self.config
builtins.run = legacyRun
builtins.ostream = Notify.out()
builtins.directNotify = directNotify
builtins.giveNotify = giveNotify
builtins.globalClock = globalClock
builtins.vfs = vfs
builtins.cpMgr = ConfigPageManager.getGlobalPtr()
builtins.cvMgr = ConfigVariableManager.getGlobalPtr()
builtins.pandaSystem = PandaSystem.getGlobalPtr()
builtins.wantUberdog = base.config.GetBool('want-uberdog', 1)
if __debug__:
__builtin__.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
__builtin__.onScreenDebug = OnScreenDebug.OnScreenDebug()
builtins.deltaProfiler = DeltaProfiler.DeltaProfiler("ShowBase")
builtins.onScreenDebug = OnScreenDebug.OnScreenDebug()
if self.wantRender2dp:
__builtin__.render2dp = self.render2dp
__builtin__.aspect2dp = self.aspect2dp
__builtin__.pixel2dp = self.pixel2dp
builtins.render2dp = self.render2dp
builtins.aspect2dp = self.aspect2dp
builtins.pixel2dp = self.pixel2dp
if __dev__:
ShowBase.notify.debug('__dev__ == %s' % __dev__)
@ -426,7 +453,7 @@ class ShowBase(DirectObject.DirectObject):
self.cTrav = self.cTravStack.pop()
def __setupProfile(self):
""" Sets up the Python profiler, if avaialable, according to
""" Sets up the Python profiler, if available, according to
some Panda config settings. """
try:
@ -445,8 +472,7 @@ class ShowBase(DirectObject.DirectObject):
return 0
def printEnvDebugInfo(self):
"""
Print some information about the environment that we are running
"""Print some information about the environment that we are running
in. Stuff like the model paths and other paths. Feel free to
add stuff to this.
"""
@ -470,11 +496,18 @@ class ShowBase(DirectObject.DirectObject):
for cb in self.finalExitCallbacks[:]:
cb()
# Remove the built-in base reference
if getattr(builtins, 'base', None) is self:
del builtins.base
del builtins.loader
del builtins.taskMgr
# [gjeon] restore sticky key settings
if self.config.GetBool('disable-sticky-keys', 0):
allowAccessibilityShortcutKeys(True)
taskMgr.destroy()
self.ignoreAll()
self.shutdown()
if getattr(self, 'musicManager', None):
self.musicManager.shutdown()
@ -501,19 +534,6 @@ class ShowBase(DirectObject.DirectObject):
vfs = VirtualFileSystem.getGlobalPtr()
vfs.unmountAll()
def exitfunc(self):
"""
This should be assigned to sys.exitfunc to be called just
before Python shutdown. It guarantees that the Panda window
is closed cleanly, so that we free system resources, restore
the desktop and keyboard functionality, etc.
"""
self.destroy()
if self.oldexitfunc:
self.oldexitfunc()
def makeDefaultPipe(self, printPipeTypes = True):
"""
Creates the default GraphicsPipe, which will be used to make
@ -1022,6 +1042,7 @@ class ShowBase(DirectObject.DirectObject):
Creates the render scene graph, the primary scene graph for
rendering 3-d geometry.
"""
## This is the root of the 3-D scene graph.
self.render = NodePath('render')
self.render.setAttrib(RescaleNormalAttrib.makeDefault())
@ -1037,6 +1058,7 @@ class ShowBase(DirectObject.DirectObject):
2-d objects and gui elements that are superimposed over the
3-d geometry in the window.
"""
## This is the root of the 2-D scene graph.
self.render2d = NodePath('render2d')
# Set up some overrides to turn off certain properties which
@ -1057,22 +1079,26 @@ class ShowBase(DirectObject.DirectObject):
self.render2d.setMaterialOff(1)
self.render2d.setTwoSided(1)
# The normal 2-d DisplayRegion has an aspect ratio that
# matches the window, but its coordinate system is square.
# This means anything we parent to render2d gets stretched.
# For things where that makes a difference, we set up
# aspect2d, which scales things back to the right aspect
# ratio.
aspectRatio = self.getAspectRatio()
## The normal 2-d DisplayRegion has an aspect ratio that
## matches the window, but its coordinate system is square.
## This means anything we parent to render2d gets stretched.
## For things where that makes a difference, we set up
## aspect2d, which scales things back to the right aspect
## ratio along the X axis (Z is still from -1 to 1)
self.aspect2d = self.render2d.attachNewNode(PGTop("aspect2d"))
aspectRatio = self.getAspectRatio()
self.aspect2d.setScale(1.0 / aspectRatio, 1.0, 1.0)
self.a2dBackground = self.aspect2d.attachNewNode("a2dBackground")
# It's important to know the bounds of the aspect2d screen.
## The Z position of the top border of the aspect2d screen.
self.a2dTop = 1.0
## The Z position of the bottom border of the aspect2d screen.
self.a2dBottom = -1.0
## The X position of the left border of the aspect2d screen.
self.a2dLeft = -aspectRatio
## The X position of the right border of the aspect2d screen.
self.a2dRight = aspectRatio
self.a2dTopCenter = self.aspect2d.attachNewNode("a2dTopCenter")
@ -1112,12 +1138,12 @@ class ShowBase(DirectObject.DirectObject):
self.a2dBottomRight.setPos(self.a2dRight, 0, self.a2dBottom)
self.a2dBottomRightNs.setPos(self.a2dRight, 0, self.a2dBottom)
# This special root, pixel2d, uses units in pixels that are relative
# to the window. The upperleft corner of the window is (0, 0),
# the lowerleft corner is (xsize, -ysize), in this coordinate system.
xsize, ysize = self.getSize()
## This special root, pixel2d, uses units in pixels that are relative
## to the window. The upperleft corner of the window is (0, 0),
## the lowerleft corner is (xsize, -ysize), in this coordinate system.
self.pixel2d = self.render2d.attachNewNode(PGTop("pixel2d"))
self.pixel2d.setPos(-1, 0, 1)
xsize, ysize = self.getSize()
if xsize > 0 and ysize > 0:
self.pixel2d.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
@ -1144,25 +1170,27 @@ class ShowBase(DirectObject.DirectObject):
self.render2dp.setMaterialOff(1)
self.render2dp.setTwoSided(1)
# The normal 2-d DisplayRegion has an aspect ratio that
# matches the window, but its coordinate system is square.
# This means anything we parent to render2d gets stretched.
# For things where that makes a difference, we set up
# aspect2d, which scales things back to the right aspect
# ratio.
aspectRatio = self.getAspectRatio()
## The normal 2-d DisplayRegion has an aspect ratio that
## matches the window, but its coordinate system is square.
## This means anything we parent to render2dp gets stretched.
## For things where that makes a difference, we set up
## aspect2dp, which scales things back to the right aspect
## ratio along the X axis (Z is still from -1 to 1)
self.aspect2dp = self.render2dp.attachNewNode(PGTop("aspect2dp"))
self.aspect2dp.node().setStartSort(16384)
aspectRatio = self.getAspectRatio()
self.aspect2dp.setScale(1.0 / aspectRatio, 1.0, 1.0)
# It's important to know the bounds of the aspect2d screen.
## The Z position of the top border of the aspect2dp screen.
self.a2dpTop = 1.0
## The Z position of the bottom border of the aspect2dp screen.
self.a2dpBottom = -1.0
## The X position of the left border of the aspect2dp screen.
self.a2dpLeft = -aspectRatio
## The X position of the right border of the aspect2dp screen.
self.a2dpRight = aspectRatio
self.a2dpTopCenter = self.aspect2dp.attachNewNode("a2dpTopCenter")
self.a2dpBottomCenter = self.aspect2dp.attachNewNode("a2dpBottomCenter")
self.a2dpLeftCenter = self.aspect2dp.attachNewNode("a2dpLeftCenter")
@ -1184,13 +1212,13 @@ class ShowBase(DirectObject.DirectObject):
self.a2dpBottomLeft.setPos(self.a2dpLeft, 0, self.a2dpBottom)
self.a2dpBottomRight.setPos(self.a2dpRight, 0, self.a2dpBottom)
# This special root, pixel2d, uses units in pixels that are relative
# to the window. The upperleft corner of the window is (0, 0),
# the lowerleft corner is (xsize, -ysize), in this coordinate system.
xsize, ysize = self.getSize()
## This special root, pixel2d, uses units in pixels that are relative
## to the window. The upperleft corner of the window is (0, 0),
## the lowerleft corner is (xsize, -ysize), in this coordinate system.
self.pixel2dp = self.render2dp.attachNewNode(PGTop("pixel2dp"))
self.pixel2dp.node().setStartSort(16384)
self.pixel2dp.setPos(-1, 0, 1)
xsize, ysize = self.getSize()
if xsize > 0 and ysize > 0:
self.pixel2dp.setScale(2.0 / xsize, 1.0, 2.0 / ysize)
@ -1280,7 +1308,7 @@ class ShowBase(DirectObject.DirectObject):
# camera.
self.camera = self.render.attachNewNode(ModelNode('camera'))
self.camera.node().setPreserveTransform(ModelNode.PTLocal)
__builtin__.camera = self.camera
builtins.camera = self.camera
self.mouse2cam.node().setNode(self.camera.node())
@ -1502,12 +1530,14 @@ class ShowBase(DirectObject.DirectObject):
np = mw.getParent().attachNewNode(mouseRecorder)
mw.reparentTo(np)
# A special ButtonThrower to generate keyboard events and
# include the time from the OS. This is separate only to
# support legacy code that did not expect a time parameter; it
# will eventually be folded into the normal ButtonThrower,
# above.
mw = self.buttonThrowers[0].getParent()
## A special ButtonThrower to generate keyboard events and
## include the time from the OS. This is separate only to
## support legacy code that did not expect a time parameter; it
## will eventually be folded into the normal ButtonThrower,
## above.
self.timeButtonThrower = mw.attachNewNode(ButtonThrower('timeButtons'))
self.timeButtonThrower.node().setPrefix('time-')
self.timeButtonThrower.node().setTimeFlag(1)
@ -1931,7 +1961,7 @@ class ShowBase(DirectObject.DirectObject):
throw_new_frame()
return Task.cont
def restart(self,clusterSync=False,cluster=None):
def restart(self, clusterSync=False, cluster=None):
self.shutdown()
# __resetPrevTransform goes at the very beginning of the frame.
self.taskMgr.add(
@ -1970,7 +2000,7 @@ class ShowBase(DirectObject.DirectObject):
self.taskMgr.remove('dataLoop')
self.taskMgr.remove('resetPrevTransform')
self.taskMgr.remove('ivalLoop')
self.taskMgr.remove('garbage_collect')
self.taskMgr.remove('garbageCollectStates')
self.eventMgr.shutdown()
def getBackgroundColor(self, win = None):
@ -2784,7 +2814,7 @@ class ShowBase(DirectObject.DirectObject):
# wx is now the main loop, not us any more.
self.run = self.wxRun
self.taskMgr.run = self.wxRun
__builtin__.run = self.wxRun
builtins.run = self.wxRun
if self.appRunner:
self.appRunner.run = self.wxRun
@ -2846,7 +2876,7 @@ class ShowBase(DirectObject.DirectObject):
# Create a new Tk root.
self.tkRoot = Pmw.initialise()
__builtin__.tkroot = self.tkRoot
builtins.tkroot = self.tkRoot
init_app_for_gui()
@ -2863,7 +2893,7 @@ class ShowBase(DirectObject.DirectObject):
# wx is now the main loop, not us any more.
self.run = self.tkRun
self.taskMgr.run = self.tkRun
__builtin__.run = self.tkRun
builtins.run = self.tkRun
if self.appRunner:
self.appRunner.run = self.tkRun
@ -2908,7 +2938,7 @@ class ShowBase(DirectObject.DirectObject):
from direct.directtools import DirectSession
base.direct.enable()
else:
__builtin__.direct = self.direct = None
builtins.direct = self.direct = None
def getRepository(self):
return None
@ -2931,11 +2961,12 @@ class ShowBase(DirectObject.DirectObject):
self.startDirect(fWantDirect = fDirect, fWantTk = fTk, fWantWx = fWx)
def run(self):
# This method runs the TaskManager when self.appRunner is
# None, which is to say, when we are not running from within a
# p3d file. When we *are* within a p3d file, the Panda
# runtime has to be responsible for running the main loop, so
# we can't allow the application to do it.
""" This method runs the TaskManager when self.appRunner is
None, which is to say, when we are not running from within a
p3d file. When we *are* within a p3d file, the Panda
runtime has to be responsible for running the main loop, so
we can't allow the application to do it. """
if self.appRunner is None or self.appRunner.dummy or \
(self.appRunner.interactiveConsole and not self.appRunner.initialAppImport):
self.taskMgr.run()

View File

@ -408,7 +408,7 @@ class VFSSharedImporter:
path = sys.path
for dir in path:
pdir = Filename.fromOsSpecific(dir).cStr()
pdir = str(Filename.fromOsSpecific(dir))
if pdir + '/' + basename == dirname:
# We found it!
return dir

View File

@ -1174,7 +1174,7 @@ class Freezer:
source = open(sourceFilename.toOsSpecific(), 'r').read()
if source and source[-1] != '\n':
source = source + '\n'
code = compile(source, sourceFilename.cStr(), 'exec')
code = compile(source, str(sourceFilename), 'exec')
self.__addPyc(multifile, filename, code, compressionLevel)

View File

@ -20,33 +20,35 @@ the next section.
Alternately, it is possible to download the source in pieces. There
are three pieces:
1. Source code from Sourceforge.
1. Source code from Github.
2. Third-party tools (not strictly necessary for Unix)
3. Sample programs.
You will need all three to use makepanda. You can download all three
pieces from the panda website. Look for the files labeled "Panda3D
source, piecewise, X of 3". You can also obtain the first piece
directly from the sourceforge CVS server:
You will need both to use makepanda. You can find the
pieces on the panda website. Look for the files labeled "Panda3D
source". You can also obtain the first piece
directly from the github:
CVSROOT=:pserver:anonymous@panda3d.cvs.sourceforge.net:/cvsroot/panda3d
Make sure you have all three pieces. If you do, then your panda
Over https:
https://github.com/panda3d/panda3d.git
Over SSH:
git@github.com:panda3d/panda3d.git
Make sure you have both pieces. If you do, then your panda
directory will contain the following subdirectories:
direct - piece 1, source code from sourceforge
dmodels - piece 1, source code from sourceforge
doc - piece 1, source code from sourceforge
dtool - piece 1, source code from sourceforge
Makefile - piece 1, source code from sourceforge
makepanda - piece 1, source code from sourceforge
models - piece 1, source code from sourceforge
panda - piece 1, source code from sourceforge
pandatool - piece 1, source code from sourceforge
ppremake - piece 1, source code from sourceforge
contrib - piece 1, source code from sourceforge
direct - piece 1, source code from github
dmodels - piece 1, source code from github
doc - piece 1, source code from github
dtool - piece 1, source code from github
makepanda - piece 1, source code from github
models - piece 1, source code from github
panda - piece 1, source code from github
pandatool - piece 1, source code from github
ppremake - piece 1, source code from github
contrib - piece 1, source code from github
samples - piece 1, sample programs
thirdparty - piece 2, third party tools
samples - piece 3, sample programs
If you have all of these, you're ready to go. If not, then you
must have missed a piece.
@ -119,14 +121,49 @@ it will show you the available command-line options:
--help (print the help message you're reading now)
--verbose (print out more information)
--runtime (build a runtime build instead of an SDK build)
--installer (build an installer)
--optimize X (optimization level can be 1,2,3,4)
--version (set the panda version number)
--lzma (use lzma compression when building installer)
--version X (set the panda version number)
--lzma (use lzma compression when building Windows installer)
--distributor X (short string identifying the distributor of the build)
--outputdir X (use the specified directory instead of 'built')
--host URL (set the host url (runtime build only))
--threads N (use the multithreaded build system. see manual)
--osxtarget N (the OSX version number to build for (OSX only))
--universal (build universal binaries (OSX only))
--override "O=V" (override dtool_config/prc option value)
--static (builds libraries for static linking)
--target X (experimental cross-compilation (android only))
--arch X (target architecture for cross-compilation)
--use-python --no-python (enable/disable use of PYTHON)
--use-direct --no-direct (enable/disable use of DIRECT)
--use-gl --no-gl (enable/disable use of GL)
--use-gles --no-gles (enable/disable use of GLES)
--use-gles2 --no-gles2 (enable/disable use of GLES2)
--use-dx9 --no-dx9 (enable/disable use of DX9)
--use-tinydisplay --no-tinydisplay (enable/disable use of TINYDISPLAY)
--use-nvidiacg --no-nvidiacg (enable/disable use of NVIDIACG)
--use-egl --no-egl (enable/disable use of EGL)
--use-eigen --no-eigen (enable/disable use of EIGEN)
--use-openal --no-openal (enable/disable use of OPENAL)
--use-fmodex --no-fmodex (enable/disable use of FMODEX)
--use-vorbis --no-vorbis (enable/disable use of VORBIS)
--use-ffmpeg --no-ffmpeg (enable/disable use of FFMPEG)
--use-swscale --no-swscale (enable/disable use of SWSCALE)
--use-swresample --no-swresample (enable/disable use of SWRESAMPLE)
--use-ode --no-ode (enable/disable use of ODE)
--use-physx --no-physx (enable/disable use of PHYSX)
--use-bullet --no-bullet (enable/disable use of BULLET)
--use-pandaphysics --no-pandaphysics (enable/disable use of PANDAPHYSICS)
--use-speedtree --no-speedtree (enable/disable use of SPEEDTREE)
--use-zlib --no-zlib (enable/disable use of ZLIB)
--use-png --no-png (enable/disable use of PNG)
--use-jpeg --no-jpeg (enable/disable use of JPEG)
--use-tiff --no-tiff (enable/disable use of TIFF)
--use-squish --no-squish (enable/disable use of SQUISH)
--use-freetype --no-freetype (enable/disable use of FREETYPE)
--use-maya6 --no-maya6 (enable/disable use of MAYA6)
--use-maya65 --no-maya65 (enable/disable use of MAYA65)
--use-maya7 --no-maya7 (enable/disable use of MAYA7)
@ -135,41 +172,63 @@ it will show you the available command-line options:
--use-maya2008 --no-maya2008 (enable/disable use of MAYA2008)
--use-maya2009 --no-maya2009 (enable/disable use of MAYA2009)
--use-maya2010 --no-maya2010 (enable/disable use of MAYA2010)
--use-maya2011 --no-maya2011 (enable/disable use of MAYA2011)
--use-maya2012 --no-maya2012 (enable/disable use of MAYA2012)
--use-maya2013 --no-maya2013 (enable/disable use of MAYA2013)
--use-maya20135 --no-maya20135 (enable/disable use of MAYA20135)
--use-maya2014 --no-maya2014 (enable/disable use of MAYA2014)
--use-maya2015 --no-maya2015 (enable/disable use of MAYA2015)
--use-max6 --no-max6 (enable/disable use of MAX6)
--use-max7 --no-max7 (enable/disable use of MAX7)
--use-max8 --no-max8 (enable/disable use of MAX8)
--use-max9 --no-max9 (enable/disable use of MAX9)
--use-max2009 --no-max2009 (enable/disable use of MAX2009)
--use-max2010 --no-max2010 (enable/disable use of MAX2010)
--use-dx9 --no-dx9 (enable/disable use of DX9)
--use-python --no-python (enable/disable use of PYTHON)
--use-zlib --no-zlib (enable/disable use of ZLIB)
--use-png --no-png (enable/disable use of PNG)
--use-jpeg --no-jpeg (enable/disable use of JPEG)
--use-tiff --no-tiff (enable/disable use of TIFF)
--use-max2011 --no-max2011 (enable/disable use of MAX2011)
--use-max2012 --no-max2012 (enable/disable use of MAX2012)
--use-max2013 --no-max2013 (enable/disable use of MAX2013)
--use-max2014 --no-max2014 (enable/disable use of MAX2014)
--use-fcollada --no-fcollada (enable/disable use of FCOLLADA)
--use-vrpn --no-vrpn (enable/disable use of VRPN)
--use-tinyxml --no-tinyxml (enable/disable use of TINYXML)
--use-fmodex --no-fmodex (enable/disable use of FMODEX)
--use-openal --no-openal (enable/disable use of OPENAL)
--use-nvidiacg --no-nvidiacg (enable/disable use of NVIDIACG)
--use-openssl --no-openssl (enable/disable use of OPENSSL)
--use-freetype --no-freetype (enable/disable use of FREETYPE)
--use-wx --no-wx (enable/disable use of WX)
--use-fftw --no-fftw (enable/disable use of FFTW)
--use-artoolkit --no-artoolkit (enable/disable use of ARTOOLKIT)
--use-squish --no-squish (enable/disable use of SQUISH)
--use-ode --no-ode (enable/disable use of ODE)
--use-directcam --no-directcam (enable/disable use of DIRECTCAM)
--use-npapi --no-npapi (enable/disable use of NPAPI)
--use-opencv --no-opencv (enable/disable use of OPENCV)
--use-ffmpeg --no-ffmpeg (enable/disable use of FFMPEG)
--use-swscale --no-swscale (enable/disable use of SWSCALE)
--use-fcollada --no-fcollada (enable/disable use of FCOLLADA)
--use-directcam --no-directcam (enable/disable use of DIRECTCAM)
--use-vision --no-vision (enable/disable use of VISION)
--use-gtk2 --no-gtk2 (enable/disable use of GTK2)
--use-npapi --no-npapi (enable/disable use of NPAPI)
--use-mfc --no-mfc (enable/disable use of MFC)
--use-wx --no-wx (enable/disable use of WX)
--use-fltk --no-fltk (enable/disable use of FLTK)
--use-rocket --no-rocket (enable/disable use of ROCKET)
--use-awesomium --no-awesomium (enable/disable use of AWESOMIUM)
--use-carbon --no-carbon (enable/disable use of CARBON)
--use-cocoa --no-cocoa (enable/disable use of COCOA)
--use-x11 --no-x11 (enable/disable use of X11)
--use-xf86dga --no-xf86dga (enable/disable use of XF86DGA)
--use-xrandr --no-xrandr (enable/disable use of XRANDR)
--use-xcursor --no-xcursor (enable/disable use of XCURSOR)
--use-pandatool --no-pandatool (enable/disable use of PANDATOOL)
--use-pview --no-pview (enable/disable use of PVIEW)
--use-deploytools --no-deploytools (enable/disable use of DEPLOYTOOLS)
--use-skel --no-skel (enable/disable use of SKEL)
--use-pandafx --no-pandafx (enable/disable use of PANDAFX)
--use-pandaparticlesystem --no-pandaparticlesystem (enable/disable use of PA
NDAPARTICLESYSTEM)
--use-contrib --no-contrib (enable/disable use of CONTRIB)
--use-sse2 --no-sse2 (enable/disable use of SSE2)
--use-neon --no-neon (enable/disable use of NEON)
--use-touchinput --no-touchinput (enable/disable use of TOUCHINPUT)
--nothing (disable every third-party lib)
--everything (enable every third-party lib)
--directx-sdk=X (specify version of DX9 SDK to use: jun2010, aug2009, mar200
9, aug2006)
--platform-sdk=X (specify MSPlatSdk to use: win71, win61, win60A, winserver20
03r2)
--use-icl (experimental setting to use an intel compiler instead of MS
VC on Windows)
Makepanda shows you all the available options, not all of which may be
relevant to your operating system. For example, makepanda can build a
@ -247,11 +306,11 @@ It is all too easy to accidentally invoke 'makepanda' with the wrong
options, thereby triggering an hour-long recompilation. To avoid this
situation, we recommend that you write a short script containing the
options you intend to use regularly. For example, I regularly compile
panda without helix. I have a very short Windows BAT file called
panda without eigen. I have a very short Windows BAT file called
"mkp.bat" that looks like this:
@echo off
makepanda --everything --no-helix
makepanda --everything --no-eigen
This helps me avoid accidentally typing makepanda with the wrong
options.

View File

@ -21,7 +21,7 @@
#include "cppClassTemplateParameter.h"
#include "cppTemplateParameterList.h"
#include "cppInstanceIdentifier.h"
#include "cppTypedef.h"
#include "cppTypedefType.h"
#include "cppTypeDeclaration.h"
#include "cppVisibility.h"
#include "cppIdentifier.h"
@ -241,7 +241,8 @@ pop_struct() {
%token KW_BOOL
%token KW_CATCH
%token KW_CHAR
%token KW_WCHAR_T
%token KW_CHAR16_T
%token KW_CHAR32_T
%token KW_CLASS
%token KW_CONST
%token KW_DELETE
@ -294,6 +295,7 @@ pop_struct() {
%token KW_VIRTUAL
%token KW_VOID
%token KW_VOLATILE
%token KW_WCHAR_T
%token KW_WHILE
/* These special tokens are used to set the starting state of the
@ -325,8 +327,7 @@ pop_struct() {
%type <u.type> full_type
%type <u.struct_type> anonymous_struct
%type <u.struct_type> named_struct
%type <u.enum_type> anonymous_enum
%type <u.enum_type> named_enum
%type <u.enum_type> enum
%type <u.extension_enum> enum_keyword
%type <u.extension_enum> struct_keyword
%type <u.simple_type> simple_type
@ -334,6 +335,7 @@ pop_struct() {
%type <u.simple_type> simple_float_type
%type <u.simple_type> simple_void_type
%type <u.type> class_derivation_name
%type <u.type> enum_element_type
/*%type <u.type> typedefname*/
%type <u.identifier> name
%type <str> string
@ -353,7 +355,7 @@ pop_struct() {
/* Precedence rules. */
%left IDENTIFIER TYPENAME_IDENTIFIER TYPEDEFNAME KW_ENUM ELLIPSIS KW_OPERATOR KW_TYPENAME KW_INT KW_SHORT KW_UNSIGNED KW_SIGNED KW_LONG KW_FLOAT KW_DOUBLE KW_CHAR KW_WCHAR_T KW_BOOL
%left IDENTIFIER TYPENAME_IDENTIFIER TYPEDEFNAME KW_ENUM ELLIPSIS KW_OPERATOR KW_TYPENAME KW_INT KW_SHORT KW_UNSIGNED KW_SIGNED KW_LONG KW_FLOAT KW_DOUBLE KW_CHAR KW_WCHAR_T KW_CHAR16_T KW_CHAR32_T KW_BOOL
%left '{' ',' ';'
@ -493,17 +495,21 @@ declaration:
CPPDeclaration *getter = $5->find_symbol(current_scope, global_scope, current_lexer);
if (getter == (CPPDeclaration *)NULL || getter->get_subtype() != CPPDeclaration::ST_function_group) {
yyerror("Reference to non-existent or invalid getter: " + $5->get_fully_scoped_name(), @1);
}
CPPDeclaration *setter = $7->find_symbol(current_scope, global_scope, current_lexer);
if (setter == (CPPDeclaration *)NULL || setter->get_subtype() != CPPDeclaration::ST_function_group) {
yyerror("Reference to non-existent or invalid setter: " + $7->get_fully_scoped_name(), @1);
}
} else {
CPPDeclaration *setter = $7->find_symbol(current_scope, global_scope, current_lexer);
CPPFunctionGroup *setter_func = NULL;
CPPMakeProperty *make_property = new CPPMakeProperty($3, getter->as_function_group(),
setter->as_function_group(),
current_scope, @1.file);
current_scope->add_declaration(make_property, global_scope, current_lexer, @1);
if (setter == (CPPDeclaration *)NULL || setter->get_subtype() != CPPDeclaration::ST_function_group) {
yyerror("Reference to non-existent or invalid setter: " + $7->get_fully_scoped_name(), @1);
} else {
setter_func = setter->as_function_group();
}
CPPMakeProperty *make_property = new CPPMakeProperty($3, getter->as_function_group(),
setter_func, current_scope, @1.file);
current_scope->add_declaration(make_property, global_scope, current_lexer, @1);
}
}
| KW_MAKE_SEQ '(' name ',' name ',' name ')' ';'
{
@ -717,7 +723,8 @@ typedef_declaration:
if (inst != (CPPInstance *)NULL) {
inst->_storage_class |= (current_storage_class | $1);
current_scope->add_declaration(inst, global_scope, current_lexer, @2);
current_scope->add_declaration(new CPPTypedef(inst, current_scope == global_scope), global_scope, current_lexer, @2);
CPPTypedefType *typedef_type = new CPPTypedefType(inst->_type, inst->_ident, current_scope);
current_scope->add_declaration(typedef_type, global_scope, current_lexer, @2);
}
}
}
@ -726,19 +733,15 @@ typedef_declaration:
typedef_instance_identifiers:
instance_identifier maybe_initialize_or_function_body
{
CPPInstance *inst = new CPPInstance(current_type, $1,
current_storage_class,
@1.file);
inst->set_initializer($2);
current_scope->add_declaration(new CPPTypedef(inst, current_scope == global_scope), global_scope, current_lexer, @1);
CPPType *target_type = current_type;
CPPTypedefType *typedef_type = new CPPTypedefType(target_type, $1, current_scope, @1.file);
current_scope->add_declaration(typedef_type, global_scope, current_lexer, @1);
}
| instance_identifier maybe_initialize ',' typedef_instance_identifiers
{
CPPInstance *inst = new CPPInstance(current_type, $1,
current_storage_class,
@1.file);
inst->set_initializer($2);
current_scope->add_declaration(new CPPTypedef(inst, current_scope == global_scope), global_scope, current_lexer, @1);
CPPType *target_type = current_type;
CPPTypedefType *typedef_type = new CPPTypedefType(target_type, $1, current_scope, @1.file);
current_scope->add_declaration(typedef_type, global_scope, current_lexer, @1);
}
;
@ -746,20 +749,16 @@ typedef_const_instance_identifiers:
instance_identifier maybe_initialize_or_function_body
{
$1->add_modifier(IIT_const);
CPPInstance *inst = new CPPInstance(current_type, $1,
current_storage_class,
@1.file);
inst->set_initializer($2);
current_scope->add_declaration(new CPPTypedef(inst, current_scope == global_scope), global_scope, current_lexer, @1);
CPPType *target_type = current_type;
CPPTypedefType *typedef_type = new CPPTypedefType(target_type, $1, current_scope, @1.file);
current_scope->add_declaration(typedef_type, global_scope, current_lexer, @1);
}
| instance_identifier maybe_initialize ',' typedef_const_instance_identifiers
{
$1->add_modifier(IIT_const);
CPPInstance *inst = new CPPInstance(current_type, $1,
current_storage_class,
@1.file);
inst->set_initializer($2);
current_scope->add_declaration(new CPPTypedef(inst, current_scope == global_scope), global_scope, current_lexer, @1);
CPPType *target_type = current_type;
CPPTypedefType *typedef_type = new CPPTypedefType(target_type, $1, current_scope, @1.file);
current_scope->add_declaration(typedef_type, global_scope, current_lexer, @1);
}
;
@ -1585,11 +1584,7 @@ type:
{
$$ = CPPType::new_type($1);
}
| anonymous_enum
{
$$ = CPPType::new_type($1);
}
| named_enum
| enum
{
$$ = CPPType::new_type($1);
}
@ -1609,7 +1604,7 @@ type:
$$ = et;
}
}
| enum_keyword name
| enum_keyword name ':' enum_element_type
{
CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer);
if (type != NULL) {
@ -1649,11 +1644,7 @@ type_decl:
{
$$ = new CPPTypeDeclaration(CPPType::new_type($1));
}
| anonymous_enum
{
$$ = CPPType::new_type($1);
}
| named_enum
| enum
{
$$ = new CPPTypeDeclaration(CPPType::new_type($1));
}
@ -1672,9 +1663,27 @@ type_decl:
}
$$ = et;
}
}
| enum_keyword name ':' enum_element_type
{
CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer);
if (type != NULL) {
$$ = type;
} else {
CPPExtensionType *et =
CPPType::new_type(new CPPExtensionType($1, $2, current_scope, @1.file))
->as_extension_type();
CPPScope *scope = $2->get_scope(current_scope, global_scope);
if (scope != NULL) {
scope->define_extension_type(et);
}
$$ = et;
}
}
| enum_keyword name
{
yywarning(string("C++ does not permit forward declaration of untyped enum ") + $2->get_fully_scoped_name(), @1);
CPPType *type = $2->find_type(current_scope, global_scope, false, current_lexer);
if (type != NULL) {
$$ = type;
@ -1858,27 +1867,41 @@ base_specification:
}
;
anonymous_enum:
enum_keyword '{'
{
current_enum = new CPPEnumType(NULL, current_scope, @1.file);
}
enum_body '}'
enum:
enum_decl '{' enum_body '}'
{
$$ = current_enum;
current_enum = NULL;
}
;
named_enum:
enum_keyword name '{'
enum_decl:
enum_keyword name ':' enum_element_type
{
current_enum = new CPPEnumType($2, $4, current_scope, @1.file);
}
| enum_keyword name
{
current_enum = new CPPEnumType($2, current_scope, @1.file);
}
enum_body '}'
| enum_keyword ':' enum_element_type
{
$$ = current_enum;
current_enum = NULL;
current_enum = new CPPEnumType(NULL, $3, current_scope, @1.file);
}
| enum_keyword
{
current_enum = new CPPEnumType(NULL, current_scope, @1.file);
}
;
enum_element_type:
simple_int_type
{
$$ = CPPType::new_type($1);
}
| TYPENAME_IDENTIFIER
{
$$ = $1->find_type(current_scope, global_scope, false, current_lexer);
}
;
@ -1994,6 +2017,14 @@ simple_int_type:
| KW_WCHAR_T
{
$$ = new CPPSimpleType(CPPSimpleType::T_wchar_t);
}
| KW_CHAR16_T
{
$$ = new CPPSimpleType(CPPSimpleType::T_char16_t);
}
| KW_CHAR32_T
{
$$ = new CPPSimpleType(CPPSimpleType::T_char32_t);
}
| KW_SHORT
{
@ -2132,7 +2163,8 @@ element:
| SCOPE | PLUSPLUS | MINUSMINUS
| TIMESEQUAL | DIVIDEEQUAL | MODEQUAL | PLUSEQUAL | MINUSEQUAL
| OREQUAL | ANDEQUAL | XOREQUAL | LSHIFTEQUAL | RSHIFTEQUAL
| KW_BOOL | KW_CATCH | KW_CHAR | KW_WCHAR_T | KW_CLASS | KW_CONST
| KW_BOOL | KW_CATCH | KW_CHAR | KW_CHAR16_T | KW_CHAR32_T
| KW_WCHAR_T | KW_CLASS | KW_CONST
| KW_DELETE | KW_DOUBLE | KW_DYNAMIC_CAST | KW_ELSE | KW_ENUM
| KW_EXTERN | KW_EXPLICIT | KW_FALSE
| KW_FLOAT | KW_FRIEND | KW_FOR | KW_GOTO
@ -2369,6 +2401,18 @@ const_expr:
CPPType *type =
CPPType::new_type(new CPPSimpleType(CPPSimpleType::T_wchar_t));
$$ = new CPPExpression(CPPExpression::construct_op(type, $3));
}
| KW_CHAR16_T '(' optional_const_expr_comma ')'
{
CPPType *type =
CPPType::new_type(new CPPSimpleType(CPPSimpleType::T_char16_t));
$$ = new CPPExpression(CPPExpression::construct_op(type, $3));
}
| KW_CHAR32_T '(' optional_const_expr_comma ')'
{
CPPType *type =
CPPType::new_type(new CPPSimpleType(CPPSimpleType::T_char32_t));
$$ = new CPPExpression(CPPExpression::construct_op(type, $3));
}
| KW_BOOL '(' optional_const_expr_comma ')'
{

View File

@ -177,13 +177,13 @@ as_class_template_parameter() {
}
////////////////////////////////////////////////////////////////////
// Function: CPPDeclaration::as_typedef
// Function: CPPDeclaration::as_typedef_type
// Access: Public, Virtual
// Description:
////////////////////////////////////////////////////////////////////
CPPTypedef *CPPDeclaration::
as_typedef() {
return (CPPTypedef *)NULL;
CPPTypedefType *CPPDeclaration::
as_typedef_type() {
return (CPPTypedefType *)NULL;
}
////////////////////////////////////////////////////////////////////
@ -399,3 +399,24 @@ is_less(const CPPDeclaration *other) const {
return this < other;
}
ostream &
operator << (ostream &out, const CPPDeclaration::SubstDecl &subst) {
CPPDeclaration::SubstDecl::const_iterator it;
for (it = subst.begin(); it != subst.end(); ++it) {
out << " ";
if (it->first == NULL) {
out << "(null)";
} else {
out << *(it->first);
}
out << " -> ";
if (it->second == NULL) {
out << "(null)";
} else {
out << *(it->second);
}
out << "\n";
}
return out;
}

View File

@ -30,7 +30,7 @@ using namespace std;
class CPPInstance;
class CPPTemplateParameterList;
class CPPTypedef;
class CPPTypedefType;
class CPPTypeDeclaration;
class CPPExpression;
class CPPType;
@ -64,7 +64,6 @@ public:
enum SubType {
// Subtypes of CPPDeclaration
ST_instance,
ST_typedef,
ST_type_declaration,
ST_expression,
ST_type,
@ -87,6 +86,7 @@ public:
ST_class_template_parameter,
ST_tbd,
ST_type_proxy,
ST_typedef,
};
CPPDeclaration(const CPPFile &file);
@ -120,7 +120,7 @@ public:
virtual CPPInstance *as_instance();
virtual CPPClassTemplateParameter *as_class_template_parameter();
virtual CPPTypedef *as_typedef();
virtual CPPTypedefType *as_typedef_type();
virtual CPPTypeDeclaration *as_type_declaration();
virtual CPPExpression *as_expression();
virtual CPPType *as_type();
@ -157,4 +157,7 @@ operator << (ostream &out, const CPPDeclaration &decl) {
return out;
}
ostream &
operator << (ostream &out, const CPPDeclaration::SubstDecl &decl);
#endif

View File

@ -13,7 +13,7 @@
////////////////////////////////////////////////////////////////////
#include "cppEnumType.h"
#include "cppTypedef.h"
#include "cppTypedefType.h"
#include "cppExpression.h"
#include "cppSimpleType.h"
#include "cppConstType.h"
@ -24,14 +24,37 @@
////////////////////////////////////////////////////////////////////
// Function: CPPEnumType::Constructor
// Access: Public
// Description:
// Description: Creates an untyped, unscoped enum.
////////////////////////////////////////////////////////////////////
CPPEnumType::
CPPEnumType(CPPIdentifier *ident, CPPScope *current_scope,
const CPPFile &file) :
CPPExtensionType(T_enum, ident, current_scope, file),
_parent_scope(current_scope),
_element_type(NULL),
_last_value(NULL)
{
if (ident != NULL) {
ident->_native_scope = current_scope;
}
}
////////////////////////////////////////////////////////////////////
// Function: CPPEnumType::Constructor
// Access: Public
// Description: Creates a typed but unscoped enum.
////////////////////////////////////////////////////////////////////
CPPEnumType::
CPPEnumType(CPPIdentifier *ident, CPPType *element_type,
CPPScope *current_scope, const CPPFile &file) :
CPPExtensionType(T_enum, ident, current_scope, file),
_parent_scope(current_scope),
_element_type(element_type),
_last_value(NULL)
{
if (ident != NULL) {
ident->_native_scope = current_scope;
}
}
////////////////////////////////////////////////////////////////////
@ -41,12 +64,24 @@ CPPEnumType(CPPIdentifier *ident, CPPScope *current_scope,
////////////////////////////////////////////////////////////////////
CPPInstance *CPPEnumType::
add_element(const string &name, CPPExpression *value) {
CPPType *type =
CPPType::new_type(new CPPConstType(new CPPSimpleType(
CPPSimpleType::T_int, CPPSimpleType::F_unsigned)));
CPPIdentifier *ident = new CPPIdentifier(name);
CPPInstance *inst = new CPPInstance(type, ident);
ident->_native_scope = _parent_scope;
CPPInstance *inst;
static CPPType *default_element_type = NULL;
if (_element_type == NULL) {
// This enum is untyped. Use a suitable default, ie. 'int'.
if (default_element_type == NULL) {
default_element_type =
CPPType::new_type(new CPPConstType(new CPPSimpleType(CPPSimpleType::T_int, 0)));
}
inst = new CPPInstance(default_element_type, ident);
} else {
// This enum has an explicit type, so use that.
inst = new CPPInstance(CPPType::new_type(new CPPConstType(_element_type)), ident);
}
_elements.push_back(inst);
if (value == (CPPExpression *)NULL) {
@ -81,6 +116,38 @@ is_incomplete() const {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: CPPEnumType::is_fully_specified
// Access: Public, Virtual
// Description: Returns true if this declaration is an actual,
// factual declaration, or false if some part of the
// declaration depends on a template parameter which has
// not yet been instantiated.
////////////////////////////////////////////////////////////////////
bool CPPEnumType::
is_fully_specified() const {
if (!CPPDeclaration::is_fully_specified()) {
return false;
}
if (_ident != NULL && !_ident->is_fully_specified()) {
return false;
}
if (_element_type != NULL && !_element_type->is_fully_specified()) {
return false;
}
Elements::const_iterator ei;
for (ei = _elements.begin(); ei != _elements.end(); ++ei) {
if (!(*ei)->is_fully_specified()) {
return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////
// Function: CPPEnumType::substitute_decl
// Access: Public, Virtual
@ -95,12 +162,34 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
}
CPPEnumType *rep = new CPPEnumType(*this);
if (_ident != NULL) {
rep->_ident =
_ident->substitute_decl(subst, current_scope, global_scope);
}
if (rep->_ident == _ident) {
if (_element_type != NULL) {
rep->_element_type =
_element_type->substitute_decl(subst, current_scope, global_scope)
->as_type();
}
bool any_changed = false;
for (int i = 0; i < _elements.size(); ++i) {
CPPInstance *elem_rep =
_elements[i]->substitute_decl(subst, current_scope, global_scope)
->as_instance();
if (elem_rep != _elements[i]) {
rep->_elements[i] = elem_rep;
any_changed = true;
}
}
if (rep->_ident == _ident &&
rep->_element_type == _element_type &&
!any_changed) {
delete rep;
rep = this;
}
@ -124,15 +213,14 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const {
}
out << _ident->get_local_name(scope);
} else if (!complete && !_typedefs.empty()) {
// If we have a typedef name, use it.
out << _typedefs.front()->get_local_name(scope);
} else {
out << _type;
if (_ident != NULL) {
out << " " << _ident->get_local_name(scope);
}
if (_element_type != NULL) {
out << " : " << _element_type->get_local_name(scope);
}
out << " {\n";
Elements::const_iterator ei;

View File

@ -34,12 +34,15 @@ class CPPEnumType : public CPPExtensionType {
public:
CPPEnumType(CPPIdentifier *ident, CPPScope *current_scope,
const CPPFile &file);
CPPEnumType(CPPIdentifier *ident, CPPType *element_type,
CPPScope *current_scope, const CPPFile &file);
CPPInstance *add_element(const string &name,
CPPExpression *value = (CPPExpression *)NULL);
virtual bool is_incomplete() const;
virtual bool is_fully_specified() const;
virtual CPPDeclaration *substitute_decl(SubstDecl &subst,
CPPScope *current_scope,
CPPScope *global_scope);
@ -50,6 +53,9 @@ public:
virtual CPPEnumType *as_enum_type();
CPPScope *_parent_scope;
CPPType *_element_type;
typedef vector<CPPInstance *> Elements;
Elements _elements;
CPPExpression *_last_value;

View File

@ -147,6 +147,30 @@ as_pointer() const {
}
}
////////////////////////////////////////////////////////////////////
// Function: CPPExpression::Result::as_boolean
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
bool CPPExpression::Result::
as_boolean() const {
switch (_type) {
case RT_integer:
return (_u._integer != 0);
case RT_real:
return (_u._real != 0.0);
case RT_pointer:
return (_u._pointer != NULL);
default:
cerr << "Invalid type\n";
assert(false);
return false;
}
}
////////////////////////////////////////////////////////////////////
// Function: CPPExpression::Result::output
// Access: Public
@ -226,7 +250,7 @@ CPPExpression(CPPIdentifier *ident, CPPScope *current_scope,
CPPDeclaration(CPPFile())
{
CPPDeclaration *decl =
ident->find_symbol(current_scope, global_scope, error_sink);
ident->find_symbol(current_scope, global_scope);
if (decl != NULL) {
CPPInstance *inst = decl->as_instance();
@ -245,6 +269,7 @@ CPPExpression(CPPIdentifier *ident, CPPScope *current_scope,
_type = T_unknown_ident;
_u._ident = ident;
_u._ident->_native_scope = current_scope;
}
////////////////////////////////////////////////////////////////////
@ -801,6 +826,66 @@ determine_type() const {
return NULL; // Compiler kludge; can't get here.
}
////////////////////////////////////////////////////////////////////
// Function: CPPExpression::is_fully_specified
// Access: Public, Virtual
// Description: Returns true if this declaration is an actual,
// factual declaration, or false if some part of the
// declaration depends on a template parameter which has
// not yet been instantiated.
////////////////////////////////////////////////////////////////////
bool CPPExpression::
is_fully_specified() const {
if (!CPPDeclaration::is_fully_specified()) {
return false;
}
switch (_type) {
case T_integer:
case T_real:
case T_string:
return false;
case T_variable:
return _u._variable->is_fully_specified();
case T_function:
return _u._fgroup->is_fully_specified();
case T_unknown_ident:
return _u._ident->is_fully_specified();
case T_typecast:
case T_construct:
case T_new:
return (_u._typecast._to->is_fully_specified() &&
_u._typecast._op1->is_fully_specified());
case T_default_construct:
case T_default_new:
case T_sizeof:
return _u._typecast._to->is_fully_specified();
case T_trinary_operation:
if (!_u._op._op3->is_fully_specified()) {
return false;
}
// Fall through
case T_binary_operation:
if (!_u._op._op2->is_fully_specified()) {
return false;
}
// Fall through
case T_unary_operation:
return _u._op._op1->is_fully_specified();
default:
return true;
}
}
////////////////////////////////////////////////////////////////////
// Function: CPPExpression::substitute_decl
// Access: Public, Virtual
@ -827,6 +912,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
// Replacing the variable reference with another variable reference.
rep->_u._variable = decl->as_instance();
any_changed = true;
} else if (decl->as_expression()) {
// Replacing the variable reference with an expression.
delete rep;
@ -836,6 +922,43 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
}
break;
case T_unknown_ident:
rep->_u._ident = _u._ident->substitute_decl(subst, current_scope, global_scope);
any_changed = any_changed || (rep->_u._ident != _u._ident);
// See if we can define it now.
decl = rep->_u._ident->find_symbol(current_scope, global_scope, subst);
if (decl != NULL) {
CPPInstance *inst = decl->as_instance();
if (inst != NULL) {
rep->_type = T_variable;
rep->_u._variable = inst;
any_changed = true;
decl = inst->substitute_decl(subst, current_scope, global_scope);
if (decl != inst) {
if (decl->as_instance()) {
// Replacing the variable reference with another variable reference.
rep->_u._variable = decl->as_instance();
} else if (decl->as_expression()) {
// Replacing the variable reference with an expression.
delete rep;
rep = decl->as_expression();
}
}
break;
}
CPPFunctionGroup *fgroup = decl->as_function_group();
if (fgroup != NULL) {
rep->_type = T_function;
rep->_u._fgroup = fgroup;
any_changed = true;
}
}
break;
case T_typecast:
case T_construct:
case T_new:
@ -909,6 +1032,9 @@ is_tbd() const {
return true;
case T_unknown_ident:
return true;
case T_typecast:
case T_construct:
case T_new:
@ -996,8 +1122,12 @@ output(ostream &out, int indent_level, CPPScope *scope, bool) const {
break;
case T_variable:
// We can just refer to the variable by name, except if it's a
// private constant, in which case we have to compute the value,
// since we may have to use it in generated code.
if (_u._variable->_type != NULL &&
_u._variable->_initializer != NULL) {
_u._variable->_initializer != NULL &&
_u._variable->_vis > V_public) {
// A const variable. Fetch its assigned value.
CPPConstType *const_type = _u._variable->_type->as_const_type();
if (const_type != NULL) {
@ -1434,4 +1564,3 @@ is_less(const CPPDeclaration *other) const {
return false;
}

View File

@ -63,6 +63,7 @@ public:
int as_integer() const;
double as_real() const;
void *as_pointer() const;
bool as_boolean() const;
void output(ostream &out) const;
ResultType _type;
@ -78,6 +79,7 @@ public:
CPPType *determine_type() const;
bool is_tbd() const;
virtual bool is_fully_specified() const;
virtual CPPDeclaration *substitute_decl(SubstDecl &subst,
CPPScope *current_scope,
CPPScope *global_scope);

View File

@ -14,7 +14,7 @@
#include "cppExtensionType.h"
#include "cppTypedef.h"
#include "cppTypedefType.h"
#include "cppIdentifier.h"
#include "cppParser.h"
#include "indent.h"
@ -130,6 +130,29 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
return rep;
}
////////////////////////////////////////////////////////////////////
// Function: CPPExtensionType::resolve_type
// Access: Public, Virtual
// Description: If this CPPType object is a forward reference or
// other nonspecified reference to a type that might now
// be known a real type, returns the real type.
// Otherwise returns the type itself.
////////////////////////////////////////////////////////////////////
CPPType *CPPExtensionType::
resolve_type(CPPScope *current_scope, CPPScope *global_scope) {
if (_ident == NULL) {
// We can't resolve anonymous types. But that's OK, since they
// can't be forward declared anyway.
return this;
}
// Maybe it has been defined by now.
CPPType *type = _ident->find_type(current_scope, global_scope);
if (type != NULL) {
return type;
}
return this;
}
////////////////////////////////////////////////////////////////////
// Function: CPPExtensionType::is_equivalent_type

View File

@ -25,7 +25,9 @@ class CPPIdentifier;
///////////////////////////////////////////////////////////////////
// Class : CPPExtensionType
// Description :
// Description : Base class of enum, class, struct, and union types.
// An instance of the base class (instead of one of
// the specializations) is used for forward references.
////////////////////////////////////////////////////////////////////
class CPPExtensionType : public CPPType {
public:
@ -50,6 +52,9 @@ public:
CPPScope *current_scope,
CPPScope *global_scope);
virtual CPPType *resolve_type(CPPScope *current_scope,
CPPScope *global_scope);
virtual bool is_equivalent(const CPPType &other) const;

View File

@ -39,7 +39,7 @@ CPPIdentifier(const string &name, const CPPFile &file) : _file(file) {
// Description:
////////////////////////////////////////////////////////////////////
CPPIdentifier::
CPPIdentifier(const CPPNameComponent &name) {
CPPIdentifier(const CPPNameComponent &name, const CPPFile &file) : _file(file) {
_names.push_back(name);
_native_scope = (CPPScope *)NULL;
}
@ -146,8 +146,10 @@ get_local_name(CPPScope *scope) const {
if (scope == NULL || (_native_scope == NULL && _names.size() == 1)) {
result = _names.back().get_name_with_templ(scope);
} else if (_names.front().empty()) {
result = get_fully_scoped_name();
} else {
// Determine the scope of everything up until but not including the
// last name.
@ -382,6 +384,7 @@ find_type(CPPScope *current_scope, CPPScope *global_scope,
if (scope == NULL) {
return NULL;
}
CPPType *type = scope->find_type(get_simple_name(), subst, global_scope);
if (type != NULL && _names.back().has_templ()) {
// This is a template type.
@ -398,7 +401,6 @@ find_type(CPPScope *current_scope, CPPScope *global_scope,
assert(new_type != NULL);
if (new_type == type) {
type = CPPType::new_type(new CPPTBDType((CPPIdentifier *)this));
// type = new_type;
} else {
type = new_type;
}
@ -424,6 +426,7 @@ find_symbol(CPPScope *current_scope, CPPScope *global_scope,
if (scope == NULL) {
return NULL;
}
CPPDeclaration *sym;
if (!_names.back().has_templ()) {
sym = scope->find_symbol(get_simple_name());
@ -446,6 +449,43 @@ find_symbol(CPPScope *current_scope, CPPScope *global_scope,
return sym;
}
////////////////////////////////////////////////////////////////////
// Function: CPPIdentifier::find_symbol
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
CPPDeclaration *CPPIdentifier::
find_symbol(CPPScope *current_scope, CPPScope *global_scope,
CPPDeclaration::SubstDecl &subst,
CPPPreprocessor *error_sink) const {
CPPScope *scope = get_scope(current_scope, global_scope, subst, error_sink);
if (scope == NULL) {
return NULL;
}
CPPDeclaration *sym;
if (!_names.back().has_templ()) {
sym = scope->find_symbol(get_simple_name());
} else {
sym = scope->find_template(get_simple_name());
if (sym != NULL) {
CPPType *type = sym->as_type();
if (type != NULL && type->is_incomplete()) {
// We can't instantiate an incomplete type.
sym = CPPType::new_type(new CPPTBDType((CPPIdentifier *)this));
} else {
// Instantiate the symbol.
sym = sym->instantiate(_names.back().get_templ(), current_scope,
global_scope, error_sink);
}
}
}
return sym;
}
////////////////////////////////////////////////////////////////////
// Function: CPPIdentifier::find_template
// Access: Public

View File

@ -36,7 +36,7 @@ class CPPTemplateParameterList;
class CPPIdentifier {
public:
CPPIdentifier(const string &name, const CPPFile &file = CPPFile());
CPPIdentifier(const CPPNameComponent &name);
CPPIdentifier(const CPPNameComponent &name, const CPPFile &file = CPPFile());
void add_name(const string &name);
void add_name(const CPPNameComponent &name);
@ -69,6 +69,10 @@ public:
CPPDeclaration *find_symbol(CPPScope *current_scope,
CPPScope *global_scope,
CPPPreprocessor *error_sink = NULL) const;
CPPDeclaration *find_symbol(CPPScope *current_scope,
CPPScope *global_scope,
CPPDeclaration::SubstDecl &subst,
CPPPreprocessor *error_sink = NULL) const;
CPPDeclaration *find_template(CPPScope *current_scope,
CPPScope *global_scope,
CPPPreprocessor *error_sink = NULL) const;

View File

@ -372,6 +372,7 @@ CPPDeclaration *CPPInstance::
instantiate(const CPPTemplateParameterList *actual_params,
CPPScope *current_scope, CPPScope *global_scope,
CPPPreprocessor *error_sink) const {
if (!is_template()) {
if (error_sink != NULL) {
error_sink->warning("Ignoring template parameters for instance " +
@ -457,7 +458,6 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
rep->_type = new_type->as_type();
if (rep->_type == NULL) {
cerr << "Type " << *_type << " became " << *new_type << " which isn't a type\n";
rep->_type = _type;
}

View File

@ -47,8 +47,8 @@ ExpansionNode(const string &str, bool paste) :
////////////////////////////////////////////////////////////////////
CPPManifest::
CPPManifest(const string &args, const CPPFile &file) :
_file(file),
_variadic_param(-1),
_file(file),
_expr((CPPExpression *)NULL)
{
assert(!args.empty());
@ -184,7 +184,7 @@ expand(const vector_string &args) const {
// to a comma and no arguments are passed, the comma
// is removed. MSVC does this automatically. Not sure
// if we should allow MSVC behavior as well.
if (*result.rbegin() == ',') {
if (!result.empty() && *result.rbegin() == ',') {
result.resize(result.size() - 1);
}
}

View File

@ -200,6 +200,7 @@ CPPPreprocessor() {
_warning_count = 0;
_error_count = 0;
_error_abort = false;
#ifdef CPP_VERBOSE_LEX
_token_index = 0;
#endif
@ -404,8 +405,7 @@ get_next_token0() {
int token_type = IDENTIFIER;
CPPDeclaration *decl = ident->find_symbol(current_scope, global_scope);
if (decl != NULL &&
(decl->as_typedef() != NULL || decl->as_type() != NULL)) {
if (decl != NULL && decl->as_type() != NULL) {
token_type = TYPENAME_IDENTIFIER;
}
@ -432,10 +432,14 @@ warning(const string &message, int line, int col, CPPFile file) {
if (file.empty()) {
file = get_file();
}
indent(cerr, _files.size() * 2)
int indent_level = 0;
if (_verbose >= 3) {
indent_level = _files.size() * 2;
}
indent(cerr, indent_level)
<< "*** Warning in " << file
<< " near line " << line << ", column " << col << ":\n";
indent(cerr, _files.size() * 2)
indent(cerr, indent_level)
<< message << "\n";
}
_warning_count++;
@ -452,7 +456,7 @@ error(const string &message, int line, int col, CPPFile file) {
// Don't report or log errors in the nested state. These will be
// reported when the nesting level collapses.
return;
};
}
if (_verbose >= 1) {
if (line == 0) {
@ -462,11 +466,20 @@ error(const string &message, int line, int col, CPPFile file) {
if (file.empty()) {
file = get_file();
}
indent(cerr, _files.size() * 2)
int indent_level = 0;
if (_verbose >= 3) {
indent_level = _files.size() * 2;
}
indent(cerr, indent_level)
<< "*** Error in " << file
<< " near line " << line << ", column " << col << ":\n";
indent(cerr, _files.size() * 2)
indent(cerr, indent_level)
<< message << "\n";
if (_error_abort) {
cerr << "Aborting.\n";
abort();
}
}
_error_count++;
}
@ -603,7 +616,7 @@ init_type(const string &type) {
////////////////////////////////////////////////////////////////////
bool CPPPreprocessor::
push_file(const CPPFile &file) {
if (_verbose >= 2) {
if (_verbose >= 3) {
indent(cerr, _files.size() * 2)
<< "Reading " << file << "\n";
}
@ -2009,7 +2022,8 @@ check_keyword(const string &name) {
if (name == "bool") return KW_BOOL;
if (name == "catch") return KW_CATCH;
if (name == "char") return KW_CHAR;
if (name == "wchar_t") return KW_WCHAR_T;
if (name == "char16_t") return KW_CHAR16_T;
if (name == "char32_t") return KW_CHAR32_T;
if (name == "class") return KW_CLASS;
if (name == "const") return KW_CONST;
if (name == "delete") return KW_DELETE;
@ -2061,6 +2075,7 @@ check_keyword(const string &name) {
if (name == "virtual") return KW_VIRTUAL;
if (name == "void") return KW_VOID;
if (name == "volatile") return KW_VOLATILE;
if (name == "wchar_t") return KW_WCHAR_T;
if (name == "while") return KW_WHILE;
// These are alternative ways to refer to built-in operators.
@ -2287,7 +2302,6 @@ unget(int c) {
_unget = c;
}
////////////////////////////////////////////////////////////////////
// Function: CPPPreprocessor::nested_parse_template_instantiation
// Access: Private

View File

@ -209,6 +209,7 @@ private:
int _warning_count;
int _error_count;
bool _error_abort;
};
#endif

View File

@ -16,7 +16,7 @@
#include "cppScope.h"
#include "cppDeclaration.h"
#include "cppNamespace.h"
#include "cppTypedef.h"
#include "cppTypedefType.h"
#include "cppTypeDeclaration.h"
#include "cppExtensionType.h"
#include "cppInstance.h"
@ -136,7 +136,7 @@ add_declaration(CPPDeclaration *decl, CPPScope *global_scope,
_declarations.push_back(decl);
handle_declaration(decl, global_scope);
handle_declaration(decl, global_scope, preprocessor);
}
////////////////////////////////////////////////////////////////////
@ -185,9 +185,12 @@ add_enum_value(CPPInstance *inst, CPPPreprocessor *preprocessor,
// Description:
////////////////////////////////////////////////////////////////////
void CPPScope::
define_extension_type(CPPExtensionType *type) {
define_extension_type(CPPExtensionType *type, CPPPreprocessor *error_sink) {
assert(type != NULL);
string name = type->get_simple_name();
string name = type->get_local_name(this);
if (name.empty()) {
return;
}
switch (type->_type) {
case CPPExtensionType::T_class:
@ -200,34 +203,59 @@ define_extension_type(CPPExtensionType *type) {
case CPPExtensionType::T_union:
_unions[name] = type;
break;
case CPPExtensionType::T_enum:
_enums[name] = type;
break;
}
// Create an implicit typedef for the extension.
CPPIdentifier *ident = new CPPIdentifier(name);
CPPTypedef *td = new CPPTypedef(new CPPInstance(type, ident), false);
pair<Typedefs::iterator, bool> result =
_typedefs.insert(Typedefs::value_type(name, td));
//CPPTypedefType *td = new CPPTypedefType(type, name);
pair<Types::iterator, bool> result =
_types.insert(Types::value_type(name, type));
if (!result.second) {
// There's already a typedef for this extension. This one
// overrides if it has template parameters and the other one
// doesn't.
CPPType *other_type = (*result.first).second->_type;
if (type->is_template() && !other_type->is_template()) {
(*result.first).second = td;
// overrides it only if the other is a forward declaration.
CPPType *other_type = (*result.first).second;
// Or if the other one is a forward reference.
} else if (other_type->get_subtype() == CPPDeclaration::ST_extension) {
(*result.first).second = td;
if (other_type->get_subtype() == CPPDeclaration::ST_extension) {
CPPExtensionType *other_ext = other_type->as_extension_type();
if (other_ext->_type != type->_type) {
if (error_sink != NULL) {
ostringstream errstr;
errstr << other_ext->_type << " " << type->get_fully_scoped_name()
<< " was previously declared as " << other_ext->_type << "\n";
error_sink->error(errstr.str());
}
}
(*result.first).second = type;
} else {
CPPTypedefType *other_td = other_type->as_typedef_type();
// Error out if the declaration is different than the previous one.
if (other_type != type &&
(other_td == NULL || other_td->_type != type)) {
if (error_sink != NULL) {
ostringstream errstr;
type->output(errstr, 0, NULL, false);
errstr << " has conflicting declaration as ";
other_type->output(errstr, 0, NULL, true);
error_sink->error(errstr.str());
}
}
}
}
if (type->is_template()) {
string simple_name = type->get_simple_name();
pair<Templates::iterator, bool> result =
_templates.insert(Templates::value_type(name, type));
_templates.insert(Templates::value_type(simple_name, type));
if (!result.second) {
// The template was not inserted because we already had a
@ -277,7 +305,7 @@ add_using(CPPUsing *using_decl, CPPScope *global_scope,
} else {
CPPDeclaration *decl = using_decl->_ident->find_symbol(this, global_scope);
if (decl != NULL) {
handle_declaration(decl, global_scope);
handle_declaration(decl, global_scope, error_sink);
} else {
if (error_sink != NULL) {
error_sink->warning("Attempt to use unknown symbol: " + using_decl->_ident->get_fully_scoped_name());
@ -391,11 +419,13 @@ instantiate(const CPPTemplateParameterList *actual_params,
CPPDeclaration *decl = (*pi);
CPPClassTemplateParameter *ctp = decl->as_class_template_parameter();
if (ctp != NULL) {
CPPInstance *inst = new CPPInstance(ctp, ctp->_ident);
CPPTypedef *td = new CPPTypedef(inst, true);
scope->_typedefs.insert(Typedefs::value_type
(ctp->_ident->get_local_name(),
td));
//CPPTypedefType *td = new CPPTypedefType(ctp, ctp->_ident);
//scope->_typedefs.insert(Typedefs::value_type
// (ctp->_ident->get_local_name(),
// td));
scope->_types.insert(Types::value_type
(ctp->_ident->get_local_name(),
ctp));
}
}
}
@ -465,10 +495,10 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
////////////////////////////////////////////////////////////////////
CPPType *CPPScope::
find_type(const string &name, bool recurse) const {
Typedefs::const_iterator ti;
ti = _typedefs.find(name);
if (ti != _typedefs.end()) {
return (*ti).second->_type;
Types::const_iterator ti;
ti = _types.find(name);
if (ti != _types.end()) {
return ti->second;
}
Using::const_iterator ui;
@ -509,11 +539,11 @@ find_type(const string &name, bool recurse) const {
CPPType *CPPScope::
find_type(const string &name, CPPDeclaration::SubstDecl &subst,
CPPScope *global_scope, bool recurse) const {
Typedefs::const_iterator ti;
ti = _typedefs.find(name);
if (ti != _typedefs.end()) {
Types::const_iterator ti;
ti = _types.find(name);
if (ti != _types.end()) {
CPPScope *current_scope = (CPPScope *)this;
return (*ti).second->_type->substitute_decl
return (*ti).second->substitute_decl
(subst, current_scope, global_scope)->as_type();
}
@ -562,10 +592,14 @@ find_scope(const string &name, bool recurse) const {
CPPType *type = (CPPType *)NULL;
Typedefs::const_iterator ti;
ti = _typedefs.find(name);
if (ti != _typedefs.end()) {
type = (*ti).second->_type;
Types::const_iterator ti;
ti = _types.find(name);
if (ti != _types.end()) {
type = (*ti).second;
// Resolve if this is a typedef.
while (type->as_typedef_type() != (CPPTypedefType *)NULL) {
type = type->as_typedef_type()->_type;
}
} else if (_struct_type != NULL) {
CPPStructType::Derivation::const_iterator di;
@ -613,10 +647,17 @@ find_scope(const string &name, CPPDeclaration::SubstDecl &subst,
if (type == NULL) {
return NULL;
}
// Resolve this if it is a typedef.
while (type->get_subtype() == CPPDeclaration::ST_typedef) {
type = type->as_typedef_type()->_type;
}
CPPStructType *st = type->as_struct_type();
if (st == NULL) {
return NULL;
}
return st->_scope;
}
@ -631,10 +672,10 @@ find_symbol(const string &name, bool recurse) const {
return _struct_type;
}
Typedefs::const_iterator ti;
ti = _typedefs.find(name);
if (ti != _typedefs.end()) {
return (*ti).second->_type;
Types::const_iterator ti;
ti = _types.find(name);
if (ti != _types.end()) {
return (*ti).second;
}
Variables::const_iterator vi;
@ -755,9 +796,14 @@ get_local_name(CPPScope *scope) const {
}
*/
if (scope != NULL && _parent_scope != NULL && _parent_scope != scope) {
return _parent_scope->get_local_name(scope) + "::" +
_name.get_name_with_templ();
if (scope != NULL && _parent_scope != NULL/* && _parent_scope != scope*/) {
string parent_scope_name = _parent_scope->get_local_name(scope);
if (parent_scope_name.empty()) {
return _name.get_name_with_templ();
} else {
return parent_scope_name + "::" +
_name.get_name_with_templ();
}
} else {
return _name.get_name_with_templ();
}
@ -816,8 +862,7 @@ write(ostream &out, int indent_level, CPPScope *scope) const {
}
bool complete = false;
if (cd->as_typedef() != NULL || cd->as_type() != NULL ||
cd->as_namespace() != NULL) {
if (cd->as_type() != NULL || cd->as_namespace() != NULL) {
complete = true;
}
@ -880,7 +925,7 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst,
}
to_scope->_struct_type =
new CPPStructType(_struct_type->_type,
new CPPIdentifier(to_scope->_name),
new CPPIdentifier(to_scope->_name, _struct_type->_file),
native_scope, to_scope, _struct_type->_file);
to_scope->_struct_type->_incomplete = false;
@ -985,11 +1030,11 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst,
}
}
Typedefs::const_iterator ti;
for (ti = _typedefs.begin(); ti != _typedefs.end(); ++ti) {
CPPTypedef *td =
(*ti).second->substitute_decl(subst, to_scope, global_scope)->as_typedef();
to_scope->_typedefs.insert(Typedefs::value_type((*ti).first, td));
Types::const_iterator ti;
for (ti = _types.begin(); ti != _types.end(); ++ti) {
CPPType *td =
(*ti).second->substitute_decl(subst, to_scope, global_scope)->as_type();
to_scope->_types.insert(Types::value_type((*ti).first, td));
if (td != (*ti).second) {
anything_changed = true;
}
@ -999,6 +1044,19 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst,
CPPInstance *inst =
(*vi).second->substitute_decl(subst, to_scope, global_scope)->as_instance();
to_scope->_variables.insert(Variables::value_type((*vi).first, inst));
if (inst != (*vi).second) {
// I don't know if this _native_scope assignment is right, but it
// fixes some issues with variables in instantiated template scopes
// being printed out with an uninstantiated template scope prefix. ~rdb
inst->_ident->_native_scope = to_scope;
anything_changed = true;
}
}
for (vi = _enum_values.begin(); vi != _enum_values.end(); ++vi) {
CPPInstance *inst =
(*vi).second->substitute_decl(subst, to_scope, global_scope)->as_instance();
to_scope->_enum_values.insert(Variables::value_type((*vi).first, inst));
if (inst != (*vi).second) {
anything_changed = true;
}
@ -1026,25 +1084,41 @@ copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst,
// functions, or whatever.
////////////////////////////////////////////////////////////////////
void CPPScope::
handle_declaration(CPPDeclaration *decl, CPPScope *global_scope) {
CPPTypedef *def = decl->as_typedef();
handle_declaration(CPPDeclaration *decl, CPPScope *global_scope,
CPPPreprocessor *error_sink) {
CPPTypedefType *def = decl->as_typedef_type();
if (def != NULL) {
string name = def->get_simple_name();
_typedefs[name] = def;
pair<Types::iterator, bool> result =
_types.insert(Types::value_type(name, def));
if (!result.second) {
CPPType *other_type = result.first->second;
CPPTypedefType *other_td = other_type->as_typedef_type();
// We don't do redefinitions of typedefs. But we don't complain
// as long as this is actually a typedef to the previous definition.
if (other_type != def->_type &&
(other_td == NULL || other_td->_type != def->_type)) {
if (error_sink != NULL) {
ostringstream errstr;
def->output(errstr, 0, NULL, false);
errstr << " has conflicting declaration as ";
other_type->output(errstr, 0, NULL, true);
error_sink->error(errstr.str());
}
}
} else {
_types[name] = def;
}
CPPExtensionType *et = def->_type->as_extension_type();
if (et != NULL) {
define_extension_type(et);
define_extension_type(et, error_sink);
}
if (!name.empty() && def->get_scope(this, global_scope) == this) {
// Don't add a new template definition if we already had one
// by the same name in another scope.
if (find_template(name) == NULL) {
_templates.insert(Templates::value_type(name, def));
}
}
return;
}
@ -1052,7 +1126,7 @@ handle_declaration(CPPDeclaration *decl, CPPScope *global_scope) {
if (typedecl != (CPPTypeDeclaration *)NULL) {
CPPExtensionType *et = typedecl->_type->as_extension_type();
if (et != NULL) {
define_extension_type(et);
define_extension_type(et, error_sink);
}
return;
}
@ -1061,6 +1135,13 @@ handle_declaration(CPPDeclaration *decl, CPPScope *global_scope) {
if (inst != NULL) {
inst->check_for_constructor(this, global_scope);
if (inst->_ident != NULL) {
// Not sure if this is the best place to assign this. However,
// this fixes a bug with variables in expressions not having
// the proper scoping prefix. ~rdb
inst->_ident->_native_scope = this;
}
string name = inst->get_simple_name();
if (!name.empty() && inst->get_scope(this, global_scope) == this) {
if (inst->_type->as_function_type()) {
@ -1107,6 +1188,6 @@ handle_declaration(CPPDeclaration *decl, CPPScope *global_scope) {
CPPExtensionType *et = decl->as_extension_type();
if (et != NULL) {
define_extension_type(et);
define_extension_type(et, error_sink);
}
}

View File

@ -34,7 +34,7 @@ class CPPExtensionType;
class CPPStructType;
class CPPNamespace;
class CPPUsing;
class CPPTypedef;
class CPPTypedefType;
class CPPInstance;
class CPPFunctionGroup;
class CPPTemplateScope;
@ -66,7 +66,8 @@ public:
virtual void add_enum_value(CPPInstance *inst,
CPPPreprocessor *preprocessor,
const cppyyltype &pos);
virtual void define_extension_type(CPPExtensionType *type);
virtual void define_extension_type(CPPExtensionType *type,
CPPPreprocessor *error_sink = NULL);
virtual void define_namespace(CPPNamespace *scope);
virtual void add_using(CPPUsing *using_decl, CPPScope *global_scope,
CPPPreprocessor *error_sink = NULL);
@ -113,7 +114,8 @@ private:
copy_substitute_decl(CPPScope *to_scope, CPPDeclaration::SubstDecl &subst,
CPPScope *global_scope) const;
void handle_declaration(CPPDeclaration *decl, CPPScope *global_scope);
void handle_declaration(CPPDeclaration *decl, CPPScope *global_scope,
CPPPreprocessor *error_sink = NULL);
public:
typedef vector<CPPDeclaration *> Declarations;
@ -128,8 +130,8 @@ public:
typedef map<string, CPPNamespace *> Namespaces;
Namespaces _namespaces;
typedef map<string, CPPTypedef *> Typedefs;
Typedefs _typedefs;
typedef map<string, CPPType *> Types;
Types _types;
typedef map<string, CPPInstance *> Variables;
Variables _variables;
Variables _enum_values;

View File

@ -99,6 +99,10 @@ output(ostream &out, int, CPPScope *, bool) const {
}
switch (_type) {
case T_unknown:
out << "unknown";
break;
case T_bool:
out << "bool";
break;
@ -111,6 +115,14 @@ output(ostream &out, int, CPPScope *, bool) const {
out << "wchar_t";
break;
case T_char16_t:
out << "char16_t";
break;
case T_char32_t:
out << "char32_t";
break;
case T_int:
out << "int";
break;
@ -127,10 +139,6 @@ output(ostream &out, int, CPPScope *, bool) const {
out << "void";
break;
case T_unknown:
out << "unknown";
break;
case T_parameter:
out << "parameter";
break;

View File

@ -26,14 +26,16 @@
class CPPSimpleType : public CPPType {
public:
enum Type {
T_unknown,
T_bool,
T_char,
T_wchar_t, // Not strictly a builtin type, but we pretend.
T_wchar_t,
T_char16_t,
T_char32_t,
T_int,
T_float,
T_double,
T_void,
T_unknown,
// T_parameter is a special type which is assigned to expressions
// that are discovered where a formal parameter was expected.

View File

@ -14,7 +14,7 @@
#include "cppStructType.h"
#include "cppTypedef.h"
#include "cppTypedefType.h"
#include "cppScope.h"
#include "cppTypeProxy.h"
#include "cppTemplateScope.h"
@ -91,6 +91,13 @@ operator = (const CPPStructType &copy) {
void CPPStructType::
append_derivation(CPPType *base, CPPVisibility vis, bool is_virtual) {
if (base != NULL) {
// Unwrap any typedefs, since we can't inherit from a typedef.
CPPTypedefType *def = base->as_typedef_type();
while (def != NULL) {
base = def->_type;
def = base->as_typedef_type();
}
Base b;
b._base = base;
b._vis = vis;
@ -110,7 +117,6 @@ get_scope() const {
return _scope;
}
////////////////////////////////////////////////////////////////////
// Function: CPPStructType::is_abstract
// Access: Public
@ -246,7 +252,7 @@ instantiate(const CPPTemplateParameterList *actual_params,
// don't yet know what its associated struct type will be.
// Postpone the evaluation of this type.
CPPIdentifier *ident = new CPPIdentifier(get_fully_scoped_name());
CPPIdentifier *ident = new CPPIdentifier(get_fully_scoped_name(), _file);
return CPPType::new_type(new CPPTBDType(ident));
}
@ -318,7 +324,7 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
rep->_template_scope = (CPPTemplateScope *)NULL;
CPPNameComponent nc(get_simple_name());
nc.set_templ(pscope->_name.get_templ());
rep->_ident = new CPPIdentifier(nc);
rep->_ident = new CPPIdentifier(nc, _file);
}
}
}
@ -356,7 +362,6 @@ substitute_decl(CPPDeclaration::SubstDecl &subst,
assert(rep != NULL);
if (rep != this) {
_instantiations.insert(rep);
// cerr << "Subst for " << *this << " is " << *rep << "\n";
}
return rep;
}
@ -377,15 +382,9 @@ output(ostream &out, int indent_level, CPPScope *scope, bool complete) const {
if (is_template()) {
CPPTemplateScope *tscope = get_template_scope();
out << "< ";
tscope->_parameters.output(out, scope);
out << " >";
}
} else if (!complete && !_typedefs.empty()) {
// If we have a typedef name, use it.
out << _typedefs.front()->get_local_name(scope);
} else {
if (is_template()) {
get_template_scope()->_parameters.write_formal(out, scope);

View File

@ -52,6 +52,7 @@ void CPPTemplateParameterList::
build_subst_decl(const CPPTemplateParameterList &formal_params,
CPPDeclaration::SubstDecl &subst,
CPPScope *current_scope, CPPScope *global_scope) const {
Parameters::const_iterator pfi, pai;
for (pfi = formal_params._parameters.begin(), pai = _parameters.begin();
pfi != formal_params._parameters.end() && pai != _parameters.end();

Some files were not shown because too many files have changed in this diff Show More