+resource::type_lookup_ptr resource::type_lookup_;
+
+
+#if USE_HOTLOADING
+static hash<int,std::string,hash_function> monitor_lookup_;
+static int monitor_fd_ = inotify_init1(IN_NONBLOCK);
+#endif
+
+int resource::reload_as_needed()
+{
+ int num_resources = 0;
+
+#if USE_HOTLOADING
+ log_info("hotloading?");
+ char bytes[BUF_SIZE];
+ int num_bytes;
+ if (0 < (num_bytes = read(monitor_fd_, bytes, num_bytes)))
+ {
+ char* end = bytes + num_bytes;
+ char* byte = bytes;
+
+ log_warning("num_bytes:", num_bytes);
+ log_error("1");
+
+ while (byte < end)
+ {
+ struct inotify_event* event = (struct inotify_event*)byte;
+
+ if (event->mask & IN_IGNORED)
+ {
+ log_warning("watch", event->wd, "removed");
+ }
+
+ log_error("2");
+ hash<int,std::string,hash_function>::iterator it;
+ it = monitor_lookup_.find(event->wd);
+ if (it != monitor_lookup_.end())
+ {
+ log_error("3");
+ std::string path = (*it).second;
+ monitor_lookup_.erase(it);
+ resource::reload(path);
+ }
+
+ byte += sizeof(*event) + event->len;
+
+ ++num_resources;
+ }
+ }
+#endif
+
+ return num_resources;
+}
+
+
+resource::~resource()
+{
+#if USE_HOTLOADING
+ inotify_rm_watch(monitor_fd_, wd_);
+#endif
+}
+
+
+resource_ptr resource::load(const std::string& path)
+{
+ std::string extension = stlplus::extension_part(path);
+
+ if (!find(path)) return resource_ptr();
+
+ hash<std::string,resource_weakptr,hash_function>::iterator it;
+ it = resource_table_.find(path);
+ if (it != resource_table_.end())
+ {
+ resource_weakptr rsrc = (*it).second;
+ resource_ptr locked = rsrc.lock();
+ if (locked) return locked;
+ }
+
+ std::map<std::string,loader_ptr>::iterator jt;
+ jt = type_lookup_->find(extension);
+ if (jt != type_lookup_->end())
+ {
+ resource_ptr rsrc((*jt).second->load(path));
+ rsrc->set_loader(path, (*jt).second);
+ resource_table_[path] = rsrc;
+
+#if USE_HOTLOADING
+ int wd = inotify_add_watch(monitor_fd_,
+ path.c_str(), IN_MODIFY);
+ rsrc->set_watch_descriptor(wd);
+ monitor_lookup_[wd] = path;
+#endif
+
+ log_info("loaded", rsrc.get());
+ return rsrc;
+ }
+
+ return resource_ptr();
+}
+
+
+resource_ptr resource::reload(std::string& path)
+{
+ log_info("reloading...", path);
+ hash<std::string,resource_weakptr,hash_function>::iterator it;
+ it = resource_table_.find(path);
+ if (it != resource_table_.end())
+ {
+ resource_weakptr rsrc = (*it).second;
+ resource_ptr locked = rsrc.lock();
+ if (locked)
+ {
+ locked->reload();
+ return locked;
+ }
+ }
+
+ return load(path);
+}
+
+void resource::reload()
+{
+ log_info("reloaded", path_);
+
+ resource* resource = loader_->load(path_);
+ //*this = *resource;
+ resource_ = resource->resource_;
+ typeinfo_ = resource->typeinfo_;
+ unloader_ = resource->unloader_;
+
+#if USE_HOTLOADING
+ int wd = inotify_add_watch(monitor_fd_,
+ path_.c_str(), IN_MODIFY);
+ set_watch_descriptor(wd);
+ monitor_lookup_[wd] = path_;
+#endif
+
+ delete resource;
+}