shubhamgoyal

VirtualWorld.py (modified and backup copy)

Jul 16th, 2012
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.15 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2011-2012 Wiktor Starzyk, Faisal Z. Qureshi
  4. #
  5. # This file is part of the Virtual Vision Simulator.
  6. #
  7. # The Virtual Vision Simulator is free software: you can
  8. # redistribute it and/or modify it under the terms
  9. # of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License,
  11. # or (at your option) any later version.
  12. #
  13. # The Virtual Vision Simulator is distributed in the hope
  14. # that it will be useful, but WITHOUT ANY WARRANTY;
  15. # without even the implied warranty of MERCHANTABILITY or
  16. # FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with the Virtual Vision Simulator.  
  21. # If not, see <http://www.gnu.org/licenses/>.
  22. #
  23.  
  24.  
  25. import sys, os
  26. import logging
  27.  
  28. from math import tan, radians
  29.  
  30. from direct.showbase.ShowBase import ShowBase
  31. from direct.gui.OnscreenText import OnscreenText as OST
  32. from direct.task import Task
  33.  
  34. from pandac.PandaModules import AntialiasAttrib, ClockObject, TextNode
  35. from pandac.PandaModules import Vec3, VBase4
  36. from pandac.PandaModules import Camera, OrthographicLens
  37. from pandac.PandaModules import loadPrcFileData
  38. from pandac.PandaModules import WindowProperties
  39.  
  40. from builders.object_builder import ObjectBuilder
  41. from builders.pedestrian_builder import PedestrianBuilder
  42. from builders.light_builder import LightBuilder
  43. from builders.camera_builder import PandaCameraBuilder
  44. from file_io.scene_file import *
  45. from file_io.pedestrian_file import *
  46.  
  47. from simulator.model import Model
  48. from simulator.model import DIRECTIONALLIGHT
  49. from simulator.panda3d.controller import Controller
  50.  
  51. WIDTH = 1024
  52. HEIGHT = 768
  53.  
  54. loadPrcFileData("", "win-size %s %s" % (WIDTH, HEIGHT))
  55. loadPrcFileData("", "texture-anisotropic-degree 10")
  56.  
  57. LIGHTS_PER_OBJECT = 4
  58.  
  59. PTZ_CAMERA = 1
  60. WIDE_FOV_CAMERA = 2
  61.  
  62. MANUAL_CAMERA = False
  63.  
  64.  
  65. def Length(a, b):
  66.     ax, ay, az = a
  67.     bx, by, bz = b
  68.     length = (ax-bx) ** 2 + (ay-by) ** 2
  69.     return length
  70.  
  71.  
  72. class VirtualWorld(ShowBase):
  73.  
  74.     def __init__(self, scene_file, pedestrian_file, dir, mode):
  75.         ShowBase.__init__(self)
  76.  
  77.         self.globalClock = ClockObject.getGlobalClock()
  78.         self.globalClock.setMode(ClockObject.MSlave)
  79.        
  80.         self.directory = dir
  81.         self.model = Model(dir)
  82.         self.loadScene(scene_file)
  83.         self.loadPedestrians(pedestrian_file)
  84.        
  85.         #self.cam_label = OST("Top Down", pos=(0, 0.95), fg=(1,1,1,1),
  86.         #                     scale=0.05, mayChange=True)
  87.         #self.time_label = OST("Time: 0.0", pos=(-1.3, 0.95), fg=(1,1,1,1),
  88.         #                      scale=0.06, mayChange=True, align=TextNode.ALeft)
  89.                                        
  90.         #self.accept("arrow_right", self.changeCamera, [1])
  91.         #self.accept("arrow_left", self.changeCamera, [-1])
  92.         self.accept("escape", self.exit)
  93.         self.accept("aspectRatioChanged", self.setAspectRatio)
  94.         self.accept("window-event", self.windowChanged)
  95.        
  96.         #base.disableMouse()
  97.         lens = OrthographicLens()
  98.         lens.setFilmSize(1550, 1000)
  99.        
  100.         self.default_camera = render.attachNewNode(Camera("top down"))
  101.         self.default_camera.node().setLens(lens)
  102.         self.default_camera.setPosHpr(Vec3( -75, 0, 2200), Vec3(0, -90, 0))
  103.        
  104.         self.display_regions = []
  105.         self.display_regions.append(base.win.makeDisplayRegion(0, 0.33, 0.5, 1))
  106.         self.display_regions.append(base.win.makeDisplayRegion(0.33, 0.66, 0.5, 1))
  107.         self.display_regions.append(base.win.makeDisplayRegion(0.66, 1, 0.5, 1))
  108.         self.display_regions.append(base.win.makeDisplayRegion(0, 0.33, 0, 0.5))
  109.         self.display_regions.append(base.win.makeDisplayRegion(0.33, 0.66, 0, 0.5))
  110.         self.display_regions.append(base.win.makeDisplayRegion(0.66, 1, 0, 0.5))
  111.         for i in range(0, len(self.display_regions)):
  112.         self.assign_display_region_to_camera(self.display_regions[i], i)
  113.  
  114.         #self.setCamera(0)
  115.  
  116.         self.controller = Controller(self, mode)
  117.         self.taskMgr.add(self.updateCameraModules, "Update Camera Modules", 80)
  118.        
  119.         self.globalClock.setFrameTime(0.0)
  120.         self.width = WIDTH
  121.         self.height = HEIGHT
  122.  
  123.         props = WindowProperties( )
  124.         props.setTitle( 'Virtual Vision Simulator' )
  125.         base.win.requestProperties( props )
  126.  
  127.  
  128.     def assign_display_region_to_camera(self, display_region, camera_number):
  129.        
  130.         display_region.setClearColor(VBase4(0, 0, 0, 1))
  131.         display_region.setClearColorActive(True)
  132.         display_region.setClearDepthActive(True)
  133.         if camera_number == 0:
  134.             display_region.setCamera(self.default_camera)
  135.         else:
  136.             camera_list = self.model.getCameraList()
  137.             index = camera_number - 1
  138.             if index < len(camera_list):
  139.                 camera = camera_list[index]
  140.                 camera_np = camera.getCameraNode()
  141.                 display_region.setCamera(camera_np)
  142.        
  143.        
  144.     def getModel(self):
  145.         """
  146.        Returns the model that stores all of the cameras, pedestrians and
  147.        static objects in the scene.
  148.        """
  149.         return self.model
  150.  
  151.  
  152.     def getController(self):
  153.         """
  154.        Returns a controller that is used to control the world time.
  155.        """
  156.         return self.controller
  157.  
  158.  
  159.     def getTime(self):
  160.         """
  161.        Returns the current time in the world.
  162.        """
  163.         return self.globalClock.getFrameTime()
  164.  
  165.  
  166.     def loadScene(self, scene_file):
  167.         """
  168.        Loads the static objects that make up the scene. Also loads the lights
  169.        that illuminate the scene and for performance implications, sets what
  170.        lights affect what objects.
  171.        """
  172.         if not os.path.exists(scene_file):
  173.             logging.error("The path '%s' does not exist" % scene_file)
  174.             sys.exit()
  175.         light_builder = LightBuilder(self)
  176.         object_builder = ObjectBuilder(self, self.directory)
  177.         parser = SceneFileParser(self.model, object_builder, light_builder)
  178.         parser.parse(scene_file)
  179.        
  180.         self.setUpLights()
  181.  
  182.  
  183.     def setUpLights(self):
  184.         # Set what lights illuminate what objects
  185.         light_list = self.model.getLightList()
  186.         static_objects = self.model.getObjectList()
  187.         for object in static_objects:
  188.             if object.hasLighting():
  189.                 model_root = object.getModel().getChildren()[0]
  190.                 children = model_root.getChildren()
  191.                 for child in children:
  192.                     light_map = {}
  193.                     for index, light in enumerate(light_list):
  194.                         distance = Length(child.getPos(render), light.getPos())
  195.                         half_fov = light.node().getLens().getFov()[0] / 2.0
  196.                         height = light.getPos()[2]
  197.                         radius = height * tan(radians(half_fov))
  198.                         if distance > radius ** 2 + 2500 + 10:
  199.                             continue
  200.                         if distance not in light_map:
  201.                             light_map[distance] = [index]
  202.                         else:
  203.                             light_map[distance].append(index)
  204.  
  205.                     sorted_lights = sorted(light_map.keys())
  206.                     light_count = 0
  207.                     for key in sorted_lights:
  208.                         for i in light_map[key]:
  209.                             child.setLight(light_list[i])
  210.                             light_count += 1
  211.                             if light_count > LIGHTS_PER_OBJECT:
  212.                                 break
  213.                         if light_count > LIGHTS_PER_OBJECT:
  214.                             break
  215.                     child.flattenStrong()
  216.        
  217.         # Apply a directional light to the static models        
  218.         light_list = self.model.getLightList(DIRECTIONALLIGHT)
  219.         if light_list:
  220.             for object in static_objects:
  221.                 if object.hasLighting():
  222.                     model_root = object.getModel().getChildren()[0]
  223.                     model_root.setLight(light_list[0])
  224.  
  225.         render.setShaderAuto()
  226.         render.setAntialias(AntialiasAttrib.MLine)
  227.  
  228.  
  229.     def loadPedestrians(self, pedestrian_file):
  230.         """Loads the pedestrians into the scene."""
  231.         if not os.path.exists(pedestrian_file):
  232.             logging.error("The path '%s' does not exist" % pedestrian_file)
  233.             sys.exit()
  234.         pedestrian_builder = PedestrianBuilder(self, "../media/characters/")
  235.         parser = PedestrianFileParser(self.model, pedestrian_builder)
  236.         parser.parse("../media/characters/pedestrians.xml")
  237.         parser.parse(pedestrian_file)
  238.  
  239.  
  240.     def addCamera(self, config):
  241.         """
  242.        This method is used to add a new panda camera to the world. The panda
  243.        camera is returned so that it can be linked with a camera module.
  244.        """
  245.         type = config.type
  246.         cam_builder = PandaCameraBuilder(self)
  247.         if type == WIDE_FOV_CAMERA:
  248.             pass
  249.         else:
  250.             camera = cam_builder.buildPandaPTZCamera(config)
  251.             self.model.addCamera(camera)
  252.         return camera
  253.  
  254.  
  255.     def setAspectRatio(self):
  256.         """
  257.        This method is called when the aspect ratio of the window changes.
  258.        It updates the aspect ratios of all the cameras.
  259.        """
  260.         width = base.win.getXSize()
  261.         height = base.win.getYSize()
  262.         ratio = self.camLens.getAspectRatio()
  263.         camera_list = self.model.getCameraList()
  264.         for camera in camera_list:
  265.             camera.setAspectRatio(ratio)
  266.             camera.setImageSize(width, height)
  267.  
  268.         self.default_camera.node().getLens().setAspectRatio(ratio)
  269.         r =  width / float(height)
  270.         #self.time_label.setPos(-r, 0.95)
  271.  
  272.  
  273.     def changeCamera(self, num):
  274.         """
  275.        This method is used to toggle the camera that is viewed in the main
  276.        window. Typically num is either 1 or -1 denoting whether to toggle up
  277.        or down the camera list.
  278.        """
  279.         number = self.cur_camera + 1 + num
  280.         num_cameras = len(self.model.getCameraList())
  281.         if number > num_cameras:
  282.             number = 0
  283.         elif number < 0:
  284.             number = num_cameras
  285.         self.setCamera(number)
  286.  
  287.  
  288.     def setCamera(self, num):
  289.         """
  290.        This method sets which cameras view is shown in the panda3d window.
  291.        """
  292.         if MANUAL_CAMERA:
  293.             self.cur_camera = num -1
  294.             return
  295.        
  296.         self.display_region.setClearColor(VBase4(0, 0, 0, 1))
  297.         self.display_region.setClearColorActive(True)
  298.         self.display_region.setClearDepthActive(True)
  299.         if num == 0:
  300.             self.cur_camera = -1
  301.             self.display_region.setCamera(self.default_camera)
  302.             self.cam_label.setText("Top Down")
  303.         else:
  304.             camera_list = self.model.getCameraList()
  305.             index = num - 1
  306.             if index < len(camera_list):
  307.                 self.cur_camera = index
  308.                 camera = camera_list[index]
  309.                 camera_np = camera.getCameraNode()
  310.                 self.display_region.setCamera(camera_np)
  311.                 name = camera.getName()
  312.                 status_label = camera.getStatusLabel()
  313.                 label = "%s: %s" %(name, status_label)
  314.                 self.cam_label.setText(label)
  315.  
  316.  
  317.     def step(self, increment):
  318.         """
  319.        This method updates the world by one time step.
  320.        """
  321.         if increment:
  322.             new_time = self.globalClock.getFrameTime() + increment
  323.         else:
  324.             new_time = self.globalClock.getRealTime()
  325.            
  326.         self.globalClock.setFrameTime(new_time)
  327.         #self.time_label.setText("Time: %.2f" % new_time)
  328.        
  329.         self.updateActors()
  330.         self.updateCameras()
  331.  
  332.  
  333.     def updateActors(self):
  334.         """
  335.        This method updates the pedestrians in the scene by calling their update
  336.        functions.
  337.        """
  338.         pedestrians = self.model.getPedestrianList()
  339.         time = self.getTime()
  340.         for pedestrian in pedestrians:
  341.             if pedestrian.isActive(time):
  342.                 pedestrian.update(time)
  343.  
  344.  
  345.     def updateCameras(self):
  346.         """
  347.        This method updates the panda cameras which are used to provide the
  348.        higher level camera modules with rendered images of the scene. There
  349.        is one panda camera for each camera module.
  350.        """
  351.         time = self.getTime()
  352.         camera_list = self.model.getCameraList()
  353.         for camera in camera_list:
  354.             camera.update(time)
  355.        
  356.         """if self.cur_camera != -1:
  357.            cur_camera = camera_list[self.cur_camera]
  358.            if cur_camera.statusChanged():
  359.                name = cur_camera.getName()
  360.                status_label = cur_camera.getStatusLabel()
  361.                label = "%s: %s" %(name, status_label)
  362.                self.cam_label.setText(label)"""
  363.  
  364.  
  365.     def updateCameraModules(self, task):
  366.         """
  367.        This method updates the camera modules by calling their update function.
  368.        This allows the camera modules to process messages and complete any
  369.        tasks that were assigned to them.
  370.        """
  371.         time = self.getTime()
  372.         for camera in self.model.getCameraModules():
  373.             camera.update(time)
  374.         return Task.cont
  375.  
  376.  
  377.     def windowChanged(self, window):
  378.         """
  379.        This function is called when the window is modified. It updates the
  380.        image size used by the cameras when getting the rendered image from the
  381.        texture.
  382.        """
  383.         wp = window.getProperties()
  384.         width = wp.getXSize()
  385.         height = wp.getYSize()
  386.         if width != self.width or height != self.height:
  387.             self.width = width
  388.             self.height = height
  389.             camera_list = self.model.getCameraList()
  390.             for camera in camera_list:
  391.                 camera.setImageSize(width, height)
  392.         self.windowEvent(window)
  393.  
  394.  
  395.     def exit(self):
  396.         sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment